title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
PyQt5 – How to change the text of existing push button ?
22 Apr, 2020 In this article we will see how to change the text of existing push button. We know when we create a button, we set the text to it but sometimes, conditions occur in which re-usability of push button occur i.e button should do its normal operation just change the text of it, so it look different. In order to do this we use setText method. This method will over-write the existing text of push button. Syntax : button.setText(new_text) Argument : It takes string as argument. Action performed : It over-write the text of button. Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # changing the text of button button.setText("Over-write") # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 326, "s": 28, "text": "In this article we will see how to change the text of existing push button. We know when we create a button, we set the text to it but sometimes, conditions occur in which re-usability of push button occur i.e button should do its normal operation just change the text of it, so it look different." }, { "code": null, "e": 431, "s": 326, "text": "In order to do this we use setText method. This method will over-write the existing text of push button." }, { "code": null, "e": 465, "s": 431, "text": "Syntax : button.setText(new_text)" }, { "code": null, "e": 505, "s": 465, "text": "Argument : It takes string as argument." }, { "code": null, "e": 558, "s": 505, "text": "Action performed : It over-write the text of button." }, { "code": null, "e": 565, "s": 558, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # changing the text of button button.setText(\"Over-write\") # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1606, "s": 565, "text": null }, { "code": null, "e": 1615, "s": 1606, "text": "Output :" }, { "code": null, "e": 1626, "s": 1615, "text": "Python-gui" }, { "code": null, "e": 1638, "s": 1626, "text": "Python-PyQt" }, { "code": null, "e": 1645, "s": 1638, "text": "Python" }, { "code": null, "e": 1743, "s": 1645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1775, "s": 1743, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1802, "s": 1775, "text": "Python Classes and Objects" }, { "code": null, "e": 1833, "s": 1802, "text": "Python | os.path.join() method" }, { "code": null, "e": 1856, "s": 1833, "text": "Introduction To PYTHON" }, { "code": null, "e": 1877, "s": 1856, "text": "Python OOPs Concepts" }, { "code": null, "e": 1933, "s": 1877, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1975, "s": 1933, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2017, "s": 1975, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2056, "s": 2017, "text": "Python | Get unique values from a list" } ]
How to use SCSS mixins with angular 7?
27 Jun, 2020 When working with the Angular CLI, the default stylesheets have the .css extension. Starting an Angular CLI Project with Sass Normally, when we run ng new my-app, our app will have .css files. To get the CLI to generate .scss files (or .sass/.less) is an easy matter. Create a new project with Sass with the following: ng new my-sassy-app --style=scss Converting a Current App to Sass: If you’ve already created your Angular CLI app with the default .css files, it will take a bit more work to convert it over. You can tell Angular to start processing Sass files with the following command: ng set defaults.styleExt scss This will go ahead and tell the Angular CLI to start processing .scss files. If you want to peek under the hood at what this command did, check out the Angular CLI config file: .angular-cli.json. You’ll find the new config line at the bottom of the file: "defaults": { "styleExt": "scss", "component": { } }sd Changing the CSS Files to Sass: The Angular CLI will start processing Sass files now. However, it doesn’t go through the process of converting your already existing .css files to .scss files. You’ll have to make the conversion manually. Using Sass Imports: I personally like creating Sass files for project variables and for project mixins. This way, we can bring in any variables/mixins we’ll need quickly and easily. For instance, let’s create a brand new CLI app: ng new my-sassy-app --style=scss Next, create the following files: |- src/ |- sass/ |- _variables.scss |- _mixins.scss |- styles.scss To start using these new Sass files, we’ll import the _variables.scss and _mixins.scss into the main styles.scss. @import './variables'; @import './mixins'; The last step is to update our .angular-cli.json config to use this new src/sass/styles.scss instead of the src/styles.scss. In our .angular-cli.json file, just change the following line to point to the right styles.scss. "styles": [ "sass/styles.scss" ], Note: Separating out our Sass into its own folder because it allows us to create a more robust Sass foundation. Now when we start up our app, these new Sass files will be used! Importing Sass Files Into Angular Components: We have new _variables.scss and _mixins.scss files that we will probably want to use in our components. In other projects, you may be used to having access to your Sass variables in all locations since your Sass is compiled by a task runner. In the Angular CLI, all components are self-contained and so are their Sass files. In order to use a variable from within a component’s Sass file, you’ll need to import the _variables.scss file. One way to do this is to @import with a relative path from the component. This may not scale if you have many nested folders or eventually move files around. No matter what component Sass file we’re in, we can do an import like so: // src/app/app.component.scss @import '~sass/variables'; // now we can use those variables! The tilde (~) will tell Sass to look in the src/ folder and is a quick shortcut to importing Sass files. Sass Include Paths: In addition to using the ~, we can specify the includePaths configuration when working with the CLI. To tell Sass to look in certain folders, add the config lines to .angular-cli.json like in the app object next to the styles setting. "styles": [ "styles.scss" ], "stylePreprocessorOptions": { "includePaths": [ "../node_modules/bootstrap/scss" ] }, Using Bootstrap Sass Files: Another scenario we’ll need to do often is to import third party libraries and their Sass files. We’ll bring in Bootstrap and see how we can import the Sass files into our project. This is good since we can pick and choose what parts of Bootstrap we want to use. We can also import the Bootstrap mixins and use them in our own projects. To get us started, install bootstrap: npm install --save bootstrap Adding Bootstrap CSS File Now that we have Bootstrap, let’s look at how we can include the basic CSS file. This is an easy process by adding the bootstrap.css file to our .angular-cli.json config: "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.css", "sass/styles.scss" ], Note: We’re using the .. because the CLI starts looking from within the src/ folder. We had to go up one folder to get to the node_modules folder. While we can import the Bootstrap CSS this way, this doesn’t let us import just sections of Bootstrap or use the Sass variables/mixins that Bootstrap provides. Let’s look at how we can use the Bootstrap Sass files instead of the CSS file. Adding Bootstrap Sass Files @import "functions"; @import "variables"; @import "mixins"; @import "print"; @import "reboot"; @import "type"; @import "images"; @import "code"; @import "grid"; @import "tables"; @import "forms"; @import "buttons"; @import "transitions"; @import "dropdown"; @import "button-group"; @import "input-group"; @import "custom-forms"; @import "nav"; @import "navbar"; @import "card"; @import "breadcrumb"; @import "pagination"; @import "badge"; @import "jumbotron"; @import "alert"; @import "progress"; @import "media"; @import "list-group"; @import "close"; @import "modal"; @import "tooltip"; @import "popover"; @import "carousel"; @import "utilities"; That’s a lot of tools that you may not use in your own project. Inside our src/sass/styles.scss file, let’s import only the Bootstrap files we’ll need. Just like we imported Sass files from the src folder using the tilde (~), the tilde will also look into the node_modules folder. While we could use the tilde, since we already added Bootstrap to our include_paths in the stylePreprocessorOptions section of our .angular-cli.json: "styles": [ "styles.scss" ], "stylePreprocessorOptions": { "includePaths": [ "../node_modules/bootstrap/scss" ] }, We can do the following to only get the Bootstrap base tools: @import 'functions', 'variables', 'mixins', 'print', 'reboot', 'type'; Reference: https://scotch.io/tutorials/using-sass-with-the-angular-cli Picked SASS AngularJS Bootstrap CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Auth Guards in Angular 9/10/11 Routing in Angular 9/10 How to make a Bootstrap Modal Popup in Angular 9/8 ? What is AOT and JIT Compiler in Angular ? AngularJS | ng-model Directive Form validation using jQuery How to change navigation bar color in Bootstrap ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jun, 2020" }, { "code": null, "e": 112, "s": 28, "text": "When working with the Angular CLI, the default stylesheets have the .css extension." }, { "code": null, "e": 154, "s": 112, "text": "Starting an Angular CLI Project with Sass" }, { "code": null, "e": 296, "s": 154, "text": "Normally, when we run ng new my-app, our app will have .css files. To get the CLI to generate .scss files (or .sass/.less) is an easy matter." }, { "code": null, "e": 347, "s": 296, "text": "Create a new project with Sass with the following:" }, { "code": null, "e": 380, "s": 347, "text": "ng new my-sassy-app --style=scss" }, { "code": null, "e": 414, "s": 380, "text": "Converting a Current App to Sass:" }, { "code": null, "e": 619, "s": 414, "text": "If you’ve already created your Angular CLI app with the default .css files, it will take a bit more work to convert it over. You can tell Angular to start processing Sass files with the following command:" }, { "code": null, "e": 649, "s": 619, "text": "ng set defaults.styleExt scss" }, { "code": null, "e": 845, "s": 649, "text": "This will go ahead and tell the Angular CLI to start processing .scss files. If you want to peek under the hood at what this command did, check out the Angular CLI config file: .angular-cli.json." }, { "code": null, "e": 904, "s": 845, "text": "You’ll find the new config line at the bottom of the file:" }, { "code": null, "e": 965, "s": 904, "text": "\"defaults\": {\n \"styleExt\": \"scss\",\n \"component\": {\n }\n}sd" }, { "code": null, "e": 997, "s": 965, "text": "Changing the CSS Files to Sass:" }, { "code": null, "e": 1202, "s": 997, "text": "The Angular CLI will start processing Sass files now. However, it doesn’t go through the process of converting your already existing .css files to .scss files. You’ll have to make the conversion manually." }, { "code": null, "e": 1222, "s": 1202, "text": "Using Sass Imports:" }, { "code": null, "e": 1384, "s": 1222, "text": "I personally like creating Sass files for project variables and for project mixins. This way, we can bring in any variables/mixins we’ll need quickly and easily." }, { "code": null, "e": 1432, "s": 1384, "text": "For instance, let’s create a brand new CLI app:" }, { "code": null, "e": 1465, "s": 1432, "text": "ng new my-sassy-app --style=scss" }, { "code": null, "e": 1499, "s": 1465, "text": "Next, create the following files:" }, { "code": null, "e": 1595, "s": 1499, "text": "|- src/\n |- sass/\n |- _variables.scss\n |- _mixins.scss\n |- styles.scss\n" }, { "code": null, "e": 1709, "s": 1595, "text": "To start using these new Sass files, we’ll import the _variables.scss and _mixins.scss into the main styles.scss." }, { "code": null, "e": 1752, "s": 1709, "text": "@import './variables';\n@import './mixins';" }, { "code": null, "e": 1974, "s": 1752, "text": "The last step is to update our .angular-cli.json config to use this new src/sass/styles.scss instead of the src/styles.scss. In our .angular-cli.json file, just change the following line to point to the right styles.scss." }, { "code": null, "e": 2011, "s": 1974, "text": "\"styles\": [\n \"sass/styles.scss\"\n],\n" }, { "code": null, "e": 2123, "s": 2011, "text": "Note: Separating out our Sass into its own folder because it allows us to create a more robust Sass foundation." }, { "code": null, "e": 2188, "s": 2123, "text": "Now when we start up our app, these new Sass files will be used!" }, { "code": null, "e": 2234, "s": 2188, "text": "Importing Sass Files Into Angular Components:" }, { "code": null, "e": 2476, "s": 2234, "text": "We have new _variables.scss and _mixins.scss files that we will probably want to use in our components. In other projects, you may be used to having access to your Sass variables in all locations since your Sass is compiled by a task runner." }, { "code": null, "e": 2671, "s": 2476, "text": "In the Angular CLI, all components are self-contained and so are their Sass files. In order to use a variable from within a component’s Sass file, you’ll need to import the _variables.scss file." }, { "code": null, "e": 2829, "s": 2671, "text": "One way to do this is to @import with a relative path from the component. This may not scale if you have many nested folders or eventually move files around." }, { "code": null, "e": 2903, "s": 2829, "text": "No matter what component Sass file we’re in, we can do an import like so:" }, { "code": null, "e": 2998, "s": 2903, "text": "// src/app/app.component.scss\n\n@import '~sass/variables';\n\n// now we can use those variables!\n" }, { "code": null, "e": 3103, "s": 2998, "text": "The tilde (~) will tell Sass to look in the src/ folder and is a quick shortcut to importing Sass files." }, { "code": null, "e": 3123, "s": 3103, "text": "Sass Include Paths:" }, { "code": null, "e": 3358, "s": 3123, "text": "In addition to using the ~, we can specify the includePaths configuration when working with the CLI. To tell Sass to look in certain folders, add the config lines to .angular-cli.json like in the app object next to the styles setting." }, { "code": null, "e": 3484, "s": 3358, "text": "\"styles\": [\n \"styles.scss\"\n],\n\"stylePreprocessorOptions\": {\n \"includePaths\": [\n \"../node_modules/bootstrap/scss\"\n ]\n},\n" }, { "code": null, "e": 3512, "s": 3484, "text": "Using Bootstrap Sass Files:" }, { "code": null, "e": 3609, "s": 3512, "text": "Another scenario we’ll need to do often is to import third party libraries and their Sass files." }, { "code": null, "e": 3849, "s": 3609, "text": "We’ll bring in Bootstrap and see how we can import the Sass files into our project. This is good since we can pick and choose what parts of Bootstrap we want to use. We can also import the Bootstrap mixins and use them in our own projects." }, { "code": null, "e": 3887, "s": 3849, "text": "To get us started, install bootstrap:" }, { "code": null, "e": 3916, "s": 3887, "text": "npm install --save bootstrap" }, { "code": null, "e": 3942, "s": 3916, "text": "Adding Bootstrap CSS File" }, { "code": null, "e": 4113, "s": 3942, "text": "Now that we have Bootstrap, let’s look at how we can include the basic CSS file. This is an easy process by adding the bootstrap.css file to our .angular-cli.json config:" }, { "code": null, "e": 4204, "s": 4113, "text": "\"styles\": [\n \"../node_modules/bootstrap/dist/css/bootstrap.css\",\n \"sass/styles.scss\"\n],\n" }, { "code": null, "e": 4351, "s": 4204, "text": "Note: We’re using the .. because the CLI starts looking from within the src/ folder. We had to go up one folder to get to the node_modules folder." }, { "code": null, "e": 4511, "s": 4351, "text": "While we can import the Bootstrap CSS this way, this doesn’t let us import just sections of Bootstrap or use the Sass variables/mixins that Bootstrap provides." }, { "code": null, "e": 4590, "s": 4511, "text": "Let’s look at how we can use the Bootstrap Sass files instead of the CSS file." }, { "code": null, "e": 4618, "s": 4590, "text": "Adding Bootstrap Sass Files" }, { "code": null, "e": 5268, "s": 4618, "text": "@import \"functions\";\n@import \"variables\";\n@import \"mixins\";\n@import \"print\";\n@import \"reboot\";\n@import \"type\";\n@import \"images\";\n@import \"code\";\n@import \"grid\";\n@import \"tables\";\n@import \"forms\";\n@import \"buttons\";\n@import \"transitions\";\n@import \"dropdown\";\n@import \"button-group\";\n@import \"input-group\";\n@import \"custom-forms\";\n@import \"nav\";\n@import \"navbar\";\n@import \"card\";\n@import \"breadcrumb\";\n@import \"pagination\";\n@import \"badge\";\n@import \"jumbotron\";\n@import \"alert\";\n@import \"progress\";\n@import \"media\";\n@import \"list-group\";\n@import \"close\";\n@import \"modal\";\n@import \"tooltip\";\n@import \"popover\";\n@import \"carousel\";\n@import \"utilities\";\n" }, { "code": null, "e": 5332, "s": 5268, "text": "That’s a lot of tools that you may not use in your own project." }, { "code": null, "e": 5549, "s": 5332, "text": "Inside our src/sass/styles.scss file, let’s import only the Bootstrap files we’ll need. Just like we imported Sass files from the src folder using the tilde (~), the tilde will also look into the node_modules folder." }, { "code": null, "e": 5699, "s": 5549, "text": "While we could use the tilde, since we already added Bootstrap to our include_paths in the stylePreprocessorOptions section of our .angular-cli.json:" }, { "code": null, "e": 5825, "s": 5699, "text": "\"styles\": [\n \"styles.scss\"\n],\n\"stylePreprocessorOptions\": {\n \"includePaths\": [\n \"../node_modules/bootstrap/scss\"\n ]\n},\n" }, { "code": null, "e": 5887, "s": 5825, "text": "We can do the following to only get the Bootstrap base tools:" }, { "code": null, "e": 5972, "s": 5887, "text": "@import \n 'functions',\n 'variables',\n 'mixins',\n 'print',\n 'reboot',\n 'type';\n" }, { "code": null, "e": 6043, "s": 5972, "text": "Reference: https://scotch.io/tutorials/using-sass-with-the-angular-cli" }, { "code": null, "e": 6050, "s": 6043, "text": "Picked" }, { "code": null, "e": 6055, "s": 6050, "text": "SASS" }, { "code": null, "e": 6065, "s": 6055, "text": "AngularJS" }, { "code": null, "e": 6075, "s": 6065, "text": "Bootstrap" }, { "code": null, "e": 6079, "s": 6075, "text": "CSS" }, { "code": null, "e": 6096, "s": 6079, "text": "Web Technologies" }, { "code": null, "e": 6194, "s": 6096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6225, "s": 6194, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 6249, "s": 6225, "text": "Routing in Angular 9/10" }, { "code": null, "e": 6302, "s": 6249, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 6344, "s": 6302, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 6375, "s": 6344, "text": "AngularJS | ng-model Directive" }, { "code": null, "e": 6404, "s": 6375, "text": "Form validation using jQuery" }, { "code": null, "e": 6454, "s": 6404, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 6495, "s": 6454, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 6536, "s": 6495, "text": "How to Show Images on Click using HTML ?" } ]
String from prefix and suffix of given two strings
20 May, 2021 Given two strings a and b, form a new string of length l, from these strings by combining the prefix of string a and suffix of string b.Examples : Input : string a = remuneration string b = acquiesce length of pre/suffix(l) = 5 Output :remuniesce Input : adulation obstreperous 6 Output :adulatperous Approach : 1. Get first l letters from string a, and last l letters from string b. 2. Combine both results, and this will be resultant string. C++ Java Python3 C# PHP Javascript // CPP code to form new string from// pre/suffix of given strings.#include<bits/stdc++.h>using namespace std; // Returns a string which contains first l// characters of 'a' and last l characters of 'b'.string GetPrefixSuffix(string a, string b, int l){ // Getting prefix of first // string of given length string prefix = a.substr(0, l); // length of string b int lb = b.length(); // Calculating suffix of second string string suffix = b.substr(lb - l); // Concatenating both prefix and suffix return (prefix + suffix);} // Driver codeint main(){ string a = "remuneration" , b = "acquiesce"; int l = 5; cout << GetPrefixSuffix(a, b, l); return 0;} // Java Program to form new string// from pre/suffix of given stringsimport java.io.*; class GFG{ // Returns a string which contains first l // characters of 'a' and last l characters of 'b'. public static String prefixSuffix(String a, String b, int l) { // Calculating prefix of first // string of given length String prefix = a.substring(0, l); int lb = b.length(); // Calculating suffix of second // string of given length String suffix = b.substring(lb - l); return (prefix + suffix); } // Driver code public static void main(String args[]) throws IOException { String a = "remuneration" , b = "acquiesce"; int l = 5; System.out.println(prefixSuffix(a, b, l)); }} # Python code to form new from# pre/suffix of given strings. # Returns a string which contains first l# characters of 'a' and last l characters of 'b'.def GetPrefixSuffix(a, b, l): # Getting prefix of first # of given length prefix = a[: l]; # length of string b lb = len(b); # Calculating suffix of second string suffix = b[lb - l:]; # Concatenating both prefix and suffix return (prefix + suffix); # Driver codea = "remuneration";b = "acquiesce";l = 5;print(GetPrefixSuffix(a, b, l)); # This code contributed by Rajput-Ji // C# Program to form new string// from pre/suffix of given strings.using System; class GFG{ // Returns a string which contains first l // characters of 'a' and last l characters of 'b'. public static String prefixSuffix(String a, String b, int l) { // Calculating prefix of first // string of given length String prefix = a.Substring(0, l); int lb = b.Length; // Calculating suffix of second // string of given length String suffix = b.Substring(lb - l); return (prefix + suffix); } // Driver Code public static void Main() { String a = "remuneration" , b = "acquiesce"; int l = 5; Console.Write(prefixSuffix(a, b, l)); }} // This code is contributed by Nitin Mittal. <?php// PHP code to form new string from// pre/suffix of given strings. // Returns a string which contains// first l characters of 'a' and// last l characters of 'b'.function GetPrefixSuffix($a, $b, $l){ // Getting prefix of first // string of given length $prefix = substr($a, 0, $l); // length of string b $lb = strlen($b); // Calculating suffix of // second string $suffix = substr($b, $lb - $l); // Concatenating both // prefix and suffix return ($prefix.$suffix);} // Driver code $a = "remuneration"; $b = "acquiesce"; $l = 5; echo GetPrefixSuffix($a, $b, $l); // This code is contributed by Sam007?> <script> // JavaScript Program to form new string// from pre/suffix of given strings // Returns a string which contains first l// characters of 'a' and last l characters of 'b'.function prefixSuffix(a, b, l){ // Calculating prefix of first // string of given length var prefix = a.substring(0, l); var lb = b.length; // Calculating suffix of second // string of given length var suffix = b.substring(lb - l); return (prefix + suffix);} // Driver code var a = "remuneration" , b = "acquiesce"; var l = 5; document.write(prefixSuffix(a, b, l)); // This code contributed by shikhasingrajput </script> Output: remuniesce String from prefix and suffix of given two strings | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersString from prefix and suffix of given two strings | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=6PMRRgQ5WWQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> nitin mittal Sam007 Rajput-Ji Akanksha_Rai shikhasingrajput Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Convert string to char array in C++ Check whether two strings are anagram of each other Reverse words in a given string What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Reverse string in Python (6 different ways)
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2021" }, { "code": null, "e": 201, "s": 52, "text": "Given two strings a and b, form a new string of length l, from these strings by combining the prefix of string a and suffix of string b.Examples : " }, { "code": null, "e": 388, "s": 201, "text": "Input : string a = remuneration\n string b = acquiesce\n length of pre/suffix(l) = 5\nOutput :remuniesce\n\nInput : adulation\n obstreperous\n 6\nOutput :adulatperous" }, { "code": null, "e": 534, "s": 390, "text": "Approach : 1. Get first l letters from string a, and last l letters from string b. 2. Combine both results, and this will be resultant string. " }, { "code": null, "e": 538, "s": 534, "text": "C++" }, { "code": null, "e": 543, "s": 538, "text": "Java" }, { "code": null, "e": 551, "s": 543, "text": "Python3" }, { "code": null, "e": 554, "s": 551, "text": "C#" }, { "code": null, "e": 558, "s": 554, "text": "PHP" }, { "code": null, "e": 569, "s": 558, "text": "Javascript" }, { "code": "// CPP code to form new string from// pre/suffix of given strings.#include<bits/stdc++.h>using namespace std; // Returns a string which contains first l// characters of 'a' and last l characters of 'b'.string GetPrefixSuffix(string a, string b, int l){ // Getting prefix of first // string of given length string prefix = a.substr(0, l); // length of string b int lb = b.length(); // Calculating suffix of second string string suffix = b.substr(lb - l); // Concatenating both prefix and suffix return (prefix + suffix);} // Driver codeint main(){ string a = \"remuneration\" , b = \"acquiesce\"; int l = 5; cout << GetPrefixSuffix(a, b, l); return 0;}", "e": 1281, "s": 569, "text": null }, { "code": "// Java Program to form new string// from pre/suffix of given stringsimport java.io.*; class GFG{ // Returns a string which contains first l // characters of 'a' and last l characters of 'b'. public static String prefixSuffix(String a, String b, int l) { // Calculating prefix of first // string of given length String prefix = a.substring(0, l); int lb = b.length(); // Calculating suffix of second // string of given length String suffix = b.substring(lb - l); return (prefix + suffix); } // Driver code public static void main(String args[]) throws IOException { String a = \"remuneration\" , b = \"acquiesce\"; int l = 5; System.out.println(prefixSuffix(a, b, l)); }}", "e": 2174, "s": 1281, "text": null }, { "code": "# Python code to form new from# pre/suffix of given strings. # Returns a string which contains first l# characters of 'a' and last l characters of 'b'.def GetPrefixSuffix(a, b, l): # Getting prefix of first # of given length prefix = a[: l]; # length of string b lb = len(b); # Calculating suffix of second string suffix = b[lb - l:]; # Concatenating both prefix and suffix return (prefix + suffix); # Driver codea = \"remuneration\";b = \"acquiesce\";l = 5;print(GetPrefixSuffix(a, b, l)); # This code contributed by Rajput-Ji", "e": 2742, "s": 2174, "text": null }, { "code": "// C# Program to form new string// from pre/suffix of given strings.using System; class GFG{ // Returns a string which contains first l // characters of 'a' and last l characters of 'b'. public static String prefixSuffix(String a, String b, int l) { // Calculating prefix of first // string of given length String prefix = a.Substring(0, l); int lb = b.Length; // Calculating suffix of second // string of given length String suffix = b.Substring(lb - l); return (prefix + suffix); } // Driver Code public static void Main() { String a = \"remuneration\" , b = \"acquiesce\"; int l = 5; Console.Write(prefixSuffix(a, b, l)); }} // This code is contributed by Nitin Mittal.", "e": 3609, "s": 2742, "text": null }, { "code": "<?php// PHP code to form new string from// pre/suffix of given strings. // Returns a string which contains// first l characters of 'a' and// last l characters of 'b'.function GetPrefixSuffix($a, $b, $l){ // Getting prefix of first // string of given length $prefix = substr($a, 0, $l); // length of string b $lb = strlen($b); // Calculating suffix of // second string $suffix = substr($b, $lb - $l); // Concatenating both // prefix and suffix return ($prefix.$suffix);} // Driver code $a = \"remuneration\"; $b = \"acquiesce\"; $l = 5; echo GetPrefixSuffix($a, $b, $l); // This code is contributed by Sam007?>", "e": 4288, "s": 3609, "text": null }, { "code": "<script> // JavaScript Program to form new string// from pre/suffix of given strings // Returns a string which contains first l// characters of 'a' and last l characters of 'b'.function prefixSuffix(a, b, l){ // Calculating prefix of first // string of given length var prefix = a.substring(0, l); var lb = b.length; // Calculating suffix of second // string of given length var suffix = b.substring(lb - l); return (prefix + suffix);} // Driver code var a = \"remuneration\" , b = \"acquiesce\"; var l = 5; document.write(prefixSuffix(a, b, l)); // This code contributed by shikhasingrajput </script>", "e": 4919, "s": 4288, "text": null }, { "code": null, "e": 4929, "s": 4919, "text": "Output: " }, { "code": null, "e": 4940, "s": 4929, "text": "remuniesce" }, { "code": null, "e": 5860, "s": 4942, "text": "String from prefix and suffix of given two strings | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersString from prefix and suffix of given two strings | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:49•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=6PMRRgQ5WWQ\" 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": 5873, "s": 5860, "text": "nitin mittal" }, { "code": null, "e": 5880, "s": 5873, "text": "Sam007" }, { "code": null, "e": 5890, "s": 5880, "text": "Rajput-Ji" }, { "code": null, "e": 5903, "s": 5890, "text": "Akanksha_Rai" }, { "code": null, "e": 5920, "s": 5903, "text": "shikhasingrajput" }, { "code": null, "e": 5928, "s": 5920, "text": "Strings" }, { "code": null, "e": 5936, "s": 5928, "text": "Strings" }, { "code": null, "e": 6034, "s": 5936, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6091, "s": 6034, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 6129, "s": 6091, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 6190, "s": 6129, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 6235, "s": 6190, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 6271, "s": 6235, "text": "Convert string to char array in C++" }, { "code": null, "e": 6323, "s": 6271, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 6355, "s": 6323, "text": "Reverse words in a given string" }, { "code": null, "e": 6419, "s": 6355, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 6464, "s": 6419, "text": "Print all the duplicates in the input string" } ]
Sitadel – Web Application Security Scanner in Kali Linux
23 Aug, 2021 Sitadel is an open-source web application vulnerability scanner. The tool uses the technique of black-box to find various vulnerabilities. Sitadel provides a command-line interface that you can run on the Kali Linux terminal in order to scan hosts and domains. The interactive console provides a number of helpful features, such as command completion and contextual help. Sitadel provides a powerful environment in which open source web-based reconnaissance can be conducted and you can gather all information about the target. This tool is written in python language you must have python language installed in your kali linux operating system. Sitadel can be used for content delivery network detection. By using sitadel security researchers to define risk levels to allow for scans. Sitadel can be used for Plugin system detection. Step 1: Use the following command to install the tool in your kali Linux operating system. Use the second command given below to move into the directory of the tool. git clone https://github.com/shenril/Sitadel.git cd Sitadel Step 2: Use the following command to run the tool. python3 sitadel.py --help The tool is running successfully. Now we will see examples to use the tool. Example 1: Use the sitadel tool to find missing security headers of the domain. python3 sitadel.py https://secnhack.in Example 2: Use the sitadel tool to find risk levels. python3 sitadel.py <domain>--risk 2 Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples Compiling with g++ 'crontab' in Linux with Examples UDP Server-Client implementation in C touch command in Linux with Examples nohup Command in Linux with Examples echo command in Linux with Examples Cat command in Linux with examples Conditional Statements | Shell Script
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 673, "s": 28, "text": "Sitadel is an open-source web application vulnerability scanner. The tool uses the technique of black-box to find various vulnerabilities. Sitadel provides a command-line interface that you can run on the Kali Linux terminal in order to scan hosts and domains. The interactive console provides a number of helpful features, such as command completion and contextual help. Sitadel provides a powerful environment in which open source web-based reconnaissance can be conducted and you can gather all information about the target. This tool is written in python language you must have python language installed in your kali linux operating system." }, { "code": null, "e": 733, "s": 673, "text": "Sitadel can be used for content delivery network detection." }, { "code": null, "e": 813, "s": 733, "text": "By using sitadel security researchers to define risk levels to allow for scans." }, { "code": null, "e": 862, "s": 813, "text": "Sitadel can be used for Plugin system detection." }, { "code": null, "e": 1028, "s": 862, "text": "Step 1: Use the following command to install the tool in your kali Linux operating system. Use the second command given below to move into the directory of the tool." }, { "code": null, "e": 1088, "s": 1028, "text": "git clone https://github.com/shenril/Sitadel.git\ncd Sitadel" }, { "code": null, "e": 1139, "s": 1088, "text": "Step 2: Use the following command to run the tool." }, { "code": null, "e": 1165, "s": 1139, "text": "python3 sitadel.py --help" }, { "code": null, "e": 1241, "s": 1165, "text": "The tool is running successfully. Now we will see examples to use the tool." }, { "code": null, "e": 1321, "s": 1241, "text": "Example 1: Use the sitadel tool to find missing security headers of the domain." }, { "code": null, "e": 1360, "s": 1321, "text": "python3 sitadel.py https://secnhack.in" }, { "code": null, "e": 1413, "s": 1360, "text": "Example 2: Use the sitadel tool to find risk levels." }, { "code": null, "e": 1449, "s": 1413, "text": "python3 sitadel.py <domain>--risk 2" }, { "code": null, "e": 1460, "s": 1449, "text": "Kali-Linux" }, { "code": null, "e": 1472, "s": 1460, "text": "Linux-Tools" }, { "code": null, "e": 1483, "s": 1472, "text": "Linux-Unix" }, { "code": null, "e": 1581, "s": 1483, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1619, "s": 1581, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 1654, "s": 1619, "text": "tar command in Linux with examples" }, { "code": null, "e": 1673, "s": 1654, "text": "Compiling with g++" }, { "code": null, "e": 1706, "s": 1673, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 1744, "s": 1706, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 1781, "s": 1744, "text": "touch command in Linux with Examples" }, { "code": null, "e": 1818, "s": 1781, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 1854, "s": 1818, "text": "echo command in Linux with Examples" }, { "code": null, "e": 1889, "s": 1854, "text": "Cat command in Linux with examples" } ]
GATE | GATE-CS-2000 | Question 23
28 Jun, 2021 Given the relations employee (name, salary, deptno) and department (deptno, deptname, address) Which of the following queries cannot be expressed using the basic relational algebra operations (U, -, x, , , p)?(A) Department address of every employee(B) Employees whose name is the same as their department name(C) The sum of all employees’ salaries(D) All employees of a given departmentAnswer: (C)Explanation: See question 1 of https://www.geeksforgeeks.org/database-management-system-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.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 48, "s": 28, "text": "Given the relations" }, { "code": null, "e": 123, "s": 48, "text": "employee (name, salary, deptno) and\ndepartment (deptno, deptname, address)" }, { "code": null, "e": 543, "s": 123, "text": "Which of the following queries cannot be expressed using the basic relational algebra operations (U, -, x, , , p)?(A) Department address of every employee(B) Employees whose name is the same as their department name(C) The sum of all employees’ salaries(D) All employees of a given departmentAnswer: (C)Explanation: See question 1 of https://www.geeksforgeeks.org/database-management-system-set-1/Quiz of this Question" }, { "code": null, "e": 556, "s": 543, "text": "GATE-CS-2000" }, { "code": null, "e": 574, "s": 556, "text": "GATE-GATE-CS-2000" }, { "code": null, "e": 579, "s": 574, "text": "GATE" } ]
LocalDateTime format() method in Java
30 Nov, 2018 The format() method of LocalDateTime class in Java formats this date-time using the specified formatter. Syntax: public String format(DateTimeFormatter formatter) Parameter: This method accepts a parameter formatter which specifies the formatter to use, not null. Returns: The function returns the formatted date string and not null. Below programs illustrate the LocalDateTime.format() method: Program 1: // Java program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse("2018-11-03T12:45:30"); // Prints the date System.out.println("Original LocalDateTime: " + dt1); // Display d1 in different formats // using format() method System.out.println("BASIC_ISO_DATE format: " + (DateTimeFormatter.BASIC_ISO_DATE) .format(dt1)); System.out.println("ISO_LOCAL_DATE format: " + (DateTimeFormatter.ISO_LOCAL_DATE) .format(dt1)); System.out.println("ISO_DATE format: " + (DateTimeFormatter.ISO_DATE) .format(dt1)); System.out.println("ISO_LOCAL_TIME format: " + (DateTimeFormatter.ISO_LOCAL_TIME) .format(dt1)); }} Original LocalDateTime: 2018-11-03T12:45:30 BASIC_ISO_DATE format: 20181103 ISO_LOCAL_DATE format: 2018-11-03 ISO_DATE format: 2018-11-03 ISO_LOCAL_TIME format: 12:45:30 Program 2: // Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse("2016-09-06T12:45:30"); // Prints the date System.out.println(dt1); // Display d1 in different formats // using format() method System.out.println("ISO_TIME format: " + (DateTimeFormatter.ISO_TIME) .format(dt1)); System.out.println("ISO_LOCAL_DATE_TIME format: " + (DateTimeFormatter.ISO_LOCAL_DATE_TIME) .format(dt1)); System.out.println("ISO_DATE_TIME format: " + (DateTimeFormatter.ISO_DATE_TIME) .format(dt1)); System.out.println("ISO_ORDINAL_DATE format: " + (DateTimeFormatter.ISO_ORDINAL_DATE) .format(dt1)); System.out.println("ISO_WEEK_DATE format: " + (DateTimeFormatter.ISO_WEEK_DATE) .format(dt1)); }} 2016-09-06T12:45:30 ISO_TIME format: 12:45:30 ISO_LOCAL_DATE_TIME format: 2016-09-06T12:45:30 ISO_DATE_TIME format: 2016-09-06T12:45:30 ISO_ORDINAL_DATE format: 2016-250 ISO_WEEK_DATE format: 2016-W36-2 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#format(java.time.format.DateTimeFormatter) Java-Functions Java-LocalDateTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Nov, 2018" }, { "code": null, "e": 158, "s": 53, "text": "The format() method of LocalDateTime class in Java formats this date-time using the specified formatter." }, { "code": null, "e": 166, "s": 158, "text": "Syntax:" }, { "code": null, "e": 217, "s": 166, "text": "public String format(DateTimeFormatter formatter)\n" }, { "code": null, "e": 318, "s": 217, "text": "Parameter: This method accepts a parameter formatter which specifies the formatter to use, not null." }, { "code": null, "e": 388, "s": 318, "text": "Returns: The function returns the formatted date string and not null." }, { "code": null, "e": 449, "s": 388, "text": "Below programs illustrate the LocalDateTime.format() method:" }, { "code": null, "e": 460, "s": 449, "text": "Program 1:" }, { "code": "// Java program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse(\"2018-11-03T12:45:30\"); // Prints the date System.out.println(\"Original LocalDateTime: \" + dt1); // Display d1 in different formats // using format() method System.out.println(\"BASIC_ISO_DATE format: \" + (DateTimeFormatter.BASIC_ISO_DATE) .format(dt1)); System.out.println(\"ISO_LOCAL_DATE format: \" + (DateTimeFormatter.ISO_LOCAL_DATE) .format(dt1)); System.out.println(\"ISO_DATE format: \" + (DateTimeFormatter.ISO_DATE) .format(dt1)); System.out.println(\"ISO_LOCAL_TIME format: \" + (DateTimeFormatter.ISO_LOCAL_TIME) .format(dt1)); }}", "e": 1628, "s": 460, "text": null }, { "code": null, "e": 1799, "s": 1628, "text": "Original LocalDateTime: 2018-11-03T12:45:30\nBASIC_ISO_DATE format: 20181103\nISO_LOCAL_DATE format: 2018-11-03\nISO_DATE format: 2018-11-03\nISO_LOCAL_TIME format: 12:45:30\n" }, { "code": null, "e": 1810, "s": 1799, "text": "Program 2:" }, { "code": "// Program to illustrate the format() method import java.util.*;import java.time.*;import java.time.format.DateTimeFormatter; public class GfG { public static void main(String[] args) { // Parses the date LocalDateTime dt1 = LocalDateTime .parse(\"2016-09-06T12:45:30\"); // Prints the date System.out.println(dt1); // Display d1 in different formats // using format() method System.out.println(\"ISO_TIME format: \" + (DateTimeFormatter.ISO_TIME) .format(dt1)); System.out.println(\"ISO_LOCAL_DATE_TIME format: \" + (DateTimeFormatter.ISO_LOCAL_DATE_TIME) .format(dt1)); System.out.println(\"ISO_DATE_TIME format: \" + (DateTimeFormatter.ISO_DATE_TIME) .format(dt1)); System.out.println(\"ISO_ORDINAL_DATE format: \" + (DateTimeFormatter.ISO_ORDINAL_DATE) .format(dt1)); System.out.println(\"ISO_WEEK_DATE format: \" + (DateTimeFormatter.ISO_WEEK_DATE) .format(dt1)); }}", "e": 3080, "s": 1810, "text": null }, { "code": null, "e": 3284, "s": 3080, "text": "2016-09-06T12:45:30\nISO_TIME format: 12:45:30\nISO_LOCAL_DATE_TIME format: 2016-09-06T12:45:30\nISO_DATE_TIME format: 2016-09-06T12:45:30\nISO_ORDINAL_DATE format: 2016-250\nISO_WEEK_DATE format: 2016-W36-2\n" }, { "code": null, "e": 3410, "s": 3284, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#format(java.time.format.DateTimeFormatter)" }, { "code": null, "e": 3425, "s": 3410, "text": "Java-Functions" }, { "code": null, "e": 3444, "s": 3425, "text": "Java-LocalDateTime" }, { "code": null, "e": 3462, "s": 3444, "text": "Java-time package" }, { "code": null, "e": 3467, "s": 3462, "text": "Java" }, { "code": null, "e": 3472, "s": 3467, "text": "Java" } ]
Perl | chop() Function
07 May, 2019 The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters:String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string$string = "GfG is a computer science portal"; # Calling the chop() function$A = chop($string); # Printing the chopped string and # removed characterprint " Chopped String is : $string\n";print " Removed character is : $A\n"; Output: Chopped String is : GfG is a computer science porta Removed character is : l Example 2: #!/usr/bin/perl # Initialising a string$string = "[1, 2, 3]"; # Calling the chop() function$A = chop($string); # Printing the chopped string and # removed characterprint " Chopped String is : $string\n";print " Removed character is : $A\n"; Output : Chopped String is : [1, 2, 3 Removed character is : ] Perl-function Perl-String-Functions Perl Perl Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Perl | Arrays Perl Tutorial - Learn Perl With Examples Perl | Boolean Values Perl | length() Function Perl | Subroutines or Functions Use of print() and say() in Perl Hello World Program in Perl Perl | Basic Syntax of a Perl Program Perl | ne operator Perl | eq operator
[ { "code": null, "e": 28, "s": 0, "text": "\n07 May, 2019" }, { "code": null, "e": 116, "s": 28, "text": "The chop() function in Perl is used to remove the last character from the input string." }, { "code": null, "e": 137, "s": 116, "text": "Syntax: chop(String)" }, { "code": null, "e": 215, "s": 137, "text": "Parameters:String : It is the input string whose last characters are removed." }, { "code": null, "e": 252, "s": 215, "text": "Returns: the last removed character." }, { "code": null, "e": 263, "s": 252, "text": "Example 1:" }, { "code": "#!/usr/bin/perl # Initialising a string$string = \"GfG is a computer science portal\"; # Calling the chop() function$A = chop($string); # Printing the chopped string and # removed characterprint \" Chopped String is : $string\\n\";print \" Removed character is : $A\\n\";", "e": 531, "s": 263, "text": null }, { "code": null, "e": 539, "s": 531, "text": "Output:" }, { "code": null, "e": 617, "s": 539, "text": "Chopped String is : GfG is a computer science porta\nRemoved character is : l\n" }, { "code": null, "e": 628, "s": 617, "text": "Example 2:" }, { "code": "#!/usr/bin/perl # Initialising a string$string = \"[1, 2, 3]\"; # Calling the chop() function$A = chop($string); # Printing the chopped string and # removed characterprint \" Chopped String is : $string\\n\";print \" Removed character is : $A\\n\";", "e": 873, "s": 628, "text": null }, { "code": null, "e": 882, "s": 873, "text": "Output :" }, { "code": null, "e": 937, "s": 882, "text": "Chopped String is : [1, 2, 3\nRemoved character is : ]\n" }, { "code": null, "e": 951, "s": 937, "text": "Perl-function" }, { "code": null, "e": 973, "s": 951, "text": "Perl-String-Functions" }, { "code": null, "e": 978, "s": 973, "text": "Perl" }, { "code": null, "e": 983, "s": 978, "text": "Perl" }, { "code": null, "e": 1081, "s": 983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1095, "s": 1081, "text": "Perl | Arrays" }, { "code": null, "e": 1136, "s": 1095, "text": "Perl Tutorial - Learn Perl With Examples" }, { "code": null, "e": 1158, "s": 1136, "text": "Perl | Boolean Values" }, { "code": null, "e": 1183, "s": 1158, "text": "Perl | length() Function" }, { "code": null, "e": 1215, "s": 1183, "text": "Perl | Subroutines or Functions" }, { "code": null, "e": 1248, "s": 1215, "text": "Use of print() and say() in Perl" }, { "code": null, "e": 1276, "s": 1248, "text": "Hello World Program in Perl" }, { "code": null, "e": 1314, "s": 1276, "text": "Perl | Basic Syntax of a Perl Program" }, { "code": null, "e": 1333, "s": 1314, "text": "Perl | ne operator" } ]
Count total number of digits from 1 to N in C++
We are given a number N as input. The goal is to count the total number of digits between numbers 1 to N. 1 to 9 numbers require 1 digit each, 11 to 99 require 2 digits each, 100 to 999 require 3 digits each and so on. Let us understand with examples Input − N=11 Output − Count of total number of digits from 1 to N are: 13 Explanation − Numbers 1 to 9 has 1 digit each : 9 digits 10, 11 have 2 digits each. 4 digits. Total digits= 9+4=13. Input − N=999 Output − Count of the total number of digits from 1 to N are: 2889 Explanation − Numbers 1 to 9 have 1 digit each : 9 digits 10 to 99 have 2 digits each. : 180 digits. 100 to 999 have 3 digits each : 2700 digits Total digits= 2700 + 180 + 9 = 2889 digits We will use two approaches. A first naive approach using a recursive function to calculate digits in a number num. Convert passed num into a string. The length of the string is digits in num. Do this for each number bypassing current num-1 recursively. Take a number as a positive integer. Take a number as a positive integer. Function total_digits(int num) take the num and returns digit in numbers between 1 to num. Function total_digits(int num) take the num and returns digit in numbers between 1 to num. To calculate digits in num, convert num to string. (to_string(num)). To calculate digits in num, convert num to string. (to_string(num)). The length of the string is digits in num. The length of the string is digits in num. If num is 1 return 1 . Else return length+ total_digits(num-1) for rest of numbers less than num. If num is 1 return 1 . Else return length+ total_digits(num-1) for rest of numbers less than num. At last we will get total digits as a result. At last we will get total digits as a result. In this approach, we will use the logic that for each number up to N. We will traverse 10, 100, 1000 up to N. For each 10i , the number of digits is (num-i + 1). Take a number as a positive integer. Take a number as a positive integer. Function total_digits(int num) take the num and returns digit in numbers between 1 to num. Function total_digits(int num) take the num and returns digit in numbers between 1 to num. Take the total count as 0 initially. Take the total count as 0 initially. Traverse i=1 to i<=num, increment i by 10 in each iteration and add num-i+1 to count. Traverse i=1 to i<=num, increment i by 10 in each iteration and add num-i+1 to count. Return the count at the end of for loop as a result. Return the count at the end of for loop as a result. Live Demo #include <bits/stdc++.h> using namespace std; int total_digits(int num){ string str = to_string(num); int length = str.length(); if (num == 1){ return 1; } return length + total_digits(num - 1); } int main(){ int num = 20; cout<<"Count of total number of digits from 1 to n are: "<<total_digits(num); return 0; } If we run the above code it will generate the following output − Count of total number of digits from 1 to n are: 31 Live Demo #include <bits/stdc++.h> using namespace std; int total_digits(int num){ int count = 0; for(int i = 1; i <= num; i *= 10){ count = count + (num - i + 1); } return count; } int main(){ int num = 20; cout<<"Count of total number of digits from 1 to n are: "<<total_digits(num); return 0; } If we run the above code it will generate the following output − Count of total number of digits from 1 to n are: 31
[ { "code": null, "e": 1281, "s": 1062, "text": "We are given a number N as input. The goal is to count the total number of digits between numbers 1 to N. 1 to 9 numbers require 1 digit each, 11 to 99 require 2 digits each, 100 to 999 require 3 digits each and so on." }, { "code": null, "e": 1313, "s": 1281, "text": "Let us understand with examples" }, { "code": null, "e": 1326, "s": 1313, "text": "Input − N=11" }, { "code": null, "e": 1387, "s": 1326, "text": "Output − Count of total number of digits from 1 to N are: 13" }, { "code": null, "e": 1503, "s": 1387, "text": "Explanation − Numbers 1 to 9 has 1 digit each : 9 digits 10, 11 have 2 digits each. 4 digits. Total digits= 9+4=13." }, { "code": null, "e": 1517, "s": 1503, "text": "Input − N=999" }, { "code": null, "e": 1584, "s": 1517, "text": "Output − Count of the total number of digits from 1 to N are: 2889" }, { "code": null, "e": 1772, "s": 1584, "text": "Explanation − Numbers 1 to 9 have 1 digit each : 9 digits 10 to 99 have 2 digits each. : 180 digits. 100 to 999 have 3 digits each : 2700 digits Total digits= 2700 + 180 + 9 = 2889 digits" }, { "code": null, "e": 2025, "s": 1772, "text": "We will use two approaches. A first naive approach using a recursive function to calculate digits in a number num. Convert passed num into a string. The length of the string is digits in num. Do this for each number bypassing current num-1 recursively." }, { "code": null, "e": 2062, "s": 2025, "text": "Take a number as a positive integer." }, { "code": null, "e": 2099, "s": 2062, "text": "Take a number as a positive integer." }, { "code": null, "e": 2190, "s": 2099, "text": "Function total_digits(int num) take the num and returns digit in numbers between 1 to num." }, { "code": null, "e": 2281, "s": 2190, "text": "Function total_digits(int num) take the num and returns digit in numbers between 1 to num." }, { "code": null, "e": 2350, "s": 2281, "text": "To calculate digits in num, convert num to string. (to_string(num))." }, { "code": null, "e": 2419, "s": 2350, "text": "To calculate digits in num, convert num to string. (to_string(num))." }, { "code": null, "e": 2462, "s": 2419, "text": "The length of the string is digits in num." }, { "code": null, "e": 2505, "s": 2462, "text": "The length of the string is digits in num." }, { "code": null, "e": 2603, "s": 2505, "text": "If num is 1 return 1 . Else return length+ total_digits(num-1) for rest of numbers less than num." }, { "code": null, "e": 2701, "s": 2603, "text": "If num is 1 return 1 . Else return length+ total_digits(num-1) for rest of numbers less than num." }, { "code": null, "e": 2747, "s": 2701, "text": "At last we will get total digits as a result." }, { "code": null, "e": 2793, "s": 2747, "text": "At last we will get total digits as a result." }, { "code": null, "e": 2955, "s": 2793, "text": "In this approach, we will use the logic that for each number up to N. We will traverse 10, 100, 1000 up to N. For each 10i , the number of digits is (num-i + 1)." }, { "code": null, "e": 2992, "s": 2955, "text": "Take a number as a positive integer." }, { "code": null, "e": 3029, "s": 2992, "text": "Take a number as a positive integer." }, { "code": null, "e": 3120, "s": 3029, "text": "Function total_digits(int num) take the num and returns digit in numbers between 1 to num." }, { "code": null, "e": 3211, "s": 3120, "text": "Function total_digits(int num) take the num and returns digit in numbers between 1 to num." }, { "code": null, "e": 3248, "s": 3211, "text": "Take the total count as 0 initially." }, { "code": null, "e": 3285, "s": 3248, "text": "Take the total count as 0 initially." }, { "code": null, "e": 3371, "s": 3285, "text": "Traverse i=1 to i<=num, increment i by 10 in each iteration and add num-i+1 to count." }, { "code": null, "e": 3457, "s": 3371, "text": "Traverse i=1 to i<=num, increment i by 10 in each iteration and add num-i+1 to count." }, { "code": null, "e": 3510, "s": 3457, "text": "Return the count at the end of for loop as a result." }, { "code": null, "e": 3563, "s": 3510, "text": "Return the count at the end of for loop as a result." }, { "code": null, "e": 3574, "s": 3563, "text": " Live Demo" }, { "code": null, "e": 3917, "s": 3574, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint total_digits(int num){\n string str = to_string(num);\n int length = str.length();\n if (num == 1){\n return 1;\n }\n return length + total_digits(num - 1);\n}\nint main(){\n int num = 20;\n cout<<\"Count of total number of digits from 1 to n are: \"<<total_digits(num);\n return 0;\n}" }, { "code": null, "e": 3982, "s": 3917, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4034, "s": 3982, "text": "Count of total number of digits from 1 to n are: 31" }, { "code": null, "e": 4045, "s": 4034, "text": " Live Demo" }, { "code": null, "e": 4360, "s": 4045, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint total_digits(int num){\n int count = 0;\n for(int i = 1; i <= num; i *= 10){\n count = count + (num - i + 1);\n }\n return count;\n}\nint main(){\n int num = 20;\n cout<<\"Count of total number of digits from 1 to n are: \"<<total_digits(num);\n return 0;\n}" }, { "code": null, "e": 4425, "s": 4360, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4477, "s": 4425, "text": "Count of total number of digits from 1 to n are: 31" } ]
Microsoft Azure - Point-to-Site Connectivity
In the last chapter, we saw how an endpoint can be created to access a virtual machine; this is quite a tedious task. If a virtual machine in virtual network needs to be connected with on-premise machine, the point-to-site connectivity is needed. Point-to-site connectivity makes it very productive to work with remote virtual machines. Basically, a machine on-premise is connected to virtual network using point-to-site connectivity. However, we can connect up to 128 on-premise machines to virtual network in Azure. The access to the virtual network in cloud is granted through a certificate. The certificate has to be installed on each local machine that needs to be connected to the virtual network. If you have already created a virtual network in Azure, you can access it in management portal. Step 1 − Log in to Azure management portal. Step 2 − Click on ‘Networks’ in the left panel and select the network you want to work with. Step 3 − Click on ‘Configure’ as shown in the following image. Step 4 − Check the ‘Configure Point-to-site connectivity’ checkbox. It will allow you to enter the starting IP and CIDR. Step 5 − Scroll down and click ‘add gateway subnet’. Step 6 − Enter the Gateway subnet and click ‘Save’. Message shown in the following screen will pop up. Step 7 − Click Yes and a point-to-site connectivity is done. You will need a certificate to access your virtual network. Step 1 − Click New → Network Services → Virtual Network → Custom Create. Step 2 − Enter Network’s name, select location and click on Next. Step 3 − On the next screen, Select ‘Configure a point-to-site VPN’ and click next. Step 4 − You can select or enter starting IP and select CIDR. Step 5 − Enter Subnet and click ‘Add Gateway Subnet’ as done earlier and enter the required information. Step 6 − Point-to-Site connectivity is done. Step 7 − Click on the name of the network, as it is ‘MyNet’ in the above image. Step 8 − Click on ‘Dashboard’ as shown in the following screen. You will see that the gateway is not created yet. For it to happen, you will have to generate a certificate first. The point-to-site VPN supports only self-signed certificate. Step 1 − Go to the link msdn.microsoft.com or google ‘windows SDK for 8.1’. Then go to msdn link or the version of Windows for which you want the tool. Step 2 − Download the encircled file as shown in the following image. It will be saved as .exe file named sdksetup on your machine. Step 3 − Run the file. While running the installation wizard, when you reach the following screen uncheck the encircled part. By default they are checked. Step 4 − After installation is complete, run Command Prompt as Administrator on your computer. Step 5 − Enter the following commands one by one for creating root certificate cd C:\Program Files (x86)\Windows Kits\8.1\bin\x64 makecert -sky exchange -r -n "CN=MyNet" -pe -a sha1 -len 2048 -ss My First command will change the directory in command prompt. In the above command change the highlighted part to the name of your network. Step 6 − Next enter the following command for creating client certificate. makecert -n "CN=MyNetClient" -pe -sky exchange -m 96 -ss My -in "MyNet" -is my -a sha1 Step 7 − Look for ‘mmc’ on your computer and run it. Step 8 − Click ‘File’ and ‘Add/Remove Snap-in’. Step 9 − In the screen that pops up, click ‘Certificate’ and then on ‘add’. Step 10 − Select ‘My User Account’ and click on ‘Finish’. Step 11 − Expand ‘Current User’ in the left panel, then ‘Personal’ and then ‘Certificates’. You can see the certificates here. Step 12 − Right click on certificate and click ‘All Tasks’ and then ‘Export’. Step 13 − Follow the wizard. You will have to name the certificate and select a location to save it. Step 1 − Login to Azure management portal. Step 2 − Go to the network and click ‘Certificate’ and then click ‘Upload Root Certificate’. Step 3 − Click browse and select the location of the certificate you just created. Client VPN Package will connect you to the network. Step 1 − Go to network’s dashboard in azure management portal. Step 2 − Scroll down and locate the following options at the right side of the screen. Step 3 − Select the suitable option and download it. You will see a similar file on your computer. Run and install it. Step 4 − When you’ll install it, Windows might try to prevent it. Choose ‘Run Anyway’ if this happens. Step 5 − Go to ‘Networks’ on your machine and you will see a VPN connection available as shown in the following image. Step 6 − Click on that network as in this example ‘MyNet’ and connect. You will be connected to the network. 16 Lectures 11.5 hours SHIVPRASAD KOIRALA 33 Lectures 3 hours Abhishek And Pukhraj 33 Lectures 5.5 hours Abhishek And Pukhraj 40 Lectures 6.5 hours Syed Raza 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 3346, "s": 3009, "text": "In the last chapter, we saw how an endpoint can be created to access a virtual machine; this is quite a tedious task. If a virtual machine in virtual network needs to be connected with on-premise machine, the point-to-site connectivity is needed. Point-to-site connectivity makes it very productive to work with remote virtual machines." }, { "code": null, "e": 3713, "s": 3346, "text": "Basically, a machine on-premise is connected to virtual network using point-to-site connectivity. However, we can connect up to 128 on-premise machines to virtual network in Azure. The access to the virtual network in cloud is granted through a certificate. The certificate has to be installed on each local machine that needs to be connected to the virtual network." }, { "code": null, "e": 3809, "s": 3713, "text": "If you have already created a virtual network in Azure, you can access it in management portal." }, { "code": null, "e": 3853, "s": 3809, "text": "Step 1 − Log in to Azure management portal." }, { "code": null, "e": 3946, "s": 3853, "text": "Step 2 − Click on ‘Networks’ in the left panel and select the network you want to work with." }, { "code": null, "e": 4009, "s": 3946, "text": "Step 3 − Click on ‘Configure’ as shown in the following image." }, { "code": null, "e": 4130, "s": 4009, "text": "Step 4 − Check the ‘Configure Point-to-site connectivity’ checkbox. It will allow you to enter the starting IP and CIDR." }, { "code": null, "e": 4183, "s": 4130, "text": "Step 5 − Scroll down and click ‘add gateway subnet’." }, { "code": null, "e": 4286, "s": 4183, "text": "Step 6 − Enter the Gateway subnet and click ‘Save’. Message shown in the following screen will pop up." }, { "code": null, "e": 4347, "s": 4286, "text": "Step 7 − Click Yes and a point-to-site connectivity is done." }, { "code": null, "e": 4407, "s": 4347, "text": "You will need a certificate to access your virtual network." }, { "code": null, "e": 4480, "s": 4407, "text": "Step 1 − Click New → Network Services → Virtual Network → Custom Create." }, { "code": null, "e": 4546, "s": 4480, "text": "Step 2 − Enter Network’s name, select location and click on Next." }, { "code": null, "e": 4630, "s": 4546, "text": "Step 3 − On the next screen, Select ‘Configure a point-to-site VPN’ and click next." }, { "code": null, "e": 4692, "s": 4630, "text": "Step 4 − You can select or enter starting IP and select CIDR." }, { "code": null, "e": 4797, "s": 4692, "text": "Step 5 − Enter Subnet and click ‘Add Gateway Subnet’ as done earlier and enter the required information." }, { "code": null, "e": 4842, "s": 4797, "text": "Step 6 − Point-to-Site connectivity is done." }, { "code": null, "e": 4922, "s": 4842, "text": "Step 7 − Click on the name of the network, as it is ‘MyNet’ in the above image." }, { "code": null, "e": 4986, "s": 4922, "text": "Step 8 − Click on ‘Dashboard’ as shown in the following screen." }, { "code": null, "e": 5101, "s": 4986, "text": "You will see that the gateway is not created yet. For it to happen, you will have to generate a certificate first." }, { "code": null, "e": 5162, "s": 5101, "text": "The point-to-site VPN supports only self-signed certificate." }, { "code": null, "e": 5314, "s": 5162, "text": "Step 1 − Go to the link msdn.microsoft.com or google ‘windows SDK for 8.1’. Then go to msdn link or the version of Windows for which you want the tool." }, { "code": null, "e": 5446, "s": 5314, "text": "Step 2 − Download the encircled file as shown in the following image. It will be saved as .exe file named sdksetup on your machine." }, { "code": null, "e": 5601, "s": 5446, "text": "Step 3 − Run the file. While running the installation wizard, when you reach the following screen uncheck the encircled part. By default they are checked." }, { "code": null, "e": 5696, "s": 5601, "text": "Step 4 − After installation is complete, run Command Prompt as Administrator on your computer." }, { "code": null, "e": 5775, "s": 5696, "text": "Step 5 − Enter the following commands one by one for creating root certificate" }, { "code": null, "e": 5898, "s": 5775, "text": "cd C:\\Program Files (x86)\\Windows Kits\\8.1\\bin\\x64 \n\nmakecert -sky exchange -r -n \"CN=MyNet\" -pe -a sha1 -len 2048 -ss My\n" }, { "code": null, "e": 6035, "s": 5898, "text": "First command will change the directory in command prompt. In the above command change the highlighted part to the name of your network." }, { "code": null, "e": 6110, "s": 6035, "text": "Step 6 − Next enter the following command for creating client certificate." }, { "code": null, "e": 6199, "s": 6110, "text": "makecert -n \"CN=MyNetClient\" -pe -sky exchange -m 96 -ss My -in \"MyNet\" -is my -a sha1 \n" }, { "code": null, "e": 6252, "s": 6199, "text": "Step 7 − Look for ‘mmc’ on your computer and run it." }, { "code": null, "e": 6300, "s": 6252, "text": "Step 8 − Click ‘File’ and ‘Add/Remove Snap-in’." }, { "code": null, "e": 6376, "s": 6300, "text": "Step 9 − In the screen that pops up, click ‘Certificate’ and then on ‘add’." }, { "code": null, "e": 6434, "s": 6376, "text": "Step 10 − Select ‘My User Account’ and click on ‘Finish’." }, { "code": null, "e": 6526, "s": 6434, "text": "Step 11 − Expand ‘Current User’ in the left panel, then ‘Personal’ and then ‘Certificates’." }, { "code": null, "e": 6561, "s": 6526, "text": "You can see the certificates here." }, { "code": null, "e": 6639, "s": 6561, "text": "Step 12 − Right click on certificate and click ‘All Tasks’ and then ‘Export’." }, { "code": null, "e": 6740, "s": 6639, "text": "Step 13 − Follow the wizard. You will have to name the certificate and select a location to save it." }, { "code": null, "e": 6783, "s": 6740, "text": "Step 1 − Login to Azure management portal." }, { "code": null, "e": 6876, "s": 6783, "text": "Step 2 − Go to the network and click ‘Certificate’ and then click ‘Upload Root Certificate’." }, { "code": null, "e": 6959, "s": 6876, "text": "Step 3 − Click browse and select the location of the certificate you just created." }, { "code": null, "e": 7011, "s": 6959, "text": "Client VPN Package will connect you to the network." }, { "code": null, "e": 7074, "s": 7011, "text": "Step 1 − Go to network’s dashboard in azure management portal." }, { "code": null, "e": 7161, "s": 7074, "text": "Step 2 − Scroll down and locate the following options at the right side of the screen." }, { "code": null, "e": 7280, "s": 7161, "text": "Step 3 − Select the suitable option and download it. You will see a similar file on your computer. Run and install it." }, { "code": null, "e": 7383, "s": 7280, "text": "Step 4 − When you’ll install it, Windows might try to prevent it. Choose ‘Run Anyway’ if this happens." }, { "code": null, "e": 7502, "s": 7383, "text": "Step 5 − Go to ‘Networks’ on your machine and you will see a VPN connection available as shown in the following image." }, { "code": null, "e": 7611, "s": 7502, "text": "Step 6 − Click on that network as in this example ‘MyNet’ and connect. You will be connected to the network." }, { "code": null, "e": 7647, "s": 7611, "text": "\n 16 Lectures \n 11.5 hours \n" }, { "code": null, "e": 7667, "s": 7647, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 7700, "s": 7667, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 7722, "s": 7700, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7757, "s": 7722, "text": "\n 33 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7779, "s": 7757, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 7814, "s": 7779, "text": "\n 40 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7825, "s": 7814, "text": " Syed Raza" }, { "code": null, "e": 7858, "s": 7825, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 7898, "s": 7858, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 7933, "s": 7898, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7973, "s": 7933, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 7980, "s": 7973, "text": " Print" }, { "code": null, "e": 7991, "s": 7980, "text": " Add Notes" } ]
SQL - Clone Tables
There may be a situation when you need an exact copy of a table and the CREATE TABLE ... or the SELECT... commands does not suit your purposes because the copy must include the same indexes, default values and so forth. If you are using MySQL RDBMS, you can handle this situation by adhering to the steps given below − Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all. Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all. Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table. Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table. Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too. Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too. Try out the following example to create a clone table for TUTORIALS_TBL whose structure is as follows − Step 1 − Get the complete structure about the table. SQL> SHOW CREATE TABLE TUTORIALS_TBL \G; *************************** 1. row *************************** Table: TUTORIALS_TBL Create Table: CREATE TABLE 'TUTORIALS_TBL' ( 'tutorial_id' int(11) NOT NULL auto_increment, 'tutorial_title' varchar(100) NOT NULL default '', 'tutorial_author' varchar(40) NOT NULL default '', 'submission_date' date default NULL, PRIMARY KEY ('tutorial_id'), UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') ) TYPE = MyISAM 1 row in set (0.00 sec) Step 2 − Rename this table and create another table. SQL> CREATE TABLE `CLONE_TBL` ( -> 'tutorial_id' int(11) NOT NULL auto_increment, -> 'tutorial_title' varchar(100) NOT NULL default '', -> 'tutorial_author' varchar(40) NOT NULL default '', -> 'submission_date' date default NULL, -> PRIMARY KEY (`tutorial_id'), -> UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') -> ) TYPE = MyISAM; Query OK, 0 rows affected (1.80 sec) Step 3 − After executing step 2, you will clone a table in your database. If you want to copy data from an old table, then you can do it by using the INSERT INTO... SELECT statement. SQL> INSERT INTO CLONE_TBL (tutorial_id, -> tutorial_title, -> tutorial_author, -> submission_date) -> SELECT tutorial_id,tutorial_title, -> tutorial_author,submission_date, -> FROM TUTORIALS_TBL; Query OK, 3 rows affected (0.07 sec) Records: 3 Duplicates: 0 Warnings: 0 Finally, you will have an exact clone table as you wanted to have. 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2673, "s": 2453, "text": "There may be a situation when you need an exact copy of a table and the CREATE TABLE ... or the SELECT... commands does not suit your purposes because the copy must include the same indexes, default values and so forth." }, { "code": null, "e": 2772, "s": 2673, "text": "If you are using MySQL RDBMS, you can handle this situation by adhering to the steps given below −" }, { "code": null, "e": 2896, "s": 2772, "text": "Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all." }, { "code": null, "e": 3020, "s": 2896, "text": "Use SHOW CREATE TABLE command to get a CREATE TABLE statement that specifies the source table's structure, indexes and all." }, { "code": null, "e": 3165, "s": 3020, "text": "Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table." }, { "code": null, "e": 3310, "s": 3165, "text": "Modify the statement to change the table name to that of the clone table and execute the statement. This way you will have an exact clone table." }, { "code": null, "e": 3417, "s": 3310, "text": "Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too." }, { "code": null, "e": 3524, "s": 3417, "text": "Optionally, if you need the table contents copied as well, issue an INSERT INTO or a SELECT statement too." }, { "code": null, "e": 3628, "s": 3524, "text": "Try out the following example to create a clone table for TUTORIALS_TBL whose structure is as follows −" }, { "code": null, "e": 3681, "s": 3628, "text": "Step 1 − Get the complete structure about the table." }, { "code": null, "e": 4182, "s": 3681, "text": "SQL> SHOW CREATE TABLE TUTORIALS_TBL \\G; \n*************************** 1. row *************************** \n Table: TUTORIALS_TBL \nCreate Table: CREATE TABLE 'TUTORIALS_TBL' ( \n 'tutorial_id' int(11) NOT NULL auto_increment, \n 'tutorial_title' varchar(100) NOT NULL default '', \n 'tutorial_author' varchar(40) NOT NULL default '', \n 'submission_date' date default NULL, \n PRIMARY KEY ('tutorial_id'), \n UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') \n) TYPE = MyISAM \n1 row in set (0.00 sec)" }, { "code": null, "e": 4235, "s": 4182, "text": "Step 2 − Rename this table and create another table." }, { "code": null, "e": 4625, "s": 4235, "text": "SQL> CREATE TABLE `CLONE_TBL` ( \n -> 'tutorial_id' int(11) NOT NULL auto_increment, \n -> 'tutorial_title' varchar(100) NOT NULL default '', \n -> 'tutorial_author' varchar(40) NOT NULL default '', \n -> 'submission_date' date default NULL, \n -> PRIMARY KEY (`tutorial_id'), \n -> UNIQUE KEY 'AUTHOR_INDEX' ('tutorial_author') \n-> ) TYPE = MyISAM; \nQuery OK, 0 rows affected (1.80 sec) " }, { "code": null, "e": 4808, "s": 4625, "text": "Step 3 − After executing step 2, you will clone a table in your database. If you want to copy data from an old table, then you can do it by using the INSERT INTO... SELECT statement." }, { "code": null, "e": 5184, "s": 4808, "text": "SQL> INSERT INTO CLONE_TBL (tutorial_id, \n -> tutorial_title, \n -> tutorial_author, \n -> submission_date) \n -> SELECT tutorial_id,tutorial_title, \n -> tutorial_author,submission_date, \n -> FROM TUTORIALS_TBL; \nQuery OK, 3 rows affected (0.07 sec) \nRecords: 3 Duplicates: 0 Warnings: 0 " }, { "code": null, "e": 5251, "s": 5184, "text": "Finally, you will have an exact clone table as you wanted to have." }, { "code": null, "e": 5284, "s": 5251, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 5298, "s": 5284, "text": " Anadi Sharma" }, { "code": null, "e": 5331, "s": 5298, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 5345, "s": 5331, "text": " Anadi Sharma" }, { "code": null, "e": 5380, "s": 5345, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5394, "s": 5380, "text": " Anadi Sharma" }, { "code": null, "e": 5427, "s": 5394, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 5449, "s": 5427, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5484, "s": 5449, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5538, "s": 5484, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 5571, "s": 5538, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 5599, "s": 5571, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5606, "s": 5599, "text": " Print" }, { "code": null, "e": 5617, "s": 5606, "text": " Add Notes" } ]
What’s fancy about context transition in DAX? | by Salvatore Cagliari | Towards Data Science
In this article, I show you what context transition is in DAX and how to use it. I will cover only the basics of this feature. If I want to explain all details, I would have to start an entire series of articles. Instead, I want to give you some small examples of how you can work with context transition and the most important things to know about it. This way, you can start working with it and learn more as needed. You can find a list of articles and blog posts that look much deeper into context transition at the end. I use the Contoso sample dataset, like in my previous articles. From the entire data model, I need only two tables for my examples in this article: Customer (DimCustomer) Online Sales (FactOnlineSales) One important factor about the Online Sales table is that the orders stored in the Online Sales tables contain an OrderNumber and an OrderLineNumber. One order can have one or more OrderLineNumber: Each OrderLineNumber has a product mapped and has a SalesAmount. To keep the code simple, I will analyse the single OrderLines instead of the Orders. I would need to change the granularity of the data to be able to analyse the Orders. I will keep the topic of changing granularity in DAX for a future article. Let’s assume the following situation: We have a list of customers, and we would like to know the total sales per customer and get other information. To gain the required information, we would like to calculate the following results: Highest Sale per Customer in the Customer table Total Sales per Customer and Year What is the Average of Sales per Customer Percentage of Sales by Customer of all Sales Which customer is inside the Top 10 % by Total Sales per Year I cannot create Measures to calculate these results as I want to use them as filters in Slicers and as reporting attributes in my report.This means that I have to add calculated DAX columns in the Customer table. This requirement looks easy: get the MAX() from the Online Sales table per customer. But, I cannot create a calculated column in the Customer table with MAX(‘Online Sales’[SalesAmount]) as the SalesAmount column is not in the Customer table. I can write the following code: Highest OrderLine = MAXX(‘Online Sales’ , ‘Online Sales’[SalesAmount]) The result will look like this: As MAXX has no filter context, it will retrieve the OrderLine with the highest SalesAmount over all the customers. I have to use context transition to force the DAX engine to switch from row-context to filter-context. During context transition, the content of the actual row will be added to the filter context, and MAXX is executed with this filter context. I can force context transition with a CALCULATE(): Highest Order Line = VAR Result = CALCULATE( MAXX( ‘Online Sales’ ,’Online Sales’[SalesAmount]) )RETURN Result You can see the result in the following picture: What happens? During the iteration over each row in the Customer table, context transition adds the content of the actual row to the filter context, including the CustomerKey column. The CustomerKey column is used in the Relationship with the Online Sales table.The CustomerKey filters the Online Sales table for each customerNow the maximum value of the SalesAmount column is evaluated for each CustomerKey During the iteration over each row in the Customer table, context transition adds the content of the actual row to the filter context, including the CustomerKey column. The CustomerKey column is used in the Relationship with the Online Sales table. The CustomerKey filters the Online Sales table for each customer Now the maximum value of the SalesAmount column is evaluated for each CustomerKey You can leverage context transitions with all iterator functions, including FILTER() and other functions. I used this technique in one of my last articles (To weigh or not to weigh — this is the Average question ) with the following Measure: Average per Country = AVERAGEX(VALUES(‘Geography’[Region Country]) ,DIVIDE([Online Sales (By Customer)] , [Order Count (By Customer)] ) ) Even though you don’t see any CALCULATE() in that solution, I use Measures within the AVERAGEX function. Using a Measure within a Row context automatically triggers a context transition. This requirement is a little bit more complicated to solve. As mentioned above, I don’t want to create a Measure, as I want to use the calculation result in a Slicer. So, I have to create a calculated column as well: Year of Highest Order Line =VAR HighestOrderLine = ‘Customer’[Highest Order Line]VAR Result = CALCULATE( MAXX ( ‘Online Sales’ ,YEAR(‘Online Sales’[OrderDate]) ) , ‘Online Sales’[SalesAmount] = HighestOrderLine )RETURN Result Again, I use CALCULATE() to start context transition, which automatically adds the CustomerKey column to the filter context for the MAXX() function. Because of this, I don’t need to filter by CustomerKey inside CALCULATE(). I only have to search for the order line with the highest sales, which I calculated in the previous column, and use MAXX to get the last year with this sales value. The Filter added with CALCULATE() is added to the existing Filter Context, which already contains the row of the current customer in the Customer table through context transition. You can see the result in the following picture: With the knowledge you have gained until now, you should be able to solve this requirement independently. Try to think about it and develop an idea for what the solution could look like. . . . Done? OK, this is the solution for this calculated column: Average Sales = CALCULATE( AVERAGEX(‘Online Sales’ ,’Online Sales’[SalesAmount]) ) Context transition allows us to write such short and powerful DAX formulas. Another approach would have been to create a Measure with AVERAGEX(), as shown above, and use this Measure directly for the calculated column. This requirement requires us to combine the gained knowledge to create a new calculated column with the following DAX formula: % Sales of Total Sales =VAR SalesOverall = SUMX(‘Online Sales’ ,’Online Sales’[SalesAmount] )VAR SalesOfCustomer = CALCULATE( SUMX(‘Online Sales’ ,’Online Sales’[SalesAmount] ) )VAR PctOfTotalSales = DIVIDE(SalesOfCustomer, SalesOverall)RETURN PctOfTotalSales Here is the explanation of this formula: The Variable SalesOverall doesn’t use context transition. The result is the total sales overall customersThe Variable SalesOfCustomer encloses the same expression as SalesOverall with a CALCULATE(), thus enforcing a context transition.The result is the sum of Sales for the current customerThe DIVIDE in the Variable PctOfTotalSales calculates the percentage of SalesOfCustomer of SalesOverall The Variable SalesOverall doesn’t use context transition. The result is the total sales overall customers The Variable SalesOfCustomer encloses the same expression as SalesOverall with a CALCULATE(), thus enforcing a context transition.The result is the sum of Sales for the current customer The DIVIDE in the Variable PctOfTotalSales calculates the percentage of SalesOfCustomer of SalesOverall The result looks like this: For this, I need to calculate the ranking of all customers based on the Total Sales Amount. Then I need to get the highest Rank, or the number of customers, and calculate which customers are in the top 10 % of all customers. The output should be a column that contains a True or False value. As you can imagine, it is not possible to calculate this in one single step. Here I want to show you two solutions, which uses context transition in slightly different ways. With this approach, I create a calculated DAX table. Then I use LOOKUPVALUE() to map the values into the Customer table. This is the code to create the DAX table: Customer Ranking =VAR CustAndSales = ADDCOLUMNS( VALUES(Customer[CustomerKey] ) ,”Amt”, [Online Sales (By Order Date)] )VAR RankedCustomer = ADDCOLUMNS(CustAndSales ,”Rank”, RANKX(CustAndSales ,[Amt] ) )VAR MaxRank = MAXX( RankedCustomer ,[Rank] )VAR Result = ADDCOLUMNS( RankedCustomer ,”IsTop10Perc” , IF( DIVIDE( [Rank] , MaxRank ) <= 0.1 , TRUE() ,FALSE() ) )RETURN Result The variable CustAndSales creates a list of all CustomerKey and calculates a sum of the sales per customer with the Measure [Online Sales (By Order Date)] In the variable RankedCustomer, I use RANKX() to calculate the ranking overall CustomerKeys based on the total sales per customerThe variable MaxRank gets the highest Rank, which I will use in the following variableFinally, I’m adding the column IsTop10Perc with the result of an IF(). This column contains the flag if the customer is in the top 10 % of customers based on the total sales for each customer In the variable RankedCustomer, I use RANKX() to calculate the ranking overall CustomerKeys based on the total sales per customer The variable MaxRank gets the highest Rank, which I will use in the following variable Finally, I’m adding the column IsTop10Perc with the result of an IF(). This column contains the flag if the customer is in the top 10 % of customers based on the total sales for each customer Now, I use the following expression to create a new calculated column in the Customer table: Is Top 10 % customer by Sales =VAR Result = LOOKUPVALUE(‘Customer Ranking’[IsTop10Perc] , ‘Customer Ranking’[CustomerKey] , ‘Customer’[CustomerKey] )RETURN Result I can use this approach to add the following column from the calculated DAX table: Rank by Sales Is Top 10 Percent Total Sales per customer With this approach, I create a few calculated columns containing intermediate results to get the final result. Total Sales per Customer: Total Sales per Customer: To get the total sales per customer, I need to use the existing Measure [Online Sales (By Order Date)]: Total Sales per Customer = [Online Sales (By Order Date)] As DAX starts a context transition when we use a Measure inside a Row context, this is enough to get the sum of Sales Amount for each customer. 2. Calculate the ranking for each customer I need the column [Total Sales per Customer] to calculate the ranking. Like in the first solution, I use RANKX to do the job: Rank by Sales (local) = RANKX(‘Customer’ ,’Customer’[Total Sales per Customer]) 3. Set the top 10 % customer by Sales Finally, I can use the same logic as before to find if the current customer is in the top 10 % of customers by total sales: Is Top 10 Percent (local) =VAR MaxRank = MAXX( ‘Customer’ ,[Rank by Sales (local)] )VAR Result = IF( DIVIDE( [Rank by Sales (local)] , MaxRank ) <= 0.1 ,TRUE() ,FALSE() )RETURN Result As you can see, both solutions use the same basic logic but with a slightly different technique. It’s up to you which one you want to use. The result is the same with both solutions: Solution 1 was my first approach, as it looked easier to do. I hid the calculated table, as it’s of no use after I included all the columns into the Customer table. But, I don’t like unnecessary objects in my model, so I figured out how to solve the requirement without the DAX table. Context transition is a complex but very useful feature in DAX. This feature can help you solve problems more quickly than when you don’t know how to use it. But it has some significant quirks, which you need to know: Context transition is slow in measures Duplicate rows in the table used by context transition (The ‘Online Sales’ fact table in the examples above) can cause wrong results, which are extremely hard to spot. You need to know when context transition happens: always when you are iterating through rows, and you use a Measure, or you use CALCULATE() I encourage you to read the following SQL article Understanding Context Transition — SQLBI to learn the basics. You can read the article Context Transition and Filters in CALCULATE — SQLBI to learn about context transition with CALCULATE. Read this article https://www.burningsuit.co.uk/blog/2021/08/context-transition-where-the-row-context-becomes-a-filter-context/, which contains a throughout explanation of context transition, including what you need to consider when using context transition Here are some more articles and blog posts about this important topic:
[ { "code": null, "e": 253, "s": 172, "text": "In this article, I show you what context transition is in DAX and how to use it." }, { "code": null, "e": 385, "s": 253, "text": "I will cover only the basics of this feature. If I want to explain all details, I would have to start an entire series of articles." }, { "code": null, "e": 591, "s": 385, "text": "Instead, I want to give you some small examples of how you can work with context transition and the most important things to know about it. This way, you can start working with it and learn more as needed." }, { "code": null, "e": 696, "s": 591, "text": "You can find a list of articles and blog posts that look much deeper into context transition at the end." }, { "code": null, "e": 760, "s": 696, "text": "I use the Contoso sample dataset, like in my previous articles." }, { "code": null, "e": 844, "s": 760, "text": "From the entire data model, I need only two tables for my examples in this article:" }, { "code": null, "e": 867, "s": 844, "text": "Customer (DimCustomer)" }, { "code": null, "e": 898, "s": 867, "text": "Online Sales (FactOnlineSales)" }, { "code": null, "e": 1048, "s": 898, "text": "One important factor about the Online Sales table is that the orders stored in the Online Sales tables contain an OrderNumber and an OrderLineNumber." }, { "code": null, "e": 1096, "s": 1048, "text": "One order can have one or more OrderLineNumber:" }, { "code": null, "e": 1161, "s": 1096, "text": "Each OrderLineNumber has a product mapped and has a SalesAmount." }, { "code": null, "e": 1246, "s": 1161, "text": "To keep the code simple, I will analyse the single OrderLines instead of the Orders." }, { "code": null, "e": 1406, "s": 1246, "text": "I would need to change the granularity of the data to be able to analyse the Orders. I will keep the topic of changing granularity in DAX for a future article." }, { "code": null, "e": 1555, "s": 1406, "text": "Let’s assume the following situation: We have a list of customers, and we would like to know the total sales per customer and get other information." }, { "code": null, "e": 1639, "s": 1555, "text": "To gain the required information, we would like to calculate the following results:" }, { "code": null, "e": 1687, "s": 1639, "text": "Highest Sale per Customer in the Customer table" }, { "code": null, "e": 1721, "s": 1687, "text": "Total Sales per Customer and Year" }, { "code": null, "e": 1763, "s": 1721, "text": "What is the Average of Sales per Customer" }, { "code": null, "e": 1808, "s": 1763, "text": "Percentage of Sales by Customer of all Sales" }, { "code": null, "e": 1870, "s": 1808, "text": "Which customer is inside the Top 10 % by Total Sales per Year" }, { "code": null, "e": 2083, "s": 1870, "text": "I cannot create Measures to calculate these results as I want to use them as filters in Slicers and as reporting attributes in my report.This means that I have to add calculated DAX columns in the Customer table." }, { "code": null, "e": 2168, "s": 2083, "text": "This requirement looks easy: get the MAX() from the Online Sales table per customer." }, { "code": null, "e": 2325, "s": 2168, "text": "But, I cannot create a calculated column in the Customer table with MAX(‘Online Sales’[SalesAmount]) as the SalesAmount column is not in the Customer table." }, { "code": null, "e": 2357, "s": 2325, "text": "I can write the following code:" }, { "code": null, "e": 2433, "s": 2357, "text": "Highest OrderLine = MAXX(‘Online Sales’ , ‘Online Sales’[SalesAmount])" }, { "code": null, "e": 2465, "s": 2433, "text": "The result will look like this:" }, { "code": null, "e": 2580, "s": 2465, "text": "As MAXX has no filter context, it will retrieve the OrderLine with the highest SalesAmount over all the customers." }, { "code": null, "e": 2824, "s": 2580, "text": "I have to use context transition to force the DAX engine to switch from row-context to filter-context. During context transition, the content of the actual row will be added to the filter context, and MAXX is executed with this filter context." }, { "code": null, "e": 2875, "s": 2824, "text": "I can force context transition with a CALCULATE():" }, { "code": null, "e": 3043, "s": 2875, "text": "Highest Order Line = VAR Result = CALCULATE( MAXX( ‘Online Sales’ ,’Online Sales’[SalesAmount]) )RETURN Result" }, { "code": null, "e": 3092, "s": 3043, "text": "You can see the result in the following picture:" }, { "code": null, "e": 3106, "s": 3092, "text": "What happens?" }, { "code": null, "e": 3500, "s": 3106, "text": "During the iteration over each row in the Customer table, context transition adds the content of the actual row to the filter context, including the CustomerKey column. The CustomerKey column is used in the Relationship with the Online Sales table.The CustomerKey filters the Online Sales table for each customerNow the maximum value of the SalesAmount column is evaluated for each CustomerKey" }, { "code": null, "e": 3749, "s": 3500, "text": "During the iteration over each row in the Customer table, context transition adds the content of the actual row to the filter context, including the CustomerKey column. The CustomerKey column is used in the Relationship with the Online Sales table." }, { "code": null, "e": 3814, "s": 3749, "text": "The CustomerKey filters the Online Sales table for each customer" }, { "code": null, "e": 3896, "s": 3814, "text": "Now the maximum value of the SalesAmount column is evaluated for each CustomerKey" }, { "code": null, "e": 4002, "s": 3896, "text": "You can leverage context transitions with all iterator functions, including FILTER() and other functions." }, { "code": null, "e": 4138, "s": 4002, "text": "I used this technique in one of my last articles (To weigh or not to weigh — this is the Average question ) with the following Measure:" }, { "code": null, "e": 4305, "s": 4138, "text": "Average per Country = AVERAGEX(VALUES(‘Geography’[Region Country]) ,DIVIDE([Online Sales (By Customer)] , [Order Count (By Customer)] ) )" }, { "code": null, "e": 4492, "s": 4305, "text": "Even though you don’t see any CALCULATE() in that solution, I use Measures within the AVERAGEX function. Using a Measure within a Row context automatically triggers a context transition." }, { "code": null, "e": 4552, "s": 4492, "text": "This requirement is a little bit more complicated to solve." }, { "code": null, "e": 4659, "s": 4552, "text": "As mentioned above, I don’t want to create a Measure, as I want to use the calculation result in a Slicer." }, { "code": null, "e": 4709, "s": 4659, "text": "So, I have to create a calculated column as well:" }, { "code": null, "e": 4999, "s": 4709, "text": "Year of Highest Order Line =VAR HighestOrderLine = ‘Customer’[Highest Order Line]VAR Result = CALCULATE( MAXX ( ‘Online Sales’ ,YEAR(‘Online Sales’[OrderDate]) ) , ‘Online Sales’[SalesAmount] = HighestOrderLine )RETURN Result" }, { "code": null, "e": 5223, "s": 4999, "text": "Again, I use CALCULATE() to start context transition, which automatically adds the CustomerKey column to the filter context for the MAXX() function. Because of this, I don’t need to filter by CustomerKey inside CALCULATE()." }, { "code": null, "e": 5388, "s": 5223, "text": "I only have to search for the order line with the highest sales, which I calculated in the previous column, and use MAXX to get the last year with this sales value." }, { "code": null, "e": 5568, "s": 5388, "text": "The Filter added with CALCULATE() is added to the existing Filter Context, which already contains the row of the current customer in the Customer table through context transition." }, { "code": null, "e": 5617, "s": 5568, "text": "You can see the result in the following picture:" }, { "code": null, "e": 5723, "s": 5617, "text": "With the knowledge you have gained until now, you should be able to solve this requirement independently." }, { "code": null, "e": 5804, "s": 5723, "text": "Try to think about it and develop an idea for what the solution could look like." }, { "code": null, "e": 5806, "s": 5804, "text": "." }, { "code": null, "e": 5808, "s": 5806, "text": "." }, { "code": null, "e": 5810, "s": 5808, "text": "." }, { "code": null, "e": 5816, "s": 5810, "text": "Done?" }, { "code": null, "e": 5869, "s": 5816, "text": "OK, this is the solution for this calculated column:" }, { "code": null, "e": 6027, "s": 5869, "text": "Average Sales = CALCULATE( AVERAGEX(‘Online Sales’ ,’Online Sales’[SalesAmount]) )" }, { "code": null, "e": 6103, "s": 6027, "text": "Context transition allows us to write such short and powerful DAX formulas." }, { "code": null, "e": 6246, "s": 6103, "text": "Another approach would have been to create a Measure with AVERAGEX(), as shown above, and use this Measure directly for the calculated column." }, { "code": null, "e": 6373, "s": 6246, "text": "This requirement requires us to combine the gained knowledge to create a new calculated column with the following DAX formula:" }, { "code": null, "e": 6806, "s": 6373, "text": "% Sales of Total Sales =VAR SalesOverall = SUMX(‘Online Sales’ ,’Online Sales’[SalesAmount] )VAR SalesOfCustomer = CALCULATE( SUMX(‘Online Sales’ ,’Online Sales’[SalesAmount] ) )VAR PctOfTotalSales = DIVIDE(SalesOfCustomer, SalesOverall)RETURN PctOfTotalSales" }, { "code": null, "e": 6847, "s": 6806, "text": "Here is the explanation of this formula:" }, { "code": null, "e": 7241, "s": 6847, "text": "The Variable SalesOverall doesn’t use context transition. The result is the total sales overall customersThe Variable SalesOfCustomer encloses the same expression as SalesOverall with a CALCULATE(), thus enforcing a context transition.The result is the sum of Sales for the current customerThe DIVIDE in the Variable PctOfTotalSales calculates the percentage of SalesOfCustomer of SalesOverall" }, { "code": null, "e": 7347, "s": 7241, "text": "The Variable SalesOverall doesn’t use context transition. The result is the total sales overall customers" }, { "code": null, "e": 7533, "s": 7347, "text": "The Variable SalesOfCustomer encloses the same expression as SalesOverall with a CALCULATE(), thus enforcing a context transition.The result is the sum of Sales for the current customer" }, { "code": null, "e": 7637, "s": 7533, "text": "The DIVIDE in the Variable PctOfTotalSales calculates the percentage of SalesOfCustomer of SalesOverall" }, { "code": null, "e": 7665, "s": 7637, "text": "The result looks like this:" }, { "code": null, "e": 7890, "s": 7665, "text": "For this, I need to calculate the ranking of all customers based on the Total Sales Amount. Then I need to get the highest Rank, or the number of customers, and calculate which customers are in the top 10 % of all customers." }, { "code": null, "e": 7957, "s": 7890, "text": "The output should be a column that contains a True or False value." }, { "code": null, "e": 8034, "s": 7957, "text": "As you can imagine, it is not possible to calculate this in one single step." }, { "code": null, "e": 8131, "s": 8034, "text": "Here I want to show you two solutions, which uses context transition in slightly different ways." }, { "code": null, "e": 8252, "s": 8131, "text": "With this approach, I create a calculated DAX table. Then I use LOOKUPVALUE() to map the values into the Customer table." }, { "code": null, "e": 8294, "s": 8252, "text": "This is the code to create the DAX table:" }, { "code": null, "e": 9168, "s": 8294, "text": "Customer Ranking =VAR CustAndSales = ADDCOLUMNS( VALUES(Customer[CustomerKey] ) ,”Amt”, [Online Sales (By Order Date)] )VAR RankedCustomer = ADDCOLUMNS(CustAndSales ,”Rank”, RANKX(CustAndSales ,[Amt] ) )VAR MaxRank = MAXX( RankedCustomer ,[Rank] )VAR Result = ADDCOLUMNS( RankedCustomer ,”IsTop10Perc” , IF( DIVIDE( [Rank] , MaxRank ) <= 0.1 , TRUE() ,FALSE() ) )RETURN Result" }, { "code": null, "e": 9323, "s": 9168, "text": "The variable CustAndSales creates a list of all CustomerKey and calculates a sum of the sales per customer with the Measure [Online Sales (By Order Date)]" }, { "code": null, "e": 9730, "s": 9323, "text": "In the variable RankedCustomer, I use RANKX() to calculate the ranking overall CustomerKeys based on the total sales per customerThe variable MaxRank gets the highest Rank, which I will use in the following variableFinally, I’m adding the column IsTop10Perc with the result of an IF(). This column contains the flag if the customer is in the top 10 % of customers based on the total sales for each customer" }, { "code": null, "e": 9860, "s": 9730, "text": "In the variable RankedCustomer, I use RANKX() to calculate the ranking overall CustomerKeys based on the total sales per customer" }, { "code": null, "e": 9947, "s": 9860, "text": "The variable MaxRank gets the highest Rank, which I will use in the following variable" }, { "code": null, "e": 10139, "s": 9947, "text": "Finally, I’m adding the column IsTop10Perc with the result of an IF(). This column contains the flag if the customer is in the top 10 % of customers based on the total sales for each customer" }, { "code": null, "e": 10232, "s": 10139, "text": "Now, I use the following expression to create a new calculated column in the Customer table:" }, { "code": null, "e": 10473, "s": 10232, "text": "Is Top 10 % customer by Sales =VAR Result = LOOKUPVALUE(‘Customer Ranking’[IsTop10Perc] , ‘Customer Ranking’[CustomerKey] , ‘Customer’[CustomerKey] )RETURN Result" }, { "code": null, "e": 10556, "s": 10473, "text": "I can use this approach to add the following column from the calculated DAX table:" }, { "code": null, "e": 10570, "s": 10556, "text": "Rank by Sales" }, { "code": null, "e": 10588, "s": 10570, "text": "Is Top 10 Percent" }, { "code": null, "e": 10613, "s": 10588, "text": "Total Sales per customer" }, { "code": null, "e": 10724, "s": 10613, "text": "With this approach, I create a few calculated columns containing intermediate results to get the final result." }, { "code": null, "e": 10750, "s": 10724, "text": "Total Sales per Customer:" }, { "code": null, "e": 10776, "s": 10750, "text": "Total Sales per Customer:" }, { "code": null, "e": 10880, "s": 10776, "text": "To get the total sales per customer, I need to use the existing Measure [Online Sales (By Order Date)]:" }, { "code": null, "e": 10938, "s": 10880, "text": "Total Sales per Customer = [Online Sales (By Order Date)]" }, { "code": null, "e": 11082, "s": 10938, "text": "As DAX starts a context transition when we use a Measure inside a Row context, this is enough to get the sum of Sales Amount for each customer." }, { "code": null, "e": 11125, "s": 11082, "text": "2. Calculate the ranking for each customer" }, { "code": null, "e": 11196, "s": 11125, "text": "I need the column [Total Sales per Customer] to calculate the ranking." }, { "code": null, "e": 11251, "s": 11196, "text": "Like in the first solution, I use RANKX to do the job:" }, { "code": null, "e": 11360, "s": 11251, "text": "Rank by Sales (local) = RANKX(‘Customer’ ,’Customer’[Total Sales per Customer])" }, { "code": null, "e": 11398, "s": 11360, "text": "3. Set the top 10 % customer by Sales" }, { "code": null, "e": 11522, "s": 11398, "text": "Finally, I can use the same logic as before to find if the current customer is in the top 10 % of customers by total sales:" }, { "code": null, "e": 11836, "s": 11522, "text": "Is Top 10 Percent (local) =VAR MaxRank = MAXX( ‘Customer’ ,[Rank by Sales (local)] )VAR Result = IF( DIVIDE( [Rank by Sales (local)] , MaxRank ) <= 0.1 ,TRUE() ,FALSE() )RETURN Result" }, { "code": null, "e": 11933, "s": 11836, "text": "As you can see, both solutions use the same basic logic but with a slightly different technique." }, { "code": null, "e": 11975, "s": 11933, "text": "It’s up to you which one you want to use." }, { "code": null, "e": 12019, "s": 11975, "text": "The result is the same with both solutions:" }, { "code": null, "e": 12304, "s": 12019, "text": "Solution 1 was my first approach, as it looked easier to do. I hid the calculated table, as it’s of no use after I included all the columns into the Customer table. But, I don’t like unnecessary objects in my model, so I figured out how to solve the requirement without the DAX table." }, { "code": null, "e": 12462, "s": 12304, "text": "Context transition is a complex but very useful feature in DAX. This feature can help you solve problems more quickly than when you don’t know how to use it." }, { "code": null, "e": 12522, "s": 12462, "text": "But it has some significant quirks, which you need to know:" }, { "code": null, "e": 12561, "s": 12522, "text": "Context transition is slow in measures" }, { "code": null, "e": 12729, "s": 12561, "text": "Duplicate rows in the table used by context transition (The ‘Online Sales’ fact table in the examples above) can cause wrong results, which are extremely hard to spot." }, { "code": null, "e": 12869, "s": 12729, "text": "You need to know when context transition happens: always when you are iterating through rows, and you use a Measure, or you use CALCULATE()" }, { "code": null, "e": 12981, "s": 12869, "text": "I encourage you to read the following SQL article Understanding Context Transition — SQLBI to learn the basics." }, { "code": null, "e": 13108, "s": 12981, "text": "You can read the article Context Transition and Filters in CALCULATE — SQLBI to learn about context transition with CALCULATE." }, { "code": null, "e": 13366, "s": 13108, "text": "Read this article https://www.burningsuit.co.uk/blog/2021/08/context-transition-where-the-row-context-becomes-a-filter-context/, which contains a throughout explanation of context transition, including what you need to consider when using context transition" } ]
Trim a string in Java to remove leading and trailing spaces
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space. Let’s say the following is our string with leading and trailing spaces − String str = new String(" Jack Sparrow "); Now, let us trim the string − str.trim() Following is an example to remove the leading and trailing spaces in Java − import java.io.*; public class Main { public static void main(String args[]) { String str = new String(" Jack Sparrow "); System.out.println("String: "+str); System.out.print("Result after removing leading and trailing spaces:" ); System.out.println(str.trim() ); } } String: Jack Sparrow Result after removing leading and trailing spaces:Jack Sparrow
[ { "code": null, "e": 1282, "s": 1062, "text": "To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space." }, { "code": null, "e": 1355, "s": 1282, "text": "Let’s say the following is our string with leading and trailing spaces −" }, { "code": null, "e": 1398, "s": 1355, "text": "String str = new String(\" Jack Sparrow \");" }, { "code": null, "e": 1428, "s": 1398, "text": "Now, let us trim the string −" }, { "code": null, "e": 1439, "s": 1428, "text": "str.trim()" }, { "code": null, "e": 1515, "s": 1439, "text": "Following is an example to remove the leading and trailing spaces in Java −" }, { "code": null, "e": 1813, "s": 1515, "text": "import java.io.*;\npublic class Main {\n public static void main(String args[]) {\n String str = new String(\" Jack Sparrow \");\n System.out.println(\"String: \"+str);\n System.out.print(\"Result after removing leading and trailing spaces:\" );\n System.out.println(str.trim() );\n }\n}" }, { "code": null, "e": 1897, "s": 1813, "text": "String: Jack Sparrow\nResult after removing leading and trailing spaces:Jack Sparrow" } ]
Perl do...while Loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. The syntax of a do...while loop in Perl is − do { statement(s); }while( condition ); It should be noted that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false. The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. #!/usr/local/bin/perl $a = 10; # do...while loop execution do{ printf "Value of a: $a\n"; $a = $a + 1; }while( $a < 20 ); When the above code is executed, it produces the following result − Value of a: 10 Value of a: 11 Value of a: 12 Value of a: 13 Value of a: 14 Value of a: 15 Value of a: 16 Value of a: 17 Value of a: 18 Value of a: 19 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2370, "s": 2220, "text": "Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop." }, { "code": null, "e": 2490, "s": 2370, "text": "A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time." }, { "code": null, "e": 2535, "s": 2490, "text": "The syntax of a do...while loop in Perl is −" }, { "code": null, "e": 2579, "s": 2535, "text": "do {\n statement(s);\n}while( condition );\n" }, { "code": null, "e": 2918, "s": 2579, "text": "It should be noted that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false." }, { "code": null, "e": 3121, "s": 2918, "text": "The number 0, the strings '0' and \"\" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value." }, { "code": null, "e": 3252, "s": 3121, "text": "#!/usr/local/bin/perl\n \n$a = 10;\n\n# do...while loop execution\ndo{\n printf \"Value of a: $a\\n\";\n $a = $a + 1;\n}while( $a < 20 );" }, { "code": null, "e": 3320, "s": 3252, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3471, "s": 3320, "text": "Value of a: 10\nValue of a: 11\nValue of a: 12\nValue of a: 13\nValue of a: 14\nValue of a: 15\nValue of a: 16\nValue of a: 17\nValue of a: 18\nValue of a: 19\n" }, { "code": null, "e": 3506, "s": 3471, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3520, "s": 3506, "text": " Devi Killada" }, { "code": null, "e": 3555, "s": 3520, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3575, "s": 3555, "text": " Harshit Srivastava" }, { "code": null, "e": 3608, "s": 3575, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 3624, "s": 3608, "text": " TELCOMA Global" }, { "code": null, "e": 3657, "s": 3624, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3674, "s": 3657, "text": " Mohammad Nauman" }, { "code": null, "e": 3707, "s": 3674, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3730, "s": 3707, "text": " Stone River ELearning" }, { "code": null, "e": 3765, "s": 3730, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3788, "s": 3765, "text": " Stone River ELearning" }, { "code": null, "e": 3795, "s": 3788, "text": " Print" }, { "code": null, "e": 3806, "s": 3795, "text": " Add Notes" } ]
C Program for nth Catalan Number
Given an interger n; the task is to find the Catalan Number on that nth position. So, before doing the program we must know what is a Catalan Number? Catlan numbers are the sequence of natural numbers, which occurs in the form of various counting number problems. Catalan numbers C0, C1, C2,... Cn are driven by formula − cn=1n+1(2nn)=2n!(n+1)!n! The few Catalan numbers for every n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ... So if we entered n =3 we should get 5 as an output from the program Some of few applications of Catalan numbers − Counting the number of possible binary search trees with n keys. Finding the number of expressions containing n pair of parenthesis which are correctly matched. Like for n = 3 the possible parenthesis expression would be ((())), ()(()), ()()(), (())(), (()()). Finding number of ways to connect point on circle disjoint chords, and many more. Input: n = 6 Output: 132 Input: n = 8 Output: 1430 Approach we will be using to solve the given problem − Taking and input n. Check If n <= 1 then, Return 1 Loop from i=0 to i<n and i++ For every i Set result = result + (catalan(i)*catalan(n-i-1)) Return and print the result. Start Step 1 -> In function unsigned long int catalan(unsigned int n) If n <= 1 then, Return 1 End if Declare an unsigned long variable res = 0 Loop For i=0 and i<n and i++ Set res = res + (catalan(i)*catalan(n-i-1)) End Loop Return res Step 2 -> int main() Declare an input n = 6 Print "catalan is : then call function catalan(n) Stop #include <stdio.h> // using recursive approach to find the catalan number unsigned long int catalan(unsigned int n) { // Base case if (n <= 1) return 1; // catalan(n) is sum of catalan(i)*catalan(n-i-1) unsigned long int res = 0; for (int i=0; i<n; i++) res += catalan(i)*catalan(n-i-1); return res; } //Main function int main() { int n = 6; printf("catalan is :%ld\n", catalan(n)); return 0; } catalan is :132
[ { "code": null, "e": 1212, "s": 1062, "text": "Given an interger n; the task is to find the Catalan Number on that nth position. So, before doing the program we must know what is a Catalan Number?" }, { "code": null, "e": 1326, "s": 1212, "text": "Catlan numbers are the sequence of natural numbers, which occurs in the form of various counting number problems." }, { "code": null, "e": 1384, "s": 1326, "text": "Catalan numbers C0, C1, C2,... Cn are driven by formula −" }, { "code": null, "e": 1409, "s": 1384, "text": "cn=1n+1(2nn)=2n!(n+1)!n!" }, { "code": null, "e": 1513, "s": 1409, "text": "The few Catalan numbers for every n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ..." }, { "code": null, "e": 1581, "s": 1513, "text": "So if we entered n =3 we should get 5 as an output from the program" }, { "code": null, "e": 1627, "s": 1581, "text": "Some of few applications of Catalan numbers −" }, { "code": null, "e": 1692, "s": 1627, "text": "Counting the number of possible binary search trees with n keys." }, { "code": null, "e": 1888, "s": 1692, "text": "Finding the number of expressions containing n pair of parenthesis which are correctly matched. Like for n = 3 the possible parenthesis expression would be ((())), ()(()), ()()(), (())(), (()())." }, { "code": null, "e": 1970, "s": 1888, "text": "Finding number of ways to connect point on circle disjoint chords, and many more." }, { "code": null, "e": 2021, "s": 1970, "text": "Input: n = 6\nOutput: 132\nInput: n = 8\nOutput: 1430" }, { "code": null, "e": 2076, "s": 2021, "text": "Approach we will be using to solve the given problem −" }, { "code": null, "e": 2096, "s": 2076, "text": "Taking and input n." }, { "code": null, "e": 2127, "s": 2096, "text": "Check If n <= 1 then, Return 1" }, { "code": null, "e": 2156, "s": 2127, "text": "Loop from i=0 to i<n and i++" }, { "code": null, "e": 2218, "s": 2156, "text": "For every i Set result = result + (catalan(i)*catalan(n-i-1))" }, { "code": null, "e": 2247, "s": 2218, "text": "Return and print the result." }, { "code": null, "e": 2649, "s": 2247, "text": "Start\n Step 1 -> In function unsigned long int catalan(unsigned int n)\n If n <= 1 then,\n Return 1\n End if\n Declare an unsigned long variable res = 0\n Loop For i=0 and i<n and i++\n Set res = res + (catalan(i)*catalan(n-i-1))\n End Loop\n Return res\n Step 2 -> int main()\n Declare an input n = 6\n Print \"catalan is : then call function catalan(n)\nStop" }, { "code": null, "e": 3077, "s": 2649, "text": "#include <stdio.h>\n// using recursive approach to find the catalan number\nunsigned long int catalan(unsigned int n) {\n // Base case\n if (n <= 1) return 1;\n // catalan(n) is sum of catalan(i)*catalan(n-i-1)\n unsigned long int res = 0;\n for (int i=0; i<n; i++)\n res += catalan(i)*catalan(n-i-1);\n return res;\n}\n//Main function\nint main() {\n int n = 6;\n printf(\"catalan is :%ld\\n\", catalan(n));\n return 0;\n}" }, { "code": null, "e": 3093, "s": 3077, "text": "catalan is :132" } ]
Optimising pairwise Euclidean distance calculations using Python | by TU | Towards Data Science
Euclidean distance is one of the most commonly used metric, serving as a basis for many machine learning algorithms. However when one is faced with very large data sets, containing multiple features, the simple distance calculation becomes a source of headaches and memory errors. Although being aware that packages like SciPy provide robust solution, I couldn’t resist to explore other ways of calculating the distance in hope to find the high-performing approach for large data sets. We begin with quick reminder of the formula, which is quite straightforward. Given two vectors x and y, we take a square root of the sum of squared differences in their elements. This question comes up a lot when dealing with extremely large data sets... Now, let’s say we have 1k vectors for which we need to calculate pairwise distances. This would result in the output matrix with 1m entries, meaning that for larger volumes of data you are very likely to run out of memory. For all the computations Python uses local memory, as well as it does not give back allocated memory straightaway. This implies that you are bounded by the specs of your computer. Working in cloud services can help to scale the memory accordingly, however in most of the cases you would still have to parallelise computations. Although memory limitation is not going anywhere, it is desirable to have optimised script. On to the calculations... For the task of testing the performance of different approaches to calculating the distance, I needed fairly large data set. The data set is available on Kaggle and can be dowloaded using link below. www.kaggle.com Some of the features in the data set aren’t so useful in this case, so we will be using the reduced set. import pandas as pdcc_customers = pd.read_csv('BankChurners.csv')cc_customers = cc_customers[['CLIENTNUM', 'Attrition_Flag', 'Customer_Age', 'Gender','Dependent_count', 'Education_Level', 'Marital_Status','Income_Category', 'Card_Category', 'Months_on_book','Total_Relationship_Count','Months_Inactive_12_mon','Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal', 'Total_Trans_Amt','Total_Trans_Ct']] We have mixed-type data set that represents information on individual customers with demographic and credit card related attributes. Before we can use the data as an input, we need to ensure we transform categorical variables to numeric. cat_col = ['Attrition_Flag', 'Gender', 'Education_Level', 'Marital_Status', 'Income_Category', 'Card_Category']for col in cat_col: cc_customers[col]=cc_customers[col].astype('category').cat.codes When dealing with large data sets, feature transformation is quite important aspect to consider, it can help to reduce the amount of memory used by the matrix (not only). Let’s look at the memory breakdown for the data frame before and after transformations take place. Once we transformed the categorical variables to numeric we can see that the memory usage reduced quite substantially. Now that we are done with the basic transformations, we can return to our goal which is calculating pairwise Euclidean distances barring in my mind the speed of computation. We have 10127 unique customers, this would result in matrix 10127x10127 dimension. To understand how the code scales with larger data sets, for loop was introduced where at each iteration we consider larger random sample from the original data. We start with 10% from the data and each step our sample increases by 10%, when it comes to the performance time of the code we take average of 20 runs. The code below was used for every approach, the only differences would be the distance function. import numpy as npimport timefrom tqdm import tqdm_notebook as tqdminput_data = cc_customers.drop('CLIENTNUM', axis=1) # drop the customer IDiter_times = []for l,z in zip(range(0, 20), tqdm(range(0, 20))): times = [] for r in np.arange(0.1, 1.1, 0.1): data_reduced = input_data.sample(frac=r, random_state=1) tic = time.perf_counter() ###INSERT DISTANCE CALCULATIONS### toc = time.perf_counter() times.append(toc-tic) iter_times.append(times) tot_time = [sum(i)/20 for i in zip(*iter_times)]data_size = [len(input_data.sample(frac=r, random_state=1)) for r in np.arange(0.1, 1.1, 0.1)]for i, j in zip(tot_time, data_size): print(f"# of customers {j}: {i:0.4f} seconds") Using python packages might be a trivial choice, however since they usually provide quite good speed, it can serve as a good baseline. from scipy.spatial.distance import cdistfrom sklearn.metrics.pairwise import euclidean_distancesscipy_cdist = cdist(data_reduced, data_reduced, metric='euclidean')sklearn_dist = euclidean_distances(data_reduced, data_reduced) Quite interestingly, Sklearn euclidean_distances outperformed SciPy cdist, with the differences in time becoming more noticeable with larger data sets. Difference in implementation can be a reason for better performance of Sklearn package, since it uses vectorisation trick for computing the distances which is more efficient. Meanwhile, after looking at the source code for cdist implementation, SciPy uses double loop. Optimisation and for loops aren’t usually best friends! However when it comes to pairwise distances...can be difficult to avoid, unless going the vectorisation route (implementation presented later in the article). # Without pre-allocating memorydist = []for i in range(len(data_reduced)): dist.append(((data_reduced- data_reduced[i])**2).sum(axis=1)**0.5) # pre-allocating memoryD = np.empty((len(data_reduced),len(data_reduced)))for i in range(len(data_reduced)): D[i, :] = ((data_reduced-data_reduced[i])**2).sum(axis=1)**0.5return D We compared two approaches, with and without pre-allocating memory before calculating the distance. It comes to no surprise that pre-allocating memory helped improve performance, though the time taken still exceeded Sklearn implementation. Despite the slower performance in some cases it still might be preferential to use this approach, as it is capable to handle larger data sets without running out of memory. After reading few research papers online on this topic, I have to say, I was very hopeful about the performance of this approach. As well as seeing performance of Sklearn euclidean_distances, did boost those hopes even higher... import numpy as npx = np.sum(data_reduced**2, axis=1)[:, np.newaxis]y = np.sum(data_reduced**2, axis=1)xy = np.dot(data_reduced, data_reduced.T)dist = np.sqrt(x + y - 2*xy) The approach comes quite close in time to cdist implementation for smaller data samples, however it doesn’t scale very well. For the largest data sample the time is almost the same as for loop approach without pre-allocating the memory. Unsurprisingly, it didn’t outperform euclidean_distances. Wrap up After testing multiple approaches to calculate pairwise Euclidean distance, we found that Sklearn euclidean_distances has the best performance. Since it uses vectorisation implementation, which we also tried implementing using NumPy commands, without much success in reducing computation time. Although we yet again showed that in most cases Python modules provide optimal solution, sometimes one would still have to go with different option, depending on the nature of the task.
[ { "code": null, "e": 453, "s": 172, "text": "Euclidean distance is one of the most commonly used metric, serving as a basis for many machine learning algorithms. However when one is faced with very large data sets, containing multiple features, the simple distance calculation becomes a source of headaches and memory errors." }, { "code": null, "e": 658, "s": 453, "text": "Although being aware that packages like SciPy provide robust solution, I couldn’t resist to explore other ways of calculating the distance in hope to find the high-performing approach for large data sets." }, { "code": null, "e": 837, "s": 658, "text": "We begin with quick reminder of the formula, which is quite straightforward. Given two vectors x and y, we take a square root of the sum of squared differences in their elements." }, { "code": null, "e": 1136, "s": 837, "text": "This question comes up a lot when dealing with extremely large data sets... Now, let’s say we have 1k vectors for which we need to calculate pairwise distances. This would result in the output matrix with 1m entries, meaning that for larger volumes of data you are very likely to run out of memory." }, { "code": null, "e": 1463, "s": 1136, "text": "For all the computations Python uses local memory, as well as it does not give back allocated memory straightaway. This implies that you are bounded by the specs of your computer. Working in cloud services can help to scale the memory accordingly, however in most of the cases you would still have to parallelise computations." }, { "code": null, "e": 1555, "s": 1463, "text": "Although memory limitation is not going anywhere, it is desirable to have optimised script." }, { "code": null, "e": 1581, "s": 1555, "text": "On to the calculations..." }, { "code": null, "e": 1781, "s": 1581, "text": "For the task of testing the performance of different approaches to calculating the distance, I needed fairly large data set. The data set is available on Kaggle and can be dowloaded using link below." }, { "code": null, "e": 1796, "s": 1781, "text": "www.kaggle.com" }, { "code": null, "e": 1901, "s": 1796, "text": "Some of the features in the data set aren’t so useful in this case, so we will be using the reduced set." }, { "code": null, "e": 2312, "s": 1901, "text": "import pandas as pdcc_customers = pd.read_csv('BankChurners.csv')cc_customers = cc_customers[['CLIENTNUM', 'Attrition_Flag', 'Customer_Age', 'Gender','Dependent_count', 'Education_Level', 'Marital_Status','Income_Category', 'Card_Category', 'Months_on_book','Total_Relationship_Count','Months_Inactive_12_mon','Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal', 'Total_Trans_Amt','Total_Trans_Ct']]" }, { "code": null, "e": 2445, "s": 2312, "text": "We have mixed-type data set that represents information on individual customers with demographic and credit card related attributes." }, { "code": null, "e": 2550, "s": 2445, "text": "Before we can use the data as an input, we need to ensure we transform categorical variables to numeric." }, { "code": null, "e": 2749, "s": 2550, "text": "cat_col = ['Attrition_Flag', 'Gender', 'Education_Level', 'Marital_Status', 'Income_Category', 'Card_Category']for col in cat_col: cc_customers[col]=cc_customers[col].astype('category').cat.codes" }, { "code": null, "e": 3019, "s": 2749, "text": "When dealing with large data sets, feature transformation is quite important aspect to consider, it can help to reduce the amount of memory used by the matrix (not only). Let’s look at the memory breakdown for the data frame before and after transformations take place." }, { "code": null, "e": 3138, "s": 3019, "text": "Once we transformed the categorical variables to numeric we can see that the memory usage reduced quite substantially." }, { "code": null, "e": 3395, "s": 3138, "text": "Now that we are done with the basic transformations, we can return to our goal which is calculating pairwise Euclidean distances barring in my mind the speed of computation. We have 10127 unique customers, this would result in matrix 10127x10127 dimension." }, { "code": null, "e": 3710, "s": 3395, "text": "To understand how the code scales with larger data sets, for loop was introduced where at each iteration we consider larger random sample from the original data. We start with 10% from the data and each step our sample increases by 10%, when it comes to the performance time of the code we take average of 20 runs." }, { "code": null, "e": 3807, "s": 3710, "text": "The code below was used for every approach, the only differences would be the distance function." }, { "code": null, "e": 4527, "s": 3807, "text": "import numpy as npimport timefrom tqdm import tqdm_notebook as tqdminput_data = cc_customers.drop('CLIENTNUM', axis=1) # drop the customer IDiter_times = []for l,z in zip(range(0, 20), tqdm(range(0, 20))): times = [] for r in np.arange(0.1, 1.1, 0.1): data_reduced = input_data.sample(frac=r, random_state=1) tic = time.perf_counter() ###INSERT DISTANCE CALCULATIONS### toc = time.perf_counter() times.append(toc-tic) iter_times.append(times) tot_time = [sum(i)/20 for i in zip(*iter_times)]data_size = [len(input_data.sample(frac=r, random_state=1)) for r in np.arange(0.1, 1.1, 0.1)]for i, j in zip(tot_time, data_size): print(f\"# of customers {j}: {i:0.4f} seconds\")" }, { "code": null, "e": 4662, "s": 4527, "text": "Using python packages might be a trivial choice, however since they usually provide quite good speed, it can serve as a good baseline." }, { "code": null, "e": 4888, "s": 4662, "text": "from scipy.spatial.distance import cdistfrom sklearn.metrics.pairwise import euclidean_distancesscipy_cdist = cdist(data_reduced, data_reduced, metric='euclidean')sklearn_dist = euclidean_distances(data_reduced, data_reduced)" }, { "code": null, "e": 5040, "s": 4888, "text": "Quite interestingly, Sklearn euclidean_distances outperformed SciPy cdist, with the differences in time becoming more noticeable with larger data sets." }, { "code": null, "e": 5309, "s": 5040, "text": "Difference in implementation can be a reason for better performance of Sklearn package, since it uses vectorisation trick for computing the distances which is more efficient. Meanwhile, after looking at the source code for cdist implementation, SciPy uses double loop." }, { "code": null, "e": 5524, "s": 5309, "text": "Optimisation and for loops aren’t usually best friends! However when it comes to pairwise distances...can be difficult to avoid, unless going the vectorisation route (implementation presented later in the article)." }, { "code": null, "e": 5855, "s": 5524, "text": "# Without pre-allocating memorydist = []for i in range(len(data_reduced)): dist.append(((data_reduced- data_reduced[i])**2).sum(axis=1)**0.5) # pre-allocating memoryD = np.empty((len(data_reduced),len(data_reduced)))for i in range(len(data_reduced)): D[i, :] = ((data_reduced-data_reduced[i])**2).sum(axis=1)**0.5return D" }, { "code": null, "e": 5955, "s": 5855, "text": "We compared two approaches, with and without pre-allocating memory before calculating the distance." }, { "code": null, "e": 6095, "s": 5955, "text": "It comes to no surprise that pre-allocating memory helped improve performance, though the time taken still exceeded Sklearn implementation." }, { "code": null, "e": 6268, "s": 6095, "text": "Despite the slower performance in some cases it still might be preferential to use this approach, as it is capable to handle larger data sets without running out of memory." }, { "code": null, "e": 6497, "s": 6268, "text": "After reading few research papers online on this topic, I have to say, I was very hopeful about the performance of this approach. As well as seeing performance of Sklearn euclidean_distances, did boost those hopes even higher..." }, { "code": null, "e": 6673, "s": 6497, "text": "import numpy as npx = np.sum(data_reduced**2, axis=1)[:, np.newaxis]y = np.sum(data_reduced**2, axis=1)xy = np.dot(data_reduced, data_reduced.T)dist = np.sqrt(x + y - 2*xy)" }, { "code": null, "e": 6968, "s": 6673, "text": "The approach comes quite close in time to cdist implementation for smaller data samples, however it doesn’t scale very well. For the largest data sample the time is almost the same as for loop approach without pre-allocating the memory. Unsurprisingly, it didn’t outperform euclidean_distances." }, { "code": null, "e": 6976, "s": 6968, "text": "Wrap up" }, { "code": null, "e": 7270, "s": 6976, "text": "After testing multiple approaches to calculate pairwise Euclidean distance, we found that Sklearn euclidean_distances has the best performance. Since it uses vectorisation implementation, which we also tried implementing using NumPy commands, without much success in reducing computation time." } ]
C# Program to Generate Random Even Numbers Using LINQ Parallel Query - GeeksforGeeks
28 Nov, 2021 LINQ is known as Language Integrated Query and was introduced in .NET 3.5. It gives power to .NET languages to generate or create queries to retrieve data from the data source. In this article, we will generate random even numbers in parallel using LINQ. So, we will use ParallelQuery{TSource} to generate a sequence of integral numbers in parallel within the given range. Along with it, we have to use the where and select clause to get the even numbers. Remember that it will throw an ArgumentOutOfRangeException if the stop is less than 0 or start +stop-1 is greater than the MaxValue. Syntax: IEnumerable<int> variable = ((ParallelQuery<int>)ParallelEnumerable.Range(start, stop)).Where(x => x % 2 == 0).Select(i => i); Where the start is the first integer value in the sequence and the stop is the number of sequential integers to generate. Example: Input : Range(start, stop) = Range(1, 20) Output : 2 6 12 16 4 8 14 18 10 20 Input : Range(start, stop) = Range(10, 20) Output : 10 12 14 16 18 20 22 24 26 28 Approach: To print even numbers in parallel follow the following steps: Implement a parallelQuery{TSource} and mention the range.Use where clause to check the modulus of y by 2 is equal to zero.Now Select is used to check if the value of the j variable is greater than or equal to the value of the variable(i.e., j).Iterate the even numbers using the foreach loop Implement a parallelQuery{TSource} and mention the range. Use where clause to check the modulus of y by 2 is equal to zero. Now Select is used to check if the value of the j variable is greater than or equal to the value of the variable(i.e., j). Iterate the even numbers using the foreach loop Example: C# // C# program to generate random even numbers// using LINQ Parallel Queryusing System;using System.Collections.Generic;using System.Linq; class GFG{ static void Main(string[] args){ // Creating data IEnumerable<int> data = ((ParallelQuery<int>)ParallelEnumerable.Range( // Condition for generating even numbers 10, 20)).Where(i => i % 2 == 0).Select( value => value); // Display even numbers foreach(int even in data) { Console.WriteLine(even); }}} Output: 12 14 16 18 20 22 24 26 28 10 Picked C# C# Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | Inheritance Convert String to Character Array in C# Socket Programming in C# Getting a Month Name Using Month Number in C# Program to Print a New Line in C# Program to find absolute value of a given number
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Nov, 2021" }, { "code": null, "e": 24891, "s": 24302, "text": "LINQ is known as Language Integrated Query and was introduced in .NET 3.5. It gives power to .NET languages to generate or create queries to retrieve data from the data source. In this article, we will generate random even numbers in parallel using LINQ. So, we will use ParallelQuery{TSource} to generate a sequence of integral numbers in parallel within the given range. Along with it, we have to use the where and select clause to get the even numbers. Remember that it will throw an ArgumentOutOfRangeException if the stop is less than 0 or start +stop-1 is greater than the MaxValue." }, { "code": null, "e": 24899, "s": 24891, "text": "Syntax:" }, { "code": null, "e": 25054, "s": 24899, "text": "IEnumerable<int> variable = ((ParallelQuery<int>)ParallelEnumerable.Range(start,\n stop)).Where(x => x % 2 == 0).Select(i => i);" }, { "code": null, "e": 25176, "s": 25054, "text": "Where the start is the first integer value in the sequence and the stop is the number of sequential integers to generate." }, { "code": null, "e": 25185, "s": 25176, "text": "Example:" }, { "code": null, "e": 25347, "s": 25185, "text": "Input : Range(start, stop) = Range(1, 20)\nOutput :\n2\n6\n12\n16\n4\n8\n14\n18\n10\n20\n\nInput : Range(start, stop) = Range(10, 20)\nOutput :\n10\n12\n14\n16\n18\n20\n22\n24\n26\n28" }, { "code": null, "e": 25357, "s": 25347, "text": "Approach:" }, { "code": null, "e": 25419, "s": 25357, "text": "To print even numbers in parallel follow the following steps:" }, { "code": null, "e": 25711, "s": 25419, "text": "Implement a parallelQuery{TSource} and mention the range.Use where clause to check the modulus of y by 2 is equal to zero.Now Select is used to check if the value of the j variable is greater than or equal to the value of the variable(i.e., j).Iterate the even numbers using the foreach loop" }, { "code": null, "e": 25769, "s": 25711, "text": "Implement a parallelQuery{TSource} and mention the range." }, { "code": null, "e": 25835, "s": 25769, "text": "Use where clause to check the modulus of y by 2 is equal to zero." }, { "code": null, "e": 25958, "s": 25835, "text": "Now Select is used to check if the value of the j variable is greater than or equal to the value of the variable(i.e., j)." }, { "code": null, "e": 26006, "s": 25958, "text": "Iterate the even numbers using the foreach loop" }, { "code": null, "e": 26015, "s": 26006, "text": "Example:" }, { "code": null, "e": 26018, "s": 26015, "text": "C#" }, { "code": "// C# program to generate random even numbers// using LINQ Parallel Queryusing System;using System.Collections.Generic;using System.Linq; class GFG{ static void Main(string[] args){ // Creating data IEnumerable<int> data = ((ParallelQuery<int>)ParallelEnumerable.Range( // Condition for generating even numbers 10, 20)).Where(i => i % 2 == 0).Select( value => value); // Display even numbers foreach(int even in data) { Console.WriteLine(even); }}}", "e": 26624, "s": 26018, "text": null }, { "code": null, "e": 26632, "s": 26624, "text": "Output:" }, { "code": null, "e": 26662, "s": 26632, "text": "12\n14\n16\n18\n20\n22\n24\n26\n28\n10" }, { "code": null, "e": 26669, "s": 26662, "text": "Picked" }, { "code": null, "e": 26672, "s": 26669, "text": "C#" }, { "code": null, "e": 26684, "s": 26672, "text": "C# Programs" }, { "code": null, "e": 26782, "s": 26684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26791, "s": 26782, "text": "Comments" }, { "code": null, "e": 26804, "s": 26791, "text": "Old Comments" }, { "code": null, "e": 26827, "s": 26804, "text": "Extension Method in C#" }, { "code": null, "e": 26855, "s": 26827, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26895, "s": 26855, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26938, "s": 26895, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26955, "s": 26938, "text": "C# | Inheritance" }, { "code": null, "e": 26995, "s": 26955, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27020, "s": 26995, "text": "Socket Programming in C#" }, { "code": null, "e": 27066, "s": 27020, "text": "Getting a Month Name Using Month Number in C#" }, { "code": null, "e": 27100, "s": 27066, "text": "Program to Print a New Line in C#" } ]
Program to count Number of connected components in an undirected graph - GeeksforGeeks
11 Apr, 2022 Given an undirected graph g, the task is to print the number of connected components in the graph. Examples: Input: Output: 3 There are three connected components: 1 – 5, 0 – 2 – 4 and 3 Approach: DFS visit all the connected vertices of the given vertex. When iterating over all vertices, whenever we see unvisited node, it is because it was not visited by DFS done on vertices so far. That means it is not connected to any previous nodes visited so far i.e it was not part of previous components. Hence this node belongs to new component. This means, before visiting this node, we just finished visiting all nodes previous component and that component is now complete. So we need to increment component counter as we completed a component. The idea is to use a variable count to store the number of connected components and do the following steps: Initialize all vertices as unvisited.For all the vertices check if a vertex has not been visited, then perform DFS on that vertex and increment the variable count by 1. Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for above approach#include <bits/stdc++.h>using namespace std; // Graph class represents a undirected graph// using adjacency list representationclass Graph { // No. of vertices int V; // Pointer to an array containing adjacency lists list<int>* adj; // A function used by DFS void DFSUtil(int v, bool visited[]); public: // Constructor Graph(int V); void addEdge(int v, int w); int NumberOfconnectedComponents();}; // Function to return the number of// connected components in an undirected graphint Graph::NumberOfconnectedComponents(){ // Mark all the vertices as not visited bool* visited = new bool[V]; // To store the number of connected components int count = 0; for (int v = 0; v < V; v++) visited[v] = false; for (int v = 0; v < V; v++) { if (visited[v] == false) { DFSUtil(v, visited); count += 1; } } return count;} void Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Add an undirected edgevoid Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v);} // Driver codeint main(){ Graph g(5); g.addEdge(1, 0); g.addEdge(2, 3); g.addEdge(3, 4); cout << g.NumberOfconnectedComponents(); return 0;} import java.util.*;class Graph { private int V; // No. of vertices in graph. private LinkedList<Integer>[] adj; // Adjacency List // representation ArrayList<ArrayList<Integer> > components = new ArrayList<>(); @SuppressWarnings("unchecked") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; i++) adj[i] = new LinkedList(); } void addEdge(int u, int w) { adj[u].add(w); adj[w].add(u); // Undirected Graph. } void DFSUtil(int v, boolean[] visited, ArrayList<Integer> al) { visited[v] = true; al.add(v); System.out.print(v + " "); Iterator<Integer> it = adj[v].iterator(); while (it.hasNext()) { int n = it.next(); if (!visited[n]) DFSUtil(n, visited, al); } } void DFS() { boolean[] visited = new boolean[V]; for (int i = 0; i < V; i++) { ArrayList<Integer> al = new ArrayList<>(); if (!visited[i]) { DFSUtil(i, visited, al); components.add(al); } } } int ConnecetedComponents() { return components.size(); }}public class Main { public static void main(String[] args) { Graph g = new Graph(6); g.addEdge(1, 5); g.addEdge(0, 2); g.addEdge(2, 4); System.out.println("Graph DFS:"); g.DFS(); System.out.println( "\nNumber of Conneceted Components: " + g.ConnecetedComponents()); }}// Code contributed by Madhav Chittlangia. # Python3 program for above approach # Graph class represents a undirected graph# using adjacency list representationclass Graph: def __init__(self, V): # No. of vertices self.V = V # Pointer to an array containing # adjacency lists self.adj = [[] for i in range(self.V)] # Function to return the number of # connected components in an undirected graph def NumberOfconnectedComponents(self): # Mark all the vertices as not visited visited = [False for i in range(self.V)] # To store the number of connected # components count = 0 for v in range(self.V): if (visited[v] == False): self.DFSUtil(v, visited) count += 1 return count def DFSUtil(self, v, visited): # Mark the current node as visited visited[v] = True # Recur for all the vertices # adjacent to this vertex for i in self.adj[v]: if (not visited[i]): self.DFSUtil(i, visited) # Add an undirected edge def addEdge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) # Driver code if __name__=='__main__': g = Graph(5) g.addEdge(1, 0) g.addEdge(2, 3) g.addEdge(3, 4) print(g.NumberOfconnectedComponents()) # This code is contributed by rutvik_56 <script> // JavaScript program for above approach // Graph class represents a undirected graph// using adjacency list representationclass Graph{ constructor(V){ // No. of vertices this.V = V // Pointer to an array containing // adjacency lists this.adj = new Array(this.V); for(let i=0;i<V;i++){ this.adj[i] = new Array() } } // Function to return the number of // connected components in an undirected graph NumberOfconnectedComponents(){ // Mark all the vertices as not visited let visited = new Array(this.V).fill(false); // To store the number of connected // components let count = 0 for(let v=0;v<this.V;v++){ if (visited[v] == false){ this.DFSUtil(v, visited) count += 1 } } return count } DFSUtil(v, visited){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(let i of this.adj[v]){ if (visited[i] == false){ this.DFSUtil(i, visited) } } } // Add an undirected edge addEdge(v, w){ this.adj[v].push(w) this.adj[w].push(v) } } // Driver code let g = new Graph(5)g.addEdge(1, 0)g.addEdge(2, 3)g.addEdge(3, 4) document.write(g.NumberOfconnectedComponents(),"</br>") // This code is contributed by shinjanpatra</script> 2 Complexity Analysis: Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.Space Complexity: O(V), since an extra visited array of size V is required. alfiskaria rutvik_56 prashantkumar dhotre ruhelaa48 madhavchitlangia saurabh1990aror shinjanpatra prophet1999 DFS C++ Programs Data Structures Graph Data Structures DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments CSV file management using C++ Shallow Copy and Deep Copy in C++ cin in C++ Passing a function as a parameter in C++ Generics in C++ SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Implementing a Linked List in Java using Class
[ { "code": null, "e": 25138, "s": 25110, "text": "\n11 Apr, 2022" }, { "code": null, "e": 25237, "s": 25138, "text": "Given an undirected graph g, the task is to print the number of connected components in the graph." }, { "code": null, "e": 25249, "s": 25237, "text": "Examples: " }, { "code": null, "e": 25258, "s": 25249, "text": "Input: " }, { "code": null, "e": 25330, "s": 25258, "text": "Output: 3 There are three connected components: 1 – 5, 0 – 2 – 4 and 3 " }, { "code": null, "e": 25341, "s": 25330, "text": "Approach: " }, { "code": null, "e": 25399, "s": 25341, "text": "DFS visit all the connected vertices of the given vertex." }, { "code": null, "e": 25530, "s": 25399, "text": "When iterating over all vertices, whenever we see unvisited node, it is because it was not visited by DFS done on vertices so far." }, { "code": null, "e": 25642, "s": 25530, "text": "That means it is not connected to any previous nodes visited so far i.e it was not part of previous components." }, { "code": null, "e": 25684, "s": 25642, "text": "Hence this node belongs to new component." }, { "code": null, "e": 25814, "s": 25684, "text": "This means, before visiting this node, we just finished visiting all nodes previous component and that component is now complete." }, { "code": null, "e": 25885, "s": 25814, "text": "So we need to increment component counter as we completed a component." }, { "code": null, "e": 25993, "s": 25885, "text": "The idea is to use a variable count to store the number of connected components and do the following steps:" }, { "code": null, "e": 26162, "s": 25993, "text": "Initialize all vertices as unvisited.For all the vertices check if a vertex has not been visited, then perform DFS on that vertex and increment the variable count by 1." }, { "code": null, "e": 26214, "s": 26162, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26218, "s": 26214, "text": "C++" }, { "code": null, "e": 26223, "s": 26218, "text": "Java" }, { "code": null, "e": 26231, "s": 26223, "text": "Python3" }, { "code": null, "e": 26242, "s": 26231, "text": "Javascript" }, { "code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Graph class represents a undirected graph// using adjacency list representationclass Graph { // No. of vertices int V; // Pointer to an array containing adjacency lists list<int>* adj; // A function used by DFS void DFSUtil(int v, bool visited[]); public: // Constructor Graph(int V); void addEdge(int v, int w); int NumberOfconnectedComponents();}; // Function to return the number of// connected components in an undirected graphint Graph::NumberOfconnectedComponents(){ // Mark all the vertices as not visited bool* visited = new bool[V]; // To store the number of connected components int count = 0; for (int v = 0; v < V; v++) visited[v] = false; for (int v = 0; v < V; v++) { if (visited[v] == false) { DFSUtil(v, visited); count += 1; } } return count;} void Graph::DFSUtil(int v, bool visited[]){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited);} Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Add an undirected edgevoid Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v);} // Driver codeint main(){ Graph g(5); g.addEdge(1, 0); g.addEdge(2, 3); g.addEdge(3, 4); cout << g.NumberOfconnectedComponents(); return 0;}", "e": 27831, "s": 26242, "text": null }, { "code": "import java.util.*;class Graph { private int V; // No. of vertices in graph. private LinkedList<Integer>[] adj; // Adjacency List // representation ArrayList<ArrayList<Integer> > components = new ArrayList<>(); @SuppressWarnings(\"unchecked\") Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; i++) adj[i] = new LinkedList(); } void addEdge(int u, int w) { adj[u].add(w); adj[w].add(u); // Undirected Graph. } void DFSUtil(int v, boolean[] visited, ArrayList<Integer> al) { visited[v] = true; al.add(v); System.out.print(v + \" \"); Iterator<Integer> it = adj[v].iterator(); while (it.hasNext()) { int n = it.next(); if (!visited[n]) DFSUtil(n, visited, al); } } void DFS() { boolean[] visited = new boolean[V]; for (int i = 0; i < V; i++) { ArrayList<Integer> al = new ArrayList<>(); if (!visited[i]) { DFSUtil(i, visited, al); components.add(al); } } } int ConnecetedComponents() { return components.size(); }}public class Main { public static void main(String[] args) { Graph g = new Graph(6); g.addEdge(1, 5); g.addEdge(0, 2); g.addEdge(2, 4); System.out.println(\"Graph DFS:\"); g.DFS(); System.out.println( \"\\nNumber of Conneceted Components: \" + g.ConnecetedComponents()); }}// Code contributed by Madhav Chittlangia.", "e": 29479, "s": 27831, "text": null }, { "code": "# Python3 program for above approach # Graph class represents a undirected graph# using adjacency list representationclass Graph: def __init__(self, V): # No. of vertices self.V = V # Pointer to an array containing # adjacency lists self.adj = [[] for i in range(self.V)] # Function to return the number of # connected components in an undirected graph def NumberOfconnectedComponents(self): # Mark all the vertices as not visited visited = [False for i in range(self.V)] # To store the number of connected # components count = 0 for v in range(self.V): if (visited[v] == False): self.DFSUtil(v, visited) count += 1 return count def DFSUtil(self, v, visited): # Mark the current node as visited visited[v] = True # Recur for all the vertices # adjacent to this vertex for i in self.adj[v]: if (not visited[i]): self.DFSUtil(i, visited) # Add an undirected edge def addEdge(self, v, w): self.adj[v].append(w) self.adj[w].append(v) # Driver code if __name__=='__main__': g = Graph(5) g.addEdge(1, 0) g.addEdge(2, 3) g.addEdge(3, 4) print(g.NumberOfconnectedComponents()) # This code is contributed by rutvik_56", "e": 30937, "s": 29479, "text": null }, { "code": "<script> // JavaScript program for above approach // Graph class represents a undirected graph// using adjacency list representationclass Graph{ constructor(V){ // No. of vertices this.V = V // Pointer to an array containing // adjacency lists this.adj = new Array(this.V); for(let i=0;i<V;i++){ this.adj[i] = new Array() } } // Function to return the number of // connected components in an undirected graph NumberOfconnectedComponents(){ // Mark all the vertices as not visited let visited = new Array(this.V).fill(false); // To store the number of connected // components let count = 0 for(let v=0;v<this.V;v++){ if (visited[v] == false){ this.DFSUtil(v, visited) count += 1 } } return count } DFSUtil(v, visited){ // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(let i of this.adj[v]){ if (visited[i] == false){ this.DFSUtil(i, visited) } } } // Add an undirected edge addEdge(v, w){ this.adj[v].push(w) this.adj[w].push(v) } } // Driver code let g = new Graph(5)g.addEdge(1, 0)g.addEdge(2, 3)g.addEdge(3, 4) document.write(g.NumberOfconnectedComponents(),\"</br>\") // This code is contributed by shinjanpatra</script>", "e": 32513, "s": 30937, "text": null }, { "code": null, "e": 32515, "s": 32513, "text": "2" }, { "code": null, "e": 32536, "s": 32515, "text": "Complexity Analysis:" }, { "code": null, "e": 32715, "s": 32536, "text": "Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.Space Complexity: O(V), since an extra visited array of size V is required." }, { "code": null, "e": 32726, "s": 32715, "text": "alfiskaria" }, { "code": null, "e": 32736, "s": 32726, "text": "rutvik_56" }, { "code": null, "e": 32757, "s": 32736, "text": "prashantkumar dhotre" }, { "code": null, "e": 32767, "s": 32757, "text": "ruhelaa48" }, { "code": null, "e": 32784, "s": 32767, "text": "madhavchitlangia" }, { "code": null, "e": 32800, "s": 32784, "text": "saurabh1990aror" }, { "code": null, "e": 32813, "s": 32800, "text": "shinjanpatra" }, { "code": null, "e": 32825, "s": 32813, "text": "prophet1999" }, { "code": null, "e": 32829, "s": 32825, "text": "DFS" }, { "code": null, "e": 32842, "s": 32829, "text": "C++ Programs" }, { "code": null, "e": 32858, "s": 32842, "text": "Data Structures" }, { "code": null, "e": 32864, "s": 32858, "text": "Graph" }, { "code": null, "e": 32880, "s": 32864, "text": "Data Structures" }, { "code": null, "e": 32884, "s": 32880, "text": "DFS" }, { "code": null, "e": 32890, "s": 32884, "text": "Graph" }, { "code": null, "e": 32988, "s": 32890, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32997, "s": 32988, "text": "Comments" }, { "code": null, "e": 33010, "s": 32997, "text": "Old Comments" }, { "code": null, "e": 33040, "s": 33010, "text": "CSV file management using C++" }, { "code": null, "e": 33074, "s": 33040, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 33085, "s": 33074, "text": "cin in C++" }, { "code": null, "e": 33126, "s": 33085, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 33142, "s": 33126, "text": "Generics in C++" }, { "code": null, "e": 33191, "s": 33142, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 33235, "s": 33191, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33260, "s": 33235, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 33316, "s": 33260, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" } ]
How to use CheckBox in Android - GeeksforGeeks
19 Feb, 2021 CheckBox belongs to android.widget.CheckBox class. Android CheckBox class is the subclass of CompoundButton class. It is generally used in a place where user can select one or more than choices from a given list of choices. For example, selecting hobbies. public class CheckBox extends CompoundButton Class Hierarchy : java.lang.Object ↳ android.view.View ↳ android.widget.TextView ↳ android.widget.Button ↳ android.widget.CompoundButton ↳ android.widget.CheckBox It has two states – checked or unchecked. Methods of CheckBox class public boolean isChecked(): If CheckBox is in checked state then return true otherwise false. public void setChecked(boolean status): It changes the state of the CheckBox. Below is the code for an example where the user chooses its hobbies from the given list containing Painting, Reading, Singing and Cooking with the help of CheckBox. MainActivity.java //Below is the code for MainActivity.javapackage com.geeksforgeeks.gfg.checkbox; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.CheckBox;import android.widget.Toast; public class MainActivity extends AppCompatActivity { CheckBox ch, ch1, ch2, ch3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Binding MainActivity.java with activity_main.xml file setContentView(R.layout.activity_main); // Finding CheckBox by its unique ID ch=(CheckBox)findViewById(R.id.checkBox); ch1=(CheckBox)findViewById(R.id.checkBox2); ch2=(CheckBox)findViewById(R.id.checkBox3); ch3=(CheckBox)findViewById(R.id.checkBox4); } // This function is invoked when the button is pressed. public void Check(View v) { String msg=""; // Concatenation of the checked options in if // isChecked() is used to check whether // the CheckBox is in true state or not. if(ch.isChecked()) msg = msg + " Painting "; if(ch1.isChecked()) msg = msg + " Reading "; if(ch2.isChecked()) msg = msg + " Singing "; if(ch3.isChecked()) msg = msg + " Cooking "; // Toast is created to display the // message using show() method. Toast.makeText(this, msg + "are selected", Toast.LENGTH_LONG).show(); }} activity_main.xml The activity_main.xml has a TextView, 4 CheckBoxes and a button.The TextView prompts the user to select his/her hobbies.First user select its choices and then presses the Submit button. After pressing Submit button, a toast will generate showing the selected hobbies. <!-- Below is the code for activity_main.xml --><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical" tools:context="com.example.hp.checkbox.MainActivity"> <TextView android:id="@+id/textView" <!-- covers the entire width of the screen --> android:layout_width="match_parent" <!-- covers as much height as required. --> android:layout_height="wrap_content" <!--create 8dp space from margin ends--> android:layout_marginEnd="8dp" <!--create 8dp space from start of margin--> android:layout_marginStart="8dp" <!--create 48dp space from the top of margin--> android:layout_marginTop="48dp" android:text="Choose your hobbies:" android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <CheckBox android:id="@+id/checkBox" <!-- covers the entire width of the screen --> android:layout_width="match_parent" <!-- covers as much height as required. --> android:layout_height="wrap_content" android:text="Painting" android:layout_marginTop="16dp" android:textSize="18sp" /> <CheckBox android:id="@+id/checkBox2" <!-- covers the entire width of the screen --> android:layout_width="match_parent" <!-- covers as much height as required. --> android:layout_height="wrap_content" android:text="Reading" android:layout_marginTop="16dp" android:textSize="18sp" /> <CheckBox android:id="@+id/checkBox3" <!-- covers the entire width of the screen --> android:layout_width="match_parent" <!-- covers as much height as required. --> android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Singing" android:textSize="18sp" app:layout_constraintTop_toTopOf="@+id/textView" tools:layout_editor_absoluteX="382dp" /> <CheckBox android:id="@+id/checkBox4" <!-- covers the entire width of the screen --> android:layout_width="match_parent" <!-- covers as much height as required. --> android:layout_height="wrap_content" android:text="Cooking" android:layout_marginTop="16dp" android:textSize="18sp" app:layout_constraintTop_toBottomOf="@+id/checkBox" tools:layout_editor_absoluteX="386dp" /> <Button android:id="@+id/button" <!-- covers the entire width of the screen --> android:layout_width="match_parent" <!-- covers as much height as required. --> android:layout_height="wrap_content" android:layout_marginTop="16dp" android:onClick="Check" android:text="submit" /></LinearLayout> Output: Android-Button Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio Android RecyclerView in Kotlin Content Providers in Android with Example 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": 25476, "s": 25448, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25732, "s": 25476, "text": "CheckBox belongs to android.widget.CheckBox class. Android CheckBox class is the subclass of CompoundButton class. It is generally used in a place where user can select one or more than choices from a given list of choices. For example, selecting hobbies." }, { "code": null, "e": 25778, "s": 25732, "text": "public class CheckBox extends CompoundButton\n" }, { "code": null, "e": 25796, "s": 25778, "text": "Class Hierarchy :" }, { "code": null, "e": 26012, "s": 25796, "text": "java.lang.Object\n ↳ android.view.View\n ↳ android.widget.TextView\n ↳ android.widget.Button\n ↳ android.widget.CompoundButton\n ↳ android.widget.CheckBox\n" }, { "code": null, "e": 26054, "s": 26012, "text": "It has two states – checked or unchecked." }, { "code": null, "e": 26080, "s": 26054, "text": "Methods of CheckBox class" }, { "code": null, "e": 26174, "s": 26080, "text": "public boolean isChecked(): If CheckBox is in checked state then return true otherwise false." }, { "code": null, "e": 26252, "s": 26174, "text": "public void setChecked(boolean status): It changes the state of the CheckBox." }, { "code": null, "e": 26417, "s": 26252, "text": "Below is the code for an example where the user chooses its hobbies from the given list containing Painting, Reading, Singing and Cooking with the help of CheckBox." }, { "code": null, "e": 26435, "s": 26417, "text": "MainActivity.java" }, { "code": "//Below is the code for MainActivity.javapackage com.geeksforgeeks.gfg.checkbox; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.CheckBox;import android.widget.Toast; public class MainActivity extends AppCompatActivity { CheckBox ch, ch1, ch2, ch3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Binding MainActivity.java with activity_main.xml file setContentView(R.layout.activity_main); // Finding CheckBox by its unique ID ch=(CheckBox)findViewById(R.id.checkBox); ch1=(CheckBox)findViewById(R.id.checkBox2); ch2=(CheckBox)findViewById(R.id.checkBox3); ch3=(CheckBox)findViewById(R.id.checkBox4); } // This function is invoked when the button is pressed. public void Check(View v) { String msg=\"\"; // Concatenation of the checked options in if // isChecked() is used to check whether // the CheckBox is in true state or not. if(ch.isChecked()) msg = msg + \" Painting \"; if(ch1.isChecked()) msg = msg + \" Reading \"; if(ch2.isChecked()) msg = msg + \" Singing \"; if(ch3.isChecked()) msg = msg + \" Cooking \"; // Toast is created to display the // message using show() method. Toast.makeText(this, msg + \"are selected\", Toast.LENGTH_LONG).show(); }}", "e": 27971, "s": 26435, "text": null }, { "code": null, "e": 27990, "s": 27971, "text": " activity_main.xml" }, { "code": null, "e": 28258, "s": 27990, "text": "The activity_main.xml has a TextView, 4 CheckBoxes and a button.The TextView prompts the user to select his/her hobbies.First user select its choices and then presses the Submit button. After pressing Submit button, a toast will generate showing the selected hobbies." }, { "code": "<!-- Below is the code for activity_main.xml --><?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#ffffff\" android:orientation=\"vertical\" tools:context=\"com.example.hp.checkbox.MainActivity\"> <TextView android:id=\"@+id/textView\" <!-- covers the entire width of the screen --> android:layout_width=\"match_parent\" <!-- covers as much height as required. --> android:layout_height=\"wrap_content\" <!--create 8dp space from margin ends--> android:layout_marginEnd=\"8dp\" <!--create 8dp space from start of margin--> android:layout_marginStart=\"8dp\" <!--create 48dp space from the top of margin--> android:layout_marginTop=\"48dp\" android:text=\"Choose your hobbies:\" android:textSize=\"24sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <CheckBox android:id=\"@+id/checkBox\" <!-- covers the entire width of the screen --> android:layout_width=\"match_parent\" <!-- covers as much height as required. --> android:layout_height=\"wrap_content\" android:text=\"Painting\" android:layout_marginTop=\"16dp\" android:textSize=\"18sp\" /> <CheckBox android:id=\"@+id/checkBox2\" <!-- covers the entire width of the screen --> android:layout_width=\"match_parent\" <!-- covers as much height as required. --> android:layout_height=\"wrap_content\" android:text=\"Reading\" android:layout_marginTop=\"16dp\" android:textSize=\"18sp\" /> <CheckBox android:id=\"@+id/checkBox3\" <!-- covers the entire width of the screen --> android:layout_width=\"match_parent\" <!-- covers as much height as required. --> android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:text=\"Singing\" android:textSize=\"18sp\" app:layout_constraintTop_toTopOf=\"@+id/textView\" tools:layout_editor_absoluteX=\"382dp\" /> <CheckBox android:id=\"@+id/checkBox4\" <!-- covers the entire width of the screen --> android:layout_width=\"match_parent\" <!-- covers as much height as required. --> android:layout_height=\"wrap_content\" android:text=\"Cooking\" android:layout_marginTop=\"16dp\" android:textSize=\"18sp\" app:layout_constraintTop_toBottomOf=\"@+id/checkBox\" tools:layout_editor_absoluteX=\"386dp\" /> <Button android:id=\"@+id/button\" <!-- covers the entire width of the screen --> android:layout_width=\"match_parent\" <!-- covers as much height as required. --> android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:onClick=\"Check\" android:text=\"submit\" /></LinearLayout>", "e": 31454, "s": 28258, "text": null }, { "code": null, "e": 31462, "s": 31454, "text": "Output:" }, { "code": null, "e": 31477, "s": 31462, "text": "Android-Button" }, { "code": null, "e": 31485, "s": 31477, "text": "Android" }, { "code": null, "e": 31490, "s": 31485, "text": "Java" }, { "code": null, "e": 31495, "s": 31490, "text": "Java" }, { "code": null, "e": 31503, "s": 31495, "text": "Android" }, { "code": null, "e": 31601, "s": 31503, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31659, "s": 31601, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 31702, "s": 31659, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 31740, "s": 31702, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 31771, "s": 31740, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 31813, "s": 31771, "text": "Content Providers in Android with Example" }, { "code": null, "e": 31828, "s": 31813, "text": "Arrays in Java" }, { "code": null, "e": 31872, "s": 31828, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31894, "s": 31872, "text": "For-each loop in Java" }, { "code": null, "e": 31945, "s": 31894, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
unordered_set find() function in C++ STL - GeeksforGeeks
28 Sep, 2018 The unordered_set::find() function is a built-in function in C++ STL which is used to search for an element in the container. It returns an iterator to the element, if found else, it returns an iterator pointing to unordered_set::end(). Syntax : unordered_set_name.find(key) Parameter: This function accepts a mandatory parameter key which specifies the element to be searched for. Return Value: It returns an iterator to the element if found, else returns an iterator pointing to the end of unordered_set. Below programs illustrate the unordered_set::find() function: Program 1: // C++ program to illustrate the// unordered_set::find() function #include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ unordered_set<string> sampleSet = { "geeks1", "for", "geeks2" }; // use of find() function if (sampleSet.find("geeks1") != sampleSet.end()) { cout << "element found." << endl; } else { cout << "element not found" << endl; } return 0;} element found. Program 2: // CPP program to illustrate the// unordered_set::find() function #include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ unordered_set<string> sampleSet = { "geeks1", "for", "geeks2" }; // use of find() function if (sampleSet.find("geeksforgeeks") != sampleSet.end()) { cout << "found" << endl; } else { cout << "Not found" << endl; } return 0;} Not found CPP-Functions cpp-unordered_set cpp-unordered_set-functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Inline Functions in C++ Array of Strings in C++ (5 Different Ways to Create) Convert string to char array in C++
[ { "code": null, "e": 25367, "s": 25339, "text": "\n28 Sep, 2018" }, { "code": null, "e": 25604, "s": 25367, "text": "The unordered_set::find() function is a built-in function in C++ STL which is used to search for an element in the container. It returns an iterator to the element, if found else, it returns an iterator pointing to unordered_set::end()." }, { "code": null, "e": 25613, "s": 25604, "text": "Syntax :" }, { "code": null, "e": 25642, "s": 25613, "text": "unordered_set_name.find(key)" }, { "code": null, "e": 25749, "s": 25642, "text": "Parameter: This function accepts a mandatory parameter key which specifies the element to be searched for." }, { "code": null, "e": 25874, "s": 25749, "text": "Return Value: It returns an iterator to the element if found, else returns an iterator pointing to the end of unordered_set." }, { "code": null, "e": 25936, "s": 25874, "text": "Below programs illustrate the unordered_set::find() function:" }, { "code": null, "e": 25947, "s": 25936, "text": "Program 1:" }, { "code": "// C++ program to illustrate the// unordered_set::find() function #include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ unordered_set<string> sampleSet = { \"geeks1\", \"for\", \"geeks2\" }; // use of find() function if (sampleSet.find(\"geeks1\") != sampleSet.end()) { cout << \"element found.\" << endl; } else { cout << \"element not found\" << endl; } return 0;}", "e": 26386, "s": 25947, "text": null }, { "code": null, "e": 26402, "s": 26386, "text": "element found.\n" }, { "code": null, "e": 26413, "s": 26402, "text": "Program 2:" }, { "code": "// CPP program to illustrate the// unordered_set::find() function #include <iostream>#include <string>#include <unordered_set> using namespace std; int main(){ unordered_set<string> sampleSet = { \"geeks1\", \"for\", \"geeks2\" }; // use of find() function if (sampleSet.find(\"geeksforgeeks\") != sampleSet.end()) { cout << \"found\" << endl; } else { cout << \"Not found\" << endl; } return 0;}", "e": 26842, "s": 26413, "text": null }, { "code": null, "e": 26853, "s": 26842, "text": "Not found\n" }, { "code": null, "e": 26867, "s": 26853, "text": "CPP-Functions" }, { "code": null, "e": 26885, "s": 26867, "text": "cpp-unordered_set" }, { "code": null, "e": 26913, "s": 26885, "text": "cpp-unordered_set-functions" }, { "code": null, "e": 26917, "s": 26913, "text": "C++" }, { "code": null, "e": 26921, "s": 26917, "text": "CPP" }, { "code": null, "e": 27019, "s": 26921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27047, "s": 27019, "text": "Operator Overloading in C++" }, { "code": null, "e": 27067, "s": 27047, "text": "Polymorphism in C++" }, { "code": null, "e": 27091, "s": 27067, "text": "Sorting a vector in C++" }, { "code": null, "e": 27124, "s": 27091, "text": "Friend class and function in C++" }, { "code": null, "e": 27149, "s": 27124, "text": "std::string class in C++" }, { "code": null, "e": 27193, "s": 27149, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 27238, "s": 27193, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 27262, "s": 27238, "text": "Inline Functions in C++" }, { "code": null, "e": 27315, "s": 27262, "text": "Array of Strings in C++ (5 Different Ways to Create)" } ]
p5.js | setInput() Function - GeeksforGeeks
17 Jan, 2020 The setInput() function is an inbuilt function in p5.js library. This function is used to connects to the p5sound instance that is the master output by default. By using this function you can also pass in a specific source. Syntax: setInput(snd, smoothing) Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file. Parameter: This function accepts two parameters as mentioned above and described below: snd: This parameter is use to set the sound source and it is optional. smoothing: This parameter is use to set the smooth amplitude reading and the range is between 0.0 to 1.0, this parameter is also optional. Below example illustrate the p5.setInput() function in JavaScript: function preload(){ sound1 = loadSound('song.mp3'); sound2 = loadSound('pfivesound.mp3');}function setup(){ amplitude = new p5.Amplitude(); sound1.play(); sound2.play(); amplitude.setInput(sound2);}function draw() { background(255); fill(200); let gfg = amplitude.getLevel(); let size = map(gfg, 0, 1, 0, 400); ellipse(width/1, height/1, size*2, size*2);}function mousePressed(){ sound2.pause();} function mouseReleased(){ sound2.play();} Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Supported Browsers: The browsers supported by p5.js setInput() function are listed below: Google Chrome Internet Explorer Firefox Safari Opera JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array 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": 26627, "s": 26599, "text": "\n17 Jan, 2020" }, { "code": null, "e": 26851, "s": 26627, "text": "The setInput() function is an inbuilt function in p5.js library. This function is used to connects to the p5sound instance that is the master output by default. By using this function you can also pass in a specific source." }, { "code": null, "e": 26859, "s": 26851, "text": "Syntax:" }, { "code": null, "e": 26884, "s": 26859, "text": "setInput(snd, smoothing)" }, { "code": null, "e": 27011, "s": 26884, "text": "Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file." }, { "code": null, "e": 27099, "s": 27011, "text": "Parameter: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 27170, "s": 27099, "text": "snd: This parameter is use to set the sound source and it is optional." }, { "code": null, "e": 27309, "s": 27170, "text": "smoothing: This parameter is use to set the smooth amplitude reading and the range is between 0.0 to 1.0, this parameter is also optional." }, { "code": null, "e": 27376, "s": 27309, "text": "Below example illustrate the p5.setInput() function in JavaScript:" }, { "code": "function preload(){ sound1 = loadSound('song.mp3'); sound2 = loadSound('pfivesound.mp3');}function setup(){ amplitude = new p5.Amplitude(); sound1.play(); sound2.play(); amplitude.setInput(sound2);}function draw() { background(255); fill(200); let gfg = amplitude.getLevel(); let size = map(gfg, 0, 1, 0, 400); ellipse(width/1, height/1, size*2, size*2);}function mousePressed(){ sound2.pause();} function mouseReleased(){ sound2.play();}", "e": 27829, "s": 27376, "text": null }, { "code": null, "e": 27966, "s": 27829, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 28056, "s": 27966, "text": "Supported Browsers: The browsers supported by p5.js setInput() function are listed below:" }, { "code": null, "e": 28070, "s": 28056, "text": "Google Chrome" }, { "code": null, "e": 28088, "s": 28070, "text": "Internet Explorer" }, { "code": null, "e": 28096, "s": 28088, "text": "Firefox" }, { "code": null, "e": 28103, "s": 28096, "text": "Safari" }, { "code": null, "e": 28109, "s": 28103, "text": "Opera" }, { "code": null, "e": 28126, "s": 28109, "text": "JavaScript-p5.js" }, { "code": null, "e": 28137, "s": 28126, "text": "JavaScript" }, { "code": null, "e": 28154, "s": 28137, "text": "Web Technologies" }, { "code": null, "e": 28252, "s": 28154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28292, "s": 28252, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28353, "s": 28292, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28394, "s": 28353, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28416, "s": 28394, "text": "JavaScript | Promises" }, { "code": null, "e": 28470, "s": 28416, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28510, "s": 28470, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28543, "s": 28510, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28586, "s": 28543, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28636, "s": 28586, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python string | ascii_lowercase - GeeksforGeeks
16 Oct, 2018 In Python3, ascii_lowercase is a pre-initialized string used as string constant. In Python, string ascii_lowercase will give the lowercase letters ‘abcdefghijklmnopqrstuvwxyz’. Syntax : string.ascii_lowercase Parameters : Doesn’t take any parameter, since it’s not a function. Returns : Return all lowercase letters. Note : Make sure to import string library function inorder to use ascii_lowercase. Code #1 : # import string library function import string # Storing the value in variable result result = string.ascii_lowercase # Printing the value print(result) Output : abcdefghijklmnopqrstuvwxyz Code #2 : Given code checks if the string input has only lower ASCII characters. # importing string library function import string # Function checks if input string # has lower only ascii letters or not def check(value): for letter in value: # If anything other than lower ascii # letter is present, then return # False, else return True if letter not in string.ascii_lowercase: return False return True # Driver Code input1 = "GeeksForGeeks"print(input1, "--> ", check(input1)) input2 = "geeks for geeks"print(input2, "--> ", check(input2)) input3 = "geeksforgeeks"print(input3, "--> ", check(input3)) Output: GeeksForGeeks --> False geeks for geeks --> False geeksforgeeks --> True Applications :The string constant ascii_lowercase can be used in many practical applications. Let’s see a code explaining how to use ascii_lowercase to generate strong random passwords of given size. # Importing random to generate # random string sequence import random # Importing string library function import string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_lowercase + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10) print(password) Output: 52v3bdyk63 python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 26117, "s": 26089, "text": "\n16 Oct, 2018" }, { "code": null, "e": 26294, "s": 26117, "text": "In Python3, ascii_lowercase is a pre-initialized string used as string constant. In Python, string ascii_lowercase will give the lowercase letters ‘abcdefghijklmnopqrstuvwxyz’." }, { "code": null, "e": 26326, "s": 26294, "text": "Syntax : string.ascii_lowercase" }, { "code": null, "e": 26394, "s": 26326, "text": "Parameters : Doesn’t take any parameter, since it’s not a function." }, { "code": null, "e": 26434, "s": 26394, "text": "Returns : Return all lowercase letters." }, { "code": null, "e": 26517, "s": 26434, "text": "Note : Make sure to import string library function inorder to use ascii_lowercase." }, { "code": null, "e": 26527, "s": 26517, "text": "Code #1 :" }, { "code": "# import string library function import string # Storing the value in variable result result = string.ascii_lowercase # Printing the value print(result) ", "e": 26688, "s": 26527, "text": null }, { "code": null, "e": 26697, "s": 26688, "text": "Output :" }, { "code": null, "e": 26724, "s": 26697, "text": "abcdefghijklmnopqrstuvwxyz" }, { "code": null, "e": 26806, "s": 26724, "text": " Code #2 : Given code checks if the string input has only lower ASCII characters." }, { "code": "# importing string library function import string # Function checks if input string # has lower only ascii letters or not def check(value): for letter in value: # If anything other than lower ascii # letter is present, then return # False, else return True if letter not in string.ascii_lowercase: return False return True # Driver Code input1 = \"GeeksForGeeks\"print(input1, \"--> \", check(input1)) input2 = \"geeks for geeks\"print(input2, \"--> \", check(input2)) input3 = \"geeksforgeeks\"print(input3, \"--> \", check(input3)) ", "e": 27413, "s": 26806, "text": null }, { "code": null, "e": 27421, "s": 27413, "text": "Output:" }, { "code": null, "e": 27497, "s": 27421, "text": "GeeksForGeeks --> False\ngeeks for geeks --> False\ngeeksforgeeks --> True" }, { "code": null, "e": 27697, "s": 27497, "text": "Applications :The string constant ascii_lowercase can be used in many practical applications. Let’s see a code explaining how to use ascii_lowercase to generate strong random passwords of given size." }, { "code": "# Importing random to generate # random string sequence import random # Importing string library function import string def rand_pass(size): # Takes random choices from # ascii_letters and digits generate_pass = ''.join([random.choice( string.ascii_lowercase + string.digits) for n in range(size)]) return generate_pass # Driver Code password = rand_pass(10) print(password) ", "e": 28192, "s": 27697, "text": null }, { "code": null, "e": 28200, "s": 28192, "text": "Output:" }, { "code": null, "e": 28211, "s": 28200, "text": "52v3bdyk63" }, { "code": null, "e": 28225, "s": 28211, "text": "python-string" }, { "code": null, "e": 28232, "s": 28225, "text": "Python" }, { "code": null, "e": 28330, "s": 28232, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28348, "s": 28330, "text": "Python Dictionary" }, { "code": null, "e": 28380, "s": 28348, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28402, "s": 28380, "text": "Enumerate() in Python" }, { "code": null, "e": 28444, "s": 28402, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28470, "s": 28444, "text": "Python String | replace()" }, { "code": null, "e": 28499, "s": 28470, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28543, "s": 28499, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28580, "s": 28543, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28616, "s": 28580, "text": "Convert integer to string in Python" } ]
Express.js res.send() Function - GeeksforGeeks
19 Aug, 2021 The res.send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array. Syntax: res.send( [body] ) Parameter: This function accepts a single parameter body that describe the body which is to be sent in the response. Returns: It returns an Object. Installation of express module: 1. You can visit the link to Install express module. You can install this package by using this command. npm install express 2. After installing the express module, you can check your express version in command prompt using the command. npm version express 3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. node index.js Example 1: Filename: index.js Javascript var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.send({ title: 'GeeksforGeeks' });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: 1. The project structure will look like this: 2. Make sure you have installed express module using the following command: npm install express 3. Run index.js file using below command: node index.js Output: Server listening on PORT 3000 4. Now open browser and go to http://localhost:3000/, now check your browser and you will see the following output: {"title":"GeeksforGeeks"} Example 2: Filename: index.js Javascript var express = require('express');const path = require('path');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.send({"name":"GeeksforGeeks"}); next();}); app.get('/', function(req, res){ console.log("Body Sent")}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: Server listening on PORT 3000 Body Sent And you will see the following output on your browser screen: {"name":"GeeksforGeeks"} Reference: https://expressjs.com/en/5x/api.html#res.send kalrap615 Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array 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? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26341, "s": 26313, "text": "\n19 Aug, 2021" }, { "code": null, "e": 26480, "s": 26341, "text": "The res.send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array." }, { "code": null, "e": 26489, "s": 26480, "text": "Syntax: " }, { "code": null, "e": 26508, "s": 26489, "text": "res.send( [body] )" }, { "code": null, "e": 26625, "s": 26508, "text": "Parameter: This function accepts a single parameter body that describe the body which is to be sent in the response." }, { "code": null, "e": 26656, "s": 26625, "text": "Returns: It returns an Object." }, { "code": null, "e": 26690, "s": 26656, "text": "Installation of express module: " }, { "code": null, "e": 26796, "s": 26690, "text": "1. You can visit the link to Install express module. You can install this package by using this command. " }, { "code": null, "e": 26816, "s": 26796, "text": "npm install express" }, { "code": null, "e": 26929, "s": 26816, "text": "2. After installing the express module, you can check your express version in command prompt using the command. " }, { "code": null, "e": 26949, "s": 26929, "text": "npm version express" }, { "code": null, "e": 27088, "s": 26949, "text": "3. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command. " }, { "code": null, "e": 27102, "s": 27088, "text": "node index.js" }, { "code": null, "e": 27133, "s": 27102, "text": "Example 1: Filename: index.js " }, { "code": null, "e": 27144, "s": 27133, "text": "Javascript" }, { "code": "var express = require('express');var app = express();var PORT = 3000; // Without middlewareapp.get('/', function(req, res){ res.send({ title: 'GeeksforGeeks' });}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 27427, "s": 27144, "text": null }, { "code": null, "e": 27454, "s": 27427, "text": "Steps to run the program: " }, { "code": null, "e": 27501, "s": 27454, "text": "1. The project structure will look like this: " }, { "code": null, "e": 27578, "s": 27501, "text": "2. Make sure you have installed express module using the following command: " }, { "code": null, "e": 27598, "s": 27578, "text": "npm install express" }, { "code": null, "e": 27641, "s": 27598, "text": "3. Run index.js file using below command: " }, { "code": null, "e": 27655, "s": 27641, "text": "node index.js" }, { "code": null, "e": 27664, "s": 27655, "text": "Output: " }, { "code": null, "e": 27694, "s": 27664, "text": "Server listening on PORT 3000" }, { "code": null, "e": 27811, "s": 27694, "text": "4. Now open browser and go to http://localhost:3000/, now check your browser and you will see the following output: " }, { "code": null, "e": 27837, "s": 27811, "text": "{\"title\":\"GeeksforGeeks\"}" }, { "code": null, "e": 27868, "s": 27837, "text": "Example 2: Filename: index.js " }, { "code": null, "e": 27879, "s": 27868, "text": "Javascript" }, { "code": "var express = require('express');const path = require('path');var app = express();var PORT = 3000; // With middlewareapp.use('/', function(req, res, next){ res.send({\"name\":\"GeeksforGeeks\"}); next();}); app.get('/', function(req, res){ console.log(\"Body Sent\")}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 28265, "s": 27879, "text": null }, { "code": null, "e": 28305, "s": 28265, "text": "Run index.js file using below command: " }, { "code": null, "e": 28319, "s": 28305, "text": "node index.js" }, { "code": null, "e": 28437, "s": 28319, "text": "Now open the browser and go to http://localhost:3000/, now check your console and you will see the following output: " }, { "code": null, "e": 28477, "s": 28437, "text": "Server listening on PORT 3000\nBody Sent" }, { "code": null, "e": 28541, "s": 28477, "text": "And you will see the following output on your browser screen: " }, { "code": null, "e": 28566, "s": 28541, "text": "{\"name\":\"GeeksforGeeks\"}" }, { "code": null, "e": 28624, "s": 28566, "text": "Reference: https://expressjs.com/en/5x/api.html#res.send " }, { "code": null, "e": 28634, "s": 28624, "text": "kalrap615" }, { "code": null, "e": 28645, "s": 28634, "text": "Express.js" }, { "code": null, "e": 28653, "s": 28645, "text": "Node.js" }, { "code": null, "e": 28670, "s": 28653, "text": "Web Technologies" }, { "code": null, "e": 28768, "s": 28670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28798, "s": 28768, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28827, "s": 28798, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 28884, "s": 28827, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28938, "s": 28884, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28975, "s": 28938, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 29015, "s": 28975, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29060, "s": 29015, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29103, "s": 29060, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29153, "s": 29103, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to check a webpage is loaded inside an iframe or into the browser window using JavaScript? - GeeksforGeeks
25 Apr, 2019 An iFrame is a rectangular frame or region in the webpage to load or display another separate webpage or document inside it. So basically, an iFrame is used to display a webpage within a webpage. You can see more about iFrames here : HTML iFrames There may be a variety of reasons for checking whether a webpage is loaded in an iFrame, for example, in cases where we need to dynamically adjust the height or width of an element. Comparing the object’s location with the window object’s parent location: Here, we simply compare the object’s location with the window object’s parent location. If the result is true, then the webpage is in an iFrame. If it is false, then it is not in an iFrame.<script>function iniFrame() { if ( window.location !== window.parent.location ) { // The page is in an iFrames document.write("The page is in an iFrame"); } else { // The page is not in an iFrame document.write("The page is not in an iFrame"); }} // Calling iniFrame functioniniFrame();</script>Output:The page is in an iFrame <script>function iniFrame() { if ( window.location !== window.parent.location ) { // The page is in an iFrames document.write("The page is in an iFrame"); } else { // The page is not in an iFrame document.write("The page is not in an iFrame"); }} // Calling iniFrame functioniniFrame();</script> Output: The page is in an iFrame Using window.top and window.self property: The top and self are both window objects, along with parent, so check if the current window is the top/main window.<script> // Function to check whether webpage is in iFramefunction iniFrame() { if(window.self !== window.top) { // !== operator checks whether the operands // are of not equal value or not equal type document.write("The page is in an iFrame"); } else { document.write("The page is in an iFrame"); }} // Calling iniFrame functioniniFrame();</script>Output:The page is in an iFrame <script> // Function to check whether webpage is in iFramefunction iniFrame() { if(window.self !== window.top) { // !== operator checks whether the operands // are of not equal value or not equal type document.write("The page is in an iFrame"); } else { document.write("The page is in an iFrame"); }} // Calling iniFrame functioniniFrame();</script> Output: The page is in an iFrame Using the window.frameElement property: Note that this only supports webpages belonging to the same origin as the main page in which it is embedded. The function window.frameElement returns the element (like iframe and object) in which the webpage is embedded.<script>function iniFrame() { var gfg = window.frameElement; // Checking if webpage is embedded if (gfg) { // The page is in an iFrame document.write("The page is in an iFrame"); } else { // The page is not in an iFrame document.write("The page is not in an iFrame"); }} // Calling iniFrame functioniniFrame();</script>Output:The page is in an iFrameIn the above code, store the element in which the webpage is embedded to the variable gfg. If the window isn’t embedded into another document, or if the document into which it’s embedded has a different origin (such as having been located from a different domain), gfg is null. <script>function iniFrame() { var gfg = window.frameElement; // Checking if webpage is embedded if (gfg) { // The page is in an iFrame document.write("The page is in an iFrame"); } else { // The page is not in an iFrame document.write("The page is not in an iFrame"); }} // Calling iniFrame functioniniFrame();</script> Output: The page is in an iFrame In the above code, store the element in which the webpage is embedded to the variable gfg. If the window isn’t embedded into another document, or if the document into which it’s embedded has a different origin (such as having been located from a different domain), gfg is null. JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25707, "s": 25679, "text": "\n25 Apr, 2019" }, { "code": null, "e": 25903, "s": 25707, "text": "An iFrame is a rectangular frame or region in the webpage to load or display another separate webpage or document inside it. So basically, an iFrame is used to display a webpage within a webpage." }, { "code": null, "e": 25954, "s": 25903, "text": "You can see more about iFrames here : HTML iFrames" }, { "code": null, "e": 26136, "s": 25954, "text": "There may be a variety of reasons for checking whether a webpage is loaded in an iFrame, for example, in cases where we need to dynamically adjust the height or width of an element." }, { "code": null, "e": 26787, "s": 26136, "text": "Comparing the object’s location with the window object’s parent location: Here, we simply compare the object’s location with the window object’s parent location. If the result is true, then the webpage is in an iFrame. If it is false, then it is not in an iFrame.<script>function iniFrame() { if ( window.location !== window.parent.location ) { // The page is in an iFrames document.write(\"The page is in an iFrame\"); } else { // The page is not in an iFrame document.write(\"The page is not in an iFrame\"); }} // Calling iniFrame functioniniFrame();</script>Output:The page is in an iFrame" }, { "code": "<script>function iniFrame() { if ( window.location !== window.parent.location ) { // The page is in an iFrames document.write(\"The page is in an iFrame\"); } else { // The page is not in an iFrame document.write(\"The page is not in an iFrame\"); }} // Calling iniFrame functioniniFrame();</script>", "e": 27144, "s": 26787, "text": null }, { "code": null, "e": 27152, "s": 27144, "text": "Output:" }, { "code": null, "e": 27177, "s": 27152, "text": "The page is in an iFrame" }, { "code": null, "e": 27774, "s": 27177, "text": "Using window.top and window.self property: The top and self are both window objects, along with parent, so check if the current window is the top/main window.<script> // Function to check whether webpage is in iFramefunction iniFrame() { if(window.self !== window.top) { // !== operator checks whether the operands // are of not equal value or not equal type document.write(\"The page is in an iFrame\"); } else { document.write(\"The page is in an iFrame\"); }} // Calling iniFrame functioniniFrame();</script>Output:The page is in an iFrame" }, { "code": "<script> // Function to check whether webpage is in iFramefunction iniFrame() { if(window.self !== window.top) { // !== operator checks whether the operands // are of not equal value or not equal type document.write(\"The page is in an iFrame\"); } else { document.write(\"The page is in an iFrame\"); }} // Calling iniFrame functioniniFrame();</script>", "e": 28182, "s": 27774, "text": null }, { "code": null, "e": 28190, "s": 28182, "text": "Output:" }, { "code": null, "e": 28215, "s": 28190, "text": "The page is in an iFrame" }, { "code": null, "e": 29183, "s": 28215, "text": "Using the window.frameElement property: Note that this only supports webpages belonging to the same origin as the main page in which it is embedded. The function window.frameElement returns the element (like iframe and object) in which the webpage is embedded.<script>function iniFrame() { var gfg = window.frameElement; // Checking if webpage is embedded if (gfg) { // The page is in an iFrame document.write(\"The page is in an iFrame\"); } else { // The page is not in an iFrame document.write(\"The page is not in an iFrame\"); }} // Calling iniFrame functioniniFrame();</script>Output:The page is in an iFrameIn the above code, store the element in which the webpage is embedded to the variable gfg. If the window isn’t embedded into another document, or if the document into which it’s embedded has a different origin (such as having been located from a different domain), gfg is null." }, { "code": "<script>function iniFrame() { var gfg = window.frameElement; // Checking if webpage is embedded if (gfg) { // The page is in an iFrame document.write(\"The page is in an iFrame\"); } else { // The page is not in an iFrame document.write(\"The page is not in an iFrame\"); }} // Calling iniFrame functioniniFrame();</script>", "e": 29583, "s": 29183, "text": null }, { "code": null, "e": 29591, "s": 29583, "text": "Output:" }, { "code": null, "e": 29616, "s": 29591, "text": "The page is in an iFrame" }, { "code": null, "e": 29894, "s": 29616, "text": "In the above code, store the element in which the webpage is embedded to the variable gfg. If the window isn’t embedded into another document, or if the document into which it’s embedded has a different origin (such as having been located from a different domain), gfg is null." }, { "code": null, "e": 29910, "s": 29894, "text": "JavaScript-Misc" }, { "code": null, "e": 29917, "s": 29910, "text": "Picked" }, { "code": null, "e": 29928, "s": 29917, "text": "JavaScript" }, { "code": null, "e": 29945, "s": 29928, "text": "Web Technologies" }, { "code": null, "e": 29972, "s": 29945, "text": "Web technologies Questions" }, { "code": null, "e": 30070, "s": 29972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30110, "s": 30070, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30155, "s": 30110, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30216, "s": 30155, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30288, "s": 30216, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30340, "s": 30288, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 30380, "s": 30340, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30413, "s": 30380, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30458, "s": 30413, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30501, "s": 30458, "text": "How to fetch data from an API in ReactJS ?" } ]
Flutter - Difference Between setState and Provider in State Management - GeeksforGeeks
19 Apr, 2021 In this article, we will look into how we can use state management or provider package for implementing state management in our flutter app. We are creating a simple counter app in flutter, which will help us in understanding state management in flutter application and deciding which is a better way to build our app and complete the project. We will be discussing the two of the most important aspect required for understanding state management in the flutter app, called as setState and a package named provider. We will begin with our basic flutter structure available by default. Create a stateless widget named Home Page and assign it to our home property of Material App. Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Material App', home: HomePage() ); }} Inside the ‘Home Page‘ screen, we will make it a stateful widget, and it will be consisting of two buttons that will have the functionality of increasing and decreasing counter using set state functionality. And a floating action button that will navigate us to the second screen of our app, where will again keep the track of our variable itemCount. Dart class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { int itemCount = 0 ; @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.forward), onPressed: (){ Navigator.push(context, MaterialPageRoute(builder: (_){ return SecondPage( count: itemCount, ); })); }, ), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('$itemCount',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ setState(() { itemCount++ ; }); }, child: Text('Add')), ElevatedButton(onPressed: (){ setState(() { itemCount-- ; }); }, child: Text('Delete')) ], ) ], ), ); }} Inside the second screen, we will again have the buttons for the increasing and decreasing counter. with the help of set State functionality It will be a stateful widget. Dart class SecondPage extends StatefulWidget { int count ; SecondPage({this.count}) ; @override _SecondPageState createState() => _SecondPageState();} class _SecondPageState extends State<SecondPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('${widget.count}',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ setState(() { widget.count++ ; }); }, child: Text('Add')), ElevatedButton(onPressed: (){ setState(() { widget.count-- ; }); }, child: Text('Delete')) ], ) ], ), ); }} On successfully running our code we can see that we do not get our desired outcome. The counter variable is not getting its correct value. Output So to overcome this issue and to make better functionalities inside our app we will use the provider package. It is of great use when we have to deal with a multi-screen app where our data is changing dynamically, provider provides us a better facility of keeping our data to be updated with every function of our app. First import provider dependency inside pubspec.yaml file in our flutter app. Now create a class in another file extend this class to Change Notifier. This class will contain functionalities of increase and decrease the counter variable. Do not forget to include notify Listeners to our function else it will not work properly. Also, create a getter that will return the count variable. Dart import 'package:flutter/material.dart'; class Manage extends ChangeNotifier{ int count = 0 ; int get counter{ return count ; } void increaseCounter(){ count++ ; notifyListeners(); } void decreaseCounter(){ count-- ; notifyListeners(); }} To make our app aware and know about the providers we have to add something to our Material App inside main.dart. Wrap our Material App. Inside MultiProvider feature and inside it add our class to providers option of Multi Provider. Dart class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider.value(value: Manage()) ], child: MaterialApp( home: HomePage(), ), ); }} Now the remaining and final task is to update something in our home page screen so that it can listen to our provider. First, make the home page a stateless widget. Dart class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { int itemCount = Provider.of<Manage>(context).counter; return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.forward), onPressed: (){ Navigator.push(context, MaterialPageRoute(builder: (_){ return SecondPage(); })); }, ), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('$itemCount',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen:false).increaseCounter(); }, child: Text('Add')), ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen:false).decreaseCounter(); }, child: Text('Delete')) ], ) ], ), ); }} Ensure to make the value of listen argument to be false inside the provider used to call the functions. We will make it true only when we have to use the value or listen to the value in our app screen. (Like the value of itemCount) Similarly, we can update our Second Page widget accordingly.Convert it to a stateless widget Dart class SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { int itemCount = Provider.of<Manage>(context).counter ; return Scaffold( appBar: AppBar(), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('$itemCount',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen: false).increaseCounter(); }, child: Text('Add')), ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen: false).decreaseCounter(); }, child: Text('Delete')) ], ) ], ), ); }} Output Hence we can see that provider does our job pretty well and is easy to use. Flutter Dart Difference Between Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Android Studio Setup for Flutter Development Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Differences between IPv4 and IPv6
[ { "code": null, "e": 25261, "s": 25233, "text": "\n19 Apr, 2021" }, { "code": null, "e": 25403, "s": 25261, "text": "In this article, we will look into how we can use state management or provider package for implementing state management in our flutter app. " }, { "code": null, "e": 25606, "s": 25403, "text": "We are creating a simple counter app in flutter, which will help us in understanding state management in flutter application and deciding which is a better way to build our app and complete the project." }, { "code": null, "e": 25778, "s": 25606, "text": "We will be discussing the two of the most important aspect required for understanding state management in the flutter app, called as setState and a package named provider." }, { "code": null, "e": 25941, "s": 25778, "text": "We will begin with our basic flutter structure available by default. Create a stateless widget named Home Page and assign it to our home property of Material App." }, { "code": null, "e": 25946, "s": 25941, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Material App', home: HomePage() ); }}", "e": 26197, "s": 25946, "text": null }, { "code": null, "e": 26548, "s": 26197, "text": "Inside the ‘Home Page‘ screen, we will make it a stateful widget, and it will be consisting of two buttons that will have the functionality of increasing and decreasing counter using set state functionality. And a floating action button that will navigate us to the second screen of our app, where will again keep the track of our variable itemCount." }, { "code": null, "e": 26553, "s": 26548, "text": "Dart" }, { "code": "class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { int itemCount = 0 ; @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.forward), onPressed: (){ Navigator.push(context, MaterialPageRoute(builder: (_){ return SecondPage( count: itemCount, ); })); }, ), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('$itemCount',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ setState(() { itemCount++ ; }); }, child: Text('Add')), ElevatedButton(onPressed: (){ setState(() { itemCount-- ; }); }, child: Text('Delete')) ], ) ], ), ); }}", "e": 27754, "s": 26553, "text": null }, { "code": null, "e": 27897, "s": 27754, "text": "Inside the second screen, we will again have the buttons for the increasing and decreasing counter. with the help of set State functionality " }, { "code": null, "e": 27927, "s": 27897, "text": "It will be a stateful widget." }, { "code": null, "e": 27932, "s": 27927, "text": "Dart" }, { "code": "class SecondPage extends StatefulWidget { int count ; SecondPage({this.count}) ; @override _SecondPageState createState() => _SecondPageState();} class _SecondPageState extends State<SecondPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('${widget.count}',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ setState(() { widget.count++ ; }); }, child: Text('Add')), ElevatedButton(onPressed: (){ setState(() { widget.count-- ; }); }, child: Text('Delete')) ], ) ], ), ); }}", "e": 28917, "s": 27932, "text": null }, { "code": null, "e": 29056, "s": 28917, "text": "On successfully running our code we can see that we do not get our desired outcome. The counter variable is not getting its correct value." }, { "code": null, "e": 29064, "s": 29056, "text": "Output " }, { "code": null, "e": 29384, "s": 29064, "text": "So to overcome this issue and to make better functionalities inside our app we will use the provider package. It is of great use when we have to deal with a multi-screen app where our data is changing dynamically, provider provides us a better facility of keeping our data to be updated with every function of our app. " }, { "code": null, "e": 29463, "s": 29384, "text": "First import provider dependency inside pubspec.yaml file in our flutter app. " }, { "code": null, "e": 29773, "s": 29463, "text": "Now create a class in another file extend this class to Change Notifier. This class will contain functionalities of increase and decrease the counter variable. Do not forget to include notify Listeners to our function else it will not work properly. Also, create a getter that will return the count variable. " }, { "code": null, "e": 29778, "s": 29773, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; class Manage extends ChangeNotifier{ int count = 0 ; int get counter{ return count ; } void increaseCounter(){ count++ ; notifyListeners(); } void decreaseCounter(){ count-- ; notifyListeners(); }}", "e": 30076, "s": 29778, "text": null }, { "code": null, "e": 30311, "s": 30076, "text": "To make our app aware and know about the providers we have to add something to our Material App inside main.dart. Wrap our Material App. Inside MultiProvider feature and inside it add our class to providers option of Multi Provider. " }, { "code": null, "e": 30316, "s": 30311, "text": "Dart" }, { "code": "class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider.value(value: Manage()) ], child: MaterialApp( home: HomePage(), ), ); }}", "e": 30579, "s": 30316, "text": null }, { "code": null, "e": 30699, "s": 30579, "text": "Now the remaining and final task is to update something in our home page screen so that it can listen to our provider. " }, { "code": null, "e": 30746, "s": 30699, "text": "First, make the home page a stateless widget. " }, { "code": null, "e": 30751, "s": 30746, "text": "Dart" }, { "code": "class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { int itemCount = Provider.of<Manage>(context).counter; return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.forward), onPressed: (){ Navigator.push(context, MaterialPageRoute(builder: (_){ return SecondPage(); })); }, ), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('$itemCount',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen:false).increaseCounter(); }, child: Text('Add')), ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen:false).decreaseCounter(); }, child: Text('Delete')) ], ) ], ), ); }}", "e": 31832, "s": 30751, "text": null }, { "code": null, "e": 32065, "s": 31832, "text": "Ensure to make the value of listen argument to be false inside the provider used to call the functions. We will make it true only when we have to use the value or listen to the value in our app screen. (Like the value of itemCount)" }, { "code": null, "e": 32159, "s": 32065, "text": "Similarly, we can update our Second Page widget accordingly.Convert it to a stateless widget " }, { "code": null, "e": 32164, "s": 32159, "text": "Dart" }, { "code": "class SecondPage extends StatelessWidget { @override Widget build(BuildContext context) { int itemCount = Provider.of<Manage>(context).counter ; return Scaffold( appBar: AppBar(), body: Column( children: [ Container( alignment: Alignment.center, height: 300.0, child: Text('$itemCount',style: TextStyle(fontSize: 30.0)), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen: false).increaseCounter(); }, child: Text('Add')), ElevatedButton(onPressed: (){ Provider.of<Manage>(context,listen: false).decreaseCounter(); }, child: Text('Delete')) ], ) ], ), ); }}", "e": 33032, "s": 32164, "text": null }, { "code": null, "e": 33040, "s": 33032, "text": "Output " }, { "code": null, "e": 33117, "s": 33040, "text": "Hence we can see that provider does our job pretty well and is easy to use. " }, { "code": null, "e": 33125, "s": 33117, "text": "Flutter" }, { "code": null, "e": 33130, "s": 33125, "text": "Dart" }, { "code": null, "e": 33149, "s": 33130, "text": "Difference Between" }, { "code": null, "e": 33157, "s": 33149, "text": "Flutter" }, { "code": null, "e": 33255, "s": 33157, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33294, "s": 33255, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 33320, "s": 33294, "text": "ListView Class in Flutter" }, { "code": null, "e": 33346, "s": 33320, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 33369, "s": 33346, "text": "Flutter - Stack Widget" }, { "code": null, "e": 33414, "s": 33369, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 33445, "s": 33414, "text": "Difference between BFS and DFS" }, { "code": null, "e": 33485, "s": 33445, "text": "Class method vs Static method in Python" }, { "code": null, "e": 33517, "s": 33485, "text": "Differences between TCP and UDP" }, { "code": null, "e": 33578, "s": 33517, "text": "Difference between var, let and const keywords in JavaScript" } ]
C program to Find the Largest Number Among Three Numbers - GeeksforGeeks
26 Dec, 2018 Given three numbers A, B and C; The task is to find the largest number among the three. Examples: Input: A = 2, B = 8, C = 1 Output: Largest number = 8 Input: A = 231, B = 4751, C = 75821 Output: Largest number = 75821 In the below programs, to find the largest of the three number, , , and ‘s are used. Algorithm to find the largest of three numbers: 1. Start 2. Read the three numbers to be compared, as A, B and C. 3. Check if A is greater than B. 3.1 If true, then check if A is greater than C. 3.1.1 If true, print 'A' as the greatest number. 3.1.2 If false, print 'C' as the greatest number. 3.2 If false, then check if B is greater than C. 3.1.1 If true, print 'B' as the greatest number. 3.1.2 If false, print 'C' as the greatest number. 4. End FlowChart to find the largest of three numbers: Below is the C program to find the largest among the three numbers: Example 1: Using only if statements to find the largest number. #include <stdio.h> int main(){ int A, B, C; printf("Enter the numbers A, B and C: "); scanf("%d %d %d", &A, &B, &C); if (A >= B && A >= C) printf("%d is the largest number.", A); if (B >= A && B >= C) printf("%d is the largest number.", B); if (C >= A && C >= B) printf("%d is the largest number.", C); return 0;} Output: Enter the numbers A, B and C: 2 8 1 8 is the largest number. Example 2: Using if-else statement to find the largest number. #include <stdio.h>int main(){ int A, B, C; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); if (A >= B) { if (A >= C) printf("%d is the largest number.", A); else printf("%d is the largest number.", C); } else { if (B >= C) printf("%d is the largest number.", B); else printf("%d is the largest number.", C); } return 0;} Output: Enter the numbers A, B and C: 2 8 1 8 is the largest number. Example 3: Using nested if-else statements to find the largest number. #include <stdio.h>int main(){ int A, B, C; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); if (A >= B && A >= C) printf("%d is the largest number.", A); else if (B >= A && B >= C) printf("%d is the largest number.", B); else printf("%d is the largest number.", C); return 0;} Output: Enter the numbers A, B and C: 2 8 1 8 is the largest number. Example 4: Using Ternary operator to find the largest number. #include <stdio.h>int main(){ int A, B, C, largest; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); largest = A > B ? (A > C ? A : C) : (B > C ? B : C); printf("%d is the largest number.", largest); return 0;} Output: Enter the numbers A, B and C: 2 8 1 8 is the largest number. RishabhPrabhu C Language C Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Converting Strings to Numbers in C/C++ Function Pointer in C Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File Header files in C/C++ and its uses Basics of File Handling in C
[ { "code": null, "e": 26143, "s": 26115, "text": "\n26 Dec, 2018" }, { "code": null, "e": 26231, "s": 26143, "text": "Given three numbers A, B and C; The task is to find the largest number among the three." }, { "code": null, "e": 26241, "s": 26231, "text": "Examples:" }, { "code": null, "e": 26364, "s": 26241, "text": "Input: A = 2, B = 8, C = 1\nOutput: Largest number = 8\n\nInput: A = 231, B = 4751, C = 75821\nOutput: Largest number = 75821\n" }, { "code": null, "e": 26450, "s": 26364, "text": "In the below programs, to find the largest of the three number, , , and ‘s are used." }, { "code": null, "e": 26498, "s": 26450, "text": "Algorithm to find the largest of three numbers:" }, { "code": null, "e": 26922, "s": 26498, "text": "1. Start\n2. Read the three numbers to be compared, as A, B and C.\n3. Check if A is greater than B.\n\n 3.1 If true, then check if A is greater than C.\n 3.1.1 If true, print 'A' as the greatest number.\n 3.1.2 If false, print 'C' as the greatest number.\n\n 3.2 If false, then check if B is greater than C.\n 3.1.1 If true, print 'B' as the greatest number.\n 3.1.2 If false, print 'C' as the greatest number.\n4. End\n" }, { "code": null, "e": 26970, "s": 26922, "text": "FlowChart to find the largest of three numbers:" }, { "code": null, "e": 27038, "s": 26970, "text": "Below is the C program to find the largest among the three numbers:" }, { "code": null, "e": 27102, "s": 27038, "text": "Example 1: Using only if statements to find the largest number." }, { "code": "#include <stdio.h> int main(){ int A, B, C; printf(\"Enter the numbers A, B and C: \"); scanf(\"%d %d %d\", &A, &B, &C); if (A >= B && A >= C) printf(\"%d is the largest number.\", A); if (B >= A && B >= C) printf(\"%d is the largest number.\", B); if (C >= A && C >= B) printf(\"%d is the largest number.\", C); return 0;}", "e": 27469, "s": 27102, "text": null }, { "code": null, "e": 27477, "s": 27469, "text": "Output:" }, { "code": null, "e": 27540, "s": 27477, "text": "Enter the numbers A, B and C: 2 8 1 \n8 is the largest number.\n" }, { "code": null, "e": 27603, "s": 27540, "text": "Example 2: Using if-else statement to find the largest number." }, { "code": "#include <stdio.h>int main(){ int A, B, C; printf(\"Enter three numbers: \"); scanf(\"%d %d %d\", &A, &B, &C); if (A >= B) { if (A >= C) printf(\"%d is the largest number.\", A); else printf(\"%d is the largest number.\", C); } else { if (B >= C) printf(\"%d is the largest number.\", B); else printf(\"%d is the largest number.\", C); } return 0;}", "e": 28042, "s": 27603, "text": null }, { "code": null, "e": 28050, "s": 28042, "text": "Output:" }, { "code": null, "e": 28113, "s": 28050, "text": "Enter the numbers A, B and C: 2 8 1 \n8 is the largest number.\n" }, { "code": null, "e": 28184, "s": 28113, "text": "Example 3: Using nested if-else statements to find the largest number." }, { "code": "#include <stdio.h>int main(){ int A, B, C; printf(\"Enter three numbers: \"); scanf(\"%d %d %d\", &A, &B, &C); if (A >= B && A >= C) printf(\"%d is the largest number.\", A); else if (B >= A && B >= C) printf(\"%d is the largest number.\", B); else printf(\"%d is the largest number.\", C); return 0;}", "e": 28528, "s": 28184, "text": null }, { "code": null, "e": 28536, "s": 28528, "text": "Output:" }, { "code": null, "e": 28599, "s": 28536, "text": "Enter the numbers A, B and C: 2 8 1 \n8 is the largest number.\n" }, { "code": null, "e": 28661, "s": 28599, "text": "Example 4: Using Ternary operator to find the largest number." }, { "code": "#include <stdio.h>int main(){ int A, B, C, largest; printf(\"Enter three numbers: \"); scanf(\"%d %d %d\", &A, &B, &C); largest = A > B ? (A > C ? A : C) : (B > C ? B : C); printf(\"%d is the largest number.\", largest); return 0;}", "e": 28913, "s": 28661, "text": null }, { "code": null, "e": 28921, "s": 28913, "text": "Output:" }, { "code": null, "e": 28984, "s": 28921, "text": "Enter the numbers A, B and C: 2 8 1 \n8 is the largest number.\n" }, { "code": null, "e": 28998, "s": 28984, "text": "RishabhPrabhu" }, { "code": null, "e": 29009, "s": 28998, "text": "C Language" }, { "code": null, "e": 29020, "s": 29009, "text": "C Programs" }, { "code": null, "e": 29039, "s": 29020, "text": "School Programming" }, { "code": null, "e": 29137, "s": 29039, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29154, "s": 29137, "text": "Substring in C++" }, { "code": null, "e": 29189, "s": 29154, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 29235, "s": 29189, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 29274, "s": 29235, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 29296, "s": 29274, "text": "Function Pointer in C" }, { "code": null, "e": 29309, "s": 29296, "text": "Strings in C" }, { "code": null, "e": 29350, "s": 29309, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 29391, "s": 29350, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29426, "s": 29391, "text": "Header files in C/C++ and its uses" } ]
PHP | Spreadsheet_Excel_Writer | Close() Function - GeeksforGeeks
04 Oct, 2021 The close() function is an inbuilt function in PHP | Spreadsheet_Excel_Writer which is used to finalize the spreadsheet after which all the operations are done. This method should always be the last one to be called on every workbook. Syntax: mixed Workbook::close() Parameters: This function does not accept any parameter.Return Value: This function returns TRUE on success and PEAR_ERROR on failure. Example 1: PHP <?php require_once 'Spreadsheet/Excel/Writer.php'; // Add Workbook$workbook = new Spreadsheet_Excel_Writer(); // Add Format to spreadsheet$format_bold =& $workbook->addFormat(); // Set Bold Format$format_bold->setBold(); // Add Worksheet to Spreadsheet$worksheet =& $workbook->addWorksheet(); $format_bold->setBorder(2); // Write to Worksheet$worksheet->write(0, 0, "Details of GeeksforGeeks Contributors", $format_bold);$worksheet->write(1, 0, "Author", $format_bold);$worksheet->write(1, 1, "User Handle", $format_bold);$worksheet->write(2, 0, "Sarthak");$worksheet->write(2, 1, "sarthak_ishu11"); // Send .xlsx file to header$workbook->send('test.xls'); // Close Workbook Object$workbook->close();?> Output: Example 2: PHP <?php require_once 'Spreadsheet/Excel/Writer.php'; // Add Workbook$workbook = new Spreadsheet_Excel_Writer(); // Add Format to spreadsheet$format_border =& $workbook->addFormat(); // Add Worksheet to Spreadsheet$worksheet =& $workbook->addWorksheet(); // Set and Add Border Width$format_border->setBorder(2); // Set and Add Color to Border$format_border->setBorderColor('red'); // Write to Worksheet$worksheet->write(0, 0, "Details of GeeksforGeeks Contributors", $format_bold);$worksheet->write(1, 0, "Author", $format_border);$worksheet->write(1, 1, "User Handle", $format_border);$worksheet->write(2, 0, "Sarthak");$worksheet->write(2, 1, "sarthak_ishu11"); // Send .xlsx file to header$workbook->send('test.xls'); // Close Workbook Object$workbook->close();?> Output: Reference: https://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.spreadsheet-excel-writer-workbook.close.php sooda367 PHP-function PHP-Spreadsheet PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? PHP str_replace() Function How to pass form variables from one page to other page in PHP ? Different ways for passing data to view in Laravel Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26243, "s": 26215, "text": "\n04 Oct, 2021" }, { "code": null, "e": 26478, "s": 26243, "text": "The close() function is an inbuilt function in PHP | Spreadsheet_Excel_Writer which is used to finalize the spreadsheet after which all the operations are done. This method should always be the last one to be called on every workbook." }, { "code": null, "e": 26487, "s": 26478, "text": "Syntax: " }, { "code": null, "e": 26511, "s": 26487, "text": "mixed Workbook::close()" }, { "code": null, "e": 26646, "s": 26511, "text": "Parameters: This function does not accept any parameter.Return Value: This function returns TRUE on success and PEAR_ERROR on failure." }, { "code": null, "e": 26659, "s": 26646, "text": "Example 1: " }, { "code": null, "e": 26663, "s": 26659, "text": "PHP" }, { "code": "<?php require_once 'Spreadsheet/Excel/Writer.php'; // Add Workbook$workbook = new Spreadsheet_Excel_Writer(); // Add Format to spreadsheet$format_bold =& $workbook->addFormat(); // Set Bold Format$format_bold->setBold(); // Add Worksheet to Spreadsheet$worksheet =& $workbook->addWorksheet(); $format_bold->setBorder(2); // Write to Worksheet$worksheet->write(0, 0, \"Details of GeeksforGeeks Contributors\", $format_bold);$worksheet->write(1, 0, \"Author\", $format_bold);$worksheet->write(1, 1, \"User Handle\", $format_bold);$worksheet->write(2, 0, \"Sarthak\");$worksheet->write(2, 1, \"sarthak_ishu11\"); // Send .xlsx file to header$workbook->send('test.xls'); // Close Workbook Object$workbook->close();?>", "e": 27384, "s": 26663, "text": null }, { "code": null, "e": 27393, "s": 27384, "text": "Output: " }, { "code": null, "e": 27406, "s": 27393, "text": "Example 2: " }, { "code": null, "e": 27410, "s": 27406, "text": "PHP" }, { "code": "<?php require_once 'Spreadsheet/Excel/Writer.php'; // Add Workbook$workbook = new Spreadsheet_Excel_Writer(); // Add Format to spreadsheet$format_border =& $workbook->addFormat(); // Add Worksheet to Spreadsheet$worksheet =& $workbook->addWorksheet(); // Set and Add Border Width$format_border->setBorder(2); // Set and Add Color to Border$format_border->setBorderColor('red'); // Write to Worksheet$worksheet->write(0, 0, \"Details of GeeksforGeeks Contributors\", $format_bold);$worksheet->write(1, 0, \"Author\", $format_border);$worksheet->write(1, 1, \"User Handle\", $format_border);$worksheet->write(2, 0, \"Sarthak\");$worksheet->write(2, 1, \"sarthak_ishu11\"); // Send .xlsx file to header$workbook->send('test.xls'); // Close Workbook Object$workbook->close();?>", "e": 28194, "s": 27410, "text": null }, { "code": null, "e": 28203, "s": 28194, "text": "Output: " }, { "code": null, "e": 28335, "s": 28203, "text": "Reference: https://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.spreadsheet-excel-writer-workbook.close.php " }, { "code": null, "e": 28344, "s": 28335, "text": "sooda367" }, { "code": null, "e": 28357, "s": 28344, "text": "PHP-function" }, { "code": null, "e": 28373, "s": 28357, "text": "PHP-Spreadsheet" }, { "code": null, "e": 28377, "s": 28373, "text": "PHP" }, { "code": null, "e": 28394, "s": 28377, "text": "Web Technologies" }, { "code": null, "e": 28398, "s": 28394, "text": "PHP" }, { "code": null, "e": 28496, "s": 28398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28578, "s": 28496, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28620, "s": 28578, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 28647, "s": 28620, "text": "PHP str_replace() Function" }, { "code": null, "e": 28711, "s": 28647, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 28762, "s": 28711, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 28802, "s": 28762, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28835, "s": 28802, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28880, "s": 28835, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28923, "s": 28880, "text": "How to fetch data from an API in ReactJS ?" } ]
Split Vector into Chunks in R - GeeksforGeeks
23 Sep, 2021 In this article, we will discuss how to split vectors into chunks in R programming language. In this scenario, a chuck length is specified, so that we can divide the vector using the split() function. Syntax: split(vector, ceiling(seq_along(vector) / chunk_length)) where, vector is the input vector split() function is used to split the vector ceiling() is the function that takes two parameters one parameter that is vector with sequence along to divide the vector sequentially and second is chunklength, which represents the length of chunk to be divided Example: R program to divide the vector into chunks with length R # create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk length as 2chunklength=2 # split the vector by lengthprint(split(vector,ceiling(seq_along(vector) / chunklength))) Output: Example: R program to divide the vector into chunks with length R # create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk length as 5chunklength=5 # split the vector by lengthprint(split(vector,ceiling(seq_along(vector) / chunklength))) Output: In this scenario, the number of chunks is to be provided, so that we can divide the vector using the split() function. Syntax: split(vector, cut(seq_along(vector), chunk_number, labels = FALSE) where, vector is the input vector split() function is used to split the vector cut() is the function that takes three parameters one parameter that is a vector with sequence along to divide the vector sequentially, second is the chunk number that is for number of chunks to be divided and the last is for labels to specify the chunks range Note: If the label is FALSE, it will not display the chunk size. If labels are not specified, it will display labels Example: R program to divide the vector into chunks using chunk number R # create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk number as 5chunk_no=5 # split the vector by chunk number by specifying # labels as FALSEprint(split(vector, cut(seq_along(vector),chunk_no,labels = FALSE))) Output: Example: R program to divide the vector into chunks using chunk number R # create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk number as 2chunkno=2 # split the vector by chunk number by # unspecifying labels print(split(vector, cut(seq_along(vector),chunkno))) Output: Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 Sep, 2021" }, { "code": null, "e": 26580, "s": 26487, "text": "In this article, we will discuss how to split vectors into chunks in R programming language." }, { "code": null, "e": 26688, "s": 26580, "text": "In this scenario, a chuck length is specified, so that we can divide the vector using the split() function." }, { "code": null, "e": 26696, "s": 26688, "text": "Syntax:" }, { "code": null, "e": 26755, "s": 26696, "text": "split(vector, ceiling(seq_along(vector) / chunk_length))" }, { "code": null, "e": 26762, "s": 26755, "text": "where," }, { "code": null, "e": 26789, "s": 26762, "text": "vector is the input vector" }, { "code": null, "e": 26834, "s": 26789, "text": "split() function is used to split the vector" }, { "code": null, "e": 27047, "s": 26834, "text": "ceiling() is the function that takes two parameters one parameter that is vector with sequence along to divide the vector sequentially and second is chunklength, which represents the length of chunk to be divided" }, { "code": null, "e": 27111, "s": 27047, "text": "Example: R program to divide the vector into chunks with length" }, { "code": null, "e": 27113, "s": 27111, "text": "R" }, { "code": "# create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk length as 2chunklength=2 # split the vector by lengthprint(split(vector,ceiling(seq_along(vector) / chunklength)))", "e": 27315, "s": 27113, "text": null }, { "code": null, "e": 27323, "s": 27315, "text": "Output:" }, { "code": null, "e": 27387, "s": 27323, "text": "Example: R program to divide the vector into chunks with length" }, { "code": null, "e": 27389, "s": 27387, "text": "R" }, { "code": "# create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk length as 5chunklength=5 # split the vector by lengthprint(split(vector,ceiling(seq_along(vector) / chunklength)))", "e": 27591, "s": 27389, "text": null }, { "code": null, "e": 27599, "s": 27591, "text": "Output:" }, { "code": null, "e": 27718, "s": 27599, "text": "In this scenario, the number of chunks is to be provided, so that we can divide the vector using the split() function." }, { "code": null, "e": 27726, "s": 27718, "text": "Syntax:" }, { "code": null, "e": 27794, "s": 27726, "text": "split(vector, cut(seq_along(vector), chunk_number, labels = FALSE)" }, { "code": null, "e": 27801, "s": 27794, "text": "where," }, { "code": null, "e": 27828, "s": 27801, "text": "vector is the input vector" }, { "code": null, "e": 27873, "s": 27828, "text": "split() function is used to split the vector" }, { "code": null, "e": 28134, "s": 27873, "text": "cut() is the function that takes three parameters one parameter that is a vector with sequence along to divide the vector sequentially, second is the chunk number that is for number of chunks to be divided and the last is for labels to specify the chunks range" }, { "code": null, "e": 28140, "s": 28134, "text": "Note:" }, { "code": null, "e": 28199, "s": 28140, "text": "If the label is FALSE, it will not display the chunk size." }, { "code": null, "e": 28251, "s": 28199, "text": "If labels are not specified, it will display labels" }, { "code": null, "e": 28322, "s": 28251, "text": "Example: R program to divide the vector into chunks using chunk number" }, { "code": null, "e": 28324, "s": 28322, "text": "R" }, { "code": "# create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk number as 5chunk_no=5 # split the vector by chunk number by specifying # labels as FALSEprint(split(vector, cut(seq_along(vector),chunk_no,labels = FALSE)))", "e": 28568, "s": 28324, "text": null }, { "code": null, "e": 28576, "s": 28568, "text": "Output:" }, { "code": null, "e": 28647, "s": 28576, "text": "Example: R program to divide the vector into chunks using chunk number" }, { "code": null, "e": 28649, "s": 28647, "text": "R" }, { "code": "# create a vector with 10 elementsvector=c(1,2,3,4,5,6,7,8,9,10) # specify the chunk number as 2chunkno=2 # split the vector by chunk number by # unspecifying labels print(split(vector, cut(seq_along(vector),chunkno)))", "e": 28870, "s": 28649, "text": null }, { "code": null, "e": 28878, "s": 28870, "text": "Output:" }, { "code": null, "e": 28885, "s": 28878, "text": "Picked" }, { "code": null, "e": 28903, "s": 28885, "text": "R Vector-Programs" }, { "code": null, "e": 28913, "s": 28903, "text": "R-Vectors" }, { "code": null, "e": 28924, "s": 28913, "text": "R Language" }, { "code": null, "e": 28935, "s": 28924, "text": "R Programs" }, { "code": null, "e": 29033, "s": 28935, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29085, "s": 29033, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29120, "s": 29085, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29158, "s": 29120, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29216, "s": 29158, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29259, "s": 29216, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29317, "s": 29259, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29360, "s": 29317, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29409, "s": 29360, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29459, "s": 29409, "text": "How to filter R dataframe by multiple conditions?" } ]
Working with CSV files in R Programming - GeeksforGeeks
10 May, 2020 CSV files are basically the text files wherein the values of each row are separated by a delimiter, as in a comma or a tab. In this article, we will use the following sample CSV file:sample.csv id, name, department, salary, projects 1, A, IT, 60754, 4 2, B, Tech, 59640, 2 3, C, Marketing, 69040, 8 4, D, Marketing, 65043, 5 5, E, Tech, 59943, 2 6, F, IT, 65000, 5 7, G, HR, 69000, 7 The contents of a CSV file can be read as a data frame in R using the read.csv(...) function. The CSV file to be read should be either present in the current working directory or the directory should be set accordingly using the setwd(...) command in R. The CSV file can also be read from a URL using read.csv() function. Examples: csv_data <- read.csv(file = 'sample.csv')print(csv_data) # print number of columnsprint (ncol(csv_data)) # print number of rowsprint(nrow(csv_data)) Output: id, name, department, salary, projects 1 1 A HR 60754 14 2 2 B Tech 59640 3 3 3 C Marketing 69040 8 4 4 D HR 65043 5 5 5 E Tech 59943 2 6 6 F IT 65000 5 7 7 G HR 69000 7 [1] 4 [1] 7 The header is by default set to a TRUE value in the function. The head is not included in the count of rows, therefore this CSV has 7 rows and 4 columns. SQL queries can be performed on the CSV content, and the corresponding result can be retrieved using the subset(csv_data,) function in R. Multiple queries can be applied in the function at a time where each query is separated using a logical operator. The result is stored as a data frame in R. Examples: csv_data <- read.csv(file ='sample.csv')min_pro <- min(csv_data$projects)print (min_pro) Output: 2 Aggregator functions (min, max, count etc.) can be applied on the CSV data. Here the min() function is applied on projects column using $ symbol. The minimum number of projects which is 2 is returned. csv_data <- read.csv(file ='sample.csv')new_csv <- subset(csv_data, department == "HR" & projects <10)print (new_csv) Output: id, name, department, salary, projects 4 4 D HR 65043 5 7 7 G HR 69000 7 The subset of the data that is created is stored as a data frame satisfying the conditions specified as the arguments of the function. The employees D and G are HR and have the number of projects<10. The row numbers are retained in the resultant data frame. The contents of the data frame can be written into a CSV file. The CSV file is stored in the current working directory with the name specified in the function write.csv(data frame, output CSV name) in R. Examples: csv_data <- read.csv(file ='sample.csv')new_csv <- subset(csv_data, department == "HR" & projects <10)write.csv(new_csv, "new_sample.csv")new_data <-read.csv(file ='new_sample.csv')print(new_data) Output: X id, name, department, salary, projects 1 4 4 D HR 65043 5 2 7 7 G HR 69000 7 The column X contains the row numbers of the original CSV file. In order to remove it, we can specify an additional argument in the write.csv() function that set row names to FALSE. csv_data <- read.csv(file ='sample.csv')new_csv <- subset(csv_data, department == "HR" & projects <10)write.csv(new_csv, "new_sample.csv", row.names = FALSE)new_data <-read.csv(file ='new_sample.csv')print(new_data) Output: id, name, department, salary, projects 1 4 D HR 65043 5 2 7 G HR 69000 7 The original row numbers are removed from the new CSV. Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Convert Factor to Numeric and Numeric to Factor in R Programming Group by function in R using Dplyr How to Change Axis Scales in R Plots?
[ { "code": null, "e": 30289, "s": 30261, "text": "\n10 May, 2020" }, { "code": null, "e": 30483, "s": 30289, "text": "CSV files are basically the text files wherein the values of each row are separated by a delimiter, as in a comma or a tab. In this article, we will use the following sample CSV file:sample.csv" }, { "code": null, "e": 30761, "s": 30483, "text": "id, name, department, salary, projects\n1, A, IT, 60754, 4\n2, B, Tech, 59640, 2\n3, C, Marketing, 69040, 8\n4, D, Marketing, 65043, 5\n5, E, Tech, 59943, 2\n6, F, IT, 65000, 5\n7, G, HR, 69000, 7\n" }, { "code": null, "e": 31083, "s": 30761, "text": "The contents of a CSV file can be read as a data frame in R using the read.csv(...) function. The CSV file to be read should be either present in the current working directory or the directory should be set accordingly using the setwd(...) command in R. The CSV file can also be read from a URL using read.csv() function." }, { "code": null, "e": 31093, "s": 31083, "text": "Examples:" }, { "code": "csv_data <- read.csv(file = 'sample.csv')print(csv_data) # print number of columnsprint (ncol(csv_data)) # print number of rowsprint(nrow(csv_data)) ", "e": 31247, "s": 31093, "text": null }, { "code": null, "e": 31255, "s": 31247, "text": "Output:" }, { "code": null, "e": 31703, "s": 31255, "text": " id, name, department, salary, projects\n 1 1 A HR 60754 14\n 2 2 B Tech 59640 3\n 3 3 C Marketing 69040 8\n 4 4 D HR 65043 5\n 5 5 E Tech 59943 2 \n 6 6 F IT 65000 5\n 7 7 G HR 69000 7\n [1] 4\n [1] 7\n" }, { "code": null, "e": 31857, "s": 31703, "text": "The header is by default set to a TRUE value in the function. The head is not included in the count of rows, therefore this CSV has 7 rows and 4 columns." }, { "code": null, "e": 32152, "s": 31857, "text": "SQL queries can be performed on the CSV content, and the corresponding result can be retrieved using the subset(csv_data,) function in R. Multiple queries can be applied in the function at a time where each query is separated using a logical operator. The result is stored as a data frame in R." }, { "code": null, "e": 32162, "s": 32152, "text": "Examples:" }, { "code": "csv_data <- read.csv(file ='sample.csv')min_pro <- min(csv_data$projects)print (min_pro)", "e": 32251, "s": 32162, "text": null }, { "code": null, "e": 32259, "s": 32251, "text": "Output:" }, { "code": null, "e": 32261, "s": 32259, "text": "2" }, { "code": null, "e": 32462, "s": 32261, "text": "Aggregator functions (min, max, count etc.) can be applied on the CSV data. Here the min() function is applied on projects column using $ symbol. The minimum number of projects which is 2 is returned." }, { "code": "csv_data <- read.csv(file ='sample.csv')new_csv <- subset(csv_data, department == \"HR\" & projects <10)print (new_csv)", "e": 32580, "s": 32462, "text": null }, { "code": null, "e": 32588, "s": 32580, "text": "Output:" }, { "code": null, "e": 32758, "s": 32588, "text": " \n id, name, department, salary, projects\n4 4 D HR 65043 5\n7 7 G HR 69000 7\n" }, { "code": null, "e": 33016, "s": 32758, "text": "The subset of the data that is created is stored as a data frame satisfying the conditions specified as the arguments of the function. The employees D and G are HR and have the number of projects<10. The row numbers are retained in the resultant data frame." }, { "code": null, "e": 33220, "s": 33016, "text": "The contents of the data frame can be written into a CSV file. The CSV file is stored in the current working directory with the name specified in the function write.csv(data frame, output CSV name) in R." }, { "code": null, "e": 33230, "s": 33220, "text": "Examples:" }, { "code": "csv_data <- read.csv(file ='sample.csv')new_csv <- subset(csv_data, department == \"HR\" & projects <10)write.csv(new_csv, \"new_sample.csv\")new_data <-read.csv(file ='new_sample.csv')print(new_data)", "e": 33427, "s": 33230, "text": null }, { "code": null, "e": 33435, "s": 33427, "text": "Output:" }, { "code": null, "e": 33621, "s": 33435, "text": " \n X id, name, department, salary, projects\n1 4 4 D HR 65043 5\n2 7 7 G HR 69000 7\n" }, { "code": null, "e": 33803, "s": 33621, "text": "The column X contains the row numbers of the original CSV file. In order to remove it, we can specify an additional argument in the write.csv() function that set row names to FALSE." }, { "code": "csv_data <- read.csv(file ='sample.csv')new_csv <- subset(csv_data, department == \"HR\" & projects <10)write.csv(new_csv, \"new_sample.csv\", row.names = FALSE)new_data <-read.csv(file ='new_sample.csv')print(new_data)", "e": 34019, "s": 33803, "text": null }, { "code": null, "e": 34027, "s": 34019, "text": "Output:" }, { "code": null, "e": 34193, "s": 34027, "text": " \n id, name, department, salary, projects\n1 4 D HR 65043 5\n2 7 G HR 69000 7\n" }, { "code": null, "e": 34248, "s": 34193, "text": "The original row numbers are removed from the new CSV." }, { "code": null, "e": 34255, "s": 34248, "text": "Picked" }, { "code": null, "e": 34266, "s": 34255, "text": "R Language" }, { "code": null, "e": 34364, "s": 34266, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34409, "s": 34364, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 34467, "s": 34409, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 34519, "s": 34467, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 34551, "s": 34519, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 34614, "s": 34551, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 34658, "s": 34614, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 34710, "s": 34658, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 34775, "s": 34710, "text": "Convert Factor to Numeric and Numeric to Factor in R Programming" }, { "code": null, "e": 34810, "s": 34775, "text": "Group by function in R using Dplyr" } ]
How to create X and Y axis flip animation using HTML and CSS ? - GeeksforGeeks
27 Apr, 2020 The flip animation is the kind of loading animation in which we use a square flip effect to give the feel of loading animation. These kinds of animations are useful in times when the content of the website is taking too long to load. This animation can keep visitors engage and prevent them from leaving your web page without seeing the content. The main concept behind working of this animation is the application of transform and @keyframes. Please go through them before you try to execute this code. HTML Code:: Create a HTML file and create a div in it. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>X and Y axis flip animation</title></head> <body> <center> <h1>GeeksforGeeks</h1> <b> X and Y axis flip animation</b> <div class="geeks"></div> </center></body> </html> CSS Code: In CSS, the first thing that we have done is provide a background to the body. Apply background to the div and some border-radius to have a rounded corner. Apply linear animation with identifier named as animate. Using key-frames we will apply animation to our identifier. We are rotating are square along X-axis during the first half frames and along Y-axis during rest. This is not required but you can change the angles of rotation to have a different kind of flip effect. This one is the basic flip effect. <style> body { margin: 0; padding: 0; } h1 { color: green; } .geeks { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background: green; border-radius: 13px; animation: animate 2s linear infinite; } @keyframes animate { 0% { transform: translate(-50%, -50%) perspective(200px) rotateX(0deg) rotateY(0deg); } 50% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(0deg); } 100% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(-180deg); } }</style> Final solution: It is the combination of HTML and CSS codes. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>X and Y axis flip animation</title> <style> body { margin: 0; padding: 0; } h1 { color: green; } .geeks { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background: green; border-radius: 13px; animation: animate 2s linear infinite; } @keyframes animate { 0% { transform: translate(-50%, -50%) perspective(200px) rotateX(0deg) rotateY(0deg); } 50% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(0deg); } 100% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(-180deg); } } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b> X and Y axis flip animation</b> <div class="geeks"></div> </center></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc CSS-Properties HTML-Misc CSS HTML 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? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? 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": 26231, "s": 26203, "text": "\n27 Apr, 2020" }, { "code": null, "e": 26735, "s": 26231, "text": "The flip animation is the kind of loading animation in which we use a square flip effect to give the feel of loading animation. These kinds of animations are useful in times when the content of the website is taking too long to load. This animation can keep visitors engage and prevent them from leaving your web page without seeing the content. The main concept behind working of this animation is the application of transform and @keyframes. Please go through them before you try to execute this code." }, { "code": null, "e": 26790, "s": 26735, "text": "HTML Code:: Create a HTML file and create a div in it." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>X and Y axis flip animation</title></head> <body> <center> <h1>GeeksforGeeks</h1> <b> X and Y axis flip animation</b> <div class=\"geeks\"></div> </center></body> </html>", "e": 27152, "s": 26790, "text": null }, { "code": null, "e": 27673, "s": 27152, "text": "CSS Code: In CSS, the first thing that we have done is provide a background to the body. Apply background to the div and some border-radius to have a rounded corner. Apply linear animation with identifier named as animate. Using key-frames we will apply animation to our identifier. We are rotating are square along X-axis during the first half frames and along Y-axis during rest. This is not required but you can change the angles of rotation to have a different kind of flip effect. This one is the basic flip effect." }, { "code": "<style> body { margin: 0; padding: 0; } h1 { color: green; } .geeks { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background: green; border-radius: 13px; animation: animate 2s linear infinite; } @keyframes animate { 0% { transform: translate(-50%, -50%) perspective(200px) rotateX(0deg) rotateY(0deg); } 50% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(0deg); } 100% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(-180deg); } }</style>", "e": 28635, "s": 27673, "text": null }, { "code": null, "e": 28696, "s": 28635, "text": "Final solution: It is the combination of HTML and CSS codes." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>X and Y axis flip animation</title> <style> body { margin: 0; padding: 0; } h1 { color: green; } .geeks { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background: green; border-radius: 13px; animation: animate 2s linear infinite; } @keyframes animate { 0% { transform: translate(-50%, -50%) perspective(200px) rotateX(0deg) rotateY(0deg); } 50% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(0deg); } 100% { transform: translate(-50%, -50%) perspective(200px) rotateX(-180deg) rotateY(-180deg); } } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b> X and Y axis flip animation</b> <div class=\"geeks\"></div> </center></body> </html>", "e": 30105, "s": 28696, "text": null }, { "code": null, "e": 30113, "s": 30105, "text": "Output:" }, { "code": null, "e": 30250, "s": 30113, "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": 30259, "s": 30250, "text": "CSS-Misc" }, { "code": null, "e": 30274, "s": 30259, "text": "CSS-Properties" }, { "code": null, "e": 30284, "s": 30274, "text": "HTML-Misc" }, { "code": null, "e": 30288, "s": 30284, "text": "CSS" }, { "code": null, "e": 30293, "s": 30288, "text": "HTML" }, { "code": null, "e": 30310, "s": 30293, "text": "Web Technologies" }, { "code": null, "e": 30337, "s": 30310, "text": "Web technologies Questions" }, { "code": null, "e": 30342, "s": 30337, "text": "HTML" }, { "code": null, "e": 30440, "s": 30342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30495, "s": 30440, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 30532, "s": 30495, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 30596, "s": 30532, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 30633, "s": 30596, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 30694, "s": 30633, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 30754, "s": 30694, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30807, "s": 30754, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 30868, "s": 30807, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 30892, "s": 30868, "text": "REST API (Introduction)" } ]
JavaTuples getLabel() method - GeeksforGeeks
27 Aug, 2018 The getLabel() method in org.javatuples is used to fetch the label from the TupleClassObject from the LabelValue Class. This method can be used with only LabelValue class object of javatuples library. It returns a Label which is the element present at the index 0 of the LabelValueClassObject. The returned Label is ensures the type-safety. Method Declaration: public A getLabel() Syntax: LabelValue LabelValueClassObject = LabelValue.with(A a, B b); A val = LabelValueClassObject.getLabel() Return Value: This method returns a Label which is the element present at the index 0 of the LabelValueClassObject. Below programs illustrate the various ways to use getLabel() method: Example 1: // Below is a Java program to get// a LabelValue value import java.util.*;import org.javatuples.LabelValue; class GfG { public static void main(String[] args) { // Creating a LabelValue object LabelValue<Integer, String> lv = LabelValue.with(Integer.valueOf(1), "GeeksforGeeks"); // Using getLabel() method int label = lv.getLabel(); // Printing the Label System.out.println(label); }} Output: 1 Example 2: // Below is a Java program to get// a LabelValue value import java.util.*;import org.javatuples.LabelValue; class GfG { public static void main(String[] args) { // Creating a LabelValue object LabelValue<String, String> lv = LabelValue.with("GeeksforGeeks", "A Computer Science Portal for Geeks"); // Using getLabel() method String label = lv.getLabel(); // Printing the Label System.out.println(label); }} Output: GeeksforGeeks Java-Functions JavaTuples Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Exceptions in Java Stream In Java Functional Interfaces in Java Different ways of Reading a text file in Java Internal Working of HashMap in Java Iterators in Java Java Programming Examples Strings in Java Comparator Interface in Java with Examples
[ { "code": null, "e": 23557, "s": 23529, "text": "\n27 Aug, 2018" }, { "code": null, "e": 23898, "s": 23557, "text": "The getLabel() method in org.javatuples is used to fetch the label from the TupleClassObject from the LabelValue Class. This method can be used with only LabelValue class object of javatuples library. It returns a Label which is the element present at the index 0 of the LabelValueClassObject. The returned Label is ensures the type-safety." }, { "code": null, "e": 23918, "s": 23898, "text": "Method Declaration:" }, { "code": null, "e": 23938, "s": 23918, "text": "public A getLabel()" }, { "code": null, "e": 23946, "s": 23938, "text": "Syntax:" }, { "code": null, "e": 24049, "s": 23946, "text": "LabelValue LabelValueClassObject = LabelValue.with(A a, B b);\nA val = LabelValueClassObject.getLabel()" }, { "code": null, "e": 24165, "s": 24049, "text": "Return Value: This method returns a Label which is the element present at the index 0 of the LabelValueClassObject." }, { "code": null, "e": 24234, "s": 24165, "text": "Below programs illustrate the various ways to use getLabel() method:" }, { "code": null, "e": 24245, "s": 24234, "text": "Example 1:" }, { "code": "// Below is a Java program to get// a LabelValue value import java.util.*;import org.javatuples.LabelValue; class GfG { public static void main(String[] args) { // Creating a LabelValue object LabelValue<Integer, String> lv = LabelValue.with(Integer.valueOf(1), \"GeeksforGeeks\"); // Using getLabel() method int label = lv.getLabel(); // Printing the Label System.out.println(label); }}", "e": 24699, "s": 24245, "text": null }, { "code": null, "e": 24707, "s": 24699, "text": "Output:" }, { "code": null, "e": 24710, "s": 24707, "text": "1\n" }, { "code": null, "e": 24721, "s": 24710, "text": "Example 2:" }, { "code": "// Below is a Java program to get// a LabelValue value import java.util.*;import org.javatuples.LabelValue; class GfG { public static void main(String[] args) { // Creating a LabelValue object LabelValue<String, String> lv = LabelValue.with(\"GeeksforGeeks\", \"A Computer Science Portal for Geeks\"); // Using getLabel() method String label = lv.getLabel(); // Printing the Label System.out.println(label); }}", "e": 25225, "s": 24721, "text": null }, { "code": null, "e": 25233, "s": 25225, "text": "Output:" }, { "code": null, "e": 25248, "s": 25233, "text": "GeeksforGeeks\n" }, { "code": null, "e": 25263, "s": 25248, "text": "Java-Functions" }, { "code": null, "e": 25274, "s": 25263, "text": "JavaTuples" }, { "code": null, "e": 25279, "s": 25274, "text": "Java" }, { "code": null, "e": 25284, "s": 25279, "text": "Java" }, { "code": null, "e": 25382, "s": 25284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25391, "s": 25382, "text": "Comments" }, { "code": null, "e": 25404, "s": 25391, "text": "Old Comments" }, { "code": null, "e": 25425, "s": 25404, "text": "Constructors in Java" }, { "code": null, "e": 25444, "s": 25425, "text": "Exceptions in Java" }, { "code": null, "e": 25459, "s": 25444, "text": "Stream In Java" }, { "code": null, "e": 25489, "s": 25459, "text": "Functional Interfaces in Java" }, { "code": null, "e": 25535, "s": 25489, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25571, "s": 25535, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 25589, "s": 25571, "text": "Iterators in Java" }, { "code": null, "e": 25615, "s": 25589, "text": "Java Programming Examples" }, { "code": null, "e": 25631, "s": 25615, "text": "Strings in Java" } ]
C library function - system()
The C library function int system(const char *command) passes the command name or program name specified by command to the host environment to be executed by the command processor and returns after the command has been completed. Following is the declaration for system() function. int system(const char *command) command − This is the C string containing the name of the requested variable. command − This is the C string containing the name of the requested variable. The value returned is -1 on error, and the return status of the command otherwise. The following example shows the usage of system() function to list down all the files and directories in the current directory under unix machine. #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> int main () { char command[50]; strcpy( command, "ls -l" ); system(command); return(0); } Let us compile and run the above program that will produce the following result on my unix machine − drwxr-xr-x 2 apache apache 4096 Aug 22 07:25 hsperfdata_apache drwxr-xr-x 2 railo railo 4096 Aug 21 18:48 hsperfdata_railo rw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_XXGLOBAL_1 rw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_asp_2 srwx---- 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp rw------ 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp_1280495620 srwx---- 1 apache apache 0 Aug 21 18:48 mod_mono_server_global The following example shows the usage of system() function to list down all the files and directories in the current directory under windows machine. #include <stdio.h> #include <string.h> int main () { char command[50]; strcpy( command, "dir" ); system(command); return(0); } Let us compile and run the above program that will produce the following result on my windows machine − a.txt amit.doc sachin saurav file.c 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2237, "s": 2007, "text": "The C library function int system(const char *command) passes the command name or program name specified by command to the host environment to be executed by the command processor and returns after the command has been completed." }, { "code": null, "e": 2289, "s": 2237, "text": "Following is the declaration for system() function." }, { "code": null, "e": 2321, "s": 2289, "text": "int system(const char *command)" }, { "code": null, "e": 2399, "s": 2321, "text": "command − This is the C string containing the name of the requested variable." }, { "code": null, "e": 2477, "s": 2399, "text": "command − This is the C string containing the name of the requested variable." }, { "code": null, "e": 2560, "s": 2477, "text": "The value returned is -1 on error, and the return status of the command otherwise." }, { "code": null, "e": 2707, "s": 2560, "text": "The following example shows the usage of system() function to list down all the files and directories in the current directory under unix machine." }, { "code": null, "e": 2892, "s": 2707, "text": "#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main () {\n char command[50];\n\n strcpy( command, \"ls -l\" );\n system(command);\n\n return(0);\n} " }, { "code": null, "e": 2993, "s": 2892, "text": "Let us compile and run the above program that will produce the following result on my unix machine −" }, { "code": null, "e": 3446, "s": 2993, "text": "drwxr-xr-x 2 apache apache 4096 Aug 22 07:25 hsperfdata_apache\ndrwxr-xr-x 2 railo railo 4096 Aug 21 18:48 hsperfdata_railo\nrw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_XXGLOBAL_1\nrw------ 1 apache apache 8 Aug 21 18:48 mod_mono_dashboard_asp_2\nsrwx---- 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp\nrw------ 1 apache apache 0 Aug 22 05:28 mod_mono_server_asp_1280495620\nsrwx---- 1 apache apache 0 Aug 21 18:48 mod_mono_server_global\n" }, { "code": null, "e": 3596, "s": 3446, "text": "The following example shows the usage of system() function to list down all the files and directories in the current directory under windows machine." }, { "code": null, "e": 3739, "s": 3596, "text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char command[50];\n\n strcpy( command, \"dir\" );\n system(command);\n\n return(0);\n} " }, { "code": null, "e": 3843, "s": 3739, "text": "Let us compile and run the above program that will produce the following result on my windows machine −" }, { "code": null, "e": 3880, "s": 3843, "text": "a.txt\namit.doc\nsachin\nsaurav\nfile.c\n" }, { "code": null, "e": 3913, "s": 3880, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3928, "s": 3913, "text": " Nishant Malik" }, { "code": null, "e": 3963, "s": 3928, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3978, "s": 3963, "text": " Nishant Malik" }, { "code": null, "e": 4013, "s": 3978, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4027, "s": 4013, "text": " Asif Hussain" }, { "code": null, "e": 4060, "s": 4027, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4078, "s": 4060, "text": " Richa Maheshwari" }, { "code": null, "e": 4113, "s": 4078, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4132, "s": 4113, "text": " Vandana Annavaram" }, { "code": null, "e": 4165, "s": 4132, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4177, "s": 4165, "text": " Amit Diwan" }, { "code": null, "e": 4184, "s": 4177, "text": " Print" }, { "code": null, "e": 4195, "s": 4184, "text": " Add Notes" } ]
Convert Decimal to Int64 (long) in C#
Use the Convert.ToInt64() method to convert Decimal to Int64 (long) in C#. Let’s say we have a decimal variable. decimal d = 310.23m; Now to convert it to Int64, use the Convert.ToInt64() method. long res; res = Convert.ToInt64(d); Let us see another example − Live Demo using System; class Demo { static void Main() { decimal d = 190.66m; long res; res = Convert.ToInt64(d); Console.WriteLine("Converted Decimal '{0}' to Int64 value {1}", d, res); } } Converted Decimal '190.66' to Int64 value 191
[ { "code": null, "e": 1137, "s": 1062, "text": "Use the Convert.ToInt64() method to convert Decimal to Int64 (long) in C#." }, { "code": null, "e": 1175, "s": 1137, "text": "Let’s say we have a decimal variable." }, { "code": null, "e": 1196, "s": 1175, "text": "decimal d = 310.23m;" }, { "code": null, "e": 1258, "s": 1196, "text": "Now to convert it to Int64, use the Convert.ToInt64() method." }, { "code": null, "e": 1294, "s": 1258, "text": "long res;\nres = Convert.ToInt64(d);" }, { "code": null, "e": 1323, "s": 1294, "text": "Let us see another example −" }, { "code": null, "e": 1334, "s": 1323, "text": " Live Demo" }, { "code": null, "e": 1546, "s": 1334, "text": "using System;\nclass Demo {\n static void Main() {\n decimal d = 190.66m;\n long res;\n res = Convert.ToInt64(d);\n Console.WriteLine(\"Converted Decimal '{0}' to Int64 value {1}\", d, res);\n }\n}" }, { "code": null, "e": 1592, "s": 1546, "text": "Converted Decimal '190.66' to Int64 value 191" } ]
Linux Admin - Quick Guide
Unique among business class Linux distributions, CentOS stays true to the open-source nature that Linux was founded on. The first Linux kernel was developed by a college student at the University of Helsinki (Linus Torvalds) and combined with the GNU utilities founded and promoted by Richard Stallman. CentOS has a proven, open-source licensing that can power today’s business world. CentOS has quickly become one of the most prolific server platforms in the world. Any Linux Administrator, when seeking employment, is bound to come across the words: “CentOS Linux Experience Preferred”. From startups to Fortune 10 tech titans, CentOS has placed itself amongst the higher echelons of server operating systems worldwide. What makes CentOS stand out from other Linux distributions is a great combination of − Open source licensing Open source licensing Dedicated user-base of Linux professionals Dedicated user-base of Linux professionals Good hardware support Good hardware support Rock-solid stability and reliability Rock-solid stability and reliability Focus on security and updates Focus on security and updates Strict adherence to software packaging standards needed in a corporate environment Strict adherence to software packaging standards needed in a corporate environment Before starting the lessons, we assume that the readers have a basic knowledge of Linux and Administration fundamentals such as − What is the root user? What is the root user? The power of the root user The power of the root user Basic concept of security groups and users Basic concept of security groups and users Experience using a Linux terminal emulator Experience using a Linux terminal emulator Fundamental networking concepts Fundamental networking concepts Fundamental understanding of interpreted programming languages (Perl, Python, Ruby) Fundamental understanding of interpreted programming languages (Perl, Python, Ruby) Networking protocols such as HTTP, LDAP, FTP, IMAP, SMTP Networking protocols such as HTTP, LDAP, FTP, IMAP, SMTP Cores that compose a computer operating system: file system, drivers, and the kerne Cores that compose a computer operating system: file system, drivers, and the kerne Before learning the tools of a CentOS Linux Administrator, it is important to note the philosophy behind the Linux administration command line. Linux was designed based on the Unix philosophy of “small, precise tools chained together simplifying larger tasks”. Linux, at its root, does not have large single-purpose applications for one specific use a lot of the time. Instead, there are hundreds of basic utilities that when combined offer great power to accomplish big tasks with efficiency. For example, if an administrator wants a listing of all the current users on a system, the following chained commands can be used to get a list of all system users. On execution of the command, the users are on the system are listed in an alphabetical order. [root@centosLocal centos]# cut /etc/passwd -d":" -f1 | sort abrt adm avahi bin centos chrony colord daemon dbus It is easy to export this list into a text file using the following command. [root@localhost /]# cut /etc/passwd -d ":" -f1 > system_users.txt [root@localhost /]# cat ./system_users.txt | sort | wc –l 40 [root@localhost /]# It is also possible to compare the user list with an export at a later date. [root@centosLocal centos]# cut /etc/passwd -d ":" -f1 > system_users002.txt && cat system_users002.txt | sort | wc -l 41 [root@centosLocal centos]# diff ./system_users.txt ./system_users002.txt evilBackdoor [root@centosLocal centos]# With this approach of small tools chained to accomplish bigger tasks, it is simpler to make a script performing these commands, than automatically email results at regular time intervals. Basic Commands every Linux Administrator should be proficient in are − vim grep more and less tail head wc sort uniq tee cat cut sed tr paste In the Linux world, Administrators use filtering commands every day to parse logs, filter command output, and perform actions with interactive shell scripts. As mentioned, the power of these commands come in their ability to modify one another through a process called piping. The following command shows how many words begin with the letter a from the CentOS main user dictionary. [root@centosLocal ~]# egrep '^a.*$' /usr/share/dict/words | wc -l 25192 [root@centosLocal ~]# To introduce permissions as they apply to both directories and files in CentOS Linux, let's look at the following command output. [centos@centosLocal etc]$ ls -ld /etc/yum* drwxr-xr-x. 6 root root 100 Dec 5 06:59 /etc/yum -rw-r--r--. 1 root root 970 Nov 15 08:30 /etc/yum.conf drwxr-xr-x. 2 root root 187 Nov 15 08:30 /etc/yum.repos.d Note − The three primary object types you will see are "-" − a dash for plain file "-" − a dash for plain file "d" − for a directory "d" − for a directory "l" − for a symbolic link "l" − for a symbolic link We will focus on the three blocks of output for each directory and file − drwxr-xr-x : root : root -rw-r--r-- : root : root drwxr-xr-x : root : root Now let's break this down, to better understand these lines − Understanding the difference between owner, group and world is important. Not understanding this can have big consequences on servers that host services to the Internet. Before we give a real-world example, let's first understand the permissions as they apply to directories and files. Please take a look at the following table, then continue with the instruction. Note − When files should be accessible for reading in a directory, it is common to apply read and execute permissions. Otherwise, the users will have difficulty working with the files. Leaving write disabled will assure files cannot be: renamed, deleted, copied over, or have permissions modified. When applying permissions, there are two concepts to understand − Symbolic Permissions Octal Permissions In essence, each are the same but a different way to referring to, and assigning file permissions. For a quick guide, please study and refer to the following table − When assigning permissions using the octal method, use a 3 byte number such as: 760. The number 760 translates into: Owner: rwx; Group: rw; Other (or world) no permissions. Another scenario: 733 would translate to: Owner: rwx; Group: wx; Other: wx. There is one drawback to permissions using the Octal method. Existing permission sets cannot be modified. It is only possible to reassign the entire permission set of an object. Now you might wonder, what is wrong with always re-assigning permissions? Imagine a large directory structure, for example /var/www/ on a production web-server. We want to recursively take away the w or write bit on all directories for Other. Thus, forcing it to be pro-actively added only when needed for security measures. If we re-assign the entire permission set, we take away all other custom permissions assigned to every sub-directory. Hence, it will cause a problem for both the administrator and the user of the system. At some point, a person (or persons) would need to re-assign all the custom permissions that were wiped out by re-assigning the entire permission-set for every directory and object. In this case, we would want to use the Symbolic method to modify permissions − chmod -R o-w /var/www/ The above command would not "overwrite permissions" but modify the current permission sets. So get accustomed to using the best practice Octal only to assign permissions Symbolic to modify permission sets It is important that a CentOS Administrator be proficient with both Octal and Symbolic permissions as permissions are important for the integrity of data and the entire operating system. If permissions are incorrect, the end result will be both sensitive data and the entire operating system will be compromised. With that covered, let's look at a few commands for modifying permissions and object owner/members − chmod chown chgrp umask chmod will allow us to change permissions of directories and files using octal or symbolic permission sets. We will use this to modify our assignment and uploads directories. chown can modify both owning the user and group of objects. However, unless needing to modify both at the same time, using chgrp is usually used for groups. chgrp will change the group owner to that supplied. Let's change all the subdirectory assignments in /var/www/students/ so the owning group is the students group. Then assign the root of students to the professors group. Later, make Dr. Terry Thomas the owner of the students directory, since he is tasked as being in-charge of all Computer Science academia at the school. As we can see, when created, the directory is left pretty raw. [root@centosLocal ~]# ls -ld /var/www/students/ drwxr-xr-x. 4 root root 40 Jan 9 22:03 /var/www/students/ [root@centosLocal ~]# ls -l /var/www/students/ total 0 drwxr-xr-x. 2 root root 6 Jan 9 22:03 assignments drwxr-xr-x. 2 root root 6 Jan 9 22:03 uploads [root@centosLocal ~]# As Administrators we never want to give our root credentials out to anyone. But at the same time, we need to allow users the ability to do their job. So let's allow Dr. Terry Thomas to take more control of the file structure and limit what students can do. [root@centosLocal ~]# chown -R drterryt:professors /var/www/students/ [root@centosLocal ~]# ls -ld /var/www/students/ drwxr-xr-x. 4 drterryt professors 40 Jan 9 22:03 /var/www/students/ [root@centosLocal ~]# ls -ls /var/www/students/ total 0 0 drwxr-xr-x. 2 drterryt professors 6 Jan 9 22:03 assignments 0 drwxr-xr-x. 2 drterryt professors 6 Jan 9 22:03 uploads [root@centosLocal ~]# Now, each directory and subdirectory has an owner of drterryt and the owning group is professors. Since the assignments directory is for students to turn assigned work in, let's take away the ability to list and modify files from the students group. [root@centosLocal ~]# chgrp students /var/www/students/assignments/ && chmod 736 /var/www/students/assignments/ [root@centosLocal assignments]# ls -ld /var/www/students/assignments/ drwx-wxrw-. 2 drterryt students 44 Jan 9 23:14 /var/www/students/assignments/ [root@centosLocal assignments]# Students can copy assignments to the assignments directory. But they cannot list contents of the directory, copy over current files, or modify files in the assignments directory. Thus, it just allows the students to submit completed assignments. The CentOS filesystem will provide a date-stamp of when assignments turned in. As the assignments directory owner − [drterryt@centosLocal assignments]$ whoami drterryt [drterryt@centosLocal assignments]$ ls -ld /var/www/students/assignment drwx-wxrw-. 2 drterryt students 44 Jan 9 23:14 /var/www/students/assignments/ [drterryt@centosLocal assignments]$ ls -l /var/www/students/assignments/ total 4 -rw-r--r--. 1 adama students 0 Jan 9 23:14 myassign.txt -rw-r--r--. 1 tammyr students 16 Jan 9 23:18 terryt.txt [drterryt@centosLocal assignments]$ We can see, the directory owner can list files as well as modify and remove files. umask is an important command that supplies the default modes for File and Directory Permissions as they are created. umask permissions use unary, negated logic. [adama@centosLocal umask_tests]$ ls -l ./ -rw-r--r--. 1 adama students 0 Jan 10 00:27 myDir -rw-r--r--. 1 adama students 0 Jan 10 00:27 myFile.txt [adama@centosLocal umask_tests]$ whoami adama [adama@centosLocal umask_tests]$ umask 0022 [adama@centosLocal umask_tests]$ Now, let’s change the umask for our current user, and make a new file and directory. [adama@centosLocal umask_tests]$ umask 077 [adama@centosLocal umask_tests]$ touch mynewfile.txt [adama@centosLocal umask_tests]$ mkdir myNewDir [adama@centosLocal umask_tests]$ ls -l total 0 -rw-r--r--. 1 adama students 0 Jan 10 00:27 myDir -rw-r--r--. 1 adama students 0 Jan 10 00:27 myFile.txt drwx------. 2 adama students 6 Jan 10 00:35 myNewDir -rw-------. 1 adama students 0 Jan 10 00:35 mynewfile.txt As we can see, newly created files are a little more restrictive than before. umask for users must should be changed in either − /etc/profile ~/bashrc [root@centosLocal centos]# su adama [adama@centosLocal centos]$ umask 0022 [adama@centosLocal centos]$ Generally, the default umask in CentOS will be okay. When we run into trouble with a default of 0022, is usually when different departments belonging to different groups need to collaborate on projects. This is where the role of a system administrator comes in, to balance the operations and design of the CentOS operating system. When discussing user management, we have three important terms to understand − Users Groups Permissions We have already discussed in-depth permissions as applied to files and folders. In this chapter, let's discuss about users and groups. In CentOS, there are two types accounts − System accounts − Used for a daemon or other piece of software. System accounts − Used for a daemon or other piece of software. Interactive accounts − Usually assigned to a user for accessing system resources. Interactive accounts − Usually assigned to a user for accessing system resources. The main difference between the two user types is − System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login. System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login. Interactive accounts are used by end-users to access computing resources from either a shell or physical console login. Interactive accounts are used by end-users to access computing resources from either a shell or physical console login. With this basic understanding of users, let's now create a new user for Bob Jones in the Accounting Department. A new user is added with the adduser command. Following are some adduser common switches − When creating a new user, use the -c, -m, -g, -n switches as follows − [root@localhost Downloads]# useradd -c "Bob Jones Accounting Dept Manager" -m -g accounting -n bjones Now let's see if our new user has been created − [root@localhost Downloads]# id bjones (bjones) gid = 1001(accounting) groups = 1001(accounting) [root@localhost Downloads]# grep bjones /etc/passwd bjones:x:1001:1001:Bob Jones Accounting Dept Manager:/home/bjones:/bin/bash [root@localhost Downloads]# Now we need to enable the new account using the passwd command − [root@localhost Downloads]# passwd bjones Changing password for user bjones. New password: Retype new password: passwd: all authentication tokens updated successfully. [root@localhost Downloads]# The user account is not enabled allowing the user to log into the system. There are several methods to disable accounts on a system. These range from editing the /etc/passwd file by hand. Or even using the passwd command with the -lswitch. Both of these methods have one big drawback: if the user has ssh access and uses an RSA key for authentication, they can still login using this method. Now let’s use the chage command, changing the password expiry date to a previous date. Also, it may be good to make a note on the account as to why we disabled it. [root@localhost Downloads]# chage -E 2005-10-01 bjones [root@localhost Downloads]# usermod -c "Disabled Account while Bob out of the country for five months" bjones [root@localhost Downloads]# grep bjones /etc/passwd bjones:x:1001:1001:Disabled Account while Bob out of the country for four months:/home/bjones:/bin/bash [root@localhost Downloads]# Managing groups in Linux makes it convenient for an administrator to combine the users within containers applying permission-sets applicable to all group members. For example, all users in Accounting may need access to the same files. Thus, we make an accounting group, adding Accounting users. For the most part, anything requiring special permissions should be done in a group. This approach will usually save time over applying special permissions to just one user. Example, Sally is in-charge of reports and only Sally needs access to certain files for reporting. However, what if Sally is sick one day and Bob does reports? Or the need for reporting grows? When a group is made, an Administrator only needs to do it once. The add users is applied as needs change or expand. Following are some common commands used for managing groups − chgrp groupadd groups usermod chgrp − Changes the group ownership for a file or directory. Let's make a directory for people in the accounting group to store files and create directories for files. [root@localhost Downloads]# mkdir /home/accounting [root@localhost Downloads]# ls -ld /home/accounting drwxr-xr-x. 2 root root 6 Jan 13 10:18 /home/accounting [root@localhost Downloads]# Next, let's give group ownership to the accounting group. [root@localhost Downloads]# chgrp -v accounting /home/accounting/ changed group of ‘/home/accounting/’ from root to accounting [root@localhost Downloads]# ls -ld /home/accounting/ drwxr-xr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/ [root@localhost Downloads]# Now, everyone in the accounting group has read and execute permissions to /home/accounting. They will need write permissions as well. [root@localhost Downloads]# chmod g+w /home/accounting/ [root@localhost Downloads]# ls -ld /home/accounting/ drwxrwxr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/ [root@localhost Downloads]# Since the accounting group may deal with sensitive documents, we need to apply some restrictive permissions for other or world. [root@localhost Downloads]# chmod o-rx /home/accounting/ [root@localhost Downloads]# ls -ld /home/accounting/ drwxrwx---. 2 root accounting 6 Jan 13 10:18 /home/accounting/ [root@localhost Downloads]# groupadd − Used to make a new group. Let's make a new group called secret. We will add a password to the group, allowing the users to add themselves with a known password. [root@localhost]# groupadd secret [root@localhost]# gpasswd secret Changing the password for group secret New Password: Re-enter new password: [root@localhost]# exit exit [centos@localhost ~]$ newgrp secret Password: [centos@localhost ~]$ groups secret wheel rdc [centos@localhost ~]$ In practice, passwords for groups are not used often. Secondary groups are adequate and sharing passwords amongst other users is not a great security practice. The groups command is used to show which group a user belongs to. We will use this, after making some changes to our current user. usermod is used to update account attributes. Following are the common usermod switches. [root@localhost]# groups centos centos : accounting secret [root@localhost]# [root@localhost]# usermod -a -G wheel centos [root@localhost]# groups centos centos : accounting wheel secret [root@localhost]# CentOS disk quotas can be enabled both; alerting the system administrator and denying further disk-storage-access to a user before disk capacity is exceeded. When a disk is full, depending on what resides on the disk, an entire system can come to a screeching halt until recovered. Enabling Quota Management in CentOS Linux is basically a 4 step process − Step 1 − Enable quota management for groups and users in /etc/fstab. Step 1 − Enable quota management for groups and users in /etc/fstab. Step 2 − Remount the filesystem. Step 2 − Remount the filesystem. Step 3 − Create Quota database and generate disk usage table. Step 3 − Create Quota database and generate disk usage table. Step 4 − Assign quota policies. Step 4 − Assign quota policies. First, we want to backup our /etc/fstab filen − [root@centosLocal centos]# cp -r /etc/fstab ./ We now have a copy of our known working /etc/fstab in the current working directory. # # /etc/fstab # Created by anaconda on Sat Dec 17 02:44:51 2016 # # Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # /dev/mapper/cl-root / xfs defaults 0 0 UUID = 4b9a40bc-9480-4 /boot xfs defaults 0 0 /dev/mapper/cl-home /home xfs defaults,usrquota,grpquota 0 0 /dev/mapper/cl-swap swap swap defaults 0 0 We made the following changes in the options section of /etc/fstab for the volume or Label to where quotas are to be applied for users and groups. usrquota grpquota As you can see, we are using the xfs filesystem. When using xfs there are extra manual steps involved. /home is on the same disk as /. Further investigation shows / is set for noquota, which is a kernel level mounting option. We must re-configure our kernel boot options. root@localhost rdc]# mount | grep ' / ' /dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota) [root@localhost rdc]# This step is only necessary under two conditions − When the disk/partition we are enabling quotas on, is using the xfs file system When the kernel is passing noquota parameter to /etc/fstab at boot time Step 1 − Make a backup of /etc/default/grub. cp /etc/default/grub ~/ Step 2 − Modify /etc/default/grub. Here is the default file. GRUB_TIMEOUT=5 GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)" GRUB_DEFAULT=saved GRUB_DISABLE_SUBMENU=true GRUB_TERMINAL_OUTPUT="console" GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet" GRUB_DISABLE_RECOVERY="true" We want to modify the following line − GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet" to GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv =cl/swap rhgb quiet rootflags=usrquota,grpquota" Note − It is important we copy these changes verbatim. After we reconfigure grub.cfg, our system will fail to boot if any errors were made in the configuration. Please, try this part of the tutorial on a non-production system. Step 3 − Backup your working grub.cfg cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak Make a new grub.cfg [root@localhost rdc]# grub2-mkconfig -o /boot/grub2/grub.cfg Generating grub configuration file ... Found linux image: /boot/vmlinuz-3.10.0-514.el7.x86_64 Found initrd image: /boot/initramfs-3.10.0-514.el7.x86_64.img Found linux image: /boot/vmlinuz-0-rescue-dbba7fa47f73457b96628ba8f3959bfd Found initrd image: /boot/initramfs-0-rescuedbba7fa47f73457b96628ba8f3959bfd.img done [root@localhost rdc]# Reboot [root@localhost rdc]#reboot If all modifications were precise, we should not have the availability to add quotas to the xfs file system. [rdc@localhost ~]$ mount | grep ' / ' /dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,usrquota,grpquota) [rdc@localhost ~]$ We have passed the usrquota and grpquota parameters via grub. Now, again edit /etc/fstab to include / since /homeon the same physical disk. /dev/mapper/cl-root/xfs defaults,usrquota,grpquota 0 0 Now let's enable the quota databases. [root@localhost rdc]# quotacheck -acfvugM Make sure Quotas are enabled. [root@localhost rdc]# quotaon -ap group quota on / (/dev/mapper/cl-root) is on user quota on / (/dev/mapper/cl-root) is on group quota on /home (/dev/mapper/cl-home) is on user quota on /home (/dev/mapper/cl-home) is on [root@localhost rdc]# If the partition or disk is separate from the actively booted partition, we can remount without rebooting. If the quota was configured on a disk/partition booted in the root directory /, we may need to reboot the operating system. Forcing the remount and applying changes, the need to remount the filesystem may vary. [rdc@localhost ~]$ df Filesystem 1K-blocks Used Available Use% Mounted on /dev/mapper/cl-root 22447404 4081860 18365544 19% / devtmpfs 903448 0 903448 0% /dev tmpfs 919308 100 919208 1% /dev/shm tmpfs 919308 9180 910128 1% /run tmpfs 919308 0 919308 0% /sys/fs/cgroup /dev/sda2 1268736 176612 1092124 14% /boot /dev/mapper/cl-var 4872192 158024 4714168 4% /var /dev/mapper/cl-home 18475008 37284 18437724 1% /home tmpfs 183864 8 183856 1% /run/user/1000 [rdc@localhost ~]$ As we can see, LVM volumes are in use. So it's simple to just reboot. This will remount /home and load the /etc/fstab configuration changes into active configuration. CentOS is now capable of working with disk quotas on /home. To enable full quota supprt, we must run the quotacheck command. quotacheck will create two files − aquota.user aquota.group These are used to store quota information for the quota enabled disks/partitions. Following are the common quotacheck switches. For this, we will use the edquota command, followed by the username − [root@localhost rdc]# edquota centos Disk quotas for user centos (uid 1000): Filesystem blocks soft hard inodes soft hard /dev/mapper/cl-root 12 0 0 13 0 0 /dev/mapper/cl-home 4084 0 0 140 0 0 Let's look at each column. Filesystem − It is the filesystem quotas for the user applied to Filesystem − It is the filesystem quotas for the user applied to blocks − How many blocks the user is currently using on each filesystem blocks − How many blocks the user is currently using on each filesystem soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period hard − Set blocks for a hard limit. Hard limit is total allowable quota hard − Set blocks for a hard limit. Hard limit is total allowable quota inodes − How many inodes the user is currently using inodes − How many inodes the user is currently using soft − Soft inode limit soft − Soft inode limit hard − Hard inode limit hard − Hard inode limit To check our current quota as a user − [centos@localhost ~]$ quota Disk quotas for user centos (uid 1000): Filesystem blocks quota limit grace files quota limit grace /dev/mapper/cl-home 6052604 56123456 61234568 475 0 0 [centos@localhost ~]$ Following is an error given to a user when the hard quota limit has exceeded. [centos@localhost Downloads]$ cp CentOS-7-x86_64-LiveKDE-1611.iso.part ../Desktop/ cp: cannot create regular file ‘../Desktop/CentOS-7-x86_64-LiveKDE- 1611.iso.part’: Disk quota exceeded [centos@localhost Downloads]$ As we can see, we are closely within this user's disk quota. Let's set a soft limit warning. This way, the user will have advance notice before quota limits expire. From experience, you will get end-user complaints when they come into work and need to spend 45 minutes clearing files to actually get to work. As an Administrator, we can check quota usage with the repquota command. [root@localhost Downloads]# repquota /home Block limits File limits User used soft hard grace used soft hard grace ---------------------------------------------------------------------------------------- root -- 0 0 0 3 0 0 centos -+ 6189824 56123456 61234568 541 520 540 6days [root@localhost Downloads]# As we can see, the user centos has exceeded their hard block quota and can no longer use any more disk space on /home. -+denotes a hard quota has been exceeded on the filesystem. When planning quotas, it is necessary to do a little math. What an Administrator needs to know is:How many users are on the system? How much free space to allocate amongst users/groups? How many bytes make up a block on the file system? Define quotas in terms of blocks as related to free disk-space.It is recommended to leave a "safe" buffer of free-space on the file system that will remain in worst case scenario: all quotas are simultaneously exceeded. This is especially on a partition that is used by the system for writing logs. systemd is the new way of running services on Linux. systemd has a superceded sysvinit. systemd brings faster boot-times to Linux and is now, a standard way to manage Linux services. While stable, systemd is still evolving. systemd as an init system, is used to manage both services and daemons that need status changes after the Linux kernel has been booted. By status change starting, stopping, reloading, and adjusting service state is applied. First, let's check the version of systemd currently running on our server. [centos@localhost ~]$ systemctl --version systemd 219 +PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ -LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN [centos@localhost ~]$ As of CentOS version 7, fully updated at the time of this writing systemd version 219 is the current stable version. We can also analyze the last server boot time with systemd-analyze [centos@localhost ~]$ systemd-analyze Startup finished in 1.580s (kernel) + 908ms (initrd) + 53.225s (userspace) = 55.713s [centos@localhost ~]$ When the system boot times are slower, we can use the systemd-analyze blame command. [centos@localhost ~]$ systemd-analyze blame 40.882s kdump.service 5.775s NetworkManager-wait-online.service 4.701s plymouth-quit-wait.service 3.586s postfix.service 3.121s systemd-udev-settle.service 2.649s tuned.service 1.848s libvirtd.service 1.437s network.service 875ms packagekit.service 855ms gdm.service 514ms firewalld.service 438ms rsyslog.service 436ms udisks2.service 398ms sshd.service 360ms boot.mount 336ms polkit.service 321ms accounts-daemon.service When working with systemd, it is important to understand the concept of units. Units are the resources systemd knows how to interpret. Units are categorized into 12 types as follows − .service .socket .device .mount .automount .swap .target .path .timer .snapshot .slice .scope For the most part, we will be working with .service as unit targets. It is recommended to do further research on the other types. As only .service units will apply to starting and stopping systemd services. Each unit is defined in a file located in either − /lib/systemd/system − base unit files /lib/systemd/system − base unit files /etc/systemd/system − modified unit files started at run-time /etc/systemd/system − modified unit files started at run-time To work with systemd, we will need to get very familiar with the systemctl command. Following are the most common command line switches for systemctl. systemctl [operation] example: systemctl --state [servicename.service] For a quick look at all the services running on our box. [root@localhost rdc]# systemctl -t service UNIT LOAD ACTIVE SUB DESCRIPTION abrt-ccpp.service loaded active exited Install ABRT coredump hook abrt-oops.service loaded active running ABRT kernel log watcher abrt-xorg.service loaded active running ABRT Xorg log watcher abrtd.service loaded active running ABRT Automated Bug Reporting Tool accounts-daemon.service loaded active running Accounts Service alsa-state.service loaded active running Manage Sound Card State (restore and store) atd.service loaded active running Job spooling tools auditd.service loaded active running Security Auditing Service avahi-daemon.service loaded active running Avahi mDNS/DNS-SD Stack blk-availability.service loaded active exited Availability of block devices bluetooth.service loaded active running Bluetooth service chronyd.service loaded active running NTP client/server Let's first, stop the bluetooth service. [root@localhost]# systemctl stop bluetooth [root@localhost]# systemctl --all -t service | grep bluetooth bluetooth.service loaded inactive dead Bluetooth service [root@localhost]# As we can see, the bluetooth service is now inactive. To start the bluetooth service again. [root@localhost]# systemctl start bluetooth [root@localhost]# systemctl --all -t service | grep bluetooth bluetooth.service loaded active running Bluetooth service [root@localhost]# Note − We didn't specify bluetooth.service, since the .service is implied. It is a good practice to think of the unit type appending the service we are dealing with. So, from here on, we will use the .service extension to clarify we are working on service unit operations. The primary actions that can be performed on a service are − The above actions are primarily used in the following scenarios − To check the status of a service − [root@localhost]# systemctl status network.service network.service - LSB: Bring up/down networking Loaded: loaded (/etc/rc.d/init.d/network; bad; vendor preset: disabled) Active: active (exited) since Sat 2017-01-14 04:43:48 EST; 1min 31s ago Docs: man:systemd-sysv-generator(8) Process: 923 ExecStart = /etc/rc.d/init.d/network start (code=exited, status = 0/SUCCESS) localhost.localdomain systemd[1]: Starting LSB: Bring up/down networking... localhost.localdomain network[923]: Bringing up loopback interface: [ OK ] localhost.localdomain systemd[1]: Started LSB: Bring up/down networking. [root@localhost]# Show us the current status of the networking service. If we want to see all the services related to networking, we can use − [root@localhost]# systemctl --all -t service | grep -i network network.service loaded active exited LSB: Bring up/ NetworkManager-wait-online.service loaded active exited Network Manager NetworkManager.service loaded active running Network Manager ntpd.service loaded inactive dead Network Time rhel-import-state.service loaded active exited Import network [root@localhost]# For those familiar with the sysinit method of managing services, it is important to make the transition to systemd. systemd is the new way starting and stopping daemon services in Linux. systemctl is the utility used to control systemd. systemctl provides CentOS administrators with the ability to perform a multitude of operations on systemd including − Configure systemd units Get status of systemd untis Start and stop services Enable / disable systemd services for runtime, etc. The command syntax for systemctl is pretty basic, but can tangle with switches and options. We will present the most essential functions of systemctl needed for administering CentOS Linux. Basic systemctl syntax: systemctl [OPTIONS] COMMAND [NAME] Following are the common commands used with systemctl − start stop restart reload status is-active list-units enable disable cat show We have already discussed start, stop, reload, restart, enable and disable with systemctl. So let's go over the remaining commonly used commands. In its most simple form, the status command can be used to see the system status as a whole − [root@localhost rdc]# systemctl status ● localhost.localdomain State: running Jobs: 0 queued Failed: 0 units Since: Thu 2017-01-19 19:14:37 EST; 4h 5min ago CGroup: / ├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 21 ├─user.slice │ └─user-1002.slice │ └─session-1.scope │ ├─2869 gdm-session-worker [pam/gdm-password] │ ├─2881 /usr/bin/gnome-keyring-daemon --daemonize --login │ ├─2888 gnome-session --session gnome-classic │ ├─2895 dbus-launch --sh-syntax --exit-with-session The above output has been condensed. In the real-world systemctl status will output about 100 lines of treed process statuses. Let's say we want to check the status of our firewall service − [root@localhost rdc]# systemctl status firewalld ● firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2017-01-19 19:14:55 EST; 4h 12min ago Docs: man:firewalld(1) Main PID: 825 (firewalld) CGroup: /system.slice/firewalld.service └─825 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid As you see, our firewall service is currently active and has been for over 4 hours. The list-units command allows us to list all the units of a certain type. Let's check for sockets managed by systemd − [root@localhost]# systemctl list-units --type=socket UNIT LOAD ACTIVE SUB DESCRIPTION avahi-daemon.socket loaded active running Avahi mDNS/DNS-SD Stack Activation Socket cups.socket loaded active running CUPS Printing Service Sockets dbus.socket loaded active running D-Bus System Message Bus Socket dm-event.socket loaded active listening Device-mapper event daemon FIFOs iscsid.socket loaded active listening Open-iSCSI iscsid Socket iscsiuio.socket loaded active listening Open-iSCSI iscsiuio Socket lvm2-lvmetad.socket loaded active running LVM2 metadata daemon socket lvm2-lvmpolld.socket loaded active listening LVM2 poll daemon socket rpcbind.socket loaded active listening RPCbind Server Activation Socket systemd-initctl.socket loaded active listening /dev/initctl Compatibility Named Pipe systemd-journald.socket loaded active running Journal Socket systemd-shutdownd.socket loaded active listening Delayed Shutdown Socket systemd-udevd-control.socket loaded active running udev Control Socket systemd-udevd-kernel.socket loaded active running udev Kernel Socket virtlockd.socket loaded active listening Virtual machine lock manager socket virtlogd.socket loaded active listening Virtual machine log manager socket Now let’s check the current running services − [root@localhost rdc]# systemctl list-units --type=service UNIT LOAD ACTIVE SUB DESCRIPTION abrt-ccpp.service loaded active exited Install ABRT coredump hook abrt-oops.service loaded active running ABRT kernel log watcher abrt-xorg.service loaded active running ABRT Xorg log watcher abrtd.service loaded active running ABRT Automated Bug Reporting Tool accounts-daemon.service loaded active running Accounts Service alsa-state.service loaded active running Manage Sound Card State (restore and store) atd.service loaded active running Job spooling tools auditd.service loaded active running Security Auditing Service The is-active command is an example of systemctl commands designed to return the status information of a unit. [root@localhost rdc]# systemctl is-active ksm.service active cat is one of the seldomly used command. Instead of using cat at the shell and typing the path to a unit file, simply use systemctl cat. [root@localhost]# systemctl cat firewalld # /usr/lib/systemd/system/firewalld.service [Unit] Description=firewalld - dynamic firewall daemon Before=network.target Before=libvirtd.service Before = NetworkManager.service After=dbus.service After=polkit.service Conflicts=iptables.service ip6tables.service ebtables.service ipset.service Documentation=man:firewalld(1) [Service] EnvironmentFile = -/etc/sysconfig/firewalld ExecStart = /usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS ExecReload = /bin/kill -HUP $MAINPID # supress to log debug and error output also to /var/log/messages StandardOutput = null StandardError = null Type = dbus BusName = org.fedoraproject.FirewallD1 [Install] WantedBy = basic.target Alias = dbus-org.fedoraproject.FirewallD1.service [root@localhost]# Now that we have explored both systemd and systemctl in more detail, let's use them to manage the resources in cgroups or control groups. cgroups or Control Groups are a feature of the Linux kernel that allows an administrator to allocate or cap the system resources for services and also group. To list active control groups running, we can use the following ps command − [root@localhost]# ps xawf -eo pid,user,cgroup,args 8362 root - \_ [kworker/1:2] 1 root - /usr/lib/systemd/systemd --switched- root --system -- deserialize 21 507 root 7:cpuacct,cpu:/system.slice /usr/lib/systemd/systemd-journald 527 root 7:cpuacct,cpu:/system.slice /usr/sbin/lvmetad -f 540 root 7:cpuacct,cpu:/system.slice /usr/lib/systemd/systemd-udevd 715 root 7:cpuacct,cpu:/system.slice /sbin/auditd -n 731 root 7:cpuacct,cpu:/system.slice \_ /sbin/audispd 734 root 7:cpuacct,cpu:/system.slice \_ /usr/sbin/sedispatch 737 polkitd 7:cpuacct,cpu:/system.slice /usr/lib/polkit-1/polkitd --no-debug 738 rtkit 6:memory:/system.slice/rtki /usr/libexec/rtkit-daemon 740 dbus 7:cpuacct,cpu:/system.slice /bin/dbus-daemon --system -- address=systemd: --nofork --nopidfile --systemd-activation Resource Management, as of CentOS 6.X, has been redefined with the systemd init implementation. When thinking Resource Management for services, the main thing to focus on are cgroups. cgroups have advanced with systemd in both functionality and simplicity. The goal of cgroups in resource management is -no one service can take the system, as a whole, down. Or no single service process (perhaps a poorly written PHP script) will cripple the server functionality by consuming too many resources. cgroups allow resource control of units for the following resources − CPU − Limit cpu intensive tasks that are not critical as other, less intensive tasks CPU − Limit cpu intensive tasks that are not critical as other, less intensive tasks Memory − Limit how much memory a service can consume Memory − Limit how much memory a service can consume Disks − Limit disk i/o Disks − Limit disk i/o **CPU Time: ** Tasks needing less CPU priority can have custom configured CPU Slices. Let's take a look at the following two services for example. [root@localhost]# systemctl cat polite.service # /etc/systemd/system/polite.service [Unit] Description = Polite service limits CPU Slice and Memory After=remote-fs.target nss-lookup.target [Service] MemoryLimit = 1M ExecStart = /usr/bin/sha1sum /dev/zero ExecStop = /bin/kill -WINCH ${MAINPID} WantedBy=multi-user.target # /etc/systemd/system/polite.service.d/50-CPUShares.conf [Service] CPUShares = 1024 [root@localhost]# [root@localhost]# systemctl cat evil.service # /etc/systemd/system/evil.service [Unit] Description = I Eat You CPU After=remote-fs.target nss-lookup.target [Service] ExecStart = /usr/bin/md5sum /dev/zero ExecStop = /bin/kill -WINCH ${MAINPID} WantedBy=multi-user.target # /etc/systemd/system/evil.service.d/50-CPUShares.conf [Service] CPUShares = 1024 [root@localhost]# Let's set Polite Service using a lesser CPU priority − systemctl set-property polite.service CPUShares = 20 /system.slice/polite.service 1 70.5 124.0K - - /system.slice/evil.service 1 99.5 304.0K - - As we can see, over a period of normal system idle time, both rogue processes are still using CPU cycles. However, the one set to have less time-slices is using less CPU time. With this in mind, we can see how using a lesser time time-slice would allow essential tasks better access the system resources. To set services for each resource, the set-property method defines the following parameters − systemctl set-property name parameter=value Most often services will be limited by CPU use, Memory limits and Read / Write IO. After changing each, it is necessary to reload systemd and restart the service − systemctl set-property foo.service CPUShares = 250 systemctl daemon-reload systemctl restart foo.service To make custom cgroups in CentOS Linux, we need to first install services and configure them. Step 1 − Install libcgroup (if not already installed). [root@localhost]# yum install libcgroup Package libcgroup-0.41-11.el7.x86_64 already installed and latest version Nothing to do [root@localhost]# As we can see, by default CentOS 7 has libcgroup installed with the everything installer. Using a minimal installer will require us to install the libcgroup utilities along with any dependencies. Step 2 − Start and enable the cgconfig service. [root@localhost]# systemctl enable cgconfig Created symlink from /etc/systemd/system/sysinit.target.wants/cgconfig.service to /usr/lib/systemd/system/cgconfig.service. [root@localhost]# systemctl start cgconfig [root@localhost]# systemctl status cgconfig ● cgconfig.service - Control Group configuration service Loaded: loaded (/usr/lib/systemd/system/cgconfig.service; enabled; vendor preset: disabled) Active: active (exited) since Mon 2017-01-23 02:51:42 EST; 1min 21s ago Main PID: 4692 (code=exited, status = 0/SUCCESS) Memory: 0B CGroup: /system.slice/cgconfig.service Jan 23 02:51:42 localhost.localdomain systemd[1]: Starting Control Group configuration service... Jan 23 02:51:42 localhost.localdomain systemd[1]: Started Control Group configuration service. [root@localhost]# Following are the common commands used with Process Management–bg, fg, nohup, ps, pstree, top, kill, killall, free, uptime, nice. Quick Note: Process PID in Linux In Linux every running process is given a PID or Process ID Number. This PID is how CentOS identifies a particular process. As we have discussed, systemd is the first process started and given a PID of 1 in CentOS. Pgrep is used to get Linux PID for a given process name. [root@CentOS]# pgrep systemd 1 [root@CentOS]# As seen, the pgrep command returns the current PID of systemd. When working with processes in Linux it is important to know how basic foregrounding and backgrounding processes is performed at the command line. fg − Bringsthe process to the foreground fg − Bringsthe process to the foreground bg − Movesthe process to the background bg − Movesthe process to the background jobs − List of the current processes attached to the shell jobs − List of the current processes attached to the shell ctrl+z − Control + z key combination to sleep the current process ctrl+z − Control + z key combination to sleep the current process & − Startsthe process in the background & − Startsthe process in the background Let's start using the shell command sleep. sleep will simply do as it is named, sleep for a defined period of time: sleep. [root@CentOS ~]$ jobs [root@CentOS ~]$ sleep 10 & [1] 12454 [root@CentOS ~]$ sleep 20 & [2] 12479 [root@CentOS ~]$ jobs [1]- Running sleep 10 & [2]+ Running sleep 20 & [cnetos@CentOS ~]$ Now, let's bring the first job to the foreground − [root@CentOS ~]$ fg 1 sleep 10 If you are following along, you'll notice the foreground job is stuck in your shell. Now, let's put the process to sleep, then re-enable it in the background. Hit control+z Type: bg 1, sending the first job into the background and starting it. [root@CentOS ~]$ fg 1 sleep 20 ^Z [1]+ Stopped sleep 20 [root@CentOS ~]$ bg 1 [1]+ sleep 20 & [root@CentOS ~]$ When working from a shell or terminal, it is worth noting that by default all the processes and jobs attached to the shell will terminate when the shell is closed or the user logs out. When using nohup the process will continue to run if the user logs out or closes the shell to which the process is attached. [root@CentOS]# nohup ping www.google.com & [1] 27299 nohup: ignoring input and appending output to ‘nohup.out’ [root@CentOS]# pgrep ping 27299 [root@CentOS]# kill -KILL `pgrep ping` [1]+ Killed nohup ping www.google.com [root@CentOS rdc]# cat nohup.out PING www.google.com (216.58.193.68) 56(84) bytes of data. 64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 1 ttl = 128 time = 51.6 ms 64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 2 ttl = 128 time = 54.2 ms 64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 3 ttl = 128 time = 52.7 ms The ps command is commonly used by administrators to investigate snapshots of a specific process. ps is commonly used with grep to filter out a specific process to analyze. [root@CentOS ~]$ ps axw | grep python 762 ? Ssl 0:01 /usr/bin/python -Es /usr/sbin/firewalld --nofork -nopid 1296 ? Ssl 0:00 /usr/bin/python -Es /usr/sbin/tuned -l -P 15550 pts/0 S+ 0:00 grep --color=auto python In the above command, we see all the processes using the python interpreter. Also included with the results were our grep command, looking for the string python. Following are the most common command line switches used with ps. To see all processes in use by the nobody user − [root@CentOS ~]$ ps -u nobody PID TTY TIME CMD 1853 ? 00:00:00 dnsmasq [root@CentOS ~]$ To see all information about the firewalld process − [root@CentOS ~]$ ps -wl -C firewalld F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 S 0 762 1 0 80 0 - 81786 poll_s ? 00:00:01 firewalld [root@CentOS ~]$ Let's see which processes are consuming the most memory − [root@CentOS ~]$ ps aux --sort=-pmem | head -10 USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND cnetos 6130 0.7 5.7 1344512 108364 ? Sl 02:16 0:29 /usr/bin/gnome-shell cnetos 6449 0.0 3.4 1375872 64440 ? Sl 02:16 0:00 /usr/libexec/evolution-calendar-factory root 5404 0.6 2.1 190256 39920 tty1 Ssl+ 02:15 0:27 /usr/bin/Xorg :0 -background none -noreset -audit 4 -verbose -auth /run/gdm/auth-for-gdm-iDefCt/database -seat seat0 -nolisten tcp vt1 cnetos 6296 0.0 1.7 1081944 32136 ? Sl 02:16 0:00 /usr/libexec/evolution/3.12/evolution-alarm-notify cnetos 6350 0.0 1.5 560728 29844 ? Sl 02:16 0:01 /usr/bin/prlsga cnetos 6158 0.0 1.4 1026956 28004 ? Sl 02:16 0:00 /usr/libexec/gnome-shell-calendar-server cnetos 6169 0.0 1.4 1120028 27576 ? Sl 02:16 0:00 /usr/libexec/evolution-source-registry root 762 0.0 1.4 327144 26724 ? Ssl 02:09 0:01 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid cnetos 6026 0.0 1.4 1090832 26376 ? Sl 02:16 0:00 /usr/libexec/gnome-settings-daemon [root@CentOS ~]$ See all the processes by user centos and format, displaying the custom output − [cnetos@CentOS ~]$ ps -u cnetos -o pid,uname,comm PID USER COMMAND 5802 centos gnome-keyring-d 5812 cnetos gnome-session 5819 cnetos dbus-launch 5820 cnetos dbus-daemon 5888 cnetos gvfsd 5893 cnetos gvfsd-fuse 5980 cnetos ssh-agent 5996 cnetos at-spi-bus-laun pstree is similar to ps but is not often used. It displays the processes in a neater tree fashion. [centos@CentOS ~]$ pstree systemd─┬─ModemManager───2*[{ModemManager}] ├─NetworkManager─┬─dhclient │ └─2*[{NetworkManager}] ├─2*[abrt-watch-log] ├─abrtd ├─accounts-daemon───2*[{accounts-daemon}] ├─alsactl ├─at-spi-bus-laun─┬─dbus-daemon───{dbus-daemon} │ └─3*[{at-spi-bus-laun}] ├─at-spi2-registr───2*[{at-spi2-registr}] ├─atd ├─auditd─┬─audispd─┬─sedispatch │ │ └─{audispd} │ └─{auditd} ├─avahi-daemon───avahi-daemon ├─caribou───2*[{caribou}] ├─cgrulesengd ├─chronyd ├─colord───2*[{colord}] ├─crond ├─cupsd The total output from pstree can exceed 100 lines. Usually, ps will give more useful information. top is one of the most often used commands when troubleshooting performance issues in Linux. It is useful for real-time stats and process monitoring in Linux. Following is the default output of top when brought up from the command line. Tasks: 170 total, 1 running, 169 sleeping, 0 stopped, 0 zombie %Cpu(s): 2.3 us, 2.0 sy, 0.0 ni, 95.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem : 1879668 total, 177020 free, 607544 used, 1095104 buff/cache KiB Swap: 3145724 total, 3145428 free, 296 used. 1034648 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 5404 root 20 0 197832 48024 6744 S 1.3 2.6 1:13.22 Xorg 8013 centos 20 0 555316 23104 13140 S 1.0 1.2 0:14.89 gnome-terminal- 6339 centos 20 0 332336 6016 3248 S 0.3 0.3 0:23.71 prlcc 6351 centos 20 0 21044 1532 1292 S 0.3 0.1 0:02.66 prlshprof Common hot keys used while running top (hot keys are accessed by pressing the key as top is running in your shell). Following are the common command line switches for top. Sorting options screen in top, presented using Shift+F. This screen allows customization of top display and sort options. Fields Management for window 1:Def, whose current sort field is %MEM Navigate with Up/Dn, Right selects for move then <Enter> or Left commits, 'd' or <Space> toggles display, 's' sets sort. Use 'q' or <Esc> to end! * PID = Process Id TGID = Thread Group Id * USER = Effective User Name ENVIRON = Environment vars * PR = Priority vMj = Major Faults delta * NI = Nice Value vMn = Minor Faults delta * VIRT = Virtual Image (KiB) USED = Res+Swap Size (KiB) * RES = Resident Size (KiB) nsIPC = IPC namespace Inode * SHR = Shared Memory (KiB) nsMNT = MNT namespace Inode * S = Process Status nsNET = NET namespace Inode * %CPU = CPU Usage nsPID = PID namespace Inode * %MEM = Memory Usage (RES) nsUSER = USER namespace Inode * TIME+ = CPU Time, hundredths nsUTS = UTS namespace Inode * COMMAND = Command Name/Line PPID = Parent Process pid UID = Effective User Id top, showing the processes for user rdc and sorted by memory usage − PID USER %MEM PR NI VIRT RES SHR S %CPU TIME+ COMMAND 6130 rdc 6.2 20 0 1349592 117160 33232 S 0.0 1:09.34 gnome-shell 6449 rdc 3.4 20 0 1375872 64428 21400 S 0.0 0:00.43 evolution-calen 6296 rdc 1.7 20 0 1081944 32140 22596 S 0.0 0:00.40 evolution-alarm 6350 rdc 1.6 20 0 560728 29844 4256 S 0.0 0:10.16 prlsga 6281 rdc 1.5 20 0 1027176 28808 17680 S 0.0 0:00.78 nautilus 6158 rdc 1.5 20 0 1026956 28004 19072 S 0.0 0:00.20 gnome-shell-cal Showing valid top fields (condensed) − [centos@CentOS ~]$ top -O PID PPID UID USER RUID RUSER SUID SUSER GID GROUP PGRP TTY TPGID The kill command is used to kill a process from the command shell via its PID. When killing a process, we need to specify a signal to send. The signal lets the kernel know how we want to end the process. The most commonly used signals are − SIGTERM is implied as the kernel lets a process know it should stop soon as it is safe to do so. SIGTERM gives the process an opportunity to exit gracefully and perform safe exit operations. SIGTERM is implied as the kernel lets a process know it should stop soon as it is safe to do so. SIGTERM gives the process an opportunity to exit gracefully and perform safe exit operations. SIGHUP most daemons will restart when sent SIGHUP. This is often used on the processes when changes have been made to a configuration file. SIGHUP most daemons will restart when sent SIGHUP. This is often used on the processes when changes have been made to a configuration file. SIGKILL since SIGTERM is the equivalent to asking a process to shut down. The kernel needs an option to end a process that will not comply with requests. When a process is hung, the SIGKILL option is used to shut the process down explicitly. SIGKILL since SIGTERM is the equivalent to asking a process to shut down. The kernel needs an option to end a process that will not comply with requests. When a process is hung, the SIGKILL option is used to shut the process down explicitly. For a list off all signals that can be sent with kill the -l option can be used − [root@CentOS]# kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX [root@CentOS rdc]# Using SIGHUP to restart system. [root@CentOS]# pgrep systemd 1 464 500 643 15071 [root@CentOS]# kill -HUP 1 [root@CentOS]# pgrep systemd 1 464 500 643 15196 15197 15198 [root@CentOS]# pkill will allow the administrator to send a kill signal by the process name. [root@CentOS]# pgrep ping 19450 [root@CentOS]# pkill -9 ping [root@CentOS]# pgrep ping [root@CentOS]# killall will kill all the processes. Be careful using killall as root, as it will kill all the processes for all users. [root@CentOS]# killall chrome free is a pretty simple command often used to quickly check the memory of a system. It displays the total amount of used physical and swap memory. [root@CentOS]# free total used free shared buff/cache available Mem: 1879668 526284 699796 10304 653588 1141412 Swap: 3145724 0 3145724 [root@CentOS]# nice will allow an administrator to set the scheduling priority of a process in terms of CPU usages. The niceness is basically how the kernel will schedule CPU time slices for a process or job. By default, it is assumed the process is given equal access to CPU resources. First, let's use top to check the niceness of the currently running processes. PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 28 root 39 19 0 0 0 S 0.0 0.0 0:00.17 khugepaged 690 root 39 19 16808 1396 1164 S 0.0 0.1 0:00.01 alsactl] 9598 rdc 39 19 980596 21904 10284 S 0.0 1.2 0:00.27 tracker-extract 9599 rdc 39 19 469876 9608 6980 S 0.0 0.5 0:00.04 tracker-miner-a 9609 rdc 39 19 636528 13172 8044 S 0.0 0.7 0:00.12 tracker-miner-f 9611 rdc 39 19 469620 8984 6496 S 0.0 0.5 0:00.02 tracker-miner-u 27 root 25 5 0 0 0 S 0.0 0.0 0:00.00 ksmd 637 rtkit 21 1 164648 1276 1068 S 0.0 0.1 0:00.11 rtkit-daemon 1 root 20 0 128096 6712 3964 S 0.3 0.4 0:03.57 systemd 2 root 20 0 0 0 0 S 0.0 0.0 0:00.01 kthreadd 3 root 20 0 0 0 0 S 0.0 0.0 0:00.50 ksoftirqd/0 7 root 20 0 0 0 0 S 0.0 0.0 0:00.00 migration/0 8 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_bh 9 root 20 0 0 0 0 S 0.0 0.0 0:02.07 rcu_sched We want to focus on the NICE column depicted by NI. The niceness range can be anywhere between -20 to positive 19. -20 represents the highest given priority. nohup nice --20 ping www.google.com & renice allows us to change the current priority of a process that is already running. renice 17 -p 30727 The above command will lower the priority of our ping process command. firewalld is the default front-end controller for iptables on CentOS. The firewalld front-end has two main advantages over raw iptables − Uses easy-to-configure and implement zones abstracting chains and rules. Uses easy-to-configure and implement zones abstracting chains and rules. Rulesets are dynamic, meaning stateful connections are uninterrupted when the settings are changed and/or modified. Rulesets are dynamic, meaning stateful connections are uninterrupted when the settings are changed and/or modified. Remember, firewalld is the wrapper for iptables - not a replacement. While custom iptables commands can be used with firewalld, it is recommended to use firewalld as to not break the firewall functionality. First, let's make sure firewalld is both started and enabled. [root@CentOS rdc]# systemctl status firewalld ● firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2017-01-26 21:42:05 MST; 3h 46min ago Docs: man:firewalld(1) Main PID: 712 (firewalld) Memory: 34.7M CGroup: /system.slice/firewalld.service └─712 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid We can see, firewalld is both active (to start on boot) and currently running. If inactive or not started we can use − systemctl start firewalld && systemctl enable firewalld Now that we have our firewalld service configured, let's assure it is operational. [root@CentOS]# firewall-cmd --state running [root@CentOS]# We can see, the firewalld service is fully functional. Firewalld works on the concept of zones. A zone is applied to network interfaces through the Network Manager. We will discuss this in configuring networking. But for now, by default, changing the default zone will change any network adapters left in the default state of "Default Zone". Let's take a quick look at each zone that comes out-of-the-box with firewalld. drop Low trust level. All incoming connections and packetsare dropped and only outgoing connections are possible via statefullness block Incoming connections are replied with an icmp message letting the initiator know the request is prohibited public All networks are restricted. However, selected incoming connections can be explicitly allowed external Configures firewalld for NAT. Internal network remains private but reachable dmz Only certain incoming connections are allowed. Used for systems in DMZ isolation work By default, trust more computers on the network assuming the system is in a secured work environment hone By default, more services are unfiltered. Assuming a system is on a home network where services such as NFS, SAMBA and SSDP will be used trusted All machines on the network are trusted. Most incoming connections are allowed unfettered. This is not meant for interfaces exposed to the Internet The most common zones to use are:public, drop, work, and home. Some scenarios where each common zone would be used are − public − It is the most common zone used by an administrator. It will let you apply the custom settings and abide by RFC specifications for operations on a LAN. public − It is the most common zone used by an administrator. It will let you apply the custom settings and abide by RFC specifications for operations on a LAN. drop − A good example of when to use drop is at a security conference, on public WiFi, or on an interface connected directly to the Internet. drop assumes all unsolicited requests are malicious including ICMP probes. So any request out of state will not receive a reply. The downside of drop is that it can break the functionality of applications in certain situations requiring strict RFC compliance. drop − A good example of when to use drop is at a security conference, on public WiFi, or on an interface connected directly to the Internet. drop assumes all unsolicited requests are malicious including ICMP probes. So any request out of state will not receive a reply. The downside of drop is that it can break the functionality of applications in certain situations requiring strict RFC compliance. work − You are on a semi-secure corporate LAN. Where all traffic can be assumed moderately safe. This means it is not WiFi and we possibly have IDS, IPS, and physical security or 802.1x in place. We also should be familiar with the people using the LAN. work − You are on a semi-secure corporate LAN. Where all traffic can be assumed moderately safe. This means it is not WiFi and we possibly have IDS, IPS, and physical security or 802.1x in place. We also should be familiar with the people using the LAN. home − You are on a home LAN. You are personally accountable for every system and the user on the LAN. You know every machine on the LAN and that none have been compromised. Often new services are brought up for media sharing amongst trusted individuals and you don't need to take extra time for the sake of security. home − You are on a home LAN. You are personally accountable for every system and the user on the LAN. You know every machine on the LAN and that none have been compromised. Often new services are brought up for media sharing amongst trusted individuals and you don't need to take extra time for the sake of security. Zones and network interfaces work on a one to many level. One network interface can only have a single zone applied to it at a time. While, a zone can be applied to many interfaces simultaneously. Let's see what zones are available and what are the currently applied zone. [root@CentOS]# firewall-cmd --get-zones work drop internal external trusted home dmz public block [root@CentOS]# firewall-cmd --get-default-zone public [root@CentOS]# Ready to add some customized rules in firewalld? First, let's see what our box looks like, to a portscanner from outside. bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1 Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:36 MST Nmap scan report for centos.shared (10.211.55.1) Host is up (0.00046s latency). Not shown: 1023 filtered ports PORT STATE SERVICE 22/tcp open ssh Nmap done: 1 IP address (1 host up) scanned in 3.71 seconds bash-3.2# Let's allow the incoming requests to port 80. First, check to see what zone is applied as default. [root@CentOs]# firewall-cmd --get-default-zone public [root@CentOS]# Then, set the rule allowing port 80 to the current default zone. [root@CentOS]# firewall-cmd --zone=public --add-port = 80/tcp success [root@CentOS]# Now, let's check our box after allowing port 80 connections. bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1 Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:42 MST Nmap scan report for centos.shared (10.211.55.1) Host is up (0.00053s latency). Not shown: 1022 filtered ports PORT STATE SERVICE 22/tcp open ssh 80/tcp closed http Nmap done: 1 IP address (1 host up) scanned in 3.67 seconds bash-3.2# It now allows unsolicited traffic to 80. Let's put the default zone to drop and see what happens to port scan. [root@CentOS]# firewall-cmd --set-default-zone=drop success [root@CentOS]# firewall-cmd --get-default-zone drop [root@CentOs]# Now let's scan the host with the network interface in a more secure zone. bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1 Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:50 MST Nmap scan report for centos.shared (10.211.55.1) Host is up (0.00094s latency). All 1024 scanned ports on centos.shared (10.211.55.1) are filtered Nmap done: 1 IP address (1 host up) scanned in 12.61 seconds bash-3.2# Now, everything is filtered from outside. As demonstrated below, the host will not even respond to ICMP ping requests when in drop. bash-3.2# ping 10.211.55.1 PING 10.211.55.1 (10.211.55.1): 56 data bytes Request timeout for icmp_seq 0 Request timeout for icmp_seq 1 Request timeout for icmp_seq 2 Let's set the default zone to public again. [root@CentOs]# firewall-cmd --set-default-zone=public success [root@CentOS]# firewall-cmd --get-default-zone public [root@CentOS]# Now let's check our current filtering ruleset in public. [root@CentOS]# firewall-cmd --zone=public --list-all public (active) target: default icmp-block-inversion: no interfaces: enp0s5 sources: services: dhcpv6-client ssh ports: 80/tcp protocols: masquerade: no forward-ports: sourceports: icmp-blocks: rich rules: [root@CentOS rdc]# As configured, our port 80 filter rule is only within the context of the running configuration. This means once the system is rebooted or the firewalld service is restarted, our rule will be discarded. We will be configuring an httpd daemon soon, so let's make our changes persistent − [root@CentOS]# firewall-cmd --zone=public --add-port=80/tcp --permanent success [root@CentOS]# systemctl restart firewalld [root@CentOS]# Now our port 80 rule in the public zone is persistent across reboots and service restarts. Following are the common firewalld commands applied with firewall-cmd. These are the basic concepts of administrating and configuring firewalld. Configuring host-based firewall services in CentOS can be a complex task in more sophisticated networking scenarios. Advanced usage and configuration of firewalld and iptables in CentOS can take an entire tutorial. However, we have presented the basics that should be enough to complete a majority of daily tasks. PHP is the one of the most prolific web languages in use today. Installing a LAMP Stack on CentOS is something every system administrator will need to perform, most likely sooner than later. A traditional LAMP Stack consists of (L)inux (A)pache (M)ySQL (P)HP. There are three main components to a LAMP Stack on CentOS − Web Server Web Development Platform / Language Database Server Note − The term LAMP Stack can also include the following technologies: PostgreSQL, MariaDB, Perl, Python, Ruby, NGINX Webserver. For this tutorial, we will stick with the traditional LAMP Stack of CentOS GNU Linux: Apache web server, MySQL Database Server, and PHP. We will actually be using MariaDB. MySQL configuration files, databases and tables are transparent to MariaDB. MariaDB is now included in the standard CentOS repository instead of MySQL. This is due to the limitations of licensing and open-source compliance, since Oracle has taken over the development of MySQL. The first thing we need to do is install Apache. [root@CentOS]# yum install httpd Loaded plugins: fastestmirror, langpacks base | 3.6 kB 00:00:00 extras | 3.4 kB 00:00:00 updates | 3.4 kB 00:00:00 extras/7/x86_64/primary_d | 121 kB 00:00:00 Loading mirror speeds from cached hostfile * base: mirror.sigmanet.com * extras: linux.mirrors.es.net * updates: mirror.eboundhost.com Resolving Dependencies --> Running transaction check ---> Package httpd.x86_64 0:2.4.6-45.el7.centos will be installed --> Processing Dependency: httpd-tools = 2.4.6-45.el7.centos for package: httpd-2.4.6-45.el7.centos.x86_64 --> Processing Dependency: /etc/mime.types for package: httpd-2.4.645.el7.centos.x86_64 --> Running transaction check ---> Package httpd-tools.x86_64 0:2.4.6-45.el7.centos will be installed ---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed --> Finished Dependency Resolution Installed: httpd.x86_64 0:2.4.6-45.el7.centos Dependency Installed: httpd-tools.x86_64 0:2.4.6-45.el7.centos mailcap.noarch 0:2.1.41-2.el7 Complete! [root@CentOS]# Let's configure httpd service. [root@CentOS]# systemctl start httpd && systemctl enable httpd Now, let's make sure the web-server is accessible through firewalld. bash-3.2# nmap -sS -p 1-1024 -T 5 -sV 10.211.55.1 Starting Nmap 7.30 ( https://nmap.org ) at 2017-01-28 02:00 MST Nmap scan report for centos.shared (10.211.55.1) Host is up (0.00054s latency). Not shown: 1022 filtered ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.6.1 (protocol 2.0) 80/tcp open http Apache httpd 2.4.6 ((CentOS)) Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 10.82 seconds bash-3.2# As you can see by the nmap service probe, Apache webserver is listening and responding to requests on the CentOS host. [root@CentOS rdc]# yum install mariadb-server.x86_64 && yum install mariadb- devel.x86_64 && mariadb.x86_64 && mariadb-libs.x86_64 We are installing the following repository packages for MariaDB − The main MariaDB Server daemon package. Files need to compile from the source with MySQL/MariaDB compatibility. MariaDB client utilities for administering MariaDB Server from the command line. Common libraries for MariaDB that could be needed for other applications compiled with MySQL/MariaDB support. Now, let's start and enable the MariaDB Service. [root@CentOS]# systemctl start mariadb [root@CentOS]# systemctl enable mariadb Note − Unlike Apache, we will not enable connections to MariaDB through our host-based firewall (firewalld). When using a database server, it's considered best security practice to only allow local socket connections, unless the remote socket access is specifically needed. Let's make sure the MariaDB Server is accepting connections. [root@CentOS#] netstat -lnt Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN tcp 0 0 192.168.122.1:53 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN [root@CentOS rdc]# As we can see, MariaDB is listening on port 3306 tcp. We will leave our host-based firewall (firewalld) blocking incoming connections to port 3306. [root@CentOS#] yum install php.x86_64 && php-common.x86_64 && php-mysql.x86_64 && php-mysqlnd.x86_64 && php-pdo.x86_64 && php-soap.x86_64 && php-xml.x86_64 I'd recommend installing the following php packages for common compatibility − php-common.x86_64 php-mysql.x86_64 php-mysqlnd.x86_64 php-pdo.x86_64 php-soap.x86_64 php-xml.x86_64 [root@CentOS]# yum install -y php-common.x86_64 php-mysql.x86_64 php- mysqlnd.x86_64 php-pdo.x86_64 php-soap.x86_64 php-xml.x86_64 This is our simple php file located in the Apache webroot of /var/www/html/ [root@CentOS]# cat /var/www/html/index.php <html> <head> <title>PHP Test Page</title> </head> <body> PHP Install <?php echo "We are now running PHP on GNU Centos Linux!<br />" ?> </body> </html> [root@CentOS]# Let's change the owning group of our page to the system user our http daemon is running under. [root@CentOS]# chgrp httpd /var/www/html/index.php && chmod g+rx /var/www/html/index.php --- When requested manually via ncat. bash-3.2# ncat 10.211.55.1 80 GET / index.php HTTP/1.1 200 OK Date: Sat, 28 Jan 2017 12:06:02 GMT Server: Apache/2.4.6 (CentOS) PHP/5.4.16 X-Powered-By: PHP/5.4.16 Content-Length: 137 Connection: close Content-Type: text/html; charset=UTF-8 <html> <head> <title>PHP Test Page</title> </head> <body> PHP Install We are now running PHP on GNU Centos Linux!<br /> </body> </html> bash-3.2# PHP and LAMP are very popular web-programming technologies. LAMP installation and configuration is sure to come up on your list of needs as a CentOS Administrator. Easy to use CentOS packages have taken a lot of work from compiling Apache, MySQL, and PHP from the source code. Python is a widely used interpreted language that has brought professionalism to the world of coding scripted applications on Linux (and other operating systems). Where Perl was once the industry standard, Python has surpassed Perl in many respects. Some strengths of Python versus Perl are − Rapid progression in refinement Rapid progression in refinement Libraries that are standard to the language Libraries that are standard to the language Readability of the code is thought out in language definition Readability of the code is thought out in language definition Many professional frameworks for everything from GUI support to web-development Many professional frameworks for everything from GUI support to web-development Python can do anything Perl can do, and in a lot of cases in a better manner. Though Perl still has its place amongst the toolbox of a Linux admin, learning Python is a great choice as a skill set. The biggest drawbacks of Python are sometimes related to its strengths. In history, Python was originally designed to teach programming. At times, its core foundations of "easily readable" and "doing things the right way" can cause unnecessary complexities when writing a simple code. Also, its standard libraries have caused problems in transitioning from versions 2.X to 3.X. Python scripts are actually used at the core of CentOS for functions vital to the functionality of the operating system. Because of this, it is important to isolate our development Python environment from CentOS' core Python environment. For starters, there are currently two versions of Python: Python 2.X and Python 3.X. Both stages are still in active production, though version 2.X is quickly closing in on depreciation (and has been for a few years). The reason for the two active versions of Python was basically fixing the shortcomings of version 2.X. This required some core functionality of version 3.X to be redone in ways it could not support some version 2.X scripts. Basically, the best way to overcome this transition is: Develop for 3.X and keep up with the latest 2.X version for legacy scripts. Currently, CentOS 7.X relies on a semi-current revision of version 2.X. As of this writing, the most current versions of Python are: 3.4.6 and 2.7.13. Don't let this confuse or draw any conclusions of Python. Setting up a Python environment is really pretty simple. With Python frameworks and libraries, this task is actually really easy to accomplish. Before setting up our Python environments, we need a sane environment. To start, let's make sure our CentOS install is fully updated and get some building utilities installed. Step 1 − Update CentOS. [root@CentOS]# yum -y update Step 2 − Install build utilities. [root@CentOS]# yum -y groupinstall "development tools" Step 3 − Install some needed packages. [root@CentOS]# yum install -y zlib-dev openssl-devel sqlite-devel bip2-devel Now we need to install current Python 2.X and 3.X from source. Download compressed archives Extract files Compile source code Let's start by creating a build directory for each Python install in /usr/src/ [root@CentOS]# mkdir -p /usr/src/pythonSource Now let's download the source tarballs for each − [root@CentOS]# wget https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tar.xz [root@CentOS]# wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz Now we need to extract each from the archive. Step 1 − Install xz-libs and extract the tarballs. [root@CentOS]# yum install xz-libs [root@CentOS python3]# xz -d ./*.xz [root@CentOS python3]# ls Python-2.7.13.tar Python-3.6.0.tar [root@CentOS python3]# Step 2 − Untar each installer from its tarball. [root@CentOS]# tar -xvf ./Python-2.7.13.tar [root@CentOS]# tar -xvf ./Python-3.6.0.tar Step 3 − Enter each directory and run the configure script. [root@CentOS]# ./configure --prefix=/usr/local root@CentOS]# make altinstall Note − Be sure to use altinstall and not install. This will keep CentOS and development versions of Python separated. Otherwise, you may break the functionality of CentOS. You will now see the compilation process begins. Grab a cup of coffee and take a 15minute break until completion. Since we installed all the needed dependencies for Python, the compilation process should complete without error. Let's make sure we have the latest 2.X version of Python installed. [root@CentOS Python-2.7.13]# /usr/local/bin/python2.7 -V Python 2.7.13 [root@CentOS Python-2.7.13]# Note − You will want to prefix the shebang line pointing to our development environment for Python 2.X. [root@CentOS Python-2.7.13]# cat ver.py #!/usr/local/bin/python2.7 import sys print(sys.version) [root@CentOS Python-2.7.13]# ./ver.py 2.7.13 (default, Jan 29 2017, 02:24:08) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] Just like that, we have separate Python installs for versions 2.X and 3.X. From here, we can use each and utilities such as pip and virtualenv to further ease the burden of managing Python environments and package installation. Ruby is a great language for both web development and Linux Administration. Ruby provides many benefits found in all the previous languages discussed: PHP, Python, and Perl. To install Ruby, it is best to bootstrap through the rbenv which allows the administrators to easily install and manage Ruby Environments. The other method for installing Ruby is the standard CentOS packages for Ruby. It is advisable to use the rbenv method with all its benefits. CentOS packages will be easier for the non-Ruby savvy. First, let's get some needed dependencies for rbenv installer. git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzzip2 autoconf automake libtool bison curl sqlite-devel Most of these packages may already be installed depending on the chosen options and roles when installing CentOS. It is good to install everything we are unsure about as this can lead to less headache when installing packages requiring dependencies. [root@CentOS]# yum -y install git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison curl sqlite-devel Now as the user who will be using Ruby − [rdc@CentOS ~]$ git clone https://github.com/rbenv/rbenv.git [rdc@CentOS ~]$ https://github.com/rbenv/ruby-build.git ruby-build will provide installation features to rbenv − Note − We need to switch to root or an administration user before running install.sh [rdc@CentOS ruby-build]$ cd ~/ruby-build [rdc@CentOS ruby-build]# ./install.sh Let's set our shell for rbenv and assure we have installedthe correct options. [rdc@CentOS ~]$ source ~/rbenv/rbenv.d/exec/gem-rehash.bash [rdc@CentOS ruby-build]$ ~/rbenv/bin/rbenv rbenv 1.1.0-2-g4f8925a Usage: rbenv <command> [<args>] Some useful rbenv commands are − Let's now install Ruby − [rdc@CentOS bin]$ ~/rbenv/bin/rbenv install -v 2.2.1 After compilation completes − [rdc@CentOS ~]$ ./ruby -v ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux] [rdc@CentOS ~]$ We now have a working Ruby environment with an updated and working version of Ruby 2.X branch. This is the most simple method. However, it can be limited by the version and gems packaged from CentOS. For serious development work, it is highly recommended to use the rbenv method to install Ruby. Install Ruby, needed development packages, and some common gems. [root@CentOS rdc]# yum install -y ruby.x86_64 ruby-devel.x86_64 ruby- libs.x86_64 ruby-gem-json.x86_64 rubygem-rake.noarch Unfortunately, we are left with somewhat outdated version of Ruby. [root@CentOS rdc]# ruby -v ruby 2.0.0p648 (2015-12-16) [x86_64-linux] [root@CentOS rdc]# Perl has been around for a long time. It was originally designed as a reporting language used for parsing text files. With increased popularity, Perl has added a module support or CPAN, sockets, threading, and other features needed in a powerful scripting language. The biggest advantage of Perl over PHP, Python, or Ruby is: it gets things done with minimal fuss. This philosophy of Perl does not always mean it gets things done the right way. However, for administration tasks on Linux, Perl is considered as the go-to choice for a scripting language. Some advantages of Perl over Python or Ruby are − Powerful text processing Powerful text processing Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby) Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby) Perl can do anything (almost) Perl can do anything (almost) Some drawbacks of Perl are − Syntax can be confusing Syntax can be confusing Coding style in Perl can be unique and bog down collaboration Coding style in Perl can be unique and bog down collaboration Perl is not really Object Oriented Perl is not really Object Oriented Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used. Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used. When deciding whether to use Perl, Python or PHP; the following questions should be asked − Will this application ever need versioning? Will other people ever need to modify the code? Will other people need to use this application? Will this application ever be used on another machine or CPU architecture? If the answers to all the above are "no", Perl is a good choice and may speed things up in terms of end-results. With this mentioned, let's configure our CentOS server to use the most recent version of Perl. Before installing Perl, we need to understand the support for Perl. Officially, Perl is only supported far back as the last two stable versions. So, we want to be sure to keep our development environment isolated from the CentOS version. The reason for isolation is: if someone releases a tool in Perl to the CentOS community, more than likely it will be modified to work on Perl as shipped with CentOS. However, we also want to have the latest version installed for development purposes. Like Python, CentOS ships Perl focused on the reliability and not cutting edge. Let's check our current version of Perl on CentOS 7. [root@CentOS]# perl -v This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi We are currently running Perl 5.16.3. The most current version as of this writing is: perl-5.24.0 We definitely want to upgrade our version, being able to use up-to-date Perl modules in our code. Fortunately, there is a great tool for maintaining Perl environments and keeping our CentOS version of Perl isolated. It is called perlbrew. Let's install Perl Brew. [root@CentOS]# curl -L https://install.perlbrew.pl | bash % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 170 100 170 0 0 396 0 --:--:-- --:--:-- --:--:-- 397 100 1247 100 1247 0 0 1929 0 --:--:-- --:--:-- --:--:-- 1929 Now that we have Perl Brew installed, let's make an environment for the latest version of Perl. First, we will need the currently installed version of Perl to bootstrap the perlbrew install. Thus, let's get some needed Perl modules from the CentOS repository. Note − When available we always want to use CentOS Perl modules versus CPAN with our CentOS Perl installation. Step 1 − Install CentOS Perl Make::Maker module. [root@CentOS]# yum -y install perl-ExtUtils-MakeMaker.noarch Step 2 − Install the latest version of perl. [root@CentOS build]# source ~/perl5/perlbrew/etc/bashrc [root@CentOS build]# perlbrew install -n -j4 --threads perl-5.24.1 The options we chose for our Perl install are − n − No tests n − No tests j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU) j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU) threads − Enable threading support for Perl threads − Enable threading support for Perl After our installation has been performed successfully, let's switch to our newest Perl environment. [root@CentOS]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1 A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it. [root@CentOS]# perl -v This is perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linuxthread-multi (with 1 registered patch, see perl -V for more detail) Copyright 1987-2017, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using "man perl" or "perldoc perl". If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page. [root@CentOS]# Simple perl script printing perl version running within the context of our perlbrew environment − [root@CentOS]# cat ./ver.pl #!/usr/bin/perl print $^V . "\n"; [root@CentOS]# perl ./ver.pl v5.24.1 [root@CentOS]# Once perl is installed, we can load cpan modules with perl brew's cpanm − [root@CentOS]# perl-brew install-cpanm Now let's use the cpanm installer to make the LWP module with our current Perl version of 5.24.1 in perl brew. Step 1 − Switch to the context of our current Perl version. [root@CentOS ~]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1 A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it. [root@CentOS ~]# Step 2 − Install LWP User Agent Perl Module. [root@CentOS ~]# ~/perl5/perlbrew/bin/cpanm -i LWP::UserAgent Step 3 − Now let's test our Perl environment with the new CPAN module. [root@CentOS ~]# cat ./get_header.pl #!/usr/bin/perl use LWP; my $browser = LWP::UserAgent->new(); my $response = $browser->get("http://www.slcc.edu/"); unless(!$response->is_success) { print $response->header("Server"); } [root@CentOS ~]# perl ./get_header.pl Microsoft-IIS/8.5 [root@CentOS ~]# There you have it! Perl Brew makes isolating perl environments a snap and can be considered as a best practice as things get with Perl. LDAP known as Light Weight Directory Access Protocol is a protocol used for accessing X.500 service containers within an enterprise known from a directory. Those who are familiar with Windows Server Administration can think of LDAP as being very similar in nature to Active Directory. It is even a widely used concept of intertwining Windows workstations into an OpenLDAP CentOS enterprise. On the other spectrum, a CentOS Linux workstation can share resources and participate with the basic functionality in a Windows Domain. Deploying LDAP on CentOS as a Directory Server Agent, Directory System Agent, or DSA (these acronyms are all one and the same) is similar to older Novell Netware installations using the Directory Tree structure with NDS. LDAP was basically created as an efficient way to access X.500 directories with enterprise resources. Both X.500 and LDAP share the same characteristics and are so similar that LDAP clients can access X.500 directories with some helpers. While LDAP also has its own directory server called slapd. The main difference between LDAP and DAP is, the lightweight version is designed to operate over TCP. While DAP uses the full OSI Model. With the advent of the Internet, TCP/IP and Ethernet prominence in networks of today, it is rare to come across a Directory Services implantation using both DAP and native X.500 enterprise directories outside specific legacy computing models. The main components used with openldap for CentOS Linux are − Note − When naming your enterprise, it is a best practice to use the .local TLD. Using a .net or .com can cause difficulties when segregating an online and internal domain infrastructure. Imagine the extra work for a company internally using acme.com for both external and internal operations. Hence, it can be wise to have Internet resources called acme.com or acme.net. Then, the local networking enterprise resources is depicted as acme.local. This will entail configuring DNS records, but will pay in simplicity, eloquence and security. Install the openldap, openldap-servers, openldap-clients and migrationstools from YUM. [root@localhost]# yum -y install openldap openldap-servers openldap-clients migration tools Loaded plugins: fastestmirror, langpacks updates | 3.4 kB 00:00:00 updates/7/x86_64/primary_db | 2.2 MB 00:00:05 Determining fastest mirrors (1/2): extras/7/x86_64/primary_db | 121 kB 00:00:01 (2/2): base/7/x86_64/primary_db | 5.6 MB 00:00:16 Package openldap-2.4.40-13.el7.x86_64 already installed and latest version Resolving Dependencies --> Running transaction check ---> Package openldap-clients.x86_64 0:2.4.40-13.el7 will be installed ---> Package openldap-servers.x86_64 0:2.4.40-13.el7 will be installed --> Finished Dependency Resolution base/7/x86_64/group_gz | 155 kB 00:00:00 Dependencies Resolved =============================================================================== =============================================================================== Package Arch Version Repository Size =============================================================================== =============================================================================== Installing: openldap-clients x86_64 2.4.40-13.el7 base 188 k openldap-servers x86_64 2.4.40-13.el7 base 2.1 M Transaction Summary =============================================================================== =============================================================================== Install 2 Packages Total download size: 2.3 M Installed size: 5.3 M Downloading packages: Installed: openldap-clients.x86_64 0:2.4.40-13.el7 openldap-servers.x86_64 0:2.4.40-13.el7 Complete! [root@localhost]# Now, let's start and enable the slapd service − [root@centos]# systemctl start slapd [root@centos]# systemctl enable slapd At this point, let's assure we have our openldap structure in /etc/openldap. root@localhost]# ls /etc/openldap/ certs check_password.conf ldap.conf schema slapd.d [root@localhost]# Then make sure our slapd service is running. root@centos]# netstat -antup | grep slapd tcp 0 0 0.0.0.0:389 0.0.0.0:* LISTEN 1641/slapd tcp6 0 0 :::389 :::* LISTEN 1641/slapd [root@centos]# Next, let's configure our Open LDAP installation. Make sure our system ldap user has been created. [root@localhost]# id ldap uid=55(ldap) gid=55(ldap) groups=55(ldap) [root@localhost]# Generate our LDAP credentials. [root@localhost]# slappasswd New password: Re-enter new password: {SSHA}20RSyjVv6S6r43DFPeJgASDLlLoSU8g.a10 [root@localhost]# We need to save the output from slappasswd. Step 1 − Configure LDAP for domain and add administrative user. First, we want to set up our openLDAP environment. Following is a template to use with the ldapmodify command. dn: olcDatabase={2}hdb,cn=config changetype: modify replace: olcSuffix olcSuffix: dc=vmnet,dc=local dn: olcDatabase = {2}hdb,cn=config changetype: modify replace: olcRootDN olcRootDN: cn=ldapadm,dc=vmnet,dc=local dn: olcDatabase = {2}hdb,cn=config changetype: modify replace: olcRootPW olcRootPW: <output from slap Make changes to: /etc/openldap/slapd.d/cn=config/olcDatabase = {1}monitor.ldif with the ldapmodify command. [root@localhost]# ldapmodify -Y EXTERNAL -H ldapi:/// -f /home/rdc/Documents/db.ldif SASL/EXTERNAL authentication started SASL username: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth SASL SSF: 0 modifying entry "olcDatabase = {2}hdb,cn=config" modifying entry "olcDatabase = {2}hdb,cn=config" modifying entry "olcDatabase = {2}hdb,cn=config" [root@localhost cn=config]# Let's check the modified LDAP configuration. root@linux1 ~]# vi /etc/openldap/slapd.d/cn=config/olcDatabase={2}hdb.ldif [root@centos]# cat /etc/openldap/slapd.d/cn\=config/olcDatabase\=\{2\}hdb.ldif # AUTO-GENERATED FILE - DO NOT EDIT!! Use ldapmodify. # CRC32 a163f14c dn: olcDatabase = {2}hdb objectClass: olcDatabaseConfig objectClass: olcHdbConfig olcDatabase: {2}hdb olcDbDirectory: /var/lib/ldap olcDbIndex: objectClass eq,pres olcDbIndex: ou,cn,mail,surname,givenname eq,pres,sub structuralObjectClass: olcHdbConfig entryUUID: 1bd9aa2a-8516-1036-934b-f7eac1189139 creatorsName: cn=config createTimestamp: 20170212022422Z olcSuffix: dc=vmnet,dc=local olcRootDN: cn=ldapadm,dc=vmnet,dc=local olcRootPW:: e1NTSEF1bUVyb1VzZTRjc2dkYVdGaDY0T0k = entryCSN: 20170215204423.726622Z#000000#000#000000 modifiersName: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth modifyTimestamp: 20170215204423Z [root@centos]# As you can see, our LDAP enterprise modifications were successful. Next, we want to create an self-signed ssl certificate for OpenLDAP. This will secure the communication between the enterprise server and clients. Step 2 − Create a self-signed certificate for OpenLDAP. We will use openssl to create a self-signed ssl certificate. Go to the next chapter, Create LDAP SSL Certificate with openssl for instructions to secure communications with OpenLDAP. Then when ssl certificates are configured, we will have completed our OpenLDAP enterprise configuration. Step 3 − Configure OpenLDAP to use secure communications with certificate. Create a certs.ldif file in vim with the following information − dn: cn=config changetype: modify replace: olcTLSCertificateFile olcTLSCertificateFile: /etc/openldap/certs/yourGeneratedCertFile.pem dn: cn=config changetype: modify replace: olcTLSCertificateKeyFile olcTLSCertificateKeyFile: /etc/openldap/certs/youGeneratedKeyFile.pem Next, again, use the ldapmodify command to merge the changes into the OpenLDAP configuration. [root@centos rdc]# ldapmodify -Y EXTERNAL -H ldapi:/// -f certs.ldif SASL/EXTERNAL authentication started SASL username: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth SASL SSF: 0 modifying entry "cn=config" [root@centos]# Finally, let's test our OpenLADP configuration. [root@centos]# slaptest -u config file testing succeeded [root@centos]# Step 4 − Set up slapd database. cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG && chown ldap:ldap /var/lib/ldap/* Updates the OpenLDAP Schema. Add the cosine and nis LDAP schemas. ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif Finally, create the enterprise schema and add it to the current OpenLDAP configuration. Following is for a domain called vmnet.local with an LDAP Admin called ldapadm. dn: dc=vmnet,dc=local dc: vmnet objectClass: top objectClass: domain dn: cn=ldapadm ,dc=vmnet,dc=local objectClass: organizationalRole cn: ldapadm description: LDAP Manager dn: ou = People,dc=vmnet,dc=local objectClass: organizationalUnit ou: People dn: ou = Group,dc=vmnet,dc=local objectClass: organizationalUnit ou: Group Finally, import this into the current OpenLDAP schema. [root@centos]# ldapadd -x -W -D "cn=ldapadm,dc=vmnet,dc=local" -f ./base.ldif Enter LDAP Password: adding new entry "dc=vmnet,dc=local" adding new entry "cn=ldapadm ,dc=vmnet,dc=local" adding new entry "ou=People,dc=vmnet,dc=local" adding new entry "ou=Group,dc=vmnet,dc=local" [root@centos]# Step 5 − Set up an OpenLDAP Enterprise Users. Open vim or your favorite text editor and copy the following format. This is setup for a user named "entacct" on the "vmnet.local" LDAP domain. dn: uid=entacct,ou=People,dc=vmnet,dc=local objectClass: top objectClass: account objectClass: posixAccount objectClass: shadowAccount cn: entacct uid: entacct uidNumber: 9999 gidNumber: 100 homeDirectory: /home/enyacct loginShell: /bin/bash gecos: Enterprise User Account 001 userPassword: {crypt}x shadowLastChange: 17058 shadowMin: 0 shadowMax: 99999 shadowWarning: 7 Now import the above files, as saved, into the OpenLdap Schema. [root@centos]# ldapadd -x -W -D "cn=ldapadm,dc=vmnet,dc=local" -f entuser.ldif Enter LDAP Password: adding new entry "uid=entacct,ou=People,dc=vmnet,dc=local" [root@centos]# Before the users can access the LDAP Enterprise, we need to assign a password as follows − ldappasswd -s password123 -W -D "cn=ldapadm,dc=entacct,dc=local" -x "uid=entacct ,ou=People,dc=vmnet,dc=local" -s specifies the password for the user -x is the username to which password updated is applied -D is the *distinguished name" to authenticate against LDAP schema. Finally, before logging into the Enterprise account, let's check our OpenLDAP entry. [root@centos rdc]# ldapsearch -x cn=entacct -b dc=vmnet,dc=local # extended LDIF # # LDAPv3 # base <dc=vmnet,dc=local> with scope subtree # filter: cn=entacct # requesting: ALL # # entacct, People, vmnet.local dn: uid=entacct,ou=People,dc=vmnet,dc=local objectClass: top objectClass: account objectClass: posixAccount objectClass: shadowAccount cn: entacct uid: entacct uidNumber: 9999 gidNumber: 100 homeDirectory: /home/enyacct loginShell: /bin/bash gecos: Enterprise User Account 001 userPassword:: e2NyeXB0fXg= shadowLastChange: 17058 shadowMin: 0 shadowMax: 99999 shadowWarning: 7 Converting things like /etc/passwd and /etc/groups to OpenLDAP authentication requires the use of migration tools. These are included in the migrationtools package. Then, installed into /usr/share/migrationtools. [root@centos openldap-servers]# ls -l /usr/share/migrationtools/ total 128 -rwxr-xr-x. 1 root root 2652 Jun 9 2014 migrate_aliases.pl -rwxr-xr-x. 1 root root 2950 Jun 9 2014 migrate_all_netinfo_offline.sh -rwxr-xr-x. 1 root root 2946 Jun 9 2014 migrate_all_netinfo_online.sh -rwxr-xr-x. 1 root root 3011 Jun 9 2014 migrate_all_nis_offline.sh -rwxr-xr-x. 1 root root 3006 Jun 9 2014 migrate_all_nis_online.sh -rwxr-xr-x. 1 root root 3164 Jun 9 2014 migrate_all_nisplus_offline.sh -rwxr-xr-x. 1 root root 3146 Jun 9 2014 migrate_all_nisplus_online.sh -rwxr-xr-x. 1 root root 5267 Jun 9 2014 migrate_all_offline.sh -rwxr-xr-x. 1 root root 7468 Jun 9 2014 migrate_all_online.sh -rwxr-xr-x. 1 root root 3278 Jun 9 2014 migrate_automount.pl -rwxr-xr-x. 1 root root 2608 Jun 9 2014 migrate_base.pl Step 6 − Finally, we need to allow access to the slapd service so it can service requests. firewall-cmd --permanent --add-service=ldap firewall-cmd --reload Configuring LDAP client access requires the following packages on the client: openldap, open-ldap clients, and nss_ldap. Configuring LDAP authentication for client systems is a bit easier. Step 1 − Install dependent packeges − # yum install -y openldap-clients nss-pam-ldapd Step 2 − Configure LDAP authentication with authconfig. authconfig --enableldap --enableldapauth --ldapserver=10.25.0.1 -- ldapbasedn="dc=vmnet,dc=local" --enablemkhomedir --update Step 3 − Restart nslcd service. systemctl restart nslcd TLS is the new standard for socket layer security, proceeding SSL. TLS offers better encryption standards with other security and protocol wrapper features advancing SSL. Often, the terms TLS and SSL are used interchangeably. However, as a professional CentOS Administrator, it is important to note the differences and history separating each. SSL goes up to version 3.0. SSL was developed and promoted as an industry standard under Netscape. After Netscape was purchased by AOL (an ISP popular in the 90's otherwise known as America Online) AOL never really promoted the change needed for security improvements to SSL. At version 3.1, SSL technology moved into the open systems standards and was changed to TLS. Since copyrights on SSL were still owned by AOL a new term was coined − TLS - Transport Layer Security. So it is important to acknowledge that TLS is in fact different from SSL. Especially, as older SSL technologies have known security issues and some are considered obsolete today. Note − This tutorial will use the term TLS when speaking of technologies 3.1 and higher. Then SSL when commenting specific to SSL technologies 3.0 and lower. The following table shows how TLS and SSL versioning would relate to one another. I have heard a few people speak in terms of SSL version 3.2. However, they probably got the terminology from reading a blog. As a professional administrator, we always want to use the standard terminology. Hence, while speaking SSL should be a reference to past technologies. Simple things can make a CentOS job seeker look like a seasoned CS Major. TLS performs two main functions important to the users of the Internet today: One, it verifies who a party is, known as authentication. Two, it offers end-to-end encryption at the transport layer for upper level protocols that lack this native feature (ftp, http, email protocols, and more). The first, verifies who a party is and is important to security as end-to-end encryption. If a consumer has an encrypted connection to a website that is not authorized to take payment, financial data is still at risk. This is what every phishing site will fail to have: a properly signed TLS certificate verifying website operators are who they claim to be from a trusted CA. There are only two methods to get around not having a properly signed certificate: trick the user into allowing trust of a web-browser for a self-signed certificate or hope the user is not tech savvy and will not know the importance of a trusted Certificate Authority (or a CA). In this tutorial, we will be using what is known as a self-signed certificate. This means, without explicitly giving this certificate the status of trusted in every web browser visiting the web-site, an error will be displayed discouraging the users from visiting the site. Then, it will make the user jump though a few actions before accessing a site with a self-signed certificate. Remember for the sake of security this is a good thing. openssl is the standard for open-source implementations of TLS. openssl is used on systems such as Linux, BSD distributions, OS X, and even supports Windows. openssl is important, as it provides transport layer security and abstracts the detailed programming of Authentication and end-to-end encryption for a developer. This is why openssl is used with almost every single open-source application using TLS. It is also installed by default on every modern version of Linux. By default, openssl should be installed on CentOS from at least version 5 onwards. Just to assure, let's try installing openssl via YUM. Just run install, as YUM is intelligent enough to let us know if a package is already installed. If we are running an older version of CentOS for compatibility reasons, doing a yum -y install will ensure openssl is updated against the semi-recent heart-bleed vulnerability. When running the installer, it was found there was actually an update to openssl. [root@centos]# yum -y install openssl Resolving Dependencies --> Running transaction check ---> Package openssl.x86_64 1:1.0.1e-60.el7 will be updated ---> Package openssl.x86_64 1:1.0.1e-60.el7_3.1 will be an update --> Processing Dependency: openssl-libs(x86-64) = 1:1.0.1e-60.el7_3.1 for package: 1:openssl-1.0.1e-60.el7_3.1.x86_64 --> Running transaction check ---> Package openssl-libs.x86_64 1:1.0.1e-60.el7 will be updated ---> Package openssl-libs.x86_64 1:1.0.1e-60.el7_3.1 will be an update --> Finished Dependency Resolution Dependencies Resolved =============================================================================== =============================================================================== Package Arch Version Repository Size =============================================================================== =============================================================================== Updating: openssl x86_64 1:1.0.1e-60.el7_3.1 updates 713 k Updating for dependencies: This is a method to create a self-signed for our previous OpenLDAP installation. To create an self-signed OpenLDAP Certificate. openssl req -new -x509 -nodes -out /etc/openldap/certs/myldaplocal.pem -keyout /etc/openldap/certs/myldaplocal.pem -days 365 [root@centos]# openssl req -new -x509 -nodes -out /etc/openldap/certs/vmnet.pem -keyout /etc/openldap/certs/vmnet.pem -days 365 Generating a 2048 bit RSA private key .............................................+++ ................................................+++ writing new private key to '/etc/openldap/certs/vmnet.pem' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [XX]:US State or Province Name (full name) []:Califonia Locality Name (eg, city) [Default City]:LA Organization Name (eg, company) [Default Company Ltd]:vmnet Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []:centos Email Address []:bob@bobber.net [root@centos]# Now our OpenLDAP certificates should be placed in /etc/openldap/certs/ [root@centos]# ls /etc/openldap/certs/*.pem /etc/openldap/certs/vmnetcert.pem /etc/openldap/certs/vmnetkey.pem [root@centos]# As you can see, we have both the certificate and key installed in the /etc/openldap/certs/ directories. Finally, we need to change the permissions to each, since they are currently owned by the root user. [root@centos]# chown -R ldap:ldap /etc/openldap/certs/*.pem [root@centos]# ls -ld /etc/openldap/certs/*.pem -rw-r--r--. 1 ldap ldap 1395 Feb 20 10:00 /etc/openldap/certs/vmnetcert.pem -rw-r--r--. 1 ldap ldap 1704 Feb 20 10:00 /etc/openldap/certs/vmnetkey.pem [root@centos]# In this tutorial, we will assume Apache is already installed. We did install Apache in another tutorial (configuring CentOS Firewall) and will go into advanced installation of Apache for a future tutorial. So, if you have not already installed Apache, please follow along. Once Apache HTTPd can be installed using the following steps − Step 1 − Install mod_ssl for Apache httpd server. First we need to configure Apache with mod_ssl. Using the YUM package manager this is pretty simple − [root@centos]# yum -y install mod_ssl Then reload your Apache daemon to ensure Apache uses the new configuration. [root@centos]# systemctl reload httpd At this point, Apache is configured to support TLS connections on the local host. Step 2 − Create the self-signed ssl certificate. First, let's configure our private TLS key directory. [root@centos]# mkdir /etc/ssl/private [root@centos]# chmod 700 /etc/ssl/private/ Note − Be sure only the root has read/write access to this directory. With world read/write access, your private key can be used to decrypt sniffed traffic. Generating the certificate and key files. [root@centos]# sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/self-gen-apache.key -out /etc/ssl/certs/self-sign-apache.crt Generating a 2048 bit RSA private key ..........+++ ....+++ ----- Country Name (2 letter code) [XX]:US State or Province Name (full name) []:xx Locality Name (eg, city) [Default City]:xxxx Organization Name (eg, company) [Default Company Ltd]:VMNET Organizational Unit Name (eg, section) []: Common Name (eg, your name or your server's hostname) []:centos.vmnet.local Email Address []: [root@centos]# Note − You can use public IP Address of the server if you don't have a registered domain name. Let's take a look at our certificate − [root@centos]# openssl x509 -in self-sign-apache.crt -text -noout Certificate: Data: Version: 3 (0x2) Serial Number: 17620849408802622302 (0xf489d52d94550b5e) Signature Algorithm: sha256WithRSAEncryption Issuer: C=US, ST=UT, L=xxxx, O=VMNET, CN=centos.vmnet.local Validity Not Before: Feb 24 07:07:55 2017 GMT Not After : Feb 24 07:07:55 2018 GMT Subject: C=US, ST=UT, L=xxxx, O=VMNET, CN=centos.vmnet.local Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:c1:74:3e:fc:03:ca:06:95:8d:3a:0b:7e:1a:56: f3:8d:de:c4:7e:ee:f9:fa:79:82:bf:db:a9:6d:2a: 57:e5:4c:31:83:cf:92:c4:e7:16:57:59:02:9e:38: 47:00:cd:b8:31:b8:34:55:1c:a3:5d:cd:b4:8c:b0: 66:0c:0c:81:8b:7e:65:26:50:9d:b7:ab:78:95:a5: 31:5e:87:81:cd:43:fc:4d:00:47:5e:06:d0:cb:71: 9b:2a:ab:f0:90:ce:81:45:0d:ae:a8:84:80:c5:0e: 79:8a:c1:9b:f4:38:5d:9e:94:4e:3a:3f:bd:cc:89: e5:96:4a:44:f5:3d:13:20:3d:6a:c6:4d:91:be:aa: ef:2e:d5:81:ea:82:c6:09:4f:40:74:c1:b1:37:6c: ff:50:08:dc:c8:f0:67:75:12:ab:cd:8d:3e:7b:59: e0:83:64:5d:0c:ab:93:e2:1c:78:f0:f4:80:9e:42: 7d:49:57:71:a2:96:c6:b8:44:16:93:6c:62:87:0f: 5c:fe:df:29:89:03:6e:e5:6d:db:0a:65:b2:5e:1d: c8:07:3d:8a:f0:6c:7f:f3:b9:32:b4:97:f6:71:81: 6b:97:e3:08:bd:d6:f8:19:40:f1:15:7e:f2:fd:a5: 12:24:08:39:fa:b6:cc:69:4e:53:1d:7e:9a:be:4b: Here is an explanation for each option we used with the openssl command − Next, we want to create a Diffie-Heliman group for negotiating PFS with clients. [centos#] openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048 This will take from 5 to 15 minutes. Perfect Forward Secrecy − Used to secure session data in case the private key has been compromised. This will generate a key used between the client and the server that is unique for each session. Now, add the Perfect Forward Secrecy configuration to our certificate. [root@centos]# cat /etc/ssl/certs/dhparam.pem | tee -a /etc/ssl/certs/self-sign-apache.crt We will be making changes to /etc/httpd/conf.d/ssl.conf − We will make the following changes to ssl.conf. However, before we do that we should back the original file up. When making changes to a production server in an advanced text editor like vi or emcas, it is a best practice to always backup configuration files before making edits. [root@centos]# cp /etc/httpd/conf.d/ssl.conf ~/ Now let's continue our edits after copying a known-working copy of ssl.conf to the root of our home folder. Locate Edit both DocumentRoot and ServerName as follows. \\# General setup for the virtual host, inherited from global configuration DocumentRoot "/var/www/html" ServerName centos.vmnet.local:443 DocumentRoot this is the path to your default apache directory. In this folder should be a default page that will display a HTTP request asking for the default page of your web server or site. ServerName is the server name that can be either an ip address or the host name of the server. For TLS, it is a best practice to create a certificate with a host name. From our OpenLdap tutorial, we created a hostname of centos on the local enterprise domain: vmnet.local Now we want to comment the following lines out. # SSL Protocol support: # List the enable protocol levels with which clients will be able to # connect. Disable SSLv2 access by default: ~~~~> #SSLProtocol all -SSLv2 # SSL Cipher Suite: # List the ciphers that the client is permitted to negotiate. # See the mod_ssl documentation for a complete list. ~~~~> #SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5:!SEED:!IDEA Then let Apache know where to find our certificate and private/public key pair. # Server Certificate: # Point SSLCertificateFile at a PEM encoded certificate. If # the certificate is encrypted, then you will be prompted for a # pass phrase. Note that a kill -HUP will prompt again. A new # certificate can be generated using the genkey(1) command. ~~~~> SSLCertificateFile /etc/ssl/certs/self-sign-apache.crt specify path to our private key file # Server Private Key: # If the key is not combined with the certificate, use this # directive to point at the key file. Keep in mind that if # you've both a RSA and a DSA private key you can configure # both in parallel (to also allow the use of DSA ciphers, etc.) ~~~~> SSLCertificateKeyFile /etc/ssl/private/self-gen-apache.key Finally, we need to allow inbound connections to https over port 443. In this chapter, we will learn a little about the background of how Apache HTTP Server came into existence and then install the most current stable version on CentOS Linux 7. Apache is a web server that has been around for a long time. In fact, almost as long as the existence of http itself! Apache started out as a rather small project at the National Center for Supercomputing Applications also known as NCSA. In the mid-90's "httpd", as it was called, was by far the most popular web-server platform on the Internet, having about 90% or more of the market share. At this time, it was a simple project. Skilled I.T. staff known as webmaster were responsible for: maintaining web server platforms and web server software as well as both front-end and back-end site development. At the core of httpd was its ability to use custom modules known as plugins or extensions. A webmaster was also skilled enough to write patches to core server software. Sometime in the late-mid-90's, the senior developer and project manager for httpd left NCSA to do other things. This left the most popular web-daemon in a state of stagnation. Since the use of httpd was so widespread a group of seasoned httpd webmasters called for a summit reqarding the future of httpd. It was decided to coordinate and apply the best extensions and patches into a current stable release. Then, the current grand-daddy of http servers was born and christened Apache HTTP Server. Little Known Historical Fact − Apache was not named after a Native American Tribe of warriors. It was in fact coined and named with a twist: being made from many fixes (or patches) from many talented Computer Scientists: a patchy or Apache. Step 1 − Install httpd via yum. yum -y install httpd At this point Apache HTTP Server will install via yum. Step 2 − Edit httpd.conf file specific to your httpd needs. With a default Apache install, the configuration file for Apache is named httpd.conf and is located in /etc/httpd/. So, let's open it in vim. The first few lines of httpd.conf opened in vim − # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. We will make the following changes to allow our CentOS install to serve http requests from http port 80. # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # #Listen 12.34.56.78:80 Listen 80 From here, we change Apache to listen on a certain port or IP Address. For example, if we want to run httpd services on an alternative port such as 8080. Or if we have our web-server configured with multiple interfaces with separate IP addresses. Keeps Apache from attaching to every listening daemon onto every IP Address. This is useful to stop specifying only IPv6 or IPv4 traffic. Or even binding to all network interfaces on a multi-homed host. # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # Listen 10.0.0.25:80 #Listen 80 The "document root" is the default directory where Apache will look for an index file to serve for requests upon visiting your sever: http://www.yoursite.com/ will retrieve and serve the index file from your document root. # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/var/www/html" Step 3 − Start and Enable the httpd Service. [root@centos rdc]# systemctl start httpd && systemctl reload httpd [root@centos rdc]# Step 4 − Configure firewall to allow access to port 80 requests. [root@centos]# firewall-cmd --add-service=http --permanent As touched upon briefly when configuring CentOS for use with Maria DB, there is no native MySQL package in the CentOS 7 yum repository. To account for this, we will need to add a MySQL hosted repository. One thing to note is MySQL will require a different set of base dependencies from MariaDB. Also using MySQL will break the concept and philosophy of CentOS: production packages designed for maximum reliability. So when deciding whether to use Maria or MySQL one should weigh two options: Will my current DB Schema work with Maria? What advantage does installing MySQL over Maria give me? Maria components are 100% transparent to MySQL structure, with some added efficiency with better licensing. Unless a compelling reason comes along, it is advised to configure CentOS to use MariaDB. The biggest reasons for favoring Maria on CentOS are − Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria. Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria. CentOS is designed to run with Maria. Hence, Maria will offer better stability. CentOS is designed to run with Maria. Hence, Maria will offer better stability. Maria is officially supported for CentOS. Maria is officially supported for CentOS. We will want to download and install the MySQL repository from − http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm Step 1 − Download the Repository. The repository comes conveniently packaged in an rpm package for easy installation. It can be downloaded with wget − [root@centos]# wget http://repo.mysql.com/mysql-community-release-el75.noarch.rpm --2017-02-26 03:18:36-- http://repo.mysql.com/mysql-community-release-el75.noarch.rpm Resolving repo.mysql.com (repo.mysql.com)... 104.86.98.130 Step 2 − Install MySQL From YUM. We can now use the yum package manager to install MySQL − [root@centos]# yum -y install mysql-server Step 3 − Start and Enable the MySQL Daemon Service. [root@centos]# systemctl start mysql [root@centos]# systemctl enable mysql Step 4 − Make sure our MySQL service is up and running. [root@centos]# netstat -antup | grep 3306 tcp6 0 0 :::3306 :::* LISTEN 6572/mysqld [root@centos]# Note − We will not allow any firewall rules through. It's common to have MySQL configured to use Unix Domain Sockets. This assures only the web-server of the LAMP stack, locally, can access the MySQL database, taking out a complete dimension in the attack vector at the database software. In order to send an email from our CentOS 7 server, we will need the setup to configure a modern Mail Transfer Agent (MTA). Mail Transfer Agent is the daemon responsible for sending outbound mail for system users or corporate Internet Domains via SMTP. It is worth noting, this tutorial only teaches the process of setting up the daemon for local use. We do not go into detail about advanced configuration for setting up an MTA for business operations. This is a combination of many skills including but not limited to: DNS, getting a static routable IP address that is not blacklisted, and configuring advanced security and service settings. In short, this tutorial is meant to familiarize you with the basic configuration. Do not use this tutorial for MTA configuration of an Internet facing host. With its combined focus on both security and the ease of administration, we have chosen Postfix as the MTA for this tutorial. The default MTA installed in the older versions of CentOS is Sendmail. Sendmail is a great MTA. However, of the author's humble opinion, Postfix hits a sweet spot when addressing the following notes for an MTA. With the most current version of CentOS, Postfix has superseded Sendmail as the default MTA. Postfix is a widely used and well documented MTA. It is actively maintained and developed. It requires minimal configuration in mind (this is just email) and is efficient with system resources (again, this is just email). Step 1 − Install Postfix from YUM Package Manager. [root@centos]# yum -y install postfix Step 2 − Configure Postfix config file. The Postfix configuration file is located in − /etc/postfix/main.cf In a simple Postfix configuration, the following must be configured for a specific host: host name, domain, origin, inet_interfaces, and destination. Configure the hostname − The hostname is a fully qualified domain name of the Postfix host. In OpenLDAP chapter, we named the CentOS box: centos on the domain vmnet.local. Let’s stick with that for this chapter. # The myhostname parameter specifies the internet hostname of this # mail system. The default is to use the fully-qualified domain name # from gethostname(). $myhostname is used as a default value for many # other configuration parameters. # myhostname = centos.vmnet.local Configure the domain − As stated above, the domain we will be using in this tutorial is vmnet.local # The mydomain parameter specifies the local internet domain name. # The default is to use $myhostname minus the first component. # $mydomain is used as a default value for many other configuration # parameters. # mydomain = vmnet.local Configure the origin − For a single server and domain set up, we just need to uncomment the following sections and leave the default Postfix variables. # SENDING MAIL # # The myorigin parameter specifies the domain that locally-posted # mail appears to come from. The default is to append $myhostname, # which is fine for small sites. If you run a domain with multiple # machines, you should (1) change this to $mydomain and (2) set up # a domain-wide alias database that aliases each user to # user@that.users.mailhost. # # For the sake of consistency between sender and recipient addresses, # myorigin also specifies the default domain name that is appended # to recipient addresses that have no @domain part. # myorigin = $myhostname myorigin = $mydomain Configure the network interfaces − We will leave Postfix listening on our single network interface and all protocols and IP Addresses associated with that interface. This is done by simply leaving the default settings enabled for Postfix. # The inet_interfaces parameter specifies the network interface # addresses that this mail system receives mail on. By default, # the software claims all active interfaces on the machine. The # parameter also controls delivery of mail to user@[ip.address]. # # See also the proxy_interfaces parameter, for network addresses that # are forwarded to us via a proxy or network address translator. # # Note: you need to stop/start Postfix when this parameter changes. # #inet_interfaces = all #inet_interfaces = $myhostname #inet_interfaces = $myhostname, localhost #inet_interfaces = localhost # Enable IPv4, and IPv6 if supported inet_protocols = all Step 3 − Configure SASL Support for Postfix. Without SASL Authentication support, Postfix will only allow sending email from local users. Or it will give a relaying denied error when the users send email away from the local domain. Note − SASL or Simple Application Security Layer Framework is a framework designed for authentication supporting different techniques amongst different Application Layer protocols. Instead of leaving authentication mechanisms up to the application layer protocol, SASL developers (and consumers) leverage current authentication protocols for higher level protocols that may not have the convenience or more secure authentication (when speaking of access to secured services) built in. [root@centos]# yum -y install cyrus-sasl Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: repos.forethought.net * extras: repos.dfw.quadranet.com * updates: mirrors.tummy.com Package cyrus-sasl-2.1.26-20.el7_2.x86_64 already installed and latest version Nothing to do smtpd_sasl_auth_enable = yes smtpd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination smtpd_sasl_security_options = noanonymous smtpd_sasl_type = dovecot smtpd_sasl_path = private/auth ##Configure SASL Options Entries: smtpd_sasl_auth_enable = yes smptd_recipient_restrictions = permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination smtp_sasl_type = dovecot smtp_sasl_path = private/auth/etc Step 4 − Configure FirewallD to allow incoming SMTP Services. [root@centos]# firewall-cmd --permanent --add-service=smtp success [root@centos]# firewall-cmd --reload success [root@centos]# Now let's check to make sure our CentOS host is allowing and responding to the requests on port 25 (SMTP). Nmap scan report for 172.16.223.132 Host is up (0.00035s latency). Not shown: 993 filtered ports PORT STATE SERVICE 20/tcp closed ftp-data 21/tcp open ftp 22/tcp open ssh 25/tcp open smtp 80/tcp open http 389/tcp open ldap 443/tcp open https MAC Address: 00:0C:29:BE:DF:5F (VMware) As you can see, SMTP is listening and the daemon is responding to the requests from our internal LAN. Dovecot is a secure IMAP and POP3 Server deigned to handle incoming mail needs of a smaller to larger organization. Due to its prolific use with CentOS, we will be using Dovecot as an example of installing and configuring an incoming mail-server for CentOS and MTA SASL Provider. As noted previously, we will not be configuring MX records for DNS or creating secure rules allowing our services to handle mail for a domain. Hence, just setting these services up on an Internet facing host may leave leverage room for security holes w/o SPF Records. Step 1 − Install Dovecot. [root@centos]# yum -y install dovecot Step 2 − Configure dovecot. The main configuration file for dovecot is located at: /etc/dovecot.conf. We will first back up the main configuration file. It is a good practice to always backup configuration files before making edits. This way id (for example) line breaks get destroyed by a text editor, and years of changes are lost. Reverting is easy as copying the current backup into production. # Protocols we want to be serving. protocols = imap imaps pop3 pop3s Now, we need to enable the dovecot daemon to listen on startup − [root@localhost]# systemctl start dovecot [root@localhost]# systemctl enable dovecot Let's make sure Dovecot is listening locally on the specified ports for: imap, pop3, imap secured, and pop3 secured. [root@localhost]# netstat -antup | grep dovecot tcp 0 0 0.0.0.0:110 0.0.0.0:* LISTEN 4368/dovecot tcp 0 0 0.0.0.0:143 0.0.0.0:* LISTEN 4368/dovecot tcp 0 0 0.0.0.0:993 0.0.0.0:* LISTEN 4368/dovecot tcp 0 0 0.0.0.0:995 0.0.0.0:* LISTEN 4368/dovecot tcp6 0 0 :::110 :::* LISTEN 4368/dovecot tcp6 0 0 :::143 :::* LISTEN 4368/dovecot tcp6 0 0 :::993 :::* LISTEN 4368/dovecot tcp6 0 0 :::995 :::* LISTEN 4368/dovecot [root@localhost]# As seen, dovecot is listening on the specified ports for IPv4 and IPv4. Now, we need to make some firewall rules. [root@localhost]# firewall-cmd --permanent --add-port=110/tcp success [root@localhost]# firewall-cmd --permanent --add-port=143/tcp success [root@localhost]# firewall-cmd --permanent --add-port=995/tcp success [root@localhost]# firewall-cmd --permanent --add-port=993/tcp success [root@localhost]# firewall-cmd --reload success [root@localhost]# Our incoming mail sever is accepting requests for POP3, POP3s, IMAP, and IMAPs to hosts on the LAN. Port Scanning host: 192.168.1.143 Open TCP Port: 21 ftp Open TCP Port: 22 ssh Open TCP Port: 25 smtp Open TCP Port: 80 http Open TCP Port: 110 pop3 Open TCP Port: 143 imap Open TCP Port: 443 https Open TCP Port: 993 imaps Open TCP Port: 995 pop3s Before delving into installing FTP on CentOS, we need to learn a little about its use and security. FTP is a really efficient and well-refined protocol for transferring files between the computer systems. FTP has been used and refined for a few decades now. For transferring files efficiently over a network with latency or for sheer speed, FTP is a great choice. More so than either SAMBA or SMB. However, FTP does possess some security issues. Actually, some serious security issues. FTP uses a really weak plain-text authentication method. It is for this reason authenticated sessions should rely on sFTP or FTPS, where TLS is used for end-to-end encryption of the login and transfer sessions. With the above caveats, plain old FTP still has its use in the business environment today. The main use is, anonymous FTP file repositories. This is a situation where no authentication is warranted to download or upload files. Some examples of anonymous FTP use are − Large software companies still use anonymous ftp repositories allowing Internet users to download shareware and patches. Large software companies still use anonymous ftp repositories allowing Internet users to download shareware and patches. Allowing internet users to upload and download public documents. Allowing internet users to upload and download public documents. Some applications will automatically send encrypted, archived logs for or configuration files to a repository via FTP. Some applications will automatically send encrypted, archived logs for or configuration files to a repository via FTP. Hence, as a CentOS Administrator, being able to install and configure FTP is still a designed skill. We will be using an FTP daemon called vsFTP, or Very Secure FTP Daemon. vsFTP has been used in development for a while. It has a reputation for being secure, easy to install and configure, and is reliable. Step 1 − Install vsFTPd with the YUM Package Manager. [root@centos]# yum -y install vsftpd.x86_64 Step 2 − Configure vsFTP to Start on Boot with systemctl. [root@centos]# systemctl start vsftpd [root@centos]# systemctl enable vsftpd Created symlink from /etc/systemd/system/multi- user.target.wants/vsftpd.service to /usr/lib/systemd/system/vsftpd.service. Step 3 − Configure FirewallD to allow FTP control and transfer sessions. [root@centos]# firewall-cmd --add-service=ftp --permanent success [root@centos]# Assure our FTP daemon is running. [root@centos]# netstat -antup | grep vsftp tcp6 0 0 :::21 :::* LISTEN 13906/vsftpd [root@centos]# Step 4 − Configure vsFTPD For Anonymous Access. [root@centos]# mkdir /ftp [root@centos]# chown ftp:ftp /ftp Set minimal permissions for FTP root: [root@centos]# chmod -R 666 /ftp/ [root@centos]# ls -ld /ftp/ drw-rw-rw-. 2 ftp ftp 6 Feb 27 02:01 /ftp/ [root@centos]# In this case, we gave users read/write access to the entire root FTP tree. [root@centos]# vim /etc/vsftpd/vsftpd.conf # Example config file /etc/vsftpd/vsftpd.conf # # The default compiled in settings are fairly paranoid. This sample file # loosens things up a bit, to make the ftp daemon more usable. # Please see vsftpd.conf.5 for all compiled in defaults. # # READ THIS: This example file is NOT an exhaustive list of vsftpd options. # Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's # capabilities. We will want to change the following directives in the vsftp.conf file. Enable Anonymous uploading by uncommenting anon_mkdir_write_enable=YES Enable Anonymous uploading by uncommenting anon_mkdir_write_enable=YES chown uploaded files to owned by the system ftp user chown_uploads = YES chown_username = ftp chown uploaded files to owned by the system ftp user chown_uploads = YES chown_username = ftp Change system user used by vsftp to the ftp user: nopriv_user = ftp Change system user used by vsftp to the ftp user: nopriv_user = ftp Set the custom banner for the user to read before signing in. ftpd_banner = Welcome to our Anonymous FTP Repo. All connections are monitored and logged. Set the custom banner for the user to read before signing in. ftpd_banner = Welcome to our Anonymous FTP Repo. All connections are monitored and logged. Let's set IPv4 connections only − listen = YES listen_ipv6 = NO Let's set IPv4 connections only − listen = YES listen_ipv6 = NO Now, we need to restart or HUP the vsftp service to apply our changes. [root@centos]# systemctl restart vsftpd Let's connect to our FTP host and make sure our FTP daemon is responding. [root@centos rdc]# ftp 10.0.4.34 Connected to localhost (10.0.4.34). 220 Welcome to our Anonymous FTP Repo. All connections are monitored and logged. Name (localhost:root): anonymous 331 Please specify the password. Password: '230 Login successful. Remote system type is UNIX. Using binary mode to transfer files. ftp> When talking about remote management in CentOS as an Administrator, we will explore two methods − Console Management GUI Management Remote Console Management means performing administration tasks from the command line via a service such as ssh. To use CentOS Linux effectively, as an Administrator, you will need to be proficient with the command line. Linux at its heart was designed to be used from the console. Even today, some system administrators prefer the power of the command and save money on the hardware by running bare-bones Linux boxes with no physical terminal and no GUI installed. Remote GUI Management is usually accomplished in two ways: either a remote X-Session or a GUI application layer protocol like VNC. Each has its strengths and drawbacks. However, for the most part, VNC is the best choice for Administration. It allows graphical control from other operating systems such as Windows or OS X that do not natively support the X Windows protocol. Using remote X Sessions is native to both X-Window's Window-Managers and DesktopManagers running on X. However, the entire X Session architecture is mostly used with Linux. Not every System Administrator will have a Linux Laptop on hand to establish a remote X Session. Therefore, it is most common to use an adapted version of VNC Server. The biggest drawbacks to VNC are: VNC does not natively support a multi-user environment such as remote X-Sessions. Hence, for GUI access to end-users remote XSessions would be the best choice. However, we are mainly concerned with administering a CentOS server remotely. We will discuss configuring VNC for multiple administrators versus a few hundred endusers with remote X-Sessions. ssh or Secure Shell is now the standard for remotely administering any Linux server. SSH unlike telnet uses TLS for authenticity and end-to-end encryption of communications. When properly configured an administrator can be pretty sure both their password and the server are trusted remotely. Before configuring SSH, lets talk a little about the basic security and least common access. When SSH is running on its default port of 22; sooner rather than later, you are going to get brute force dictionary attacks against common user names and passwords. This just comes with the territory. No matter how many hosts you add to your deny files, they will just come in from different IP addresses daily. With a few common rules, you can simply take some pro-active steps and let the bad guys waste their time. Following are a few rules of security to follow using SSH for remote administration on a production server − Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH. Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH. Password policy is a must: Complex SSH user passwords like: "This&IS&a&GUD&P@ssW0rd&24&me". Change passwords every few months to eliminate susceptibility to incremental brute force attacks. Password policy is a must: Complex SSH user passwords like: "This&IS&a&GUD&P@ssW0rd&24&me". Change passwords every few months to eliminate susceptibility to incremental brute force attacks. Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example. Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example. Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits. Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits. Note On Linux Security − Anyone interested in Linux Administration should actively pursue current Cyber-Security news and technology. While we mostly hear about other operating systems being compromised, an insecure Linux box is a sought-after treasure for cybercriminals. With the power of Linux on a high-speed internet connection, a skilled cybercriminal can use Linux to leverage attacks on other operating systems. Step 1 − Install SSH Server and all dependent packages. [root@localhost]# yum -y install openssh-server 'Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: repos.centos.net * extras: repos.dfw.centos.com * updates: centos.centos.com Resolving Dependencies --> Running transaction check ---> Package openssh-server.x86_64 0:6.6.1p1-33.el7_3 will be installed --> Finished Dependency Resolution Dependencies Resolved Step 2 − Make a secure regular use to add for shell access. [root@localhost ~]# useradd choozer [root@localhost ~]# usermod -c "Remote Access" -d /home/choozer -g users -G wheel -a choozer Note − We added the new user to the wheel group enabling ability to su into root once SSH access has been authenticated. We also used a username that cannot be found in common word lists. This way, our account will not get locked out when SSH is attacked. The file holding configuration settings for sshd server is /etc/ssh/sshd_config. The portions we want to edit initially are − LoginGraceTime 60m PermitRootLogin no Step 3 − Reload the SSH daemon sshd. [root@localhost]# systemctl reload sshd It is good to set the logout grace period to 60 minutes. Some complex administration tasks can exceed the default of 2 minutes. There is really nothing more frustrating than having SSH session timeout when configuring or researching changes. Step 4 − Let's try to login using the root credentials. bash-3.2# ssh centos.vmnet.local root@centos.vmnet.local's password: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). Step 5 − We can no longer login remotely via ssh with root credentials. So let's login to our unprivileged user account and su into the root account. bash-3.2# ssh chooser@centos.vmnet.local choozer@centos.vmnet.local's password: [choozer@localhost ~]$ su root Password: [root@localhost choozer]# Step 6 − Finally, let's make sure the SSHD service loads on boot and firewalld allows outside SSH connections. [root@localhost]# systemctl enable sshd [root@localhost]# firewall-cmd --permanent --add-service=ssh success [root@localhost]# firewall-cmd --reload success [root@localhost]# SSH is now set up and ready for remote administration. Depending on your enterprise border, the packet filtering border device may need to be configured to allow SSH remote administration outside the corporate LAN. There are a few ways to enable remote CentOS administration via VNC on CentOS 6 - 7. The easiest, but most limiting way is simply using a package called vino. Vino is a Virtual Network Desktop Connection application for Linux designed around the Gnome Desktop platform. Hence, it is assumed the installation was completed with Gnome Desktop. If the Gnome Desktop has not been installed, please do so before continuing. Vino will be installed with a Gnome GUI install by default. To configure screen sharing with Vino under Gnome, we want to go into the CentOS System Preferences for screen sharing. Applications->System Tools->Settings->Sharing Notes to configuring VNC Desktop Sharing − Disable New Connections must ask for access − This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop. Disable New Connections must ask for access − This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop. Enable Require a password − This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security). Enable Require a password − This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security). Forward UP&P Ports: If available leave disabled − Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this. Forward UP&P Ports: If available leave disabled − Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this. Make sure vino is listening on the VNC Port 5900. [root@localhost]# netstat -antup | grep vino tcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 4873/vino-server tcp6 0 0 :::5900 :::* LISTEN 4873/vino-server [root@localhost]# Let's now configure our Firewall to allow incoming VNC connections. [root@localhost]# firewall-cmd --permanent --add-port=5900/tcp success [root@localhost]# firewall-cmd --reload success [root@localhost rdc]# Finally, as you can see we are able to connect our CentOS Box and administer it with a VNC client on either Windows or OS X. It is just as important to obey the same rules for VNC as we set forth for SSH. Just like SSH, VNC is continually scanned across IP ranges and tested for weak passwords. It is also worth a note that leaving the default CentOS login enabled with a console timeout does help with remote VNC security. As an attacker will need the VNC and user password, make sure your screen sharing password is different and just as hard to guess as the user password. After entering the the VNC screen sharing password, we must also enter the user password to access a locked desktop. Security Note − By default, VNC is not an encrypted protocol. Hence, the VNC connection should be tunneled through SSH for encryption. Setting up an SSH Tunnel will provide a layer of SSH encryption to tunnel the VNC connection through. Another great feature is it uses SSH compression to add another layer of compression to the VNC GUI screen updates. More secure and faster is always a good thing when dealing with the administration of CentOS servers! So from your client that will be initiating the VNC connection, let's set up a remote SSH tunnel. In this demonstration, we are using OS X. First we need to sudo -s to root. bash-3.2# sudo -s password: Enter the user password and we should now have root shell with a # prompt − bash-3.2# Now, let's create our SSH Tunnel. ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N Let's break this command down − ssh − Runs the local ssh utility ssh − Runs the local ssh utility -f − ssh should run in the background after the task fully executes -f − ssh should run in the background after the task fully executes rdc@192.168.1.143 − Remote ssh user on the CentOS server hosting VNC services rdc@192.168.1.143 − Remote ssh user on the CentOS server hosting VNC services -L 2200:192.168.1.143:5900 − Create our tunnel [Local Port]:[remote host]:[remote port of VNC service] -L 2200:192.168.1.143:5900 − Create our tunnel [Local Port]:[remote host]:[remote port of VNC service] -N tells ssh we do not wish to execute a command on the remote system -N tells ssh we do not wish to execute a command on the remote system bash-3.2# ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N rdc@192.168.1.143's password: After successfully entering the remote ssh user's password, our ssh tunnel is created. Now for the cool part! To connect we point our VNC client at the localhost on the port of our tunnel, in this case port 2200. Following is the configuration on Mac Laptop's VNC Client − And finally, our remote VNC Desktop Connection! The cool thing about SSH tunneling is it can be used for almost any protocol. SSH tunnels are commonly used to bypass egress and ingress port filtering by an ISP, as well as trick application layer IDS/IPS while evading other session layer monitoring. Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered). Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered). Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data. Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data. SSH Tunneling is great tool in a Linux Administrator's toolbox for getting things done. However, as an Administrator we want to explore locking down the availability of lesser privileged users having access to SSH tunneling. Administration Security Note − Restricting SSH Tunneling is something that requires thought on the part of an Administrator. Assessing why users need SSH Tunneling in the first place; what users need tunneling; along with practical risk probability and worst-case impact. This is an advanced topic stretching outside the realm of an intermediate level primer. Research on this topic is advised for those who wish to reach the upper echelons of CentOS Linux Administration. The design of X-Windows in Linux is really neat compared to that of Windows. If we want to control a remote Linux box from another Linux boxm we can take advantage of mechanisms built into X. X-Windows (often called just "X"), provides the mechanism to display application windows originating from one Linux box to the display portion of X on another Linux box. So through SSH we can request an X-Windows application be forwarded to the display of another Linux box across the world! To run an X Application remotely via an ssh tunnel, we just need to run a single command − [root@localhost]# ssh -X rdc@192.168.1.105 The syntax is − ssh -X [user]@[host], and the host must be running ssh with a valid user. Following is a screenshot of GIMP running on a Ubuntu Workstation through a remote XWindows ssh tunnel. It is pretty simple to run applications remotely from another Linux server or workstation. It is also possible to start an entire X-Session and have the entire desktop environment remotely through a few methods. XDMCP XDMCP Headless software packages such as NX Headless software packages such as NX Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE This method is most commonly used for headless servers with no physical display and really exceeds the scope of an intermediate level primer. However, it is good to know of the options available. There are several third party tools that can add enhanced capabilities for CentOS traffic monitoring. In this tutorial, we will focus on those that are packaged in the main CentOS distribution repositories and the Fedora EPEL repository. There will always be situations where an Administrator (for one reason or another) is left with only tools in the main CentOS repositories. Most utilities discussed are designed to be used by an Administrator with the shell of physical access. When traffic monitoring with an accessible web-gui, using third party utilities such as ntop-ng or Nagios is the best choice (versus re-creating such facilities from scratch). For further research on both configurable web-gui solutions, following are a few links to get started on research. Nagios Nagios has been around for a long time, therefore, it is both tried and tested. At one point it was all free and open-source, but has since advanced into an Enterprise solution with paid licensing models to support the need of Enterprise sophistication. Hence, before planning any rollouts with Nagios, make sure the open-source licensed versions will meet your needs or plan on spending with an Enterprise Budget in mind. Most open-source Nagios traffic monitoring software can be found at − https://www.nagios.org For a summarized history of Nagious, here is the official Nagios History page: https://www.nagios.org/about/history/ ntopng Another great tool allowing bandwidth and traffic monitoring via a web-gui is called ntopng. ntopng is similar to the Unix utility ntop, and can collect data for an entire LAN or WAN. Providing a web-gui for administration, configuration, and charting makes it easy to use for the entire IT Departments. Like Nagious, ntopng has both open-source and paid enterprise versions available. For more information about ntopng, please visit the website − http://www.ntop.org/ To access some of the needed tools for traffic monitoring, we will need to configure our CentOS system to use the EPEL Repository. The EPEL Repository is not officially maintained or supported by CentOS. However, it is maintained by a group of Fedora Core volunteers to address the packages commonly used by Enterprise Linux professionals not included in either CentOS, Fedora Core, or Red Hat Linux Enterprise. Caution Remember, the EPEL Repository is not official for CentOS and may break compatibility and functionality on production servers with common dependencies. With that in mind, it is advised to always test on a non-production server running the same services as production before deploying on a system critical box. Really, the biggest advantage of using the EHEL Repository over any other third party repository with CentOS is that we can be sure the binaries are not tainted. It is considered a best practice to not use the repositories from an untrusted source. With all that said, the official EPEL Repository is so common with CentOS that it can be easily installed via YUM. [root@CentOS rdc]# yum -y install epel-release Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: repo1.dal.innoscale.net * extras: repo1.dal.innoscale.net * updates: mirror.hmc.edu Resolving Dependencies --> Running transaction check ---> Package epel-release.noarch 0:7-9 will be installed --> Finished Dependency Resolution Dependencies Resolved --{ condensed output }-- After installing the EPEL Repository, we will want to update it. [root@CentOS rdc]# yum repolist Loaded plugins: fastestmirror, langpacks epel/x86_64/metalink | 11 kB 00:00:00 epel | 4.3 kB 00:00:00 (1/3): epel/x86_64/group_gz | 170 kB 00:00:00 (2/3): epel/x86_64/updateinfo | 753 kB 00:00:01 (3/3): epel/x86_64/primary_db --{ condensed output }-- At this point, our EPEL repository should be configured and ready to use. Let's start by installing nload for interface bandwidth monitoring. The tools we will focus on in this tutorial are − nload ntop ifstst iftop vnstat net hogs Wireshark TCP Dump Traceroute These are all standard for monitoring traffic in Linux Enterprises. The usage of each range from simple to advanced, so we will only briefly discuss tools such as Wireshark and TCP Dump. With our EPEL Repositories installed and configured in CentOS, we now should be able to install and use nload. This utility is designed to chart bandwidth per interface in real-time. Like most other basic installs nload is installed via the YUM package manager. [root@CentOS rdc]# yum -y install nload Resolving Dependencies --> Running transaction check ---> Package nload.x86_64 0:0.7.4-4.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved =============================================================================== =============================================================================== Package Arch Version Repository Size =============================================================================== =============================================================================== Installing: nload x86_64 0.7.4-4.el7 epel 70 k Transaction Summary =============================================================================== =============================================================================== Install 1 Package Total download size: 70 k Installed size: 176 k Downloading packages: --{ condensed output }-- Now we have nload installed, and using it is pretty straight forward. [root@CentOS rdc]# nload enp0s5 nload will monitor the specified interface. In this case, enp0s5 an Ethernet interface, in real-time from the terminal for network traffic loads and total bandwidth usage. As seen, nload will chart both incoming and outgoing data from the specified interface, along with providing a physical representation of the data flow with hash marks "#". The depicted screenshot is of a simple webpage being loaded with some background daemon traffic. Common command line switches for nload are − The standard syntax for nload is − nload [options] <interface> If no interface is specified, nload will automatically grab the first Ethernet interface. Let's try measuring the total data in/out in Megabytes and current data-transfer speeds in Megabits. [root@CentOS rdc]# nload -U M -u m Data coming in/out the current interface is measured in megabits per second and each "Ttl" row, representing total data in/out is displayed in Megabytes. nload is useful for an administrator to see how much data has passed through an interface and how much data is currently coming in/out a specified interface. To see other interfaces without closing nload, simply use the left/right arrow keys. This will cycle through all available interfaces on the system. It is possible to monitor multiple interfaces simultaneously using the -m switch − [root@CentOS rdc]# nload -u K -U M -m lo -m enp0s5 load monitoring two interfaces simultaneously (lo and enp0s5) − systemd has changed the way system logging is managed for CentOS Linux. Instead of every daemon on the system placing logs into individual locations than using tools such as tail or grep as the primary way of sorting and filtering log entries, journald has brought a single point of administration to analyzing system logs. The main components behind systemd logging are − journal, jounralctl, and journald.conf journald is the main logging daemon and is configured by editing journald.conf while journalctl is used to analyze events logged by journald. Events logged by journald include: kernel events, user processes, and daemon services. Before using journalctl, we need to make sure our system time is set to the correct time. To do this, we want to use timedatectl. Let's check the current system time. [root@centos rdc]# timedatectl status Local time: Mon 2017-03-20 00:14:49 MDT Universal time: Mon 2017-03-20 06:14:49 UTC RTC time: Mon 2017-03-20 06:14:49 Time zone: America/Denver (MDT, -0600) NTP enabled: yes NTP synchronized: yes RTC in local TZ: no DST active: yes Last DST change: DST began at Sun 2017-03-12 01:59:59 MST Sun 2017-03-12 03:00:00 MDT Next DST change: DST ends (the clock jumps one hour backwards) at Sun 2017-11-05 01:59:59 MDT Sun 2017-11-05 01:00:00 MST [root@centos rdc]# Currently, the system is correct to the local time zone. If your system is not, let's set the correct time zone. After changing the settings, CentOS will automatically calculate the time zone offset from the current time zone, adjusting the system clock right away. Let's list all the time zones with timedatectl − [root@centos rdc]# timedatectl list-timezones Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau That is the contended output from timedatectl list-timezones. To find a specific local time-zone, the grep command can be used − [root@centos rdc]# timedatectl list-timezones | grep -i "america/New_York" America/New_York [root@centos rdc]# The label used by CentOS is usually Country/Region with an underscore instead of space (New_York versus "New York"). Now let's set our time zone − [root@centos rdc]# timedatectl set-timezone "America/New_York" [root@centos rdc]# date Mon Mar 20 02:28:44 EDT 2017 [root@centos rdc]# Your system clock should automatically adjust the time. Common command line switches when using journalctl − First, we will examine and configure the boot logs in CentOS Linux. The first thing you will notice is that CentOS, by default, doesn't store boot logging that is persistent across reboots. To check boot logs per reboot instance, we can issue the following command − [root@centos rdc]# journalctl --list-boots -4 bca6380a31a2463aa60ba551698455b5 Sun 2017-03-19 22:01:57 MDT—Sun 2017-03-19 22:11:02 MDT -3 3aaa9b84f9504fa1a68db5b49c0c7208 Sun 2017-03-19 22:11:09 MDT—Sun 2017-03-19 22:15:03 MDT -2 f80b231272bf48ffb1d2ce9f758c5a5f Sun 2017-03-19 22:15:11 MDT—Sun 2017-03-19 22:54:06 MDT -1 a071c1eed09d4582a870c13be5984ed6 Sun 2017-03-19 22:54:26 MDT—Mon 2017-03-20 00:48:29 MDT 0 9b4e6cdb43b14a328b1fa6448bb72a56 Mon 2017-03-20 00:48:38 MDT—Mon 2017-03-20 01:07:36 MDT [root@centos rdc]# After rebooting the system, we can see another entry. [root@centos rdc]# journalctl --list-boots -5 bca6380a31a2463aa60ba551698455b5 Sun 2017-03-19 22:01:57 MDT—Sun 2017-03-19 22:11:02 MDT -4 3aaa9b84f9504fa1a68db5b49c0c7208 Sun 2017-03-19 22:11:09 MDT—Sun 2017-03-19 22:15:03 MDT -3 f80b231272bf48ffb1d2ce9f758c5a5f Sun 2017-03-19 22:15:11 MDT—Sun 2017-03-19 22:54:06 MDT -2 a071c1eed09d4582a870c13be5984ed6 Sun 2017-03-19 22:54:26 MDT—Mon 2017-03-20 00:48:29 MDT -1 9b4e6cdb43b14a328b1fa6448bb72a56 Mon 2017-03-20 00:48:38 MDT—Mon 2017-03-20 01:09:57 MDT 0 aa6aaf0f0f0d4fcf924e17849593d972 Mon 2017-03-20 01:10:07 MDT—Mon 2017-03-20 01:12:44 MDT [root@centos rdc]# Now, let's examine the last boot logging instance − root@centos rdc]# journalctl -b -5 -- Logs begin at Sun 2017-03-19 22:01:57 MDT, end at Mon 2017-03-20 01:20:27 MDT. -- Mar 19 22:01:57 localhost.localdomain systemd-journal[97]: Runtime journal is using 8.0M (max allowed 108.4M Mar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpuset Mar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpu Mar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpuacct Mar 19 22:01:57 localhost.localdomain kernel: Linux version 3.10.0514.6.2.el7.x86_64 (builder@kbuilder.dev. Mar 19 22:01:57 localhost.localdomain kernel: Command line: BOOT_IMAGE=/vmlinuz-3.10.0-514.6.2.el7.x86_64 ro Mar 19 22:01:57 localhost.localdomain kernel: Disabled fast string operations Mar 19 22:01:57 localhost.localdomain kernel: e820: BIOS-provided physical RAM map: Above is the condensed output from our last boot. We could also refer back to a boot log from hours, days, weeks, months, and even years. However, by default CentOS doesn't store persistent boot logs. To enable persistently storing boot logs, we need to make a few configuration changes − Make central storage points for boot logs Give proper permissions to a new log folder Configure journald.conf for persistent logging The initial place journald will want to store persistent boot logs is /var/log/journal. Since this doesn't exist by default, let's create it − [root@centos rdc]# mkdir /var/log/journal Now, let's give the directory proper permissions journald daemon access − systemd-tmpfiles --create --prefix /var/log/journal Finally, let's tell journald it should store persistent boot logs. In vim or your favorite text editor, open /etc/systemd/jounrald.conf". # See journald.conf(5) for details. [Journal]=Storage=peristent The line we are concerned with is, Storage=. First remove the comment #, then change to Storage = persistent as depicted above. Save and reboot your CentOS system and take care that there should be multiple entries when running journalctl list-boots. Note − A constantly changing machine-id like that from a VPS provider can cause journald to fail at storing persistent boot logs. There are many workarounds for such a scenario. It is best to peruse the current fixes posted to CentOS Admin forums, than follow the trusted advice from those who have found plausible VPS workarounds. To examine a specific boot log, we simply need to get each offset using journald --list-boots the offset with the -b switch. So to check the second boot log we'd use − journalctl -b -2 The default for -b with no boot log offset specified will always be the current boot log after the last reboot. Events from journald are numbered and categorized into 7 separate types − 0 - emerg :: System is unusable 1 - alert :: Action must be taken immediatly 2 - crit :: Action is advised to be taken immediatly 3 - err :: Error effecting functionality of application 4 - warning :: Usually means a common issue that can affect security or usilbity 5 - info :: logged informtation for common operations 6 - debug :: usually disabled by default to troubleshoot functionality Hence, if we want to see all warnings the following command can be issued via journalctl − [root@centos rdc]# journalctl -p 4 -- Logs begin at Sun 2017-03-19 22:01:57 MDT, end at Wed 2017-03-22 22:33:42 MDT. -- Mar 19 22:01:57 localhost.localdomain kernel: ACPI: RSDP 00000000000f6a10 00024 (v02 PTLTD ) Mar 19 22:01:57 localhost.localdomain kernel: ACPI: XSDT 0000000095eea65b 0005C (v01 INTEL 440BX 06040000 VMW 01 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: FACP 0000000095efee73 000F4 (v04 INTEL 440BX 06040000 PTL 00 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: DSDT 0000000095eec749 1272A (v01 PTLTD Custom 06040000 MSFT 03 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: FACS 0000000095efffc0 00040 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: BOOT 0000000095eec721 00028 (v01 PTLTD $SBFTBL$ 06040000 LTP 00 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: APIC 0000000095eeb8bd 00742 (v01 PTLTD ? APIC 06040000 LTP 00 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: MCFG 0000000095eeb881 0003C (v01 PTLTD $PCITBL$ 06040000 LTP 00 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: SRAT 0000000095eea757 008A8 (v02 VMWARE MEMPLUG 06040000 VMW 00 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: HPET 0000000095eea71f 00038 (v01 VMWARE VMW HPET 06040000 VMW 00 Mar 19 22:01:57 localhost.localdomain kernel: ACPI: WAET 0000000095eea6f7 00028 (v01 VMWARE VMW WAET 06040000 VMW 00 Mar 19 22:01:57 localhost.localdomain kernel: Zone ranges: Mar 19 22:01:57 localhost.localdomain kernel: DMA [mem 0x000010000x00ffffff] Mar 19 22:01:57 localhost.localdomain kernel: DMA32 [mem 0x010000000xffffffff] Mar 19 22:01:57 localhost.localdomain kernel: Normal empty Mar 19 22:01:57 localhost.localdomain kernel: Movable zone start for each node Mar 19 22:01:57 localhost.localdomain kernel: Early memory node ranges Mar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x000010000x0009dfff] Mar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x001000000x95edffff] Mar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x95f000000x95ffffff] Mar 19 22:01:57 localhost.localdomain kernel: Built 1 zonelists in Node order, mobility grouping on. Total pages: 60 Mar 19 22:01:57 localhost.localdomain kernel: Policy zone: DMA32 Mar 19 22:01:57 localhost.localdomain kernel: ENERGY_PERF_BIAS: Set to 'normal', was 'performance' The above shows all warnings for the past 4 days on the system. The new way of viewing and perusing logs with systemd does take little practice and research to become familiar with. However, with different output formats and particular notice to making all packaged daemon logs universal, it is worth embracing. journald offers great flexibility and efficiency over traditional log analysis methods. Before exploring methods particular to CentOS for deploying a standard backup plan, let's first discuss typical considerations for a standard level backup policy. The first thing we want to get accustomed to is the 3-2-1 backup rule. Throughout the industry, you'll often hear the term 3-2-1 backup model. This is a very good approach to live by when implementing a backup plan. 3-2-1 is defined as follows − 3 copies of data; for example, we may have the working copy; a copy put onto the CentOS server designed for redundancy using rsync; and rotated, offsite USB backups are made from data on the backup server. 2 different backup mediums. We would actually have three different backup mediums in this case: the working copy on an SSD of a laptop or workstation, the CentOS server data on a RADI6 Array, and the offsite backups put on USB drives. 1 copy of data offsite; we are rotating the USB drives offsite on a nightly basis. Another modern approach may be a cloud backup provider. A bare metal restore plan is simply a plan laid out by a CentOS administrator to get vital systems online with all data intact. Assuming 100% systems failure and loss of all past system hardware, an administrator must have a plan to achieve uptime with intact user-data costing minimal downtime. The monolithic kernel used in Linux actually makes bare metal restores using system images much easier than Windows. Where Windows uses a micro-kernel architecture. A full data restore and bare metal recovery are usually accomplished through a combination of methods including working, configured production disk-images of key operational servers, redundant backups of user data abiding by the 3-2-1 rule. Even some sensitive files that may be stored in a secure, fireproof safe with limited access to the trusted company personnel. A multiphase bare metal restore and data recovery plan using native CentOS tools may consist of − dd to make and restore production disk-images of configured servers dd to make and restore production disk-images of configured servers rsync to make incremental backups of all user data rsync to make incremental backups of all user data tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere. tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere. If a system crashes due to a hardware failure or disaster, following will be the different phases of restoring operations − Build a working server with a configured bare metal image Build a working server with a configured bare metal image Restore data to the working server from backups Restore data to the working server from backups Have physical access to credentials needed to perform the first two operations Have physical access to credentials needed to perform the first two operations rsync is a great utility for syncing directories of files either locally or to another server. rsync has been used for years by System Administrators, hence it is very refined for the purpose of backing up data. In the author's opinion, one of the best features of sync is its ability to be scripted from the command line. In this tutorial, we will discuss rsync in various ways − Explore and talk about some common options Create local backups Create remote backups over SSH Restore local backups rsync is named for its purpose: Remote Sync and is both powerful and flexible in use. Following is a basic rsync remote backup over ssh − MiNi:~ rdc$ rsync -aAvz --progress ./Desktop/ImportantStuff/ rdc@192.168.1.143:home/rdc/ Documents/RemoteStuff/ rdc@192.168.1.143's password: sending incremental file list 6,148 100% 0.00kB/s 0:00:00 (xfr#1, to-chk=23/25) 2017-02-14 16_26_47-002 - Veeam_Architecture001.png 33,144 100% 31.61MB/s 0:00:00 (xfr#2, to-chk=22/25) A Guide to the WordPress REST API | Toptal.pdf 892,406 100% 25.03MB/s 0:00:00 (xfr#3, to-chk=21/25) Rick Cardon Technologies, LLC..webloc 77 100% 2.21kB/s 0:00:00 (xfr#4, to-chk=20/25) backbox-4.5.1-i386.iso 43,188,224 1% 4.26MB/s 0:08:29 sent 2,318,683,608 bytes received 446 bytes 7,302,941.90 bytes/sec total size is 2,327,091,863 speedup is 1.00 MiNi:~ rdc$ The following sync sent nearly 2.3GB of data across our LAN. The beauty of rsync is it works incrementally at the block level on a file-by-file basis. This means, if we change just two characters in a 1MB text file, only one or two blocks will be transferred across the lan on the next sync! Furthermore, the incremental function can be disabled in favor of more network bandwidth used for less CPU utilization. This might prove advisable if constantly copying several 10MB database files every 10 minutes on a 1Gb dedicated Backup-Lan. The reasoning is: these will always be changing and will be transmitting incrementally every 10 minutes and may tax load of the remote CPU. Since the total transfer load will not exceed 5 minutes, we may just wish to sync the database files in their entirety. Following are the most common switches with rsync − rsync syntax: rsync [options] [local path] [[remote host:remote path] or [target path My personal preference for rsync is when backing up files from a source host to a target host. For example, all the home directories for data recovery or even offsite and into the cloud for disaster recovery. We have already seen how to transfer files from one host to another. The same method can be used to sync directories and files locally. Let's make a manual incremental backup of /etc/ in our root user's directory. First, we need to create a directory off ~/root for the synced backup − [root@localhost rdc]# mkdir /root/etc_baks Then, assure there is enough free disk-space. [root@localhost rdc]# du -h --summarize /etc/ 49M /etc/ [root@localhost rdc]# df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/cl-root 43G 15G 28G 35% / We are good for syncing our entire /etc/ directory − rsync -aAvr /etc/ /root/etc_baks/ Our synced /etc/ directory − [root@localhost etc_baks]# ls -l ./ total 1436 drwxr-xr-x. 3 root root 101 Feb 1 19:40 abrt -rw-r--r--. 1 root root 16 Feb 1 19:51 adjtime -rw-r--r--. 1 root root 1518 Jun 7 2013 aliases -rw-r--r--. 1 root root 12288 Feb 27 19:06 aliases.db drwxr-xr-x. 2 root root 51 Feb 1 19:41 alsa drwxr-xr-x. 2 root root 4096 Feb 27 17:11 alternatives -rw-------. 1 root root 541 Mar 31 2016 anacrontab -rw-r--r--. 1 root root 55 Nov 4 12:29 asound.conf -rw-r--r--. 1 root root 1 Nov 5 14:16 at.deny drwxr-xr-x. 2 root root 32 Feb 1 19:40 at-spi2 --{ condensed output }-- Now let's do an incremental rsync − [root@localhost etc_baks]# rsync -aAvr --progress /etc/ /root/etc_baks/ sending incremental file list test_incremental.txt 0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=1145/1282) sent 204620 bytes received 2321 bytes 413882.00 bytes/sec total size is 80245040 speedup is 387.77 [root@localhost etc_baks]# Only our test_incremental.txt file was copied. Let's do our initial rsync full backup onto a server with a backup plan deployed. This example is actually backing up a folder on a Mac OS X Workstation to a CentOS server. Another great aspect of rsync is that it can be used on any platform rsync has been ported to. MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/ rdc@192.168.1.143:Documents/RemoteStuff rdc@192.168.1.143's password: sending incremental file list ./ A Guide to the WordPress REST API | Toptal.pdf Rick Cardon Tech LLC.webloc VeeamDiagram.png backbox-4.5.1-i386.iso dhcp_admin_script_update.py DDWRT/ DDWRT/.DS_Store DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin DDWRT/ddwrt_mod_notes.docx DDWRT/factory-to-ddwrt.bin open_ldap_config_notes/ open_ldap_config_notes/ldap_directory_a.png open_ldap_config_notes/open_ldap_notes.txt perl_scripts/ perl_scripts/mysnmp.pl php_scripts/ php_scripts/chunked.php php_scripts/gettingURL.php sent 2,318,281,023 bytes received 336 bytes 9,720,257.27 bytes/sec total size is 2,326,636,892 speedup is 1.00 MiNi:~ rdc$ We have now backed up a folder from a workstation onto a server running a RAID6 volume with rotated disaster recovery media stored offsite. Using rsync has given us standard 3-2-1 backup with only one server having an expensive redundant disk array and rotated differential backups. Now let's do another backup of the same folder using rsync after a single new file named test_file.txt has been added. MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/ rdc@192.168.1.143:Documents/RemoteStuff rdc@192.168.1.143's password: sending incremental file list ./ test_file.txt sent 814 bytes received 61 bytes 134.62 bytes/sec total size is 2,326,636,910 speedup is 2,659,013.61 MiNi:~ rdc$ As you can see, only the new file was delivered to the server via rsync. The differential comparison was made on a file-by-file basis. A few things to note are: This only copies the new file: test_file.txt, since it was the only file with changes. rsync uses ssh. We did not ever need to use our root account on either machine. Simple, powerful and effective, rsync is great for backing up entire folders and directory structures. However, rsync by itself doesn't automate the process. This is where we need to dig into our toolbox and find the best, small, and simple tool for the job. To automate rsync backups with cronjobs, it is essential that SSH users be set up using SSH keys for authentication. This combined with cronjobs enables rsync to be done automatically at timed intervals. DD is a Linux utility that has been around since the dawn of the Linux kernel meeting the GNU Utilities. dd in simplest terms copies an image of a selected disk area. Then provides the ability to copy selected blocks of a physical disk. So unless you have backups, once dd writes over a disk, all blocks are replaced. Loss of previous data exceeds the recovery capabilities for even highly priced professional-level data-recovery. The entire process for making a bootable system image with dd is as follows − Boot from the CentOS server with a bootable linux distribution Find the designation of the bootable disk to be imaged Decide location where the recovery image will be stored Find the block size used on your disk Start the dd image operation In this tutorial, for the sake of time and simplicity, we will be creating an ISO image of the master-boot record from a CentOS virtual machine. We will then store this image offsite. In case our MBR becomes corrupted and needs to be restored, the same process can be applied to an entire bootable disk or partition. However, the time and disk space needed really goes a little overboard for this tutorial. It is encouraged for CentOS admins to become proficient in restoring a fully bootable disk/partition in a test environment and perform a bare metal restore. This will take a lot of pressure off when eventually one needs to complete the practice in a real life situation with Managers and a few dozen end-users counting downtime. In such a case, 10 minutes of figuring things out can seem like an eternity and make one sweat. Note − When using dd make sure to NOT confuse source and target volumes. You can destroy data and bootable servers by copying your backup location to a boot drive. Or possibly worse destroy data forever by copying over data at a very low level with DD. Following are the common command line switches and parameters for dd − Note on block size − The default block size for dd is 512 bytes. This was the standard block size of lower density hard disk drives. Today's higher density HDDs have increased to 4096 byte (4kB) block sizes to allow for disks ranging from 1TB and larger. Thus, we will want to check disk block size before using dd with newer, higher capacity hard disks. For this tutorial, instead of working on a production server with dd, we will be using a CentOS installation running in VMWare. We will also configure VMWare to boot a bootable Linux ISO image instead of working with a bootable USB Stick. First, we will need to download the CentOS image entitled − CentOS Gnome ISO. This is almost 3GB and it is advised to always keep a copy for creating bootable USB thumb-drives and booting into virtual server installations for trouble-shooting and bare metal images. Other bootable Linux distros will work just as well. Linux Mint can be used for bootable ISOs as it has great hardware support and polished GUI disk tools for maintenance. CentOS GNOME Live bootable image can be downloaded from: http://buildlogs.centos.org/rolling/7/isos/x86_64/CentOS-7-x86_64-LiveGNOME.iso Let's configure our VMWare Workstation installation to boot from our Linux bootable image. The steps are for VMWare on OS X. However, they are similar across VMWare Workstation on Linux, Windows, and even Virtual Box. Note − Using a virtual desktop solution like Virtual Box or VMWare Workstation is a great way to set up lab scenarios for learning CentOS Administration tasks. It provides the ability to install several CentOS installations, practically no hardware configuration letting the person focus on administration, and even save the server state before making changes. First let's configure a virtual cd-rom and attach our ISO image to boot instead of the virtual CentOS server installation − Now, set the startup disk − Now when booted, our virtual machine will boot from the CentOS bootable ISO image and allow access to files on the Virtual CentOS server that was previously configured. Let’s check our disks to see where we want to copy the MBR from (condensed output is as follows). MiNt ~ # fdisk -l Disk /dev/sda: 60 GiB, 21474836480 bytes, 41943040 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk /dev/sdb: 20 GiB, 21474836480 bytes, 41943040 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes We have located both our physical disks: sda and sdb. Each has a block size of 512 bytes. So, we will now run the dd command to copy the first 512 bytes for our MBR on SDA1. The best way to do this is − [root@mint rdc]# dd if=/dev/sda bs=512 count=1 | gzip -c > /mnt/sdb/images/mbr.iso.gz 1+0 records in 1+0 records out 512 bytes copied, 0.000171388 s, 3.0 MB/s [root@mint rdc]# ls /mnt/sdb/ mbr-iso.gz [root@mint rdc]# Just like that, we have full image of out master boot record. If we have enough room to image the boot drive, we could just as easily make a full system boot image − dd if=/dev/INPUT/DEVICE-NAME-HERE conv=sync,noerror bs=4K | gzip -c > /mnt/sdb/boot-server-centos-image.iso.gz The conv=sync is used when bytes must be aligned for a physical medium. In this case, dd may get an error if exact 4K alignments are not read (say... a file that is only 3K but needs to take minimum of a single 4K block on disk. Or, there is simply an error reading and the file cannot be read by dd.). Thus, dd with conv=sync,noerror will pad the 3K with trivial, but useful data to physical medium in 4K block alignments. While not presenting an error that may end a large operation. When working with data from disks we always want to include: conv=sync,noerror parameter. This is simply because the disks are not streams like TCP data. They are made up of blocks aligned to a certain size. For example, if we have 512 byte blocks, a file of only 300 bytes still needs a full 512 bytes of disk-space (possibly 2 blocks for inode information like permissions and other filesystem information). gzip and tar are two utilities a CentOS administrator must become accustomed to using. They are used for a lot more than to simply decompress archives. Tar is an archiving utility similar to winrar on Windows. Its name Tape Archive abbreviated as tar pretty much sums up the utility. tar will take files and place them into an archive for logical convenience. Hence, instead of the dozens of files stored in /etc. we could just "tar" them up into an archive for backup and storage convenience. tar has been the standard for storing archived files on Unix and Linux for many years. Hence, using tar along with gzip or bzip is considered as a best practice for archives on each system. Following is a list of common command line switches and options used with tar − Following is the basic syntax for creating a tar archive. tar -cvf [tar archive name] Note on Compression mechanisms with tar − It is advised to stick with one of two common compression schemes when using tar: gzip and bzip2. gzip files consume less CPU resources but are usually larger in size. While bzip2 will take longer to compress, they utilize more CPU resources; but will result in a smaller end filesize. When using file compression, we will always want to use standard file extensions letting everyone including ourselves know (versus guess by trial and error) what compression scheme is needed to extract archives. When needing to possibly extract archives on a Windows box or for use on Windows, it is advised to use the .tar.tbz or .tar.gz as most the three character single extensions will confuse Windows and Windows only Administrators (however, that is sometimes the desired outcome) Let's create a gzipped tar archive from our remote backups copied from the Mac Workstation − [rdc@mint Documents]$ tar -cvz -f RemoteStuff.tgz ./RemoteStuff/ ./RemoteStuff/ ./RemoteStuff/.DS_Store ./RemoteStuff/DDWRT/ ./RemoteStuff/DDWRT/.DS_Store ./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin ./RemoteStuff/DDWRT/ddwrt_mod_notes.docx ./RemoteStuff/DDWRT/factory-to-ddwrt.bin ./RemoteStuff/open_ldap_config_notes/ ./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png ./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt ./RemoteStuff/perl_scripts/ ./RemoteStuff/perl_scripts/mysnmp.pl ./RemoteStuff/php_scripts/ ./RemoteStuff/php_scripts/chunked.php ./RemoteStuff/php_scripts/gettingURL.php ./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf ./RemoteStuff/Rick Cardon Tech LLC.webloc ./RemoteStuff/VeeamDiagram.png ./RemoteStuff/backbox-4.5.1-i386.iso ./RemoteStuff/dhcp_admin_script_update.py ./RemoteStuff/test_file.txt [rdc@mint Documents]$ ls -ld RemoteStuff.tgz -rw-rw-r--. 1 rdc rdc 2317140451 Mar 12 06:10 RemoteStuff.tgz Note − Instead of adding all the files directly to the archive, we archived the entire folder RemoteStuff. This is the easiest method. Simply because when extracted, the entire directory RemoteStuff is extracted with all the files inside the current working directory as ./currentWorkingDirectory/RemoteStuff/ Now let's extract the archive inside the /root/ home directory. [root@centos ~]# tar -zxvf RemoteStuff.tgz ./RemoteStuff/ ./RemoteStuff/.DS_Store ./RemoteStuff/DDWRT/ ./RemoteStuff/DDWRT/.DS_Store ./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin ./RemoteStuff/DDWRT/ddwrt_mod_notes.docx ./RemoteStuff/DDWRT/factory-to-ddwrt.bin ./RemoteStuff/open_ldap_config_notes/ ./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png ./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt ./RemoteStuff/perl_scripts/ ./RemoteStuff/perl_scripts/mysnmp.pl ./RemoteStuff/php_scripts/ ./RemoteStuff/php_scripts/chunked.php ./RemoteStuff/php_scripts/gettingURL.php ./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf ./RemoteStuff/Rick Cardon Tech LLC.webloc ./RemoteStuff/VeeamDiagram.png ./RemoteStuff/backbox-4.5.1-i386.iso ./RemoteStuff/dhcp_admin_script_update.py ./RemoteStuff/test_file.txt [root@mint ~]# ping www.google.com As seen above, all the files were simply extracted into the containing directory within our current working directory. [root@centos ~]# ls -l total 2262872 -rw-------. 1 root root 1752 Feb 1 19:52 anaconda-ks.cfg drwxr-xr-x. 137 root root 8192 Mar 9 04:42 etc_baks -rw-r--r--. 1 root root 1800 Feb 2 03:14 initial-setup-ks.cfg drwxr-xr-x. 6 rdc rdc 4096 Mar 10 22:20 RemoteStuff -rw-r--r--. 1 root root 2317140451 Mar 12 07:12 RemoteStuff.tgz -rw-r--r--. 1 root root 9446 Feb 25 05:09 ssl.conf [root@centos ~]# As noted earlier, we can use either bzip2 or gzip from tar with the -j or -z command line switches. We can also use gzip to compress individual files. However, using bzip or gzip alone does not offer as many features as when combined with tar. When using gzip, the default action is to remove the original files, replacing each with a compressed version adding the .gz extension. Some common command line switches for gzip are − gzip more or less works on a file-by-file basis and not on an archive basis like some Windows O/S zip utilities. The main reason for this is that tar already provides advanced archiving features. gzip is designed to provide only a compression mechanism. Hence, when thinking of gzip, think of a single file. When thinking of multiple files, think of tar archives. Let's now explore this with our previous tar archive. Note − Seasoned Linux professionals will often refer to a tarred archive as a tarball. Let's make another tar archive from our rsync backup. [root@centos Documents]# tar -cvf RemoteStuff.tar ./RemoteStuff/ [root@centos Documents]# ls RemoteStuff.tar RemoteStuff/ For demonstration purposes, let's gzip the newly created tarball, and tell gzip to keep the old file. By default, without the -c option, gzip will replace the entire tar archive with a .gz file. [root@centos Documents]# gzip -c RemoteStuff.tar > RemoteStuff.tar.gz [root@centos Documents]# ls RemoteStuff RemoteStuff.tar RemoteStuff.tar.gz We now have our original directory, our tarred directory and finally our gziped tarball. Let's try to test the -l switch with gzip. [root@centos Documents]# gzip -l RemoteStuff.tar.gz compressed uncompressed ratio uncompressed_name 2317140467 2326661120 0.4% RemoteStuff.tar [root@centos Documents]# To demonstrate how gzip differs from Windows Zip Utilities, let's run gzip on a folder of text files. [root@centos Documents]# ls text_files/ file1.txt file2.txt file3.txt file4.txt file5.txt [root@centos Documents]# Now let's use the -r option to recursively compress all the text files in the directory. [root@centos Documents]# gzip -9 -r text_files/ [root@centos Documents]# ls ./text_files/ file1.txt.gz file2.txt.gz file3.txt.gz file4.txt.gz file5.txt.gz [root@centos Documents]# See? Not what some may have anticipated. All the original text files were removed and each was compressed individually. Because of this behavior, it is best to think of gzip alone when needing to work in single files. Working with tarballs, let's extract our rsynced tarball into a new directory. [root@centos Documents]# tar -C /tmp -zxvf RemoteStuff.tar.gz ./RemoteStuff/ ./RemoteStuff/.DS_Store ./RemoteStuff/DDWRT/ ./RemoteStuff/DDWRT/.DS_Store ./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin ./RemoteStuff/DDWRT/ddwrt_mod_notes.docx ./RemoteStuff/DDWRT/factory-to-ddwrt.bin ./RemoteStuff/open_ldap_config_notes/ ./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png ./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt ./RemoteStuff/perl_scripts/ ./RemoteStuff/perl_scripts/mysnmp.pl ./RemoteStuff/php_scripts/ ./RemoteStuff/php_scripts/chunked.php As seen above, we extracted and decompressed our tarball into the /tmp directory. [root@centos Documents]# ls /tmp hsperfdata_root RemoteStuff Encrypting tarball archives for storing secure documents that may need to be accessed by other employees of the organization, in case of disaster recovery, can be a tricky concept. There are basically three ways to do this: either use GnuPG, or use openssl, or use a third part utility. GnuPG is primarily designed for asymmetric encryption and has an identity-association in mind rather than a passphrase. True, it can be used with symmetrical encryption, but this is not the main strength of GnuPG. Thus, I would discount GnuPG for storing archives with physical security when more people than the original person may need access (like maybe a corporate manager who wants to protect against an Administrator holding all the keys to the kingdom as leverage). Openssl like GnuPG can do what we want and ships with CentOS. But again, is not specifically designed to do what we want and encryption has been questioned in the security community. Our choice is a utility called 7zip. 7zip is a compression utility like gzip but with many more features. Like Gnu Gzip, 7zip and its standards are in the open-source community. We just need to install 7zip from our EHEL Repository (the next chapter will cover installing the Extended Enterprise Repositories in detail). 7zip is a simple install once our EHEL repositories have been loaded and configured in CentOS. [root@centos Documents]# yum -y install p7zip.x86_64 p7zip-plugins.x86_64 Loaded plugins: fastestmirror, langpacks base | 3.6 kB 00:00:00 epel/x86_64/metalink | 13 kB 00:00:00 epel | 4.3 kB 00:00:00 extras | 3.4 kB 00:00:00 updates | 3.4 kB 00:00:00 (1/2): epel/x86_64/updateinfo | 756 kB 00:00:04 (2/2): epel/x86_64/primary_db | 4.6 MB 00:00:18 Loading mirror speeds from cached hostfile --> Running transaction check ---> Package p7zip.x86_64 0:16.02-2.el7 will be installed ---> Package p7zip-plugins.x86_64 0:16.02-2.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved Simple as that, 7zip is installed and ready be used with 256-bit AES encryption for our tarball archives. Now let's use 7z to encrypt our gzipped archive with a password. The syntax for doing so is pretty simple − 7z a -p <output filename><input filename> Where, a: add to archive, and -p: encrypt and prompt for passphrase [root@centos Documents]# 7z a -p RemoteStuff.tgz.7z RemoteStuff.tar.gz 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz (40651),ASM,AES-NI) Scanning the drive: 1 file, 2317140467 bytes (2210 MiB) Creating archive: RemoteStuff.tgz.7z Items to compress: 1 Enter password (will not be echoed): Verify password (will not be echoed) : Files read from disk: 1 Archive size: 2280453410 bytes (2175 MiB) Everything is Ok [root@centos Documents]# ls RemoteStuff RemoteStuff.tar RemoteStuff.tar.gz RemoteStuff.tgz.7z slapD text_files [root@centos Documents]# Now, we have our .7z archive that encrypts the gzipped tarball with 256-bit AES. Note − 7zip uses AES 256-bit encryption with an SHA-256 hash of the password and counter, repeated up to 512K times for key derivation. This should be secure enough if a complex key is used. The process of encrypting and recompressing the archive further can take some time with larger archives. 7zip is an advanced offering with more features than gzip or bzip2. However, it is not as standard with CentOS or amongst the Linux world. Thus, the other utilities should be used often as possible. The CentOS 7 system can be updated in three ways − Manually Automatically Update manually for major security issues and configure automatic updates In a production environment, it is recommended to update manually for production servers. Or at least establish an update plan so the administrator can assure services vital to business operations. It is plausible a simple security update can cause recursive issues with common application that requires upgrading and reconfiguration by an Administrator. So, be weary of scheduling automatic updates in production before testing in development servers and desktops first. To update CentOS 7, we will want to become familiar with the yum command. yum is used to deal with package repositories in CentOS 7. yum is the tool commonly used to − Update the CentOS 7 Linux System Search for packages Install packages Detect and install required dependencies for packages In order to use yum for updates, your CentOS server will need to be connected to the Internet. Most configurations will install a base system, then use yum to query the main CentOS repository for additional functionality in packages and apply system updates. We have already made use of yum to install a few packages. When using yum you will always need to do so as the root user. Or a user with root access. So let's search for and install an easy to use text-editor called nano. [root@centos rdc]# yum search nano Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.rackspace.com * epel: mirror.chpc.utah.edu * extras: repos.forethought.net * updates: repos.forethought.net ====================================================================== N/S matched: nano ====================================================================== nano.x86_64 : A small text editor nodejs-nano.noarch : Minimalistic couchdb driver for Node.js perl-Time-Clock.noarch : Twenty-four hour clock object with nanosecond precision Name and summary matches only, use "search all" for everything. [root@centos rdc]# Now, let's install the nano text editor. [root@centos rdc]# yum install nano Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.keystealth.org * epel: pubmirror1.math.uh.edu * extras: centos.den.host-engine.com * updates: repos.forethought.net Resolving Dependencies --> Running transaction check ---> Package nano.x86_64 0:2.3.1-10.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: nano x86_64 2.3.1-10.el7 base 440 k Transaction Summary Install 1 Package Total download size: 440 k Installed size: 1.6 M Is this ok [y/d/N]: y Downloading packages: nano-2.3.1-10.el7.x86_64.rpm | 440 kB 00:00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : nano-2.3.1-10.el7.x86_64 1/1 Verifying : nano-2.3.1-10.el7.x86_64 1/1 Installed: nano.x86_64 0:2.3.1-10.el7 Complete! [root@centos rdc]# We have installed the nano text editor. This method, IMO, is a lot easier than searching for utilities on websites and manually running the installers. Also, repositories use digital signatures to validate packages assuring they are coming from a trusted source with yum. It is up to the administrator to validate authenticity when trusting new repositories. This is why it is considered a best practice to be weary of third party repositories. Yum can also be used to remove a package. [root@centos rdc]# yum remove nano Loaded plugins: fastestmirror, langpacks Resolving Dependencies --> Running transaction check ---> Package nano.x86_64 0:2.3.1-10.el7 will be erased --> Finished Dependency Resolution Dependencies Resolved Now let's check for updates. [root@centos rdc]# yum list updates Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.keystealth.org * epel: pubmirror1.math.uh.edu * extras: centos.den.host-engine.com * updates: repos.forethought.net Updated Packages NetworkManager.x86_64 1:1.4.0-17.el7_3 updates NetworkManager-adsl.x86_64 1:1.4.0-17.el7_3 updates NetworkManager-glib.x86_64 1:1.4.0-17.el7_3 updates NetworkManager-libnm.x86_64 1:1.4.0-17.el7_3 updates NetworkManager-team.x86_64 1:1.4.0-17.el7_3 updates NetworkManager-tui.x86_64 1:1.4.0-17.el7_3 updates NetworkManager-wifi.x86_64 1:1.4.0-17.el7_3 updates audit.x86_64 2.6.5-3.el7_3.1 updates audit-libs.x86_64 2.6.5-3.el7_3.1 updates audit-libs-python.x86_64 As depicted, we have a few dozen updates pending to install. Actually, there are about 100 total updates since we have not yet configured automatic updates. Thus, let's install all pending updates. [root@centos rdc]# yum update Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirrors.usc.edu * epel: pubmirror1.math.uh.edu * extras: repos.forethought.net * updates: repos.forethought.net Resolving Dependencies --> Running transaction check ---> Package NetworkManager.x86_64 1:1.4.0-14.el7_3 will be updated ---> Package NetworkManager.x86_64 1:1.4.0-17.el7_3 will be an update selinux-policy noarch 3.13.1102.el7_3.15 updates 414 k selinux-policy-targeted noarch 3.13.1102.el7_3.15 updates 6.4 M systemd x86_64 21930.el7_3.7 updates 5.2 M systemd-libs x86_64 21930.el7_3.7 updates 369 k systemd-python x86_64 21930.el7_3.7 updates 109 k systemd-sysv x86_64 21930.el7_3.7 updates 63 k tcsh x86_64 6.18.01-13.el7_3.1 updates 338 k tzdata noarch 2017a1.el7 updates 443 k tzdata-java noarch 2017a1.el7 updates 182 k wpa_supplicant x86_64 1:2.021.el7_3 updates 788 k Transaction Summary =============================================================================== Install 2 Packages Upgrade 68 Packages Total size: 196 M Total download size: 83 M Is this ok [y/d/N]: After hitting the "y" key, updating of CentOS 7 will commence. The general process that yum goes through when updating is − Checks the current packages Looks in the repository for updated packages Calculates dependencies needed for updated packages Downloads updates Installs updates Now, let's make sure our system is up to date − [root@centos rdc]# yum list updates Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * updates: mirror.compevo.com [root@centos rdc]# As you can see, there are no updates listed. In an Enterprise environment, as mentioned earlier, automatic updates may or may not be the preferred method of installation. Let's go over the steps for configuring automatic updates with yum. First, we install a package called yum-cron. [root@centos rdc]# yum -y install yum-cron Install 1 Package Total download size: 61 k Installed size: 51 k Downloading packages: yum-cron-3.4.3-150.el7.centos.noarch.rpm | 61 kB 00:00:01 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : yum-cron-3.4.3-150.el7.centos.noarch 1/1 Verifying : yum-cron-3.4.3-150.el7.centos.noarch 1/1 Installed: yum-cron.noarch 0:3.4.3-150.el7.centos Complete! [root@centos rdc]# By default, yum-cron will only download updates and not install them. Whether to install updates automatically is on the Administrator. The biggest caveat is: some updates will require a system reboot. Also, some updates may require a configuration change before services are again operational. Updating dependencies can possibly create a recursive problem in the following situation − An update is recommended by yum for a certain library An update is recommended by yum for a certain library The library only supports Apache Server 2.4, but we have server 2.3 The library only supports Apache Server 2.4, but we have server 2.3 Our commerce site relies on a certain version of PHP Our commerce site relies on a certain version of PHP The new version of Apache installed for the library requires upgrading PHP The new version of Apache installed for the library requires upgrading PHP Our production web applications have not yet been tested with the newer PHP version Our production web applications have not yet been tested with the newer PHP version Yum may go ahead and automatically upgrade Apache and PHP without notice unless configured not to. If all 5 scenarios play out, it can result in anything from a big headache in the morning to a possible security compromise exposing the user data. While the aforementioned example is a perfect storm of sorts, we never want such a scenario to play out. It is up to the Administrator for accessing possible scenarios of potential revenue loss from time needed to restore services due to possible downtime from update reboots and reconfigurations. This practice may not be conservative enough for, say, a multi-million dollar per day ecommerce site with millions of customers. Now let's configure yum-cron to automatically install system updates. [root@centos rdc]# vim /etc/yum/yum-cron.conf # Whether updates should be applied when they are available. Note # that download_updates must also be yes for the update to be applied. apply_updates = yes We want to change apply_updates = no to apply_updates = yes. Now let's configure the update interval for yum-cron. Again, whether to use automatic updates and install updates on demand can be a double edged sword and needs to be considered by an administrator for each unique situation. Like flavors of GNU Linux, shells come in many varieties and vary in compatibility. The default shell in CentOS is known as the Bash or Bourne Again Shell. The Bash shell is a modern day, modified version of Bourne Shell developed by Stephen Bourne. Bash was the direct replacement to the original Thompson Shell on the Unix operating system developed at Bell Labs by Ken Thompson and Dennis Ritchie (Stephen Bourne was also employed by Bell Labs) Everyone has a favorite shell and each has its strengths and difficulties. But for the most part, Bash is going to be the default shell across all Linux distributions and most commonly available. With experience, everyone will want to explore and use a shell that is best for them. However at the same time, everyone will also want to master Bash shell. Other Linux shells include: Tcsh, Csh, Ksh, Zsh, and Fish. Developing skills to use any Linux shell at an expert level is extremely important to a CentOS administrator. As we mentioned previously, unlike Windows, Linux at its heart is a command line operating system. A shell is simply a user interface that allows an administrator (or user) to issue commands to the operating system. If a Linux system administrator were an airlines pilot, using the shell would be similar to taking the plane off auto-pilot and grabbing the manual controls for more maneuverable flight. A Linux shell, like Bash, is known in Computer Science terms as a Command Line Interpreter. Microsoft Windows also has two command line interpreters called DOS (not to be confused with the original DOS operating system) and PowerShell. Most modern shells like Bash provide constructs allowing more complex shell scripts to automate both common and complex tasks. Constructs include − Script flow control (ifthen and else) Logical comparison operations (greater than, less than, equality) Loops Variables Parameters defining operation (similar to switches with commands) Often when thinking about performing a task administrators ask themselves: Should I use a shell script or a scripting language such as Perl, Ruby or Python? There is no set rule here. There are only typical differences between shells versus scripting languages. Shell allows the use of Linux commands such as sed, grep, tee, cat and all other command-line based utilities on the Linux operating system. In fact, pretty much any command line Linux utility can be scripted in your shell. A great example of using a shell would be a quick script to check a list of hosts for DNS resolution. Our simple Bash Script to check DNS names − #!/bin/bash for name in $(cat $1); do host $name.$2 | grep "has address" done exit small wordlist to test DNS resolution on − dns www test dev mail rdp remote Output against google.com domain − [rdc@centos ~]$ ./dns-check.sh dns-names.txt google.com -doing dns dns.google.com has address 172.217.6.46 -doing www www.google.com has address 172.217.6.36 -doing test -doing dev -doing mail googlemail.l.google.com has address 172.217.6.37 -doing rdp -doing remote [rdc@centos ~]$ Leveraging simple Linux commands in our shell, we were able to make a simple 5-line script to audit DNS names from a word list. This would have taken some considerable time in Perl, Python, or Ruby even when using a nicely implemented DNS Library. A scripting language will give more control outside the shell. The above Bash script used a wrapper around the Linux host command. What if we wanted to do more and make our own application like host to interact outside the shell? This is where we would use a scripting language. Also, with a highly maintained scripting language we know our actions will work across different systems for the most part. Python 3.5, for example, will work on any other system running Python 3.5 with the same libraries installed. Not so, if we want to run our BASH script on both Linux and HP-UX. Sometimes the lines between a scripting language and a powerful shell can be blurred. It is possible to automate CentOS Linux administration tasks with Python, Perl or Ruby. Doing so is really quite commonplace. Also, affluent shell-script developers have made a simple, but otherwise functional, web-server daemon in Bash. With experience in scripting languages and automating tasks in shells, a CentOS administrator will be able to quickly determine where to start when needing to solve a problem. It is quite common to start a project with a shell script. Then progress to a scripting (or compiled) language as a project gets more complex. Also, it is ok to use both a scripting language and shell script for different parts of a project. An example could be a Perl script to scrape a website. Then, use a shell script to parse and format with sed, awk, and egrep. Finally, use a PHP script for inserting formatted data into MySQL database using a web GUI. With some theory behind shells, let's get started with the basic building blocks to automate tasks from a Bash shell in CentOS. Processing stdout to another command − [rdc@centos ~]$ cat ~/output.txt | wc -l 6039 [rdc@centos ~]$ Above, we have passed cat'sstoud to wc for processing with the pipe character. wc then processed the output from cat, printing the line count of output.txt to the terminal. Think of the pipe character as a "pipe" passing output from one command, to be processed by the next command. Following are the key concepts to remember when dealing with command redirection − We introduced this in chapter one without really talking much about redirection or assigning redirection. When opening a terminal in Linux, your shell is seen as the default target for − standard input < 0 standard output > 1 standard error 2 Let's see how this works − [rdc@centos ~]$ lsof -ap $BASHPID -d 0,1,2 COMMAND PID USER **FD** TYPE DEVICE SIZE/OFF NODE NAME bash 13684 rdc **0u** CHR 136,0 0t0 3 /dev/pts/0 bash 13684 rdc **1u** CHR 136,0 0t0 3 /dev/pts/0 bash 13684 rdc **2u** CHR 136,0 0t0 3 /dev/pts/0 [rdc@centos ~]$ /dev/pts/0 is our pseudo terminal. CentOS Linux looks at this and thinks of our open terminal application like a real terminal with the keyboard and display plugged in through a serial interface. However, like a hypervisor abstracts hardware to an operating system /dev/pts abstracts our terminal to applications. From the above lsof command, we can see under the FD column that all three file-descriptors are set to our virtual terminal (0,1,2). We can now send commands, see command output, as well as any errors associated with the command. Following are examples for STDIN and STDOUT − [root@centosLocal centos]# echo "I am coming from Standard output or STDOUT." > output.txt && cat output.txt I am coming from Standard output or STDOUT. [root@centosLocal centos]# It is also possible to send both stdout and stderr to separate files − bash-3.2# find / -name passwd 1> good.txt 2> err.txt bash-3.2# cat good.txt /etc/pam.d/passwd /etc/passwd bash-3.2# cat err.txt find: /dev/fd/3: Not a directory find: /dev/fd/4: Not a directory bash-3.2# When searching the entire file system, two errors were encountered. Each were sent to a separate file for later perusal, while the results returned were placed into a separate text file. Sending stderr to a text file can be useful when doing things that output a lot of data to the terminal like compiling applications. This will allow for perusal of errors that could get lost from terminal scrollback history. One note when passing STDOUT to a text file are the differences between >> and >. The double ">>" will append to a file, while the singular form will clobber the file and write new contents (so all previous data will be lost). [root@centosLocal centos]# cat < stdin.txt Hello, I am being read form Standard input, STDIN. [root@centosLocal centos]# In the above command, the text file stdin.txt was redirected to the cat command which echoed its content to STDOUT. The pipe character will take the output from the first command, passing it as an input into the next command, allowing the secondary command to perform operations on the output. Now, let's "pipe" the stdout of cat to another command − [root@centosLocal centos]# cat output.txt | wc -l 2 [root@centosLocal centos]# Above, wc performs calculations on output from cat which was passed from the pipe. The pipe command is particularly useful when filtering the output from grep or egrep − [root@centosLocal centos]# egrep "^[0-9]{4}$" /usr/dicts/nums | wc -l 9000 [root@centosLocal centos]# In the above command, we passed every 4 digit number to wc from a text file containing all numbers from 65535 passed through an egrep filter. Output can be redirected using the & character. If we want to direct the output both STDOUT and STDERR, into the same file, it can be accomplished as follows − [root@centosLocal centos]# find / -name passwd > out.txt 2>&1 [root@centosLocal centos]# cat out.txt find: /dev/fd/3: Not a directory find: /dev/fd/4: Not a directory /etc/passwd [root@centosLocal centos]# Redirecting using the & character works like this: first, the output is redirected into out.txt. Second, STDERR or the file descriptor 2 is reassigned to the same location as STDOUT, in this case out.txt. Redirection is extremely useful and comes in handy while solving problems that surgace when manipulating large text-files, compiling source code, redirecting the output in shell scripts, and issuing complex Linux commands. While powerful, redirection can get complicated for newer CentOS Administrators. Practice, research, and occasional question to a Linux forum (such as Stack Overflow Linux) will help solve advanced solutions. Now that we have a good idea of how the Bash shell works, let's learn some basic constructs, commonly used, to write scripts. In this section we will explore − Variables Loops Conditionals Loop control Reading and writing to files Basic math operations BASH can be a little tricky compared to a dedicated scripting language. Some of the biggest hang-ups in BASH scripts are from incorrectly escaping or not escaping script operations being passed to the shell. If you have looked over a script a few times and it is not working as expected, don't fret. This is common even with those who use BASH to create complex scripts daily. A quick search of Google or signing up at an expert Linux forum to ask a question will lead to a quick resolution. There is a very likely chance someone has come across the exact issue and it has already been solved. BASH scripting is a great method of quickly creating powerful scripts for everything from automating administration tasks to creating useful tools. Becoming an expert level BASH script developer takes time and practice. Hence, use BASH scripts whenever possible, it is a great tool to have in your CentOS Administration toolbox. Package management in CentOS can be performed in two ways: from the terminal and from the Graphical User Interface. More often than not a majority of a CentOS administrator's time will be using the terminal. Updating and installing packages for CentOS is no different. With this in mind, we will first explore package management in the terminal, then touch on using the graphical package management tool provided by CentOS. YUM is the tool provided for package management in CentOS. We have briefly touched this topic in previous chapters. In this chapter, we will be working from a clean CentOS install. We will first completely update our installation and then install an application. YUM has brought software installation and management in Linux a long way. YUM "automagically” checks for out-of-date dependencies, in addition to out-of-date packages. This has really taken a load off the CentOS administrator compared to the old days of compiling every application from source-code. Checks for packages that can update candidates. For this tutorial, we will assume this a production system that will be facing the Internet with no production applications that needs to be tested by DevOps before upgrading the packages. Let us now install the updated candidates onto the system. [root@localhost rdc]# yum check-update Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu NetworkManager.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-adsl.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-glib.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-libnm.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-team.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-tui.x86_64 1:1.4.0-19.el7_3 updates NetworkManager-wifi.x86_64 1:1.4.0-19.el7_3 updates audit.x86_64 2.6.5-3.el7_3.1 updates vim-common.x86_64 2:7.4.160-1.el7_3.1 updates vim-enhanced.x86_64 2:7.4.160-1.el7_3.1 updates vim-filesystem.x86_64 2:7.4.160-1.el7_3.1 updates vim-minimal.x86_64 2:7.4.160-1.el7_3.1 updates wpa_supplicant.x86_64 1:2.0-21.el7_3 updates xfsprogs.x86_64 4.5.0-9.el7_3 updates [root@localhost rdc]# This will install all updated candidates making your CentOS installation current. With a new installation, this can take a little time depending on your installation and your internet connection speed. [root@localhost rdc]# yum update vim-minimal x86_64 2:7.4.160-1.el7_3.1 updates 436 k wpa_supplicant x86_64 1:2.0-21.el7_3 updates 788 k xfsprogs x86_64 4.5.0-9.el7_3 updates 895 k Transaction Summary ====================================================================================== Install 2 Packages Upgrade 156 Packages Total download size: 371 M Is this ok [y/d/N]: Besides updating the CentOS system, the YUM package manager is our go-to tool for installing the software. Everything from network monitoring tools, video players, to text editors can be installed from a central repository with YUM. Before installing some software utilities, let's look at few YUM commands. For daily work, 90% of a CentOS Admin's usage of YUM will be with about 7 commands. We will go over each in the hope of becoming familiar with operating YUM at a proficient level for daily use. However, like most Linux utilities, YUM offers a wealth of advanced features that are always great to explore via the man page. Use man yum will always be the first step to performing unfamiliar operations with any Linux utility. Following are the commonly used YUM commands. We will now install a text-based web browser called Lynx. Before installation, we must first get the package name containing the Lynx web browser. We are not even 100% sure our default CentOS repository provides a package for the Lynx web browser, so let's search and see − [root@localhost rdc]# yum search web browser Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu ================================================================= N/S matched: web, browser ================================================================== icedtea-web.x86_64 : Additional Java components for OpenJDK - Java browser plug-in and Web Start implementation elinks.x86_64 : A text-mode Web browser firefox.i686 : Mozilla Firefox Web browser firefox.x86_64 : Mozilla Firefox Web browser lynx.x86_64 : A text-based Web browser Full name and summary matches only, use "search all" for everything. [root@localhost rdc]# We see, CentOS does offer the Lynx web browser in the repository. Let's see some more information about the package. [root@localhost rdc]# lynx.x86_64 bash: lynx.x86_64: command not found... [root@localhost rdc]# yum info lynx.x86_64 Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Available Packages Name : lynx Arch : x86_64 Version : 2.8.8 Release : 0.3.dev15.el7 Size : 1.4 M Repo : base/7/x86_64 Summary : A text-based Web browser URL : http://lynx.isc.org/ License : GPLv2 Description : Lynx is a text-based Web browser. Lynx does not display any images, : but it does support frames, tables, and most other HTML tags. One : advantage Lynx has over graphical browsers is speed; Lynx starts and : exits quickly and swiftly displays web pages. [root@localhost rdc]# Nice! Version 2.8 is current enough so let's install Lynx. [root@localhost rdc]# yum install lynx Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Resolving Dependencies --> Running transaction check ---> Package lynx.x86_64 0:2.8.8-0.3.dev15.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved =============================================================================== =============================================================================== Package Arch Version Repository Size =============================================================================== =============================================================================== Installing: lynx x86_64 2.8.80.3.dev15.el7 base 1.4 M Transaction Summary =============================================================================== =============================================================================== Install 1 Package Total download size: 1.4 M Installed size: 5.4 M Is this ok [y/d/N]: y Downloading packages: No Presto metadata available for base lynx-2.8.8-0.3.dev15.el7.x86_64.rpm | 1.4 MB 00:00:10 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : lynx-2.8.8-0.3.dev15.el7.x86_64 1/1 Verifying : lynx-2.8.8-0.3.dev15.el7.x86_64 1/1 Installed: lynx.x86_64 0:2.8.8-0.3.dev15.el7 Complete! [root@localhost rdc]# Next, let's make sure Lynx did in fact install correctly. [root@localhost rdc]# yum list installed | grep -i lynx lynx.x86_64 2.8.8-0.3.dev15.el7 @base [root@localhost rdc]# Great! Let's use Lynx to and see what the web looks like without "likes" and pretty pictures. [root@localhost rdc]# lynx www.tutorialpoint.in Great, now we have a web browser for our production server that can be used without much worry into remote exploits launched over the web. This a good thing for production servers. We are almost completed, however first we need to set this server for developers to test applications. Thus, let's make sure they have all the tools needed for their job. We could install everything individually, but CentOS and YUM have made this a lot faster. Let's install the Development Group Package. [root@localhost rdc]# yum groups list Loaded plugins: fastestmirror, langpacks Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Available Groups: Compatibility Libraries Console Internet Tools Development Tools Graphical Administration Tools Legacy UNIX Compatibility Scientific Support Security Tools Smart Card Support System Administration Tools System Management Done [root@localhost rdc]# This is a smaller list of Package Groups provided by CentOS. Let's see what is included with the "Development Group". [root@localhost rdc]# yum group info "Development Tools" Loaded plugins: fastestmirror, langpacks There is no installed groups file. Maybe run: yum groups mark convert (see man yum) Loading mirror speeds from cached hostfile * base: mirror.scalabledns.com * extras: mirror.scalabledns.com * updates: mirror.clarkson.edu Group: Development Tools Group-Id: development Description: A basic development environment. Mandatory Packages: autoconf automake binutils bison The first screen of output is as seen above. This entire list is rather comprehensive. However, this group will usually be needed to be installed in its entirety as time goes by. Let's install the entire Development Group. [root@localhost rdc]# yum groupinstall "Development Tools" This will be a larger install. When completed, your server will have most development libraries and compilers for Perl, Python, C, and C++. Gnome Desktop provides a graphical package management tool called Software. It is fairly simple to use and straightforward. Software, the Gnome package management tool for CentOS can be found by navigating to: Applications → System Tools → Software. The Software Package Management Tool is divided into groups allowing the administrator to select packages for installation. While this tool is great for ease-of-use and simplicity for end-users, YUM is a lot more powerful and will probably be used more by administrators. Following is a screenshot of the Software Package Management Tool, not really designed for System Administrators. Logical Volume Management (LVM) is a method used by Linux to manage storage volumes across different physical hard disks. This is not to be confused with RAID. However, it can be thought of in a similar concept as RAID 0 or J-Bod. With LVM, it is possible to have (for example) three physical disks of 1TB each, then a logical volume of around 3TB such as /dev/sdb. Or even two logical volumes of 1.5TB, 5 volumes of 500GB, or any combination. One single disk can even be used for snapshots of Logical Volumes. Note − Using Logical Volumes actually increases disk I/O when configured correctly. This works in a similar fashion to RAID 0 striping data across separate disks. When learning about volume management with LVM, it is easier if we know what each component in LVM is. Please study the following table to get a firm grasp of each component. If you need to, use Google to study. Understanding each piece of a logical volume is important to manage them. A physical volume will be seen as /dev/sda, /dev/sdb; a physical disk that is detected by Linux. A physical partition will be a section of the disk partitioned by a disk utility such as fdisk. Keep in mind, physical partition is not recommended in most common LVM setups. Example: disk /dev/sda is partitioned to include two physical partitions: /dev/sda1 and /dev/sda1 If we have two physical disks of 1TB each, we can create a volume group of almost 2TB amongst the two. From the volume group, we can create three logical volumes each of any-size not exceeding the total volume group size. Before being acquainted with the latest and greatest featured tools for LVM Management in CentOS 7, we should first explore more traditional tools that have been used for Linux disk management. These tools will come handy and still have use with today's advanced LVM tools such as the System Storage Manager − lsblk, parted, and mkfs.xfs. Now, assuming we have added another disk or two to our system, we need to enumerate disks detected by Linux. I'd always advise enumerating disks every time before performing operations considered as destructive. lsblk is a great tool for getting disk information. Let's see what disks CentOS detects. [root@localhost rdc]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 20G 0 disk ├─sda1 8:1 0 1G 0 part /boot └─sda2 8:2 0 19G 0 part ├─cl-root 253:0 0 17G 0 lvm / └─cl-swap 253:1 0 2G 0 lvm [SWAP] sdb 8:16 0 6G 0 disk sdc 8:32 0 4G 0 disk sr0 11:0 1 1024M 0 rom As you can see, we have three disks on this system: sda, sdb, and sdc. Disk sda contains our working CentOS installation, so we do not want to toy around with sda. Both sdb and sdc were added to the system for this tutorial. Let's make these disks usable to CentOS. [root@localhost rdc]# parted /dev/sdb mklabel GPT Warning: The existing disk label on /dev/sdb will be destroyed and all data on this disk will be lost. Do you want to continue? Yes/No? Yes [root@localhost rdc]# We now have one disk labeled. Simply run the parted command in the same manner on sdc. We will only create a single partition on each disk. To create partitions, the parted command is used again. [root@localhost rdc]# parted -a opt /dev/sdb mkpart primary ext4 0% 100% Warning − You requested a partition from 0.00B to 6442MB (sectors 0..12582911). The closest location we can manage is 17.4kB to 1048kB (sectors 34..2047). Is this still acceptable to you? Yes/No? NO [root@localhost rdc]# parted -a opt /dev/sdc mkpart primary ext4 0% 100% Information − You may need to update /etc/fstab. [root@localhost rdc]# lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 20G 0 disk ├─sda1 8:1 0 1G 0 part / boot └─sda2 8:2 0 19G 0 part ├─cl-root 253:0 0 17G 0 lvm / └─cl-swap 253:1 0 2G 0 lvm [SWAP] sdb 8:16 0 6G 0 disk └─sdb1 8:17 0 6G 0 part sdc 8:32 0 4G 0 disk └─sdc1 8:33 0 4G 0 part sr0 11:0 1 1024M 0 rom [root@localhost rdc]# As you can see from lsblk output, we now have two partitions, each on sdb and sdc. Finally, before mounting and using any volume we need to add a file system. We will be using the XFS file system. root@localhost rdc]# mkfs.xfs -f /dev/sdb1 meta-data = /dev/sdb1 isize = 512 agcount = 4, agsize = 393088 blks = sectsz = 512 attr = 2, projid32bit = 1 = crc = 1 finobt = 0, sparse = 0 data = bsize = 4096 blocks = 1572352, imaxpct = 25 = sunit = 0 swidth = 0 blks naming = version 2 bsize = 4096 ascii-ci = 0 ftype = 1 log = internal log bsize = 4096 blocks = 2560, version = 2 = sectsz = 512 sunit = 0 blks, lazy-count = 1 realtime = none extsz = 4096 blocks = 0, rtextents = 0 [root@localhost rdc]# mkfs.xfs -f /dev/sdc1 meta-data = /dev/sdc1 isize = 512 agcount = 4, agsize = 262016 blks = sectsz = 512 attr = 2, projid32bit = 1 = crc = 1 finobt = 0, sparse = 0 data = bsize = 4096 blocks = 1048064, imaxpct = 25 = sunit = 0 swidth = 0 blks naming = version 2 bsize = 4096 ascii-ci = 0 ftype = 1 log = internal log bsize = 4096 blocks = 2560, version = 2 = sectsz = 512 sunit = 0 blks, lazy-count = 1 realtime = none extsz = 4096 blocks = 0, rtextents = 0 [root@localhost rdc]# Let's check to make sure each have a usable file system. [root@localhost rdc]# lsblk -o NAME,FSTYPE NAME FSTYPE sda ├─sda1 xfs └─sda2 LVM2_member ├─cl-root xfs └─cl-swap swap sdb └─sdb1 xfs sdc └─sdc1 xfs sr0 [root@localhost rdc]# Each is now using the XFS file system. Let's mount them, check the mount, and copy a file to each. [root@localhost rdc]# mount -o defaults /dev/sdb1 /mnt/sdb [root@localhost rdc]# mount -o defaults /dev/sdc1 /mnt/sdc [root@localhost ~]# touch /mnt/sdb/myFile /mnt/sdc/myFile [root@localhost ~]# ls /mnt/sdb /mnt/sdc /mnt/sdb: myFile /mnt/sdc: myFile We have two usable disks at this point. However, they will only be usable when we mount them manually. To mount each on boot, we must edit the fstab file. Also, permissions must be set for groups needing access to the new disks. One of the greatest addition to CentOS 7 was the inclusion of a utility called System Storage Manager or ssm. System Storage Manager greatly simplifies the process of managing LVM pools and storage volumes on Linux. We will go through the process of creating a simple volume pool and logical volumes in CentOS. The first step is installing the System Storage Manager. [root@localhost rdc]# yum install system-storage-manager Let's look at our disks using the ssm list command. As seen above, a total of three disks are installed on the system. /sdba1 − Hosts our CentOS installation /sdba1 − Hosts our CentOS installation /sdb1 − Mounted at /mnt/sdb /sdb1 − Mounted at /mnt/sdb /sdc1 − Mounted at /mnt/sdc /sdc1 − Mounted at /mnt/sdc What we want to do is make a Volume Group using two disks (sdb and sdc). Then make three 3GB Logical Volumes available to the system. Let's create our Volume Group. [root@localhost rdc]# ssm create -p NEW_POOL /dev/sdb1 /dev/sdc1 By default, ssm will create a single logical volume extending the entire 10GB of the pool. We don't want this, so let's remove this. [root@localhost rdc]# ssm remove /dev/NEW_POOL/lvol001 Do you really want to remove active logical volume NEW_POOL/lvol001? [y/n]: y Logical volume "lvol001" successfully removed [root@localhost rdc]# Finally, let's create the three Logical Volumes. [root@localhost rdc]# ssm create -n disk001 --fs xfs -s 3GB -p NEW_POOL [root@localhost rdc]# ssm create -n disk002 --fs xfs -s 3GB -p NEW_POOL [root@localhost rdc]# ssm create -n disk003 --fs xfs -s 3GB -p NEW_POOL Now, let's check our new volumes. We now have three separate logical volumes spanned across two physical disk partitions. Logical volumes are a powerful feature now built into CentOS Linux. We have touched the surface on managing these. Mastering pools and logical volumes come with practice and extended learning from Tutorials Point. For now, you have learned the basics of LVM management in CentOS and possess the ability to create basic striped Logical Volumes on a single host. 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2642, "s": 2257, "text": "Unique among business class Linux distributions, CentOS stays true to the open-source nature that Linux was founded on. The first Linux kernel was developed by a college student at the University of Helsinki (Linus Torvalds) and combined with the GNU utilities founded and promoted by Richard Stallman. CentOS has a proven, open-source licensing that can power today’s business world." }, { "code": null, "e": 2979, "s": 2642, "text": "CentOS has quickly become one of the most prolific server platforms in the world. Any Linux Administrator, when seeking employment, is bound to come across the words: “CentOS Linux Experience Preferred”. From startups to Fortune 10 tech titans, CentOS has placed itself amongst the higher echelons of server operating systems worldwide." }, { "code": null, "e": 3066, "s": 2979, "text": "What makes CentOS stand out from other Linux distributions is a great combination of −" }, { "code": null, "e": 3088, "s": 3066, "text": "Open source licensing" }, { "code": null, "e": 3110, "s": 3088, "text": "Open source licensing" }, { "code": null, "e": 3153, "s": 3110, "text": "Dedicated user-base of Linux professionals" }, { "code": null, "e": 3196, "s": 3153, "text": "Dedicated user-base of Linux professionals" }, { "code": null, "e": 3218, "s": 3196, "text": "Good hardware support" }, { "code": null, "e": 3240, "s": 3218, "text": "Good hardware support" }, { "code": null, "e": 3277, "s": 3240, "text": "Rock-solid stability and reliability" }, { "code": null, "e": 3314, "s": 3277, "text": "Rock-solid stability and reliability" }, { "code": null, "e": 3344, "s": 3314, "text": "Focus on security and updates" }, { "code": null, "e": 3374, "s": 3344, "text": "Focus on security and updates" }, { "code": null, "e": 3457, "s": 3374, "text": "Strict adherence to software packaging standards needed in a corporate environment" }, { "code": null, "e": 3540, "s": 3457, "text": "Strict adherence to software packaging standards needed in a corporate environment" }, { "code": null, "e": 3672, "s": 3542, "text": "Before starting the lessons, we assume that the readers have a basic knowledge of Linux and Administration fundamentals such as −" }, { "code": null, "e": 3695, "s": 3672, "text": "What is the root user?" }, { "code": null, "e": 3718, "s": 3695, "text": "What is the root user?" }, { "code": null, "e": 3745, "s": 3718, "text": "The power of the root user" }, { "code": null, "e": 3772, "s": 3745, "text": "The power of the root user" }, { "code": null, "e": 3815, "s": 3772, "text": "Basic concept of security groups and users" }, { "code": null, "e": 3858, "s": 3815, "text": "Basic concept of security groups and users" }, { "code": null, "e": 3901, "s": 3858, "text": "Experience using a Linux terminal emulator" }, { "code": null, "e": 3944, "s": 3901, "text": "Experience using a Linux terminal emulator" }, { "code": null, "e": 3976, "s": 3944, "text": "Fundamental networking concepts" }, { "code": null, "e": 4008, "s": 3976, "text": "Fundamental networking concepts" }, { "code": null, "e": 4092, "s": 4008, "text": "Fundamental understanding of interpreted programming languages (Perl, Python, Ruby)" }, { "code": null, "e": 4176, "s": 4092, "text": "Fundamental understanding of interpreted programming languages (Perl, Python, Ruby)" }, { "code": null, "e": 4233, "s": 4176, "text": "Networking protocols such as HTTP, LDAP, FTP, IMAP, SMTP" }, { "code": null, "e": 4290, "s": 4233, "text": "Networking protocols such as HTTP, LDAP, FTP, IMAP, SMTP" }, { "code": null, "e": 4374, "s": 4290, "text": "Cores that compose a computer operating system: file system, drivers, and the kerne" }, { "code": null, "e": 4458, "s": 4374, "text": "Cores that compose a computer operating system: file system, drivers, and the kerne" }, { "code": null, "e": 4602, "s": 4458, "text": "Before learning the tools of a CentOS Linux Administrator, it is important to note the philosophy behind the Linux administration command line." }, { "code": null, "e": 4952, "s": 4602, "text": "Linux was designed based on the Unix philosophy of “small, precise tools chained together simplifying larger tasks”. Linux, at its root, does not have large single-purpose applications for one specific use a lot of the time. Instead, there are hundreds of basic utilities that when combined offer great power to accomplish big tasks with efficiency." }, { "code": null, "e": 5211, "s": 4952, "text": "For example, if an administrator wants a listing of all the current users on a system, the following chained commands can be used to get a list of all system users. On execution of the command, the users are on the system are listed in an alphabetical order." }, { "code": null, "e": 5333, "s": 5211, "text": "[root@centosLocal centos]# cut /etc/passwd -d\":\" -f1 | sort \nabrt \nadm \navahi \nbin \ncentos \nchrony \ncolord \ndaemon \ndbus\n" }, { "code": null, "e": 5410, "s": 5333, "text": "It is easy to export this list into a text file using the following command." }, { "code": null, "e": 5574, "s": 5410, "text": "[root@localhost /]# cut /etc/passwd -d \":\" -f1 > system_users.txt \n[root@localhost /]# cat ./system_users.txt | sort | wc –l \n40 \n[root@localhost /]#\n" }, { "code": null, "e": 5651, "s": 5574, "text": "It is also possible to compare the user list with an export at a later date." }, { "code": null, "e": 5895, "s": 5651, "text": "[root@centosLocal centos]# cut /etc/passwd -d \":\" -f1 > system_users002.txt && \n cat system_users002.txt | sort | wc -l \n41 \n[root@centosLocal centos]# diff ./system_users.txt ./system_users002.txt \nevilBackdoor [root@centosLocal centos]#\n" }, { "code": null, "e": 6083, "s": 5895, "text": "With this approach of small tools chained to accomplish bigger tasks, it is simpler to make a script performing these commands, than automatically email results at regular time intervals." }, { "code": null, "e": 6154, "s": 6083, "text": "Basic Commands every Linux Administrator should be proficient in are −" }, { "code": null, "e": 6158, "s": 6154, "text": "vim" }, { "code": null, "e": 6163, "s": 6158, "text": "grep" }, { "code": null, "e": 6177, "s": 6163, "text": "more and less" }, { "code": null, "e": 6182, "s": 6177, "text": "tail" }, { "code": null, "e": 6187, "s": 6182, "text": "head" }, { "code": null, "e": 6190, "s": 6187, "text": "wc" }, { "code": null, "e": 6195, "s": 6190, "text": "sort" }, { "code": null, "e": 6200, "s": 6195, "text": "uniq" }, { "code": null, "e": 6204, "s": 6200, "text": "tee" }, { "code": null, "e": 6208, "s": 6204, "text": "cat" }, { "code": null, "e": 6212, "s": 6208, "text": "cut" }, { "code": null, "e": 6216, "s": 6212, "text": "sed" }, { "code": null, "e": 6219, "s": 6216, "text": "tr" }, { "code": null, "e": 6225, "s": 6219, "text": "paste" }, { "code": null, "e": 6502, "s": 6225, "text": "In the Linux world, Administrators use filtering commands every day to parse logs, filter command output, and perform actions with interactive shell scripts. As mentioned, the power of these commands come in their ability to modify one another through a process called piping." }, { "code": null, "e": 6607, "s": 6502, "text": "The following command shows how many words begin with the letter a from the CentOS main user dictionary." }, { "code": null, "e": 6704, "s": 6607, "text": "[root@centosLocal ~]# egrep '^a.*$' /usr/share/dict/words | wc -l \n25192 \n[root@centosLocal ~]#\n" }, { "code": null, "e": 6834, "s": 6704, "text": "To introduce permissions as they apply to both directories and files in CentOS Linux, let's look at the following command output." }, { "code": null, "e": 7044, "s": 6834, "text": "[centos@centosLocal etc]$ ls -ld /etc/yum* \ndrwxr-xr-x. 6 root root 100 Dec 5 06:59 /etc/yum \n-rw-r--r--. 1 root root 970 Nov 15 08:30 /etc/yum.conf \ndrwxr-xr-x. 2 root root 187 Nov 15 08:30 /etc/yum.repos.d\n" }, { "code": null, "e": 7099, "s": 7044, "text": "Note − The three primary object types you will see are" }, { "code": null, "e": 7127, "s": 7099, "text": "\"-\" − a dash for plain file" }, { "code": null, "e": 7155, "s": 7127, "text": "\"-\" − a dash for plain file" }, { "code": null, "e": 7177, "s": 7155, "text": "\"d\" − for a directory" }, { "code": null, "e": 7199, "s": 7177, "text": "\"d\" − for a directory" }, { "code": null, "e": 7225, "s": 7199, "text": "\"l\" − for a symbolic link" }, { "code": null, "e": 7251, "s": 7225, "text": "\"l\" − for a symbolic link" }, { "code": null, "e": 7325, "s": 7251, "text": "We will focus on the three blocks of output for each directory and file −" }, { "code": null, "e": 7350, "s": 7325, "text": "drwxr-xr-x : root : root" }, { "code": null, "e": 7375, "s": 7350, "text": "-rw-r--r-- : root : root" }, { "code": null, "e": 7400, "s": 7375, "text": "drwxr-xr-x : root : root" }, { "code": null, "e": 7462, "s": 7400, "text": "Now let's break this down, to better understand these lines −" }, { "code": null, "e": 7632, "s": 7462, "text": "Understanding the difference between owner, group and world is important. Not understanding this can have big consequences on servers that host services to the Internet." }, { "code": null, "e": 7748, "s": 7632, "text": "Before we give a real-world example, let's first understand the permissions as they apply to directories and files." }, { "code": null, "e": 7827, "s": 7748, "text": "Please take a look at the following table, then continue with the instruction." }, { "code": null, "e": 8125, "s": 7827, "text": "Note − When files should be accessible for reading in a directory, it is common to apply read and execute permissions. Otherwise, the users will have difficulty working with the files. Leaving write disabled will assure files cannot be: renamed, deleted, copied over, or have permissions modified." }, { "code": null, "e": 8191, "s": 8125, "text": "When applying permissions, there are two concepts to understand −" }, { "code": null, "e": 8212, "s": 8191, "text": "Symbolic Permissions" }, { "code": null, "e": 8230, "s": 8212, "text": "Octal Permissions" }, { "code": null, "e": 8396, "s": 8230, "text": "In essence, each are the same but a different way to referring to, and assigning file permissions. For a quick guide, please study and refer to the following table −" }, { "code": null, "e": 8569, "s": 8396, "text": "When assigning permissions using the octal method, use a 3 byte number such as: 760. The number 760 translates into: Owner: rwx; Group: rw; Other (or world) no permissions." }, { "code": null, "e": 8645, "s": 8569, "text": "Another scenario: 733 would translate to: Owner: rwx; Group: wx; Other: wx." }, { "code": null, "e": 8823, "s": 8645, "text": "There is one drawback to permissions using the Octal method. Existing permission sets cannot be modified. It is only possible to reassign the entire permission set of an object." }, { "code": null, "e": 9266, "s": 8823, "text": "Now you might wonder, what is wrong with always re-assigning permissions? Imagine a large directory structure, for example /var/www/ on a production web-server. We want to recursively take away the w or write bit on all directories for Other. Thus, forcing it to be pro-actively added only when needed for security measures. If we re-assign the entire permission set, we take away all other custom permissions assigned to every sub-directory." }, { "code": null, "e": 9534, "s": 9266, "text": "Hence, it will cause a problem for both the administrator and the user of the system. At some point, a person (or persons) would need to re-assign all the custom permissions that were wiped out by re-assigning the entire permission-set for every directory and object." }, { "code": null, "e": 9613, "s": 9534, "text": "In this case, we would want to use the Symbolic method to modify permissions −" }, { "code": null, "e": 9637, "s": 9613, "text": "chmod -R o-w /var/www/\n" }, { "code": null, "e": 9774, "s": 9637, "text": "The above command would not \"overwrite permissions\" but modify the current permission sets. So get accustomed to using the best practice" }, { "code": null, "e": 9807, "s": 9774, "text": "Octal only to assign permissions" }, { "code": null, "e": 9842, "s": 9807, "text": "Symbolic to modify permission sets" }, { "code": null, "e": 10155, "s": 9842, "text": "It is important that a CentOS Administrator be proficient with both Octal and Symbolic permissions as permissions are important for the integrity of data and the entire operating system. If permissions are incorrect, the end result will be both sensitive data and the entire operating system will be compromised." }, { "code": null, "e": 10256, "s": 10155, "text": "With that covered, let's look at a few commands for modifying permissions and object owner/members −" }, { "code": null, "e": 10262, "s": 10256, "text": "chmod" }, { "code": null, "e": 10268, "s": 10262, "text": "chown" }, { "code": null, "e": 10274, "s": 10268, "text": "chgrp" }, { "code": null, "e": 10280, "s": 10274, "text": "umask" }, { "code": null, "e": 10455, "s": 10280, "text": "chmod will allow us to change permissions of directories and files using octal or symbolic permission sets. We will use this to modify our assignment and uploads directories." }, { "code": null, "e": 10612, "s": 10455, "text": "chown can modify both owning the user and group of objects. However, unless needing to modify both at the same time, using chgrp is usually used for groups." }, { "code": null, "e": 10664, "s": 10612, "text": "chgrp will change the group owner to that supplied." }, { "code": null, "e": 10985, "s": 10664, "text": "Let's change all the subdirectory assignments in /var/www/students/ so the owning group is the students group. Then assign the root of students to the professors group. Later, make Dr. Terry Thomas the owner of the students directory, since he is tasked as being in-charge of all Computer Science academia at the school." }, { "code": null, "e": 11048, "s": 10985, "text": "As we can see, when created, the directory is left pretty raw." }, { "code": null, "e": 11338, "s": 11048, "text": "[root@centosLocal ~]# ls -ld /var/www/students/ \ndrwxr-xr-x. 4 root root 40 Jan 9 22:03 /var/www/students/\n\n[root@centosLocal ~]# ls -l /var/www/students/ \ntotal 0 \ndrwxr-xr-x. 2 root root 6 Jan 9 22:03 assignments \ndrwxr-xr-x. 2 root root 6 Jan 9 22:03 uploads \n\n[root@centosLocal ~]#\n" }, { "code": null, "e": 11595, "s": 11338, "text": "As Administrators we never want to give our root credentials out to anyone. But at the same time, we need to allow users the ability to do their job. So let's allow Dr. Terry Thomas to take more control of the file structure and limit what students can do." }, { "code": null, "e": 11990, "s": 11595, "text": "[root@centosLocal ~]# chown -R drterryt:professors /var/www/students/ \n[root@centosLocal ~]# ls -ld /var/www/students/ \ndrwxr-xr-x. 4 drterryt professors 40 Jan 9 22:03 /var/www/students/\n\n[root@centosLocal ~]# ls -ls /var/www/students/ \ntotal 0 \n0 drwxr-xr-x. 2 drterryt professors 6 Jan 9 22:03 assignments \n0 drwxr-xr-x. 2 drterryt professors 6 Jan 9 22:03 uploads\n\n[root@centosLocal ~]#\n" }, { "code": null, "e": 12240, "s": 11990, "text": "Now, each directory and subdirectory has an owner of drterryt and the owning group is professors. Since the assignments directory is for students to turn assigned work in, let's take away the ability to list and modify files from the students group." }, { "code": null, "e": 12538, "s": 12240, "text": "[root@centosLocal ~]# chgrp students /var/www/students/assignments/ && chmod \n736 /var/www/students/assignments/\n\n[root@centosLocal assignments]# ls -ld /var/www/students/assignments/ \ndrwx-wxrw-. 2 drterryt students 44 Jan 9 23:14 /var/www/students/assignments/\n\n[root@centosLocal assignments]#\n" }, { "code": null, "e": 12863, "s": 12538, "text": "Students can copy assignments to the assignments directory. But they cannot list contents of the directory, copy over current files, or modify files in the assignments directory. Thus, it just allows the students to submit completed assignments. The CentOS filesystem will provide a date-stamp of when assignments turned in." }, { "code": null, "e": 12900, "s": 12863, "text": "As the assignments directory owner −" }, { "code": null, "e": 13345, "s": 12900, "text": "[drterryt@centosLocal assignments]$ whoami \ndrterryt\n\n[drterryt@centosLocal assignments]$ ls -ld /var/www/students/assignment \ndrwx-wxrw-. 2 drterryt students 44 Jan 9 23:14 /var/www/students/assignments/\n\n[drterryt@centosLocal assignments]$ ls -l /var/www/students/assignments/ \ntotal 4 \n-rw-r--r--. 1 adama students 0 Jan 9 23:14 myassign.txt \n-rw-r--r--. 1 tammyr students 16 Jan 9 23:18 terryt.txt\n\n[drterryt@centosLocal assignments]$\n" }, { "code": null, "e": 13428, "s": 13345, "text": "We can see, the directory owner can list files as well as modify and remove files." }, { "code": null, "e": 13546, "s": 13428, "text": "umask is an important command that supplies the default modes for File and Directory Permissions as they are created." }, { "code": null, "e": 13590, "s": 13546, "text": "umask permissions use unary, negated logic." }, { "code": null, "e": 13868, "s": 13590, "text": "[adama@centosLocal umask_tests]$ ls -l ./ \n-rw-r--r--. 1 adama students 0 Jan 10 00:27 myDir \n-rw-r--r--. 1 adama students 0 Jan 10 00:27 myFile.txt\n\n[adama@centosLocal umask_tests]$ whoami \nadama\n\n[adama@centosLocal umask_tests]$ umask \n0022\n\n[adama@centosLocal umask_tests]$\n" }, { "code": null, "e": 13953, "s": 13868, "text": "Now, let’s change the umask for our current user, and make a new file and directory." }, { "code": null, "e": 14369, "s": 13953, "text": "[adama@centosLocal umask_tests]$ umask 077\n\n[adama@centosLocal umask_tests]$ touch mynewfile.txt\n\n[adama@centosLocal umask_tests]$ mkdir myNewDir\n\n[adama@centosLocal umask_tests]$ ls -l \ntotal 0 \n-rw-r--r--. 1 adama students 0 Jan 10 00:27 myDir \n-rw-r--r--. 1 adama students 0 Jan 10 00:27 myFile.txt \ndrwx------. 2 adama students 6 Jan 10 00:35 myNewDir \n-rw-------. 1 adama students 0 Jan 10 00:35 mynewfile.txt\n" }, { "code": null, "e": 14447, "s": 14369, "text": "As we can see, newly created files are a little more restrictive than before." }, { "code": null, "e": 14498, "s": 14447, "text": "umask for users must should be changed in either −" }, { "code": null, "e": 14511, "s": 14498, "text": "/etc/profile" }, { "code": null, "e": 14520, "s": 14511, "text": "~/bashrc" }, { "code": null, "e": 14627, "s": 14520, "text": "[root@centosLocal centos]# su adama \n[adama@centosLocal centos]$ umask \n0022 \n[adama@centosLocal centos]$\n" }, { "code": null, "e": 14830, "s": 14627, "text": "Generally, the default umask in CentOS will be okay. When we run into trouble with a default of 0022, is usually when different departments belonging to different groups need to collaborate on projects." }, { "code": null, "e": 14958, "s": 14830, "text": "This is where the role of a system administrator comes in, to balance the operations and design of the CentOS operating system." }, { "code": null, "e": 15037, "s": 14958, "text": "When discussing user management, we have three important terms to understand −" }, { "code": null, "e": 15043, "s": 15037, "text": "Users" }, { "code": null, "e": 15050, "s": 15043, "text": "Groups" }, { "code": null, "e": 15062, "s": 15050, "text": "Permissions" }, { "code": null, "e": 15197, "s": 15062, "text": "We have already discussed in-depth permissions as applied to files and folders. In this chapter, let's discuss about users and groups." }, { "code": null, "e": 15239, "s": 15197, "text": "In CentOS, there are two types accounts −" }, { "code": null, "e": 15303, "s": 15239, "text": "System accounts − Used for a daemon or other piece of software." }, { "code": null, "e": 15367, "s": 15303, "text": "System accounts − Used for a daemon or other piece of software." }, { "code": null, "e": 15449, "s": 15367, "text": "Interactive accounts − Usually assigned to a user for accessing system resources." }, { "code": null, "e": 15531, "s": 15449, "text": "Interactive accounts − Usually assigned to a user for accessing system resources." }, { "code": null, "e": 15583, "s": 15531, "text": "The main difference between the two user types is −" }, { "code": null, "e": 15745, "s": 15583, "text": "System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login." }, { "code": null, "e": 15907, "s": 15745, "text": "System accounts are used by daemons to access files and directories. These will usually be disallowed from interactive login via shell or physical console login." }, { "code": null, "e": 16027, "s": 15907, "text": "Interactive accounts are used by end-users to access computing resources from either a shell or physical console login." }, { "code": null, "e": 16147, "s": 16027, "text": "Interactive accounts are used by end-users to access computing resources from either a shell or physical console login." }, { "code": null, "e": 16305, "s": 16147, "text": "With this basic understanding of users, let's now create a new user for Bob Jones in the Accounting Department. A new user is added with the adduser command." }, { "code": null, "e": 16350, "s": 16305, "text": "Following are some adduser common switches −" }, { "code": null, "e": 16421, "s": 16350, "text": "When creating a new user, use the -c, -m, -g, -n switches as follows −" }, { "code": null, "e": 16526, "s": 16421, "text": "[root@localhost Downloads]# useradd -c \"Bob Jones Accounting Dept Manager\" \n-m -g accounting -n bjones\n" }, { "code": null, "e": 16575, "s": 16526, "text": "Now let's see if our new user has been created −" }, { "code": null, "e": 16833, "s": 16575, "text": "[root@localhost Downloads]# id bjones \n(bjones) gid = 1001(accounting) groups = 1001(accounting)\n\n[root@localhost Downloads]# grep bjones /etc/passwd \nbjones:x:1001:1001:Bob Jones Accounting Dept Manager:/home/bjones:/bin/bash\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 16898, "s": 16833, "text": "Now we need to enable the new account using the passwd command −" }, { "code": null, "e": 17102, "s": 16898, "text": "[root@localhost Downloads]# passwd bjones \nChanging password for user bjones. \nNew password: \nRetype new password: \npasswd: all authentication tokens updated successfully.\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 17176, "s": 17102, "text": "The user account is not enabled allowing the user to log into the system." }, { "code": null, "e": 17494, "s": 17176, "text": "There are several methods to disable accounts on a system. These range from editing the /etc/passwd file by hand. Or even using the passwd command with the -lswitch. Both of these methods have one big drawback: if the user has ssh access and uses an RSA key for authentication, they can still login using this method." }, { "code": null, "e": 17658, "s": 17494, "text": "Now let’s use the chage command, changing the password expiry date to a previous date. Also, it may be good to make a note on the account as to why we disabled it." }, { "code": null, "e": 18016, "s": 17658, "text": "[root@localhost Downloads]# chage -E 2005-10-01 bjones\n \n[root@localhost Downloads]# usermod -c \"Disabled Account while Bob out of the country \nfor five months\" bjones\n\n[root@localhost Downloads]# grep bjones /etc/passwd \nbjones:x:1001:1001:Disabled Account while Bob out of the country for four \nmonths:/home/bjones:/bin/bash\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 18311, "s": 18016, "text": "Managing groups in Linux makes it convenient for an administrator to combine the users within containers applying permission-sets applicable to all group members. For example, all users in Accounting may need access to the same files. Thus, we make an accounting group, adding Accounting users." }, { "code": null, "e": 18795, "s": 18311, "text": "For the most part, anything requiring special permissions should be done in a group. This approach will usually save time over applying special permissions to just one user. Example, Sally is in-charge of reports and only Sally needs access to certain files for reporting. However, what if Sally is sick one day and Bob does reports? Or the need for reporting grows? When a group is made, an Administrator only needs to do it once. The add users is applied as needs change or expand." }, { "code": null, "e": 18857, "s": 18795, "text": "Following are some common commands used for managing groups −" }, { "code": null, "e": 18863, "s": 18857, "text": "chgrp" }, { "code": null, "e": 18872, "s": 18863, "text": "groupadd" }, { "code": null, "e": 18879, "s": 18872, "text": "groups" }, { "code": null, "e": 18887, "s": 18879, "text": "usermod" }, { "code": null, "e": 18948, "s": 18887, "text": "chgrp − Changes the group ownership for a file or directory." }, { "code": null, "e": 19055, "s": 18948, "text": "Let's make a directory for people in the accounting group to store files and create directories for files." }, { "code": null, "e": 19245, "s": 19055, "text": "[root@localhost Downloads]# mkdir /home/accounting\n\n[root@localhost Downloads]# ls -ld /home/accounting\ndrwxr-xr-x. 2 root root 6 Jan 13 10:18 /home/accounting\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 19303, "s": 19245, "text": "Next, let's give group ownership to the accounting group." }, { "code": null, "e": 19580, "s": 19303, "text": "[root@localhost Downloads]# chgrp -v accounting /home/accounting/ \nchanged group of ‘/home/accounting/’ from root to accounting\n\n[root@localhost Downloads]# ls -ld /home/accounting/ \ndrwxr-xr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 19714, "s": 19580, "text": "Now, everyone in the accounting group has read and execute permissions to /home/accounting. They will need write permissions as well." }, { "code": null, "e": 19918, "s": 19714, "text": "[root@localhost Downloads]# chmod g+w /home/accounting/\n\n[root@localhost Downloads]# ls -ld /home/accounting/ \ndrwxrwxr-x. 2 root accounting 6 Jan 13 10:18 /home/accounting/\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 20046, "s": 19918, "text": "Since the accounting group may deal with sensitive documents, we need to apply some restrictive permissions for other or world." }, { "code": null, "e": 20251, "s": 20046, "text": "[root@localhost Downloads]# chmod o-rx /home/accounting/\n\n[root@localhost Downloads]# ls -ld /home/accounting/ \ndrwxrwx---. 2 root accounting 6 Jan 13 10:18 /home/accounting/\n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 20288, "s": 20251, "text": "groupadd − Used to make a new group." }, { "code": null, "e": 20423, "s": 20288, "text": "Let's make a new group called secret. We will add a password to the group, allowing the users to add themselves with a known password." }, { "code": null, "e": 20721, "s": 20423, "text": "[root@localhost]# groupadd secret\n\n[root@localhost]# gpasswd secret \nChanging the password for group secret \nNew Password: \nRe-enter new password:\n\n[root@localhost]# exit \nexit\n\n[centos@localhost ~]$ newgrp secret \nPassword:\n\n[centos@localhost ~]$ groups \nsecret wheel rdc\n\n[centos@localhost ~]$\n" }, { "code": null, "e": 20881, "s": 20721, "text": "In practice, passwords for groups are not used often. Secondary groups are adequate and sharing passwords amongst other users is not a great security practice." }, { "code": null, "e": 21012, "s": 20881, "text": "The groups command is used to show which group a user belongs to. We will use this, after making some changes to our current user." }, { "code": null, "e": 21058, "s": 21012, "text": "usermod is used to update account attributes." }, { "code": null, "e": 21101, "s": 21058, "text": "Following are the common usermod switches." }, { "code": null, "e": 21312, "s": 21101, "text": "[root@localhost]# groups centos \ncentos : accounting secret\n\n[root@localhost]#\n\n[root@localhost]# usermod -a -G wheel centos\n\n[root@localhost]# groups centos\ncentos : accounting wheel secret\n\n[root@localhost]#\n" }, { "code": null, "e": 21594, "s": 21312, "text": "CentOS disk quotas can be enabled both; alerting the system administrator and denying further disk-storage-access to a user before disk capacity is exceeded. When a disk is full, depending on what resides on the disk, an entire system can come to a screeching halt until recovered." }, { "code": null, "e": 21668, "s": 21594, "text": "Enabling Quota Management in CentOS Linux is basically a 4 step process −" }, { "code": null, "e": 21737, "s": 21668, "text": "Step 1 − Enable quota management for groups and users in /etc/fstab." }, { "code": null, "e": 21806, "s": 21737, "text": "Step 1 − Enable quota management for groups and users in /etc/fstab." }, { "code": null, "e": 21839, "s": 21806, "text": "Step 2 − Remount the filesystem." }, { "code": null, "e": 21872, "s": 21839, "text": "Step 2 − Remount the filesystem." }, { "code": null, "e": 21934, "s": 21872, "text": "Step 3 − Create Quota database and generate disk usage table." }, { "code": null, "e": 21996, "s": 21934, "text": "Step 3 − Create Quota database and generate disk usage table." }, { "code": null, "e": 22028, "s": 21996, "text": "Step 4 − Assign quota policies." }, { "code": null, "e": 22060, "s": 22028, "text": "Step 4 − Assign quota policies." }, { "code": null, "e": 22108, "s": 22060, "text": "First, we want to backup our /etc/fstab filen −" }, { "code": null, "e": 22156, "s": 22108, "text": "[root@centosLocal centos]# cp -r /etc/fstab ./\n" }, { "code": null, "e": 22241, "s": 22156, "text": "We now have a copy of our known working /etc/fstab in the current working directory." }, { "code": null, "e": 22784, "s": 22241, "text": "# \n# /etc/fstab \n# Created by anaconda on Sat Dec 17 02:44:51 2016 \n# \n# Accessible filesystems, by reference, are maintained under '/dev/disk' \n# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info\n# \n/dev/mapper/cl-root / xfs defaults 0 0\nUUID = 4b9a40bc-9480-4 /boot xfs defaults 0 0\n\n/dev/mapper/cl-home /home xfs defaults,usrquota,grpquota 0 0\n\n/dev/mapper/cl-swap swap swap defaults 0 0\n" }, { "code": null, "e": 22931, "s": 22784, "text": "We made the following changes in the options section of /etc/fstab for the volume or Label to where quotas are to be applied for users and groups." }, { "code": null, "e": 22940, "s": 22931, "text": "usrquota" }, { "code": null, "e": 22949, "s": 22940, "text": "grpquota" }, { "code": null, "e": 23221, "s": 22949, "text": "As you can see, we are using the xfs filesystem. When using xfs there are extra manual steps involved. /home is on the same disk as /. Further investigation shows / is set for noquota, which is a kernel level mounting option. We must re-configure our kernel boot options." }, { "code": null, "e": 23365, "s": 23221, "text": "root@localhost rdc]# mount | grep ' / ' \n/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 23416, "s": 23365, "text": "This step is only necessary under two conditions −" }, { "code": null, "e": 23496, "s": 23416, "text": "When the disk/partition we are enabling quotas on, is using the xfs file system" }, { "code": null, "e": 23568, "s": 23496, "text": "When the kernel is passing noquota parameter to /etc/fstab at boot time" }, { "code": null, "e": 23613, "s": 23568, "text": "Step 1 − Make a backup of /etc/default/grub." }, { "code": null, "e": 23638, "s": 23613, "text": "cp /etc/default/grub ~/\n" }, { "code": null, "e": 23673, "s": 23638, "text": "Step 2 − Modify /etc/default/grub." }, { "code": null, "e": 23699, "s": 23673, "text": "Here is the default file." }, { "code": null, "e": 23977, "s": 23699, "text": "GRUB_TIMEOUT=5 \nGRUB_DISTRIBUTOR=\"$(sed 's, release .*$,,g' /etc/system-release)\" \nGRUB_DEFAULT=saved \nGRUB_DISABLE_SUBMENU=true \nGRUB_TERMINAL_OUTPUT=\"console\" \nGRUB_CMDLINE_LINUX=\"crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet\" \nGRUB_DISABLE_RECOVERY=\"true\"\n" }, { "code": null, "e": 24016, "s": 23977, "text": "We want to modify the following line −" }, { "code": null, "e": 24103, "s": 24016, "text": "GRUB_CMDLINE_LINUX=\"crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv=cl/swap rhgb quiet\" \n" }, { "code": null, "e": 24106, "s": 24103, "text": "to" }, { "code": null, "e": 24222, "s": 24106, "text": "GRUB_CMDLINE_LINUX=\"crashkernel=auto rd.lvm.lv=cl/root rd.lvm.lv \n=cl/swap rhgb quiet rootflags=usrquota,grpquota\"\n" }, { "code": null, "e": 24449, "s": 24222, "text": "Note − It is important we copy these changes verbatim. After we reconfigure grub.cfg, our system will fail to boot if any errors were made in the configuration. Please, try this part of the tutorial on a non-production system." }, { "code": null, "e": 24487, "s": 24449, "text": "Step 3 − Backup your working grub.cfg" }, { "code": null, "e": 24537, "s": 24487, "text": "cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak\n" }, { "code": null, "e": 24557, "s": 24537, "text": "Make a new grub.cfg" }, { "code": null, "e": 24965, "s": 24557, "text": "[root@localhost rdc]# grub2-mkconfig -o /boot/grub2/grub.cfg \nGenerating grub configuration file ... \nFound linux image: /boot/vmlinuz-3.10.0-514.el7.x86_64 \nFound initrd image: /boot/initramfs-3.10.0-514.el7.x86_64.img \nFound linux image: /boot/vmlinuz-0-rescue-dbba7fa47f73457b96628ba8f3959bfd \nFound initrd image: /boot/initramfs-0-rescuedbba7fa47f73457b96628ba8f3959bfd.img \ndone\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 24972, "s": 24965, "text": "Reboot" }, { "code": null, "e": 25001, "s": 24972, "text": "[root@localhost rdc]#reboot\n" }, { "code": null, "e": 25110, "s": 25001, "text": "If all modifications were precise, we should not have the availability to add quotas to the xfs file system." }, { "code": null, "e": 25260, "s": 25110, "text": "[rdc@localhost ~]$ mount | grep ' / ' \n/dev/mapper/cl-root on / type xfs (rw,relatime,seclabel,attr2,inode64,usrquota,grpquota)\n \n[rdc@localhost ~]$\n" }, { "code": null, "e": 25322, "s": 25260, "text": "We have passed the usrquota and grpquota parameters via grub." }, { "code": null, "e": 25400, "s": 25322, "text": "Now, again edit /etc/fstab to include / since /homeon the same physical disk." }, { "code": null, "e": 25463, "s": 25400, "text": "/dev/mapper/cl-root/xfs\ndefaults,usrquota,grpquota 0 0\n" }, { "code": null, "e": 25501, "s": 25463, "text": "Now let's enable the quota databases." }, { "code": null, "e": 25544, "s": 25501, "text": "[root@localhost rdc]# quotacheck -acfvugM\n" }, { "code": null, "e": 25574, "s": 25544, "text": "Make sure Quotas are enabled." }, { "code": null, "e": 25822, "s": 25574, "text": "[root@localhost rdc]# quotaon -ap \ngroup quota on / (/dev/mapper/cl-root) is on \nuser quota on / (/dev/mapper/cl-root) is on \ngroup quota on /home (/dev/mapper/cl-home) is on \nuser quota on /home (/dev/mapper/cl-home) is on \n[root@localhost rdc]#\n" }, { "code": null, "e": 26140, "s": 25822, "text": "If the partition or disk is separate from the actively booted partition, we can remount without rebooting. If the quota was configured on a disk/partition booted in the root directory /, we may need to reboot the operating system. Forcing the remount and applying changes, the need to remount the filesystem may vary." }, { "code": null, "e": 27010, "s": 26140, "text": "[rdc@localhost ~]$ df \nFilesystem 1K-blocks Used Available Use% Mounted on\n/dev/mapper/cl-root 22447404 4081860 18365544 19% /\ndevtmpfs 903448 0 903448 0% /dev\ntmpfs 919308 100 919208 1% /dev/shm\ntmpfs 919308 9180 910128 1% /run\ntmpfs 919308 0 919308 0% /sys/fs/cgroup\n/dev/sda2 1268736 176612 1092124 14% /boot\n/dev/mapper/cl-var 4872192 158024 4714168 4% /var\n/dev/mapper/cl-home 18475008 37284 18437724 1% /home\ntmpfs 183864 8 183856 1% /run/user/1000\n\n[rdc@localhost ~]$\n" }, { "code": null, "e": 27177, "s": 27010, "text": "As we can see, LVM volumes are in use. So it's simple to just reboot. This will remount /home and load the /etc/fstab configuration changes into active configuration." }, { "code": null, "e": 27302, "s": 27177, "text": "CentOS is now capable of working with disk quotas on /home. To enable full quota supprt, we must run the quotacheck command." }, { "code": null, "e": 27337, "s": 27302, "text": "quotacheck will create two files −" }, { "code": null, "e": 27349, "s": 27337, "text": "aquota.user" }, { "code": null, "e": 27362, "s": 27349, "text": "aquota.group" }, { "code": null, "e": 27444, "s": 27362, "text": "These are used to store quota information for the quota enabled disks/partitions." }, { "code": null, "e": 27490, "s": 27444, "text": "Following are the common quotacheck switches." }, { "code": null, "e": 27560, "s": 27490, "text": "For this, we will use the edquota command, followed by the username −" }, { "code": null, "e": 27905, "s": 27560, "text": "[root@localhost rdc]# edquota centos\n\nDisk quotas for user centos (uid 1000): \nFilesystem blocks soft hard inodes soft hard \n/dev/mapper/cl-root 12 0 0 13 0 0 \n/dev/mapper/cl-home 4084 0 0 140 0 0\n" }, { "code": null, "e": 27932, "s": 27905, "text": "Let's look at each column." }, { "code": null, "e": 27997, "s": 27932, "text": "Filesystem − It is the filesystem quotas for the user applied to" }, { "code": null, "e": 28062, "s": 27997, "text": "Filesystem − It is the filesystem quotas for the user applied to" }, { "code": null, "e": 28134, "s": 28062, "text": "blocks − How many blocks the user is currently using on each filesystem" }, { "code": null, "e": 28206, "s": 28134, "text": "blocks − How many blocks the user is currently using on each filesystem" }, { "code": null, "e": 28308, "s": 28206, "text": "soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period" }, { "code": null, "e": 28410, "s": 28308, "text": "soft − Set blocks for a soft limit. Soft limit allows the user to carry quota for a given time period" }, { "code": null, "e": 28482, "s": 28410, "text": "hard − Set blocks for a hard limit. Hard limit is total allowable quota" }, { "code": null, "e": 28554, "s": 28482, "text": "hard − Set blocks for a hard limit. Hard limit is total allowable quota" }, { "code": null, "e": 28607, "s": 28554, "text": "inodes − How many inodes the user is currently using" }, { "code": null, "e": 28660, "s": 28607, "text": "inodes − How many inodes the user is currently using" }, { "code": null, "e": 28684, "s": 28660, "text": "soft − Soft inode limit" }, { "code": null, "e": 28708, "s": 28684, "text": "soft − Soft inode limit" }, { "code": null, "e": 28733, "s": 28708, "text": "hard − Hard inode limit" }, { "code": null, "e": 28758, "s": 28733, "text": "hard − Hard inode limit" }, { "code": null, "e": 28797, "s": 28758, "text": "To check our current quota as a user −" }, { "code": null, "e": 29066, "s": 28797, "text": "[centos@localhost ~]$ quota \nDisk quotas for user centos (uid 1000): \nFilesystem blocks quota limit grace files quota limit grace \n/dev/mapper/cl-home 6052604 56123456 61234568 475 0 0 [centos@localhost ~]$\n" }, { "code": null, "e": 29144, "s": 29066, "text": "Following is an error given to a user when the hard quota limit has exceeded." }, { "code": null, "e": 29364, "s": 29144, "text": "[centos@localhost Downloads]$ cp CentOS-7-x86_64-LiveKDE-1611.iso.part ../Desktop/\n\ncp: cannot create regular file ‘../Desktop/CentOS-7-x86_64-LiveKDE-\n1611.iso.part’: Disk quota exceeded\n\n[centos@localhost Downloads]$\n" }, { "code": null, "e": 29673, "s": 29364, "text": "As we can see, we are closely within this user's disk quota. Let's set a soft limit warning. This way, the user will have advance notice before quota limits expire. From experience, you will get end-user complaints when they come into work and need to spend 45 minutes clearing files to actually get to work." }, { "code": null, "e": 29746, "s": 29673, "text": "As an Administrator, we can check quota usage with the repquota command." }, { "code": null, "e": 30250, "s": 29746, "text": "[root@localhost Downloads]# repquota /home \n Block limits File limits \nUser used soft hard grace used soft hard grace \n----------------------------------------------------------------------------------------\nroot -- 0 0 0 3 0 0 \ncentos -+ 6189824 56123456 61234568 541 520 540 6days \n\n[root@localhost Downloads]#\n" }, { "code": null, "e": 30369, "s": 30250, "text": "As we can see, the user centos has exceeded their hard block quota and can no longer use any more disk space on /home." }, { "code": null, "e": 30429, "s": 30369, "text": "-+denotes a hard quota has been exceeded on the filesystem." }, { "code": null, "e": 30666, "s": 30429, "text": "When planning quotas, it is necessary to do a little math. What an Administrator needs to know is:How many users are on the system? How much free space to allocate amongst users/groups? How many bytes make up a block on the file system?" }, { "code": null, "e": 30965, "s": 30666, "text": "Define quotas in terms of blocks as related to free disk-space.It is recommended to leave a \"safe\" buffer of free-space on the file system that will remain in worst case scenario: all quotas are simultaneously exceeded. This is especially on a partition that is used by the system for writing logs." }, { "code": null, "e": 31189, "s": 30965, "text": "systemd is the new way of running services on Linux. systemd has a superceded sysvinit. systemd brings faster boot-times to Linux and is now, a standard way to manage Linux services. While stable, systemd is still evolving." }, { "code": null, "e": 31413, "s": 31189, "text": "systemd as an init system, is used to manage both services and daemons that need status changes after the Linux kernel has been booted. By status change starting, stopping, reloading, and adjusting service state is applied." }, { "code": null, "e": 31488, "s": 31413, "text": "First, let's check the version of systemd currently running on our server." }, { "code": null, "e": 31714, "s": 31488, "text": "[centos@localhost ~]$ systemctl --version \nsystemd 219 \n+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP \n+GCRYPT +GNUTLS +ACL +XZ -LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN\n\n[centos@localhost ~]$\n" }, { "code": null, "e": 31831, "s": 31714, "text": "As of CentOS version 7, fully updated at the time of this writing systemd version 219 is the current stable version." }, { "code": null, "e": 31898, "s": 31831, "text": "We can also analyze the last server boot time with systemd-analyze" }, { "code": null, "e": 32049, "s": 31898, "text": "[centos@localhost ~]$ systemd-analyze \nStartup finished in 1.580s (kernel) + 908ms (initrd) + 53.225s (userspace) = 55.713s \n[centos@localhost ~]$\n" }, { "code": null, "e": 32134, "s": 32049, "text": "When the system boot times are slower, we can use the systemd-analyze blame command." }, { "code": null, "e": 32668, "s": 32134, "text": "[centos@localhost ~]$ systemd-analyze blame \n 40.882s kdump.service \n 5.775s NetworkManager-wait-online.service \n 4.701s plymouth-quit-wait.service \n 3.586s postfix.service \n 3.121s systemd-udev-settle.service \n 2.649s tuned.service \n 1.848s libvirtd.service \n 1.437s network.service \n 875ms packagekit.service \n 855ms gdm.service \n 514ms firewalld.service \n 438ms rsyslog.service\n 436ms udisks2.service \n 398ms sshd.service \n 360ms boot.mount \n 336ms polkit.service \n 321ms accounts-daemon.service\n" }, { "code": null, "e": 32852, "s": 32668, "text": "When working with systemd, it is important to understand the concept of units. Units are the resources systemd knows how to interpret. Units are categorized into 12 types as follows −" }, { "code": null, "e": 32861, "s": 32852, "text": ".service" }, { "code": null, "e": 32869, "s": 32861, "text": ".socket" }, { "code": null, "e": 32877, "s": 32869, "text": ".device" }, { "code": null, "e": 32884, "s": 32877, "text": ".mount" }, { "code": null, "e": 32895, "s": 32884, "text": ".automount" }, { "code": null, "e": 32901, "s": 32895, "text": ".swap" }, { "code": null, "e": 32909, "s": 32901, "text": ".target" }, { "code": null, "e": 32915, "s": 32909, "text": ".path" }, { "code": null, "e": 32922, "s": 32915, "text": ".timer" }, { "code": null, "e": 32932, "s": 32922, "text": ".snapshot" }, { "code": null, "e": 32939, "s": 32932, "text": ".slice" }, { "code": null, "e": 32946, "s": 32939, "text": ".scope" }, { "code": null, "e": 33153, "s": 32946, "text": "For the most part, we will be working with .service as unit targets. It is recommended to do further research on the other types. As only .service units will apply to starting and stopping systemd services." }, { "code": null, "e": 33204, "s": 33153, "text": "Each unit is defined in a file located in either −" }, { "code": null, "e": 33242, "s": 33204, "text": "/lib/systemd/system − base unit files" }, { "code": null, "e": 33280, "s": 33242, "text": "/lib/systemd/system − base unit files" }, { "code": null, "e": 33342, "s": 33280, "text": "/etc/systemd/system − modified unit files started at run-time" }, { "code": null, "e": 33404, "s": 33342, "text": "/etc/systemd/system − modified unit files started at run-time" }, { "code": null, "e": 33555, "s": 33404, "text": "To work with systemd, we will need to get very familiar with the systemctl command. Following are the most common command line switches for systemctl." }, { "code": null, "e": 33627, "s": 33555, "text": "systemctl [operation]\nexample: systemctl --state [servicename.service]\n" }, { "code": null, "e": 33684, "s": 33627, "text": "For a quick look at all the services running on our box." }, { "code": null, "e": 34787, "s": 33684, "text": "[root@localhost rdc]# systemctl -t service \nUNIT LOAD ACTIVE SUB DESCRIPTION\n\nabrt-ccpp.service loaded active exited Install ABRT coredump hook \nabrt-oops.service loaded active running ABRT kernel log watcher \nabrt-xorg.service loaded active running ABRT Xorg log watcher \nabrtd.service loaded active running ABRT Automated Bug Reporting Tool \naccounts-daemon.service loaded active running Accounts Service \nalsa-state.service loaded active running Manage Sound Card State (restore and store) \natd.service loaded active running Job spooling tools \nauditd.service loaded active running Security Auditing Service \navahi-daemon.service loaded active running Avahi mDNS/DNS-SD Stack \nblk-availability.service loaded active exited Availability of block devices \nbluetooth.service loaded active running Bluetooth service \nchronyd.service loaded active running NTP client/server\n" }, { "code": null, "e": 34828, "s": 34787, "text": "Let's first, stop the bluetooth service." }, { "code": null, "e": 35025, "s": 34828, "text": "[root@localhost]# systemctl stop bluetooth\n\n[root@localhost]# systemctl --all -t service | grep bluetooth \nbluetooth.service loaded inactive dead Bluetooth service\n\n[root@localhost]#\n" }, { "code": null, "e": 35079, "s": 35025, "text": "As we can see, the bluetooth service is now inactive." }, { "code": null, "e": 35117, "s": 35079, "text": "To start the bluetooth service again." }, { "code": null, "e": 35313, "s": 35117, "text": "[root@localhost]# systemctl start bluetooth\n\n[root@localhost]# systemctl --all -t service | grep bluetooth \nbluetooth.service loaded active running Bluetooth service\n\n[root@localhost]#\n" }, { "code": null, "e": 35586, "s": 35313, "text": "Note − We didn't specify bluetooth.service, since the .service is implied. It is a good practice to think of the unit type appending the service we are dealing with. So, from here on, we will use the .service extension to clarify we are working on service unit operations." }, { "code": null, "e": 35647, "s": 35586, "text": "The primary actions that can be performed on a service are −" }, { "code": null, "e": 35713, "s": 35647, "text": "The above actions are primarily used in the following scenarios −" }, { "code": null, "e": 35748, "s": 35713, "text": "To check the status of a service −" }, { "code": null, "e": 36372, "s": 35748, "text": "[root@localhost]# systemctl status network.service \nnetwork.service - LSB: Bring up/down networking \nLoaded: loaded (/etc/rc.d/init.d/network; bad; vendor preset: disabled) \nActive: active (exited) since Sat 2017-01-14 04:43:48 EST; 1min 31s ago \nDocs: man:systemd-sysv-generator(8)\n\nProcess: 923 ExecStart = /etc/rc.d/init.d/network start (code=exited, status = 0/SUCCESS)\n\nlocalhost.localdomain systemd[1]: Starting LSB: Bring up/down networking... \nlocalhost.localdomain network[923]: Bringing up loopback interface: [ OK ] \nlocalhost.localdomain systemd[1]: Started LSB: Bring up/down networking.\n\n[root@localhost]#\n" }, { "code": null, "e": 36497, "s": 36372, "text": "Show us the current status of the networking service. If we want to see all the services related to networking, we can use −" }, { "code": null, "e": 37008, "s": 36497, "text": "[root@localhost]# systemctl --all -t service | grep -i network \nnetwork.service loaded active exited LSB: Bring up/ \nNetworkManager-wait-online.service loaded active exited Network Manager \nNetworkManager.service loaded active running Network Manager \nntpd.service loaded inactive dead Network Time \nrhel-import-state.service loaded active exited Import network \n\n[root@localhost]#\n" }, { "code": null, "e": 37195, "s": 37008, "text": "For those familiar with the sysinit method of managing services, it is important to make the transition to systemd. systemd is the new way starting and stopping daemon services in Linux." }, { "code": null, "e": 37363, "s": 37195, "text": "systemctl is the utility used to control systemd. systemctl provides CentOS administrators with the ability to perform a multitude of operations on systemd including −" }, { "code": null, "e": 37387, "s": 37363, "text": "Configure systemd units" }, { "code": null, "e": 37415, "s": 37387, "text": "Get status of systemd untis" }, { "code": null, "e": 37439, "s": 37415, "text": "Start and stop services" }, { "code": null, "e": 37491, "s": 37439, "text": "Enable / disable systemd services for runtime, etc." }, { "code": null, "e": 37680, "s": 37491, "text": "The command syntax for systemctl is pretty basic, but can tangle with switches and options. We will present the most essential functions of systemctl needed for administering CentOS Linux." }, { "code": null, "e": 37741, "s": 37680, "text": "Basic systemctl syntax: \nsystemctl [OPTIONS] COMMAND [NAME]\n" }, { "code": null, "e": 37797, "s": 37741, "text": "Following are the common commands used with systemctl −" }, { "code": null, "e": 37803, "s": 37797, "text": "start" }, { "code": null, "e": 37808, "s": 37803, "text": "stop" }, { "code": null, "e": 37816, "s": 37808, "text": "restart" }, { "code": null, "e": 37823, "s": 37816, "text": "reload" }, { "code": null, "e": 37830, "s": 37823, "text": "status" }, { "code": null, "e": 37840, "s": 37830, "text": "is-active" }, { "code": null, "e": 37851, "s": 37840, "text": "list-units" }, { "code": null, "e": 37858, "s": 37851, "text": "enable" }, { "code": null, "e": 37866, "s": 37858, "text": "disable" }, { "code": null, "e": 37870, "s": 37866, "text": "cat" }, { "code": null, "e": 37875, "s": 37870, "text": "show" }, { "code": null, "e": 38021, "s": 37875, "text": "We have already discussed start, stop, reload, restart, enable and disable with systemctl. So let's go over the remaining commonly used commands." }, { "code": null, "e": 38115, "s": 38021, "text": "In its most simple form, the status command can be used to see the system status as a whole −" }, { "code": null, "e": 38709, "s": 38115, "text": "[root@localhost rdc]# systemctl status \n ● localhost.localdomain \n State: running \n Jobs: 0 queued\n Failed: 0 units \n Since: Thu 2017-01-19 19:14:37 EST; 4h 5min ago \nCGroup: / \n ├─1 /usr/lib/systemd/systemd --switched-root --system --deserialize 21 \n ├─user.slice \n │ └─user-1002.slice \n │ └─session-1.scope \n │ ├─2869 gdm-session-worker [pam/gdm-password] \n │ ├─2881 /usr/bin/gnome-keyring-daemon --daemonize --login \n │ ├─2888 gnome-session --session gnome-classic \n │ ├─2895 dbus-launch --sh-syntax --exit-with-session\n" }, { "code": null, "e": 38836, "s": 38709, "text": "The above output has been condensed. In the real-world systemctl status will output about 100 lines of treed process statuses." }, { "code": null, "e": 38900, "s": 38836, "text": "Let's say we want to check the status of our firewall service −" }, { "code": null, "e": 39340, "s": 38900, "text": "[root@localhost rdc]# systemctl status firewalld \n● firewalld.service - firewalld - dynamic firewall daemon \nLoaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled) \nActive: active (running) since Thu 2017-01-19 19:14:55 EST; 4h 12min ago \n Docs: man:firewalld(1) \nMain PID: 825 (firewalld) \nCGroup: /system.slice/firewalld.service \n └─825 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid\n" }, { "code": null, "e": 39424, "s": 39340, "text": "As you see, our firewall service is currently active and has been for over 4 hours." }, { "code": null, "e": 39543, "s": 39424, "text": "The list-units command allows us to list all the units of a certain type. Let's check for sockets managed by systemd −" }, { "code": null, "e": 41059, "s": 39543, "text": "[root@localhost]# systemctl list-units --type=socket \nUNIT LOAD ACTIVE SUB DESCRIPTION \navahi-daemon.socket loaded active running Avahi mDNS/DNS-SD Stack Activation Socket \ncups.socket loaded active running CUPS Printing Service Sockets \ndbus.socket loaded active running D-Bus System Message Bus Socket \ndm-event.socket loaded active listening Device-mapper event daemon FIFOs \niscsid.socket loaded active listening Open-iSCSI iscsid Socket\niscsiuio.socket loaded active listening Open-iSCSI iscsiuio Socket \nlvm2-lvmetad.socket loaded active running LVM2 metadata daemon socket \nlvm2-lvmpolld.socket loaded active listening LVM2 poll daemon socket \nrpcbind.socket loaded active listening RPCbind Server Activation Socket \nsystemd-initctl.socket loaded active listening /dev/initctl Compatibility Named Pipe \nsystemd-journald.socket loaded active running Journal Socket \nsystemd-shutdownd.socket loaded active listening Delayed Shutdown Socket \nsystemd-udevd-control.socket loaded active running udev Control Socket \nsystemd-udevd-kernel.socket loaded active running udev Kernel Socket \nvirtlockd.socket loaded active listening Virtual machine lock manager socket \nvirtlogd.socket loaded active listening Virtual machine log manager socket\n" }, { "code": null, "e": 41106, "s": 41059, "text": "Now let’s check the current running services −" }, { "code": null, "e": 41885, "s": 41106, "text": "[root@localhost rdc]# systemctl list-units --type=service \nUNIT LOAD ACTIVE SUB DESCRIPTION \nabrt-ccpp.service loaded active exited Install ABRT coredump hook \nabrt-oops.service loaded active running ABRT kernel log watcher \nabrt-xorg.service loaded active running ABRT Xorg log watcher \nabrtd.service loaded active running ABRT Automated Bug Reporting Tool \naccounts-daemon.service loaded active running Accounts Service \nalsa-state.service loaded active running Manage Sound Card State (restore and store) \natd.service loaded active running Job spooling tools \nauditd.service loaded active running Security Auditing Service\n" }, { "code": null, "e": 41996, "s": 41885, "text": "The is-active command is an example of systemctl commands designed to return the status information of a unit." }, { "code": null, "e": 42059, "s": 41996, "text": "[root@localhost rdc]# systemctl is-active ksm.service \nactive\n" }, { "code": null, "e": 42196, "s": 42059, "text": "cat is one of the seldomly used command. Instead of using cat at the shell and typing the path to a unit file, simply use systemctl cat." }, { "code": null, "e": 43003, "s": 42196, "text": "[root@localhost]# systemctl cat firewalld \n# /usr/lib/systemd/system/firewalld.service\n[Unit] \nDescription=firewalld - dynamic firewall daemon \nBefore=network.target \nBefore=libvirtd.service \nBefore = NetworkManager.service \nAfter=dbus.service \nAfter=polkit.service \nConflicts=iptables.service ip6tables.service ebtables.service ipset.service \nDocumentation=man:firewalld(1)\n\n[Service] \nEnvironmentFile = -/etc/sysconfig/firewalld \nExecStart = /usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS \nExecReload = /bin/kill -HUP $MAINPID \n# supress to log debug and error output also to /var/log/messages \nStandardOutput = null \nStandardError = null\n\nType = dbus \nBusName = org.fedoraproject.FirewallD1\n\n[Install] \nWantedBy = basic.target \nAlias = dbus-org.fedoraproject.FirewallD1.service\n\n[root@localhost]#\n" }, { "code": null, "e": 43141, "s": 43003, "text": "Now that we have explored both systemd and systemctl in more detail, let's use them to manage the resources in cgroups or control groups." }, { "code": null, "e": 43299, "s": 43141, "text": "cgroups or Control Groups are a feature of the Linux kernel that allows an administrator to allocate or cap the system resources for services and also group." }, { "code": null, "e": 43376, "s": 43299, "text": "To list active control groups running, we can use the following ps command −" }, { "code": null, "e": 44297, "s": 43376, "text": "[root@localhost]# ps xawf -eo pid,user,cgroup,args \n8362 root - \\_ [kworker/1:2] \n1 root - /usr/lib/systemd/systemd --switched-\n root --system -- deserialize 21 \n507 root 7:cpuacct,cpu:/system.slice /usr/lib/systemd/systemd-journald \n527 root 7:cpuacct,cpu:/system.slice /usr/sbin/lvmetad -f \n540 root 7:cpuacct,cpu:/system.slice /usr/lib/systemd/systemd-udevd \n715 root 7:cpuacct,cpu:/system.slice /sbin/auditd -n \n731 root 7:cpuacct,cpu:/system.slice \\_ /sbin/audispd \n734 root 7:cpuacct,cpu:/system.slice \\_ /usr/sbin/sedispatch \n737 polkitd 7:cpuacct,cpu:/system.slice /usr/lib/polkit-1/polkitd --no-debug \n738 rtkit 6:memory:/system.slice/rtki /usr/libexec/rtkit-daemon \n740 dbus 7:cpuacct,cpu:/system.slice /bin/dbus-daemon --system --\n address=systemd: --nofork --nopidfile --systemd-activation\n" }, { "code": null, "e": 44554, "s": 44297, "text": "Resource Management, as of CentOS 6.X, has been redefined with the systemd init implementation. When thinking Resource Management for services, the main thing to focus on are cgroups. cgroups have advanced with systemd in both functionality and simplicity." }, { "code": null, "e": 44793, "s": 44554, "text": "The goal of cgroups in resource management is -no one service can take the system, as a whole, down. Or no single service process (perhaps a poorly written PHP script) will cripple the server functionality by consuming too many resources." }, { "code": null, "e": 44863, "s": 44793, "text": "cgroups allow resource control of units for the following resources −" }, { "code": null, "e": 44948, "s": 44863, "text": "CPU − Limit cpu intensive tasks that are not critical as other, less intensive tasks" }, { "code": null, "e": 45033, "s": 44948, "text": "CPU − Limit cpu intensive tasks that are not critical as other, less intensive tasks" }, { "code": null, "e": 45086, "s": 45033, "text": "Memory − Limit how much memory a service can consume" }, { "code": null, "e": 45139, "s": 45086, "text": "Memory − Limit how much memory a service can consume" }, { "code": null, "e": 45162, "s": 45139, "text": "Disks − Limit disk i/o" }, { "code": null, "e": 45185, "s": 45162, "text": "Disks − Limit disk i/o" }, { "code": null, "e": 45200, "s": 45185, "text": "**CPU Time: **" }, { "code": null, "e": 45271, "s": 45200, "text": "Tasks needing less CPU priority can have custom configured CPU Slices." }, { "code": null, "e": 45332, "s": 45271, "text": "Let's take a look at the following two services for example." }, { "code": null, "e": 45769, "s": 45332, "text": "[root@localhost]# systemctl cat polite.service \n# /etc/systemd/system/polite.service \n[Unit] \nDescription = Polite service limits CPU Slice and Memory \nAfter=remote-fs.target nss-lookup.target\n\n[Service] \nMemoryLimit = 1M \nExecStart = /usr/bin/sha1sum /dev/zero \nExecStop = /bin/kill -WINCH ${MAINPID} \nWantedBy=multi-user.target\n\n# /etc/systemd/system/polite.service.d/50-CPUShares.conf \n[Service] \nCPUShares = 1024 \n[root@localhost]#\n" }, { "code": null, "e": 46152, "s": 45769, "text": "[root@localhost]# systemctl cat evil.service \n# /etc/systemd/system/evil.service \n[Unit] \nDescription = I Eat You CPU \nAfter=remote-fs.target nss-lookup.target\n\n[Service] \nExecStart = /usr/bin/md5sum /dev/zero \nExecStop = /bin/kill -WINCH ${MAINPID} \nWantedBy=multi-user.target\n\n# /etc/systemd/system/evil.service.d/50-CPUShares.conf \n[Service] \nCPUShares = 1024 \n[root@localhost]#\n" }, { "code": null, "e": 46207, "s": 46152, "text": "Let's set Polite Service using a lesser CPU priority −" }, { "code": null, "e": 46394, "s": 46207, "text": "systemctl set-property polite.service CPUShares = 20 \n/system.slice/polite.service\n1 70.5 124.0K - - \n\n/system.slice/evil.service\n1 99.5 304.0K - -\n" }, { "code": null, "e": 46699, "s": 46394, "text": "As we can see, over a period of normal system idle time, both rogue processes are still using CPU cycles. However, the one set to have less time-slices is using less CPU time. With this in mind, we can see how using a lesser time time-slice would allow essential tasks better access the system resources." }, { "code": null, "e": 46793, "s": 46699, "text": "To set services for each resource, the set-property method defines the following parameters −" }, { "code": null, "e": 46838, "s": 46793, "text": "systemctl set-property name parameter=value\n" }, { "code": null, "e": 46921, "s": 46838, "text": "Most often services will be limited by CPU use, Memory limits and Read / Write IO." }, { "code": null, "e": 47002, "s": 46921, "text": "After changing each, it is necessary to reload systemd and restart the service −" }, { "code": null, "e": 47110, "s": 47002, "text": "systemctl set-property foo.service CPUShares = 250 \nsystemctl daemon-reload \nsystemctl restart foo.service\n" }, { "code": null, "e": 47204, "s": 47110, "text": "To make custom cgroups in CentOS Linux, we need to first install services and configure them." }, { "code": null, "e": 47259, "s": 47204, "text": "Step 1 − Install libcgroup (if not already installed)." }, { "code": null, "e": 47409, "s": 47259, "text": "[root@localhost]# yum install libcgroup \nPackage libcgroup-0.41-11.el7.x86_64 already installed and latest version \nNothing to do \n[root@localhost]#\n" }, { "code": null, "e": 47605, "s": 47409, "text": "As we can see, by default CentOS 7 has libcgroup installed with the everything installer. Using a minimal installer will require us to install the libcgroup utilities along with any dependencies." }, { "code": null, "e": 47653, "s": 47605, "text": "Step 2 − Start and enable the cgconfig service." }, { "code": null, "e": 48454, "s": 47653, "text": "[root@localhost]# systemctl enable cgconfig \nCreated symlink from /etc/systemd/system/sysinit.target.wants/cgconfig.service to /usr/lib/systemd/system/cgconfig.service. \n[root@localhost]# systemctl start cgconfig \n[root@localhost]# systemctl status cgconfig \n● cgconfig.service - Control Group configuration service \nLoaded: loaded (/usr/lib/systemd/system/cgconfig.service; enabled; vendor preset: disabled) \nActive: active (exited) since Mon 2017-01-23 02:51:42 EST; 1min 21s ago \nMain PID: 4692 (code=exited, status = 0/SUCCESS) \nMemory: 0B \nCGroup: /system.slice/cgconfig.service \n\nJan 23 02:51:42 localhost.localdomain systemd[1]: Starting Control Group configuration service... \nJan 23 02:51:42 localhost.localdomain systemd[1]: Started Control Group configuration service. \n[root@localhost]#\n" }, { "code": null, "e": 48584, "s": 48454, "text": "Following are the common commands used with Process Management–bg, fg, nohup, ps, pstree, top, kill, killall, free, uptime, nice." }, { "code": null, "e": 48617, "s": 48584, "text": "Quick Note: Process PID in Linux" }, { "code": null, "e": 48832, "s": 48617, "text": "In Linux every running process is given a PID or Process ID Number. This PID is how CentOS identifies a particular process. As we have discussed, systemd is the first process started and given a PID of 1 in CentOS." }, { "code": null, "e": 48889, "s": 48832, "text": "Pgrep is used to get Linux PID for a given process name." }, { "code": null, "e": 48938, "s": 48889, "text": "[root@CentOS]# pgrep systemd \n1 \n[root@CentOS]#\n" }, { "code": null, "e": 49001, "s": 48938, "text": "As seen, the pgrep command returns the current PID of systemd." }, { "code": null, "e": 49148, "s": 49001, "text": "When working with processes in Linux it is important to know how basic foregrounding and backgrounding processes is performed at the command line." }, { "code": null, "e": 49189, "s": 49148, "text": "fg − Bringsthe process to the foreground" }, { "code": null, "e": 49230, "s": 49189, "text": "fg − Bringsthe process to the foreground" }, { "code": null, "e": 49270, "s": 49230, "text": "bg − Movesthe process to the background" }, { "code": null, "e": 49310, "s": 49270, "text": "bg − Movesthe process to the background" }, { "code": null, "e": 49369, "s": 49310, "text": "jobs − List of the current processes attached to the shell" }, { "code": null, "e": 49428, "s": 49369, "text": "jobs − List of the current processes attached to the shell" }, { "code": null, "e": 49494, "s": 49428, "text": "ctrl+z − Control + z key combination to sleep the current process" }, { "code": null, "e": 49560, "s": 49494, "text": "ctrl+z − Control + z key combination to sleep the current process" }, { "code": null, "e": 49600, "s": 49560, "text": "& − Startsthe process in the background" }, { "code": null, "e": 49640, "s": 49600, "text": "& − Startsthe process in the background" }, { "code": null, "e": 49763, "s": 49640, "text": "Let's start using the shell command sleep. sleep will simply do as it is named, sleep for a defined period of time: sleep." }, { "code": null, "e": 49993, "s": 49763, "text": "[root@CentOS ~]$ jobs\n\n[root@CentOS ~]$ sleep 10 & \n[1] 12454\n\n[root@CentOS ~]$ sleep 20 & \n[2] 12479\n\n[root@CentOS ~]$ jobs \n[1]- Running sleep 10 & \n[2]+ Running sleep 20 &\n\n[cnetos@CentOS ~]$\n" }, { "code": null, "e": 50044, "s": 49993, "text": "Now, let's bring the first job to the foreground −" }, { "code": null, "e": 50077, "s": 50044, "text": "[root@CentOS ~]$ fg 1 \nsleep 10\n" }, { "code": null, "e": 50236, "s": 50077, "text": "If you are following along, you'll notice the foreground job is stuck in your shell. Now, let's put the process to sleep, then re-enable it in the background." }, { "code": null, "e": 50250, "s": 50236, "text": "Hit control+z" }, { "code": null, "e": 50321, "s": 50250, "text": "Type: bg 1, sending the first job into the background and starting it." }, { "code": null, "e": 50456, "s": 50321, "text": "[root@CentOS ~]$ fg 1 \nsleep 20 \n^Z \n[1]+ Stopped sleep 20\n\n[root@CentOS ~]$ bg 1 \n[1]+ sleep 20 &\n\n[root@CentOS ~]$\n" }, { "code": null, "e": 50766, "s": 50456, "text": "When working from a shell or terminal, it is worth noting that by default all the processes and jobs attached to the shell will terminate when the shell is closed or the user logs out. When using nohup the process will continue to run if the user logs out or closes the shell to which the process is attached." }, { "code": null, "e": 51390, "s": 50766, "text": "[root@CentOS]# nohup ping www.google.com & \n[1] 27299 \nnohup: ignoring input and appending output to ‘nohup.out’\n\n[root@CentOS]# pgrep ping \n27299\n\n[root@CentOS]# kill -KILL `pgrep ping` \n[1]+ Killed nohup ping www.google.com\n\n[root@CentOS rdc]# cat nohup.out \nPING www.google.com (216.58.193.68) 56(84) bytes of data. \n64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 1 ttl = 128\ntime = 51.6 ms \n64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 2 ttl = 128\ntime = 54.2 ms \n64 bytes from sea15s07-in-f4.1e100.net (216.58.193.68): icmp_seq = 3 ttl = 128\ntime = 52.7 ms\n" }, { "code": null, "e": 51563, "s": 51390, "text": "The ps command is commonly used by administrators to investigate snapshots of a specific process. ps is commonly used with grep to filter out a specific process to analyze." }, { "code": null, "e": 51809, "s": 51563, "text": "[root@CentOS ~]$ ps axw | grep python \n762 ? Ssl 0:01 /usr/bin/python -Es /usr/sbin/firewalld --nofork -nopid \n1296 ? Ssl 0:00 /usr/bin/python -Es /usr/sbin/tuned -l -P \n15550 pts/0 S+ 0:00 grep --color=auto python\n" }, { "code": null, "e": 51971, "s": 51809, "text": "In the above command, we see all the processes using the python interpreter. Also included with the results were our grep command, looking for the string python." }, { "code": null, "e": 52037, "s": 51971, "text": "Following are the most common command line switches used with ps." }, { "code": null, "e": 52086, "s": 52037, "text": "To see all processes in use by the nobody user −" }, { "code": null, "e": 52195, "s": 52086, "text": "[root@CentOS ~]$ ps -u nobody \nPID TTY TIME CMD \n1853 ? 00:00:00 dnsmasq \n\n[root@CentOS ~]$\n" }, { "code": null, "e": 52248, "s": 52195, "text": "To see all information about the firewalld process −" }, { "code": null, "e": 52474, "s": 52248, "text": "[root@CentOS ~]$ ps -wl -C firewalld \nF S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD\n0 S 0 762 1 0 80 0 - 81786 poll_s ? 00:00:01 firewalld \n\n[root@CentOS ~]$\n" }, { "code": null, "e": 52532, "s": 52474, "text": "Let's see which processes are consuming the most memory −" }, { "code": null, "e": 53774, "s": 52532, "text": "[root@CentOS ~]$ ps aux --sort=-pmem | head -10 \nUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND \ncnetos 6130 0.7 5.7 1344512 108364 ? Sl 02:16 0:29 /usr/bin/gnome-shell \ncnetos 6449 0.0 3.4 1375872 64440 ? Sl 02:16 0:00 /usr/libexec/evolution-calendar-factory \nroot 5404 0.6 2.1 190256 39920 tty1 Ssl+ 02:15 0:27 /usr/bin/Xorg :0 -background none -noreset -audit 4 -verbose -auth /run/gdm/auth-for-gdm-iDefCt/database -seat seat0 -nolisten tcp vt1 \ncnetos 6296 0.0 1.7 1081944 32136 ? Sl 02:16 0:00 /usr/libexec/evolution/3.12/evolution-alarm-notify \ncnetos 6350 0.0 1.5 560728 29844 ? Sl 02:16 0:01 /usr/bin/prlsga \ncnetos 6158 0.0 1.4 1026956 28004 ? Sl 02:16 0:00 /usr/libexec/gnome-shell-calendar-server \ncnetos 6169 0.0 1.4 1120028 27576 ? Sl 02:16 0:00 /usr/libexec/evolution-source-registry \nroot 762 0.0 1.4 327144 26724 ? Ssl 02:09 0:01 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid \ncnetos 6026 0.0 1.4 1090832 26376 ? Sl 02:16 0:00 /usr/libexec/gnome-settings-daemon\n\n[root@CentOS ~]$\n" }, { "code": null, "e": 53854, "s": 53774, "text": "See all the processes by user centos and format, displaying the custom output −" }, { "code": null, "e": 54184, "s": 53854, "text": "[cnetos@CentOS ~]$ ps -u cnetos -o pid,uname,comm \n PID USER COMMAND \n 5802 centos gnome-keyring-d \n 5812 cnetos gnome-session \n 5819 cnetos dbus-launch \n 5820 cnetos dbus-daemon \n 5888 cnetos gvfsd \n 5893 cnetos gvfsd-fuse \n 5980 cnetos ssh-agent \n 5996 cnetos at-spi-bus-laun\n" }, { "code": null, "e": 54283, "s": 54184, "text": "pstree is similar to ps but is not often used. It displays the processes in a neater tree fashion." }, { "code": null, "e": 55067, "s": 54283, "text": "[centos@CentOS ~]$ pstree \n systemd─┬─ModemManager───2*[{ModemManager}] \n ├─NetworkManager─┬─dhclient \n │ └─2*[{NetworkManager}] \n ├─2*[abrt-watch-log] \n ├─abrtd \n ├─accounts-daemon───2*[{accounts-daemon}] \n ├─alsactl \n ├─at-spi-bus-laun─┬─dbus-daemon───{dbus-daemon} \n │ └─3*[{at-spi-bus-laun}] \n ├─at-spi2-registr───2*[{at-spi2-registr}] \n ├─atd \n ├─auditd─┬─audispd─┬─sedispatch \n │ │ └─{audispd} \n │ └─{auditd} \n ├─avahi-daemon───avahi-daemon \n ├─caribou───2*[{caribou}] \n ├─cgrulesengd \n ├─chronyd \n ├─colord───2*[{colord}] \n ├─crond \n ├─cupsd\n" }, { "code": null, "e": 55165, "s": 55067, "text": "The total output from pstree can exceed 100 lines. Usually, ps will give more useful information." }, { "code": null, "e": 55402, "s": 55165, "text": "top is one of the most often used commands when troubleshooting performance issues in Linux. It is useful for real-time stats and process monitoring in Linux. Following is the default output of top when brought up from the command line." }, { "code": null, "e": 56123, "s": 55402, "text": "Tasks: 170 total, 1 running, 169 sleeping, 0 stopped, 0 zombie \n%Cpu(s): 2.3 us, 2.0 sy, 0.0 ni, 95.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st \nKiB Mem : 1879668 total, 177020 free, 607544 used, 1095104 buff/cache \nKiB Swap: 3145724 total, 3145428 free, 296 used. 1034648 avail Mem \n \nPID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND\n5404 root 20 0 197832 48024 6744 S 1.3 2.6 1:13.22 Xorg\n8013 centos 20 0 555316 23104 13140 S 1.0 1.2 0:14.89 gnome-terminal-\n6339 centos 20 0 332336 6016 3248 S 0.3 0.3 0:23.71 prlcc\n6351 centos 20 0 21044 1532 1292 S 0.3 0.1 0:02.66 prlshprof\n" }, { "code": null, "e": 56239, "s": 56123, "text": "Common hot keys used while running top (hot keys are accessed by pressing the key as top is running in your shell)." }, { "code": null, "e": 56295, "s": 56239, "text": "Following are the common command line switches for top." }, { "code": null, "e": 56417, "s": 56295, "text": "Sorting options screen in top, presented using Shift+F. This screen allows customization of top display and sort options." }, { "code": null, "e": 57462, "s": 56417, "text": "Fields Management for window 1:Def, whose current sort field is %MEM \nNavigate with Up/Dn, Right selects for move then <Enter> or Left commits, \n 'd' or <Space> toggles display, 's' sets sort. Use 'q' or <Esc> to end!\n \n* PID = Process Id TGID = Thread Group Id \n* USER = Effective User Name ENVIRON = Environment vars \n* PR = Priority vMj = Major Faults delta \n* NI = Nice Value vMn = Minor Faults delta \n* VIRT = Virtual Image (KiB) USED = Res+Swap Size (KiB) \n* RES = Resident Size (KiB) nsIPC = IPC namespace Inode \n* SHR = Shared Memory (KiB) nsMNT = MNT namespace Inode\n* S = Process Status nsNET = NET namespace Inode \n* %CPU = CPU Usage nsPID = PID namespace Inode \n* %MEM = Memory Usage (RES) nsUSER = USER namespace Inode \n* TIME+ = CPU Time, hundredths nsUTS = UTS namespace Inode \n* COMMAND = Command Name/Line \nPPID = Parent Process pid\nUID = Effective User Id\n" }, { "code": null, "e": 57531, "s": 57462, "text": "top, showing the processes for user rdc and sorted by memory usage −" }, { "code": null, "e": 58113, "s": 57531, "text": " PID USER %MEM PR NI VIRT RES SHR S %CPU TIME+ COMMAND\n 6130 rdc 6.2 20 0 1349592 117160 33232 S 0.0 1:09.34 gnome-shell\n 6449 rdc 3.4 20 0 1375872 64428 21400 S 0.0 0:00.43 evolution-calen\n 6296 rdc 1.7 20 0 1081944 32140 22596 S 0.0 0:00.40 evolution-alarm\n 6350 rdc 1.6 20 0 560728 29844 4256 S 0.0 0:10.16 prlsga\n 6281 rdc 1.5 20 0 1027176 28808 17680 S 0.0 0:00.78 nautilus\n 6158 rdc 1.5 20 0 1026956 28004 19072 S 0.0 0:00.20 gnome-shell-cal\n" }, { "code": null, "e": 58152, "s": 58113, "text": "Showing valid top fields (condensed) −" }, { "code": null, "e": 58257, "s": 58152, "text": "[centos@CentOS ~]$ top -O \nPID \nPPID \nUID \nUSER \nRUID \nRUSER \nSUID \nSUSER \nGID \nGROUP \nPGRP \nTTY \nTPGID\n" }, { "code": null, "e": 58498, "s": 58257, "text": "The kill command is used to kill a process from the command shell via its PID. When killing a process, we need to specify a signal to send. The signal lets the kernel know how we want to end the process. The most commonly used signals are −" }, { "code": null, "e": 58689, "s": 58498, "text": "SIGTERM is implied as the kernel lets a process know it should stop soon as it is safe to do so. SIGTERM gives the process an opportunity to exit gracefully and perform safe exit operations." }, { "code": null, "e": 58880, "s": 58689, "text": "SIGTERM is implied as the kernel lets a process know it should stop soon as it is safe to do so. SIGTERM gives the process an opportunity to exit gracefully and perform safe exit operations." }, { "code": null, "e": 59020, "s": 58880, "text": "SIGHUP most daemons will restart when sent SIGHUP. This is often used on the processes when changes have been made to a configuration file." }, { "code": null, "e": 59160, "s": 59020, "text": "SIGHUP most daemons will restart when sent SIGHUP. This is often used on the processes when changes have been made to a configuration file." }, { "code": null, "e": 59402, "s": 59160, "text": "SIGKILL since SIGTERM is the equivalent to asking a process to shut down. The kernel needs an option to end a process that will not comply with requests. When a process is hung, the SIGKILL option is used to shut the process down explicitly." }, { "code": null, "e": 59644, "s": 59402, "text": "SIGKILL since SIGTERM is the equivalent to asking a process to shut down. The kernel needs an option to end a process that will not comply with requests. When a process is hung, the SIGKILL option is used to shut the process down explicitly." }, { "code": null, "e": 59726, "s": 59644, "text": "For a list off all signals that can be sent with kill the -l option can be used −" }, { "code": null, "e": 60844, "s": 59726, "text": "[root@CentOS]# kill -l \n1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP\n6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1\n11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM\n16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP\n21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ\n26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR\n31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3\n38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8\n43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 \n48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 \n53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7\n58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2\n63) SIGRTMAX-1 64) SIGRTMAX\n\n[root@CentOS rdc]#\n" }, { "code": null, "e": 60876, "s": 60844, "text": "Using SIGHUP to restart system." }, { "code": null, "e": 61043, "s": 60876, "text": "[root@CentOS]# pgrep systemd \n1 \n464 \n500 \n643 \n15071\n\n[root@CentOS]# kill -HUP 1\n\n[root@CentOS]# pgrep systemd\n1 \n464 \n500 \n643 \n15196 \n15197 \n15198\n\n[root@CentOS]#\n" }, { "code": null, "e": 61121, "s": 61043, "text": "pkill will allow the administrator to send a kill signal by the process name." }, { "code": null, "e": 61228, "s": 61121, "text": "[root@CentOS]# pgrep ping \n19450 \n[root@CentOS]# pkill -9 ping \n[root@CentOS]# pgrep ping \n[root@CentOS]#\n" }, { "code": null, "e": 61348, "s": 61228, "text": "killall will kill all the processes. Be careful using killall as root, as it will kill all the processes for all users." }, { "code": null, "e": 61379, "s": 61348, "text": "[root@CentOS]# killall chrome\n" }, { "code": null, "e": 61526, "s": 61379, "text": "free is a pretty simple command often used to quickly check the memory of a system. It displays the total amount of used physical and swap memory." }, { "code": null, "e": 61774, "s": 61526, "text": "[root@CentOS]# free \n total used free shared buff/cache available \nMem: 1879668 526284 699796 10304 653588 1141412 \nSwap: 3145724 0 3145724\n\n[root@CentOS]# \n" }, { "code": null, "e": 62046, "s": 61774, "text": "nice will allow an administrator to set the scheduling priority of a process in terms of CPU usages. The niceness is basically how the kernel will schedule CPU time slices for a process or job. By default, it is assumed the process is given equal access to CPU resources." }, { "code": null, "e": 62125, "s": 62046, "text": "First, let's use top to check the niceness of the currently running processes." }, { "code": null, "e": 63374, "s": 62125, "text": "PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND\n28 root 39 19 0 0 0 S 0.0 0.0 0:00.17 khugepaged\n690 root 39 19 16808 1396 1164 S 0.0 0.1 0:00.01 alsactl]\n9598 rdc 39 19 980596 21904 10284 S 0.0 1.2 0:00.27 tracker-extract\n9599 rdc 39 19 469876 9608 6980 S 0.0 0.5 0:00.04 tracker-miner-a\n9609 rdc 39 19 636528 13172 8044 S 0.0 0.7 0:00.12 tracker-miner-f\n9611 rdc 39 19 469620 8984 6496 S 0.0 0.5 0:00.02 tracker-miner-u\n27 root 25 5 0 0 0 S 0.0 0.0 0:00.00 ksmd\n637 rtkit 21 1 164648 1276 1068 S 0.0 0.1 0:00.11 rtkit-daemon\n1 root 20 0 128096 6712 3964 S 0.3 0.4 0:03.57 systemd\n2 root 20 0 0 0 0 S 0.0 0.0 0:00.01 kthreadd\n3 root 20 0 0 0 0 S 0.0 0.0 0:00.50 ksoftirqd/0\n7 root 20 0 0 0 0 S 0.0 0.0 0:00.00 migration/0\n8 root 20 0 0 0 0 S 0.0 0.0 0:00.00 rcu_bh\n9 root 20 0 0 0 0 S 0.0 0.0 0:02.07 rcu_sched\n" }, { "code": null, "e": 63532, "s": 63374, "text": "We want to focus on the NICE column depicted by NI. The niceness range can be anywhere between -20 to positive 19. -20 represents the highest given priority." }, { "code": null, "e": 63571, "s": 63532, "text": "nohup nice --20 ping www.google.com &\n" }, { "code": null, "e": 63657, "s": 63571, "text": "renice allows us to change the current priority of a process that is already running." }, { "code": null, "e": 63677, "s": 63657, "text": "renice 17 -p 30727\n" }, { "code": null, "e": 63748, "s": 63677, "text": "The above command will lower the priority of our ping process command." }, { "code": null, "e": 63886, "s": 63748, "text": "firewalld is the default front-end controller for iptables on CentOS. The firewalld front-end has two main advantages over raw iptables −" }, { "code": null, "e": 63959, "s": 63886, "text": "Uses easy-to-configure and implement zones abstracting chains and rules." }, { "code": null, "e": 64032, "s": 63959, "text": "Uses easy-to-configure and implement zones abstracting chains and rules." }, { "code": null, "e": 64148, "s": 64032, "text": "Rulesets are dynamic, meaning stateful connections are uninterrupted when the settings are changed and/or modified." }, { "code": null, "e": 64264, "s": 64148, "text": "Rulesets are dynamic, meaning stateful connections are uninterrupted when the settings are changed and/or modified." }, { "code": null, "e": 64471, "s": 64264, "text": "Remember, firewalld is the wrapper for iptables - not a replacement. While custom iptables commands can be used with firewalld, it is recommended to use firewalld as to not break the firewall functionality." }, { "code": null, "e": 64533, "s": 64471, "text": "First, let's make sure firewalld is both started and enabled." }, { "code": null, "e": 64988, "s": 64533, "text": "[root@CentOS rdc]# systemctl status firewalld \n● firewalld.service - firewalld - dynamic firewall daemon \nLoaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled) \nActive: active (running) since Thu 2017-01-26 21:42:05 MST; 3h 46min ago \n Docs: man:firewalld(1) \nMain PID: 712 (firewalld) \n Memory: 34.7M \n CGroup: /system.slice/firewalld.service \n └─712 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid\n" }, { "code": null, "e": 65107, "s": 64988, "text": "We can see, firewalld is both active (to start on boot) and currently running. If inactive or not started we can use −" }, { "code": null, "e": 65164, "s": 65107, "text": "systemctl start firewalld && systemctl enable firewalld\n" }, { "code": null, "e": 65247, "s": 65164, "text": "Now that we have our firewalld service configured, let's assure it is operational." }, { "code": null, "e": 65309, "s": 65247, "text": "[root@CentOS]# firewall-cmd --state \nrunning \n[root@CentOS]#\n" }, { "code": null, "e": 65364, "s": 65309, "text": "We can see, the firewalld service is fully functional." }, { "code": null, "e": 65652, "s": 65364, "text": "Firewalld works on the concept of zones. A zone is applied to network interfaces through the Network Manager. We will discuss this in configuring networking. But for now, by default, changing the default zone will change any network adapters left in the default state of \"Default Zone\". " }, { "code": null, "e": 65731, "s": 65652, "text": "Let's take a quick look at each zone that comes out-of-the-box with firewalld." }, { "code": null, "e": 65736, "s": 65731, "text": "drop" }, { "code": null, "e": 65862, "s": 65736, "text": "Low trust level. All incoming connections and packetsare dropped and only outgoing connections are possible via statefullness" }, { "code": null, "e": 65868, "s": 65862, "text": "block" }, { "code": null, "e": 65975, "s": 65868, "text": "Incoming connections are replied with an icmp message letting the initiator know the request is prohibited" }, { "code": null, "e": 65982, "s": 65975, "text": "public" }, { "code": null, "e": 66076, "s": 65982, "text": "All networks are restricted. However, selected incoming connections can be explicitly allowed" }, { "code": null, "e": 66085, "s": 66076, "text": "external" }, { "code": null, "e": 66162, "s": 66085, "text": "Configures firewalld for NAT. Internal network remains private but reachable" }, { "code": null, "e": 66166, "s": 66162, "text": "dmz" }, { "code": null, "e": 66247, "s": 66166, "text": "Only certain incoming connections are allowed. Used for systems in DMZ isolation" }, { "code": null, "e": 66252, "s": 66247, "text": "work" }, { "code": null, "e": 66353, "s": 66252, "text": "By default, trust more computers on the network assuming the system is in a secured work environment" }, { "code": null, "e": 66358, "s": 66353, "text": "hone" }, { "code": null, "e": 66495, "s": 66358, "text": "By default, more services are unfiltered. Assuming a system is on a home network where services such as NFS, SAMBA and SSDP will be used" }, { "code": null, "e": 66503, "s": 66495, "text": "trusted" }, { "code": null, "e": 66651, "s": 66503, "text": "All machines on the network are trusted. Most incoming connections are allowed unfettered. This is not meant for interfaces exposed to the Internet" }, { "code": null, "e": 66714, "s": 66651, "text": "The most common zones to use are:public, drop, work, and home." }, { "code": null, "e": 66772, "s": 66714, "text": "Some scenarios where each common zone would be used are −" }, { "code": null, "e": 66933, "s": 66772, "text": "public − It is the most common zone used by an administrator. It will let you apply the custom settings and abide by RFC specifications for operations on a LAN." }, { "code": null, "e": 67094, "s": 66933, "text": "public − It is the most common zone used by an administrator. It will let you apply the custom settings and abide by RFC specifications for operations on a LAN." }, { "code": null, "e": 67496, "s": 67094, "text": "drop − A good example of when to use drop is at a security conference, on public WiFi, or on an interface connected directly to the Internet. drop assumes all unsolicited requests are malicious including ICMP probes. So any request out of state will not receive a reply. The downside of drop is that it can break the functionality of applications in certain situations requiring strict RFC compliance." }, { "code": null, "e": 67898, "s": 67496, "text": "drop − A good example of when to use drop is at a security conference, on public WiFi, or on an interface connected directly to the Internet. drop assumes all unsolicited requests are malicious including ICMP probes. So any request out of state will not receive a reply. The downside of drop is that it can break the functionality of applications in certain situations requiring strict RFC compliance." }, { "code": null, "e": 68152, "s": 67898, "text": "work − You are on a semi-secure corporate LAN. Where all traffic can be assumed moderately safe. This means it is not WiFi and we possibly have IDS, IPS, and physical security or 802.1x in place. We also should be familiar with the people using the LAN." }, { "code": null, "e": 68406, "s": 68152, "text": "work − You are on a semi-secure corporate LAN. Where all traffic can be assumed moderately safe. This means it is not WiFi and we possibly have IDS, IPS, and physical security or 802.1x in place. We also should be familiar with the people using the LAN." }, { "code": null, "e": 68724, "s": 68406, "text": "home − You are on a home LAN. You are personally accountable for every system and the user on the LAN. You know every machine on the LAN and that none have been compromised. Often new services are brought up for media sharing amongst trusted individuals and you don't need to take extra time for the sake of security." }, { "code": null, "e": 69042, "s": 68724, "text": "home − You are on a home LAN. You are personally accountable for every system and the user on the LAN. You know every machine on the LAN and that none have been compromised. Often new services are brought up for media sharing amongst trusted individuals and you don't need to take extra time for the sake of security." }, { "code": null, "e": 69239, "s": 69042, "text": "Zones and network interfaces work on a one to many level. One network interface can only have a single zone applied to it at a time. While, a zone can be applied to many interfaces simultaneously." }, { "code": null, "e": 69315, "s": 69239, "text": "Let's see what zones are available and what are the currently applied zone." }, { "code": null, "e": 69416, "s": 69315, "text": "[root@CentOS]# firewall-cmd --get-zones \n work drop internal external trusted home dmz public block\n" }, { "code": null, "e": 69487, "s": 69416, "text": "[root@CentOS]# firewall-cmd --get-default-zone \npublic\n[root@CentOS]#\n" }, { "code": null, "e": 69536, "s": 69487, "text": "Ready to add some customized rules in firewalld?" }, { "code": null, "e": 69609, "s": 69536, "text": "First, let's see what our box looks like, to a portscanner from outside." }, { "code": null, "e": 69950, "s": 69609, "text": "bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1\n \nStarting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:36 MST \nNmap scan report for centos.shared (10.211.55.1) \nHost is up (0.00046s latency). \nNot shown: 1023 filtered ports \nPORT STATE SERVICE \n22/tcp open ssh\n\n\nNmap done: 1 IP address (1 host up) scanned in 3.71 seconds \nbash-3.2#\n" }, { "code": null, "e": 69996, "s": 69950, "text": "Let's allow the incoming requests to port 80." }, { "code": null, "e": 70049, "s": 69996, "text": "First, check to see what zone is applied as default." }, { "code": null, "e": 70120, "s": 70049, "text": "[root@CentOs]# firewall-cmd --get-default-zone \npublic\n[root@CentOS]#\n" }, { "code": null, "e": 70185, "s": 70120, "text": "Then, set the rule allowing port 80 to the current default zone." }, { "code": null, "e": 70272, "s": 70185, "text": "[root@CentOS]# firewall-cmd --zone=public --add-port = 80/tcp \nsuccess\n[root@CentOS]#\n" }, { "code": null, "e": 70333, "s": 70272, "text": "Now, let's check our box after allowing port 80 connections." }, { "code": null, "e": 70694, "s": 70333, "text": "bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1\n\nStarting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:42 MST \nNmap scan report for centos.shared (10.211.55.1) \nHost is up (0.00053s latency). \nNot shown: 1022 filtered ports \nPORT STATE SERVICE \n22/tcp open ssh \n80/tcp closed http\n\nNmap done: 1 IP address (1 host up) scanned in 3.67 seconds \nbash-3.2#\n" }, { "code": null, "e": 70735, "s": 70694, "text": "It now allows unsolicited traffic to 80." }, { "code": null, "e": 70805, "s": 70735, "text": "Let's put the default zone to drop and see what happens to port scan." }, { "code": null, "e": 70937, "s": 70805, "text": "[root@CentOS]# firewall-cmd --set-default-zone=drop \nsuccess\n\n[root@CentOS]# firewall-cmd --get-default-zone \ndrop\n\n[root@CentOs]#\n" }, { "code": null, "e": 71011, "s": 70937, "text": "Now let's scan the host with the network interface in a more secure zone." }, { "code": null, "e": 71347, "s": 71011, "text": "bash-3.2# nmap -sS -p 1-1024 -T 5 10.211.55.1 \nStarting Nmap 7.30 ( https://nmap.org ) at 2017-01-27 23:50 MST \nNmap scan report for centos.shared (10.211.55.1) \nHost is up (0.00094s latency). \nAll 1024 scanned ports on centos.shared (10.211.55.1) are filtered\n\nNmap done: 1 IP address (1 host up) scanned in 12.61 seconds \nbash-3.2#\n" }, { "code": null, "e": 71389, "s": 71347, "text": "Now, everything is filtered from outside." }, { "code": null, "e": 71479, "s": 71389, "text": "As demonstrated below, the host will not even respond to ICMP ping requests when in drop." }, { "code": null, "e": 71650, "s": 71479, "text": "bash-3.2# ping 10.211.55.1 \nPING 10.211.55.1 (10.211.55.1): 56 data bytes \nRequest timeout for icmp_seq 0 \nRequest timeout for icmp_seq 1 \nRequest timeout for icmp_seq 2\n" }, { "code": null, "e": 71694, "s": 71650, "text": "Let's set the default zone to public again." }, { "code": null, "e": 71830, "s": 71694, "text": "[root@CentOs]# firewall-cmd --set-default-zone=public \nsuccess\n\n[root@CentOS]# firewall-cmd --get-default-zone \npublic\n\n[root@CentOS]#\n" }, { "code": null, "e": 71887, "s": 71830, "text": "Now let's check our current filtering ruleset in public." }, { "code": null, "e": 72185, "s": 71887, "text": "[root@CentOS]# firewall-cmd --zone=public --list-all \npublic (active) \ntarget: default \nicmp-block-inversion: no \ninterfaces: enp0s5 \nsources: \nservices: dhcpv6-client ssh \nports: 80/tcp \nprotocols: \nmasquerade: no \nforward-ports: \nsourceports: \nicmp-blocks: \nrich rules:\n\n[root@CentOS rdc]#\n" }, { "code": null, "e": 72387, "s": 72185, "text": "As configured, our port 80 filter rule is only within the context of the running configuration. This means once the system is rebooted or the firewalld service is restarted, our rule will be discarded." }, { "code": null, "e": 72471, "s": 72387, "text": "We will be configuring an httpd daemon soon, so let's make our changes persistent −" }, { "code": null, "e": 72613, "s": 72471, "text": "[root@CentOS]# firewall-cmd --zone=public --add-port=80/tcp --permanent \nsuccess\n\n[root@CentOS]# systemctl restart firewalld\n\n[root@CentOS]#\n" }, { "code": null, "e": 72704, "s": 72613, "text": "Now our port 80 rule in the public zone is persistent across reboots and service restarts." }, { "code": null, "e": 72775, "s": 72704, "text": "Following are the common firewalld commands applied with firewall-cmd." }, { "code": null, "e": 72849, "s": 72775, "text": "These are the basic concepts of administrating and configuring firewalld." }, { "code": null, "e": 73163, "s": 72849, "text": "Configuring host-based firewall services in CentOS can be a complex task in more sophisticated networking scenarios. Advanced usage and configuration of firewalld and iptables in CentOS can take an entire tutorial. However, we have presented the basics that should be enough to complete a majority of daily tasks." }, { "code": null, "e": 73354, "s": 73163, "text": "PHP is the one of the most prolific web languages in use today. Installing a LAMP Stack on CentOS is something every system administrator will need to perform, most likely sooner than later." }, { "code": null, "e": 73423, "s": 73354, "text": "A traditional LAMP Stack consists of (L)inux (A)pache (M)ySQL (P)HP." }, { "code": null, "e": 73483, "s": 73423, "text": "There are three main components to a LAMP Stack on CentOS −" }, { "code": null, "e": 73494, "s": 73483, "text": "Web Server" }, { "code": null, "e": 73530, "s": 73494, "text": "Web Development Platform / Language" }, { "code": null, "e": 73546, "s": 73530, "text": "Database Server" }, { "code": null, "e": 73676, "s": 73546, "text": "Note − The term LAMP Stack can also include the following technologies: PostgreSQL, MariaDB, Perl, Python, Ruby, NGINX Webserver." }, { "code": null, "e": 73813, "s": 73676, "text": "For this tutorial, we will stick with the traditional LAMP Stack of CentOS GNU Linux: Apache web server, MySQL Database Server, and PHP." }, { "code": null, "e": 74126, "s": 73813, "text": "We will actually be using MariaDB. MySQL configuration files, databases and tables are transparent to MariaDB. MariaDB is now included in the standard CentOS repository instead of MySQL. This is due to the limitations of licensing and open-source compliance, since Oracle has taken over the development of MySQL." }, { "code": null, "e": 74175, "s": 74126, "text": "The first thing we need to do is install Apache." }, { "code": null, "e": 75185, "s": 74175, "text": "[root@CentOS]# yum install httpd\nLoaded plugins: fastestmirror, langpacks\nbase\n| 3.6 kB 00:00:00\nextras\n| 3.4 kB 00:00:00\nupdates\n| 3.4 kB 00:00:00\nextras/7/x86_64/primary_d\n| 121 kB 00:00:00\nLoading mirror speeds from cached hostfile\n* base: mirror.sigmanet.com\n* extras: linux.mirrors.es.net\n* updates: mirror.eboundhost.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-45.el7.centos will be installed\n--> Processing Dependency: httpd-tools = 2.4.6-45.el7.centos for package:\nhttpd-2.4.6-45.el7.centos.x86_64\n--> Processing Dependency: /etc/mime.types for package: httpd-2.4.645.el7.centos.x86_64\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.4.6-45.el7.centos will be installed\n---> Package mailcap.noarch 0:2.1.41-2.el7 will be installed\n--> Finished Dependency Resolution\nInstalled:\nhttpd.x86_64 0:2.4.6-45.el7.centos\n\nDependency Installed:\nhttpd-tools.x86_64 0:2.4.6-45.el7.centos\nmailcap.noarch 0:2.1.41-2.el7\n\nComplete!\n[root@CentOS]#\n" }, { "code": null, "e": 75216, "s": 75185, "text": "Let's configure httpd service." }, { "code": null, "e": 75280, "s": 75216, "text": "[root@CentOS]# systemctl start httpd && systemctl enable httpd\n" }, { "code": null, "e": 75349, "s": 75280, "text": "Now, let's make sure the web-server is accessible through firewalld." }, { "code": null, "e": 75882, "s": 75349, "text": "bash-3.2# nmap -sS -p 1-1024 -T 5 -sV 10.211.55.1 \nStarting Nmap 7.30 ( https://nmap.org ) at 2017-01-28 02:00 MST \nNmap scan report for centos.shared (10.211.55.1) \nHost is up (0.00054s latency). \nNot shown: 1022 filtered ports \nPORT STATE SERVICE VERSION \n22/tcp open ssh OpenSSH 6.6.1 (protocol 2.0) \n80/tcp open http Apache httpd 2.4.6 ((CentOS))\n\nService detection performed. Please report any incorrect results at \nhttps://nmap.org/submit/ . \nNmap done: 1 IP address (1 host up) scanned in 10.82 seconds bash-3.2#\n" }, { "code": null, "e": 76001, "s": 75882, "text": "As you can see by the nmap service probe, Apache webserver is listening and responding to requests on the CentOS host." }, { "code": null, "e": 76133, "s": 76001, "text": "[root@CentOS rdc]# yum install mariadb-server.x86_64 && yum install mariadb-\ndevel.x86_64 && mariadb.x86_64 && mariadb-libs.x86_64\n" }, { "code": null, "e": 76199, "s": 76133, "text": "We are installing the following repository packages for MariaDB −" }, { "code": null, "e": 76239, "s": 76199, "text": "The main MariaDB Server daemon package." }, { "code": null, "e": 76311, "s": 76239, "text": "Files need to compile from the source with MySQL/MariaDB compatibility." }, { "code": null, "e": 76392, "s": 76311, "text": "MariaDB client utilities for administering MariaDB Server from the command line." }, { "code": null, "e": 76502, "s": 76392, "text": "Common libraries for MariaDB that could be needed for other applications compiled with MySQL/MariaDB support." }, { "code": null, "e": 76551, "s": 76502, "text": "Now, let's start and enable the MariaDB Service." }, { "code": null, "e": 76633, "s": 76551, "text": "[root@CentOS]# systemctl start mariadb \n[root@CentOS]# systemctl enable mariadb\n" }, { "code": null, "e": 76907, "s": 76633, "text": "Note − Unlike Apache, we will not enable connections to MariaDB through our host-based firewall (firewalld). When using a database server, it's considered best security practice to only allow local socket connections, unless the remote socket access is specifically needed." }, { "code": null, "e": 76968, "s": 76907, "text": "Let's make sure the MariaDB Server is accepting connections." }, { "code": null, "e": 77671, "s": 76968, "text": "[root@CentOS#] netstat -lnt \nActive Internet connections (only servers) \nProto Recv-Q Send-Q Local Address Foreign Address State \ntcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN \ntcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN \ntcp 0 0 192.168.122.1:53 0.0.0.0:* LISTEN \ntcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN \ntcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN \ntcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN \n \n[root@CentOS rdc]#\n" }, { "code": null, "e": 77819, "s": 77671, "text": "As we can see, MariaDB is listening on port 3306 tcp. We will leave our host-based firewall (firewalld) blocking incoming connections to port 3306." }, { "code": null, "e": 77978, "s": 77819, "text": "[root@CentOS#] yum install php.x86_64 && php-common.x86_64 && php-mysql.x86_64 \n&& php-mysqlnd.x86_64 && php-pdo.x86_64 && php-soap.x86_64 && php-xml.x86_64\n" }, { "code": null, "e": 78057, "s": 77978, "text": "I'd recommend installing the following php packages for common compatibility −" }, { "code": null, "e": 78075, "s": 78057, "text": "php-common.x86_64" }, { "code": null, "e": 78092, "s": 78075, "text": "php-mysql.x86_64" }, { "code": null, "e": 78111, "s": 78092, "text": "php-mysqlnd.x86_64" }, { "code": null, "e": 78126, "s": 78111, "text": "php-pdo.x86_64" }, { "code": null, "e": 78142, "s": 78126, "text": "php-soap.x86_64" }, { "code": null, "e": 78157, "s": 78142, "text": "php-xml.x86_64" }, { "code": null, "e": 78289, "s": 78157, "text": "[root@CentOS]# yum install -y php-common.x86_64 php-mysql.x86_64 php-\nmysqlnd.x86_64 php-pdo.x86_64 php-soap.x86_64 php-xml.x86_64\n" }, { "code": null, "e": 78365, "s": 78289, "text": "This is our simple php file located in the Apache webroot of /var/www/html/" }, { "code": null, "e": 78636, "s": 78365, "text": "[root@CentOS]# cat /var/www/html/index.php \n<html> \n <head> \n <title>PHP Test Page</title> \n </head>\n \n <body> \n PHP Install \n <?php \n echo \"We are now running PHP on GNU Centos Linux!<br />\" \n ?> \n </body> \n</html>\n\n[root@CentOS]#" }, { "code": null, "e": 78731, "s": 78636, "text": "Let's change the owning group of our page to the system user our http daemon is running under." }, { "code": null, "e": 78825, "s": 78731, "text": "[root@CentOS]# chgrp httpd /var/www/html/index.php && chmod g+rx /var/www/html/index.php\n---\n" }, { "code": null, "e": 78859, "s": 78825, "text": "When requested manually via ncat." }, { "code": null, "e": 79323, "s": 78859, "text": "bash-3.2# ncat 10.211.55.1 80 \n GET / index.php \n HTTP/1.1 200 OK \n Date: Sat, 28 Jan 2017 12:06:02 GMT \n Server: Apache/2.4.6 (CentOS) PHP/5.4.16 \n X-Powered-By: PHP/5.4.16 \n Content-Length: 137 \n Connection: close \n Content-Type: text/html; charset=UTF-8\n \n<html> \n <head> \n <title>PHP Test Page</title> \n </head>\n \n <body> \n PHP Install \n We are now running PHP on GNU Centos Linux!<br />\n </body> \n</html>\n\nbash-3.2#" }, { "code": null, "e": 79600, "s": 79323, "text": "PHP and LAMP are very popular web-programming technologies. LAMP installation and configuration is sure to come up on your list of needs as a CentOS Administrator. Easy to use CentOS packages have taken a lot of work from compiling Apache, MySQL, and PHP from the source code." }, { "code": null, "e": 79850, "s": 79600, "text": "Python is a widely used interpreted language that has brought professionalism to the world of coding scripted applications on Linux (and other operating systems). Where Perl was once the industry standard, Python has surpassed Perl in many respects." }, { "code": null, "e": 79893, "s": 79850, "text": "Some strengths of Python versus Perl are −" }, { "code": null, "e": 79925, "s": 79893, "text": "Rapid progression in refinement" }, { "code": null, "e": 79957, "s": 79925, "text": "Rapid progression in refinement" }, { "code": null, "e": 80001, "s": 79957, "text": "Libraries that are standard to the language" }, { "code": null, "e": 80045, "s": 80001, "text": "Libraries that are standard to the language" }, { "code": null, "e": 80107, "s": 80045, "text": "Readability of the code is thought out in language definition" }, { "code": null, "e": 80169, "s": 80107, "text": "Readability of the code is thought out in language definition" }, { "code": null, "e": 80249, "s": 80169, "text": "Many professional frameworks for everything from GUI support to web-development" }, { "code": null, "e": 80329, "s": 80249, "text": "Many professional frameworks for everything from GUI support to web-development" }, { "code": null, "e": 80527, "s": 80329, "text": "Python can do anything Perl can do, and in a lot of cases in a better manner. Though Perl still has its place amongst the toolbox of a Linux admin, learning Python is a great choice as a skill set." }, { "code": null, "e": 80905, "s": 80527, "text": "The biggest drawbacks of Python are sometimes related to its strengths. In history, Python was originally designed to teach programming. At times, its core foundations of \"easily readable\" and \"doing things the right way\" can cause unnecessary complexities when writing a simple code. Also, its standard libraries have caused problems in transitioning from versions 2.X to 3.X." }, { "code": null, "e": 81143, "s": 80905, "text": "Python scripts are actually used at the core of CentOS for functions vital to the functionality of the operating system. Because of this, it is important to isolate our development Python environment from CentOS' core Python environment." }, { "code": null, "e": 81228, "s": 81143, "text": "For starters, there are currently two versions of Python: Python 2.X and Python 3.X." }, { "code": null, "e": 81585, "s": 81228, "text": "Both stages are still in active production, though version 2.X is quickly closing in on depreciation (and has been for a few years). The reason for the two active versions of Python was basically fixing the shortcomings of version 2.X. This required some core functionality of version 3.X to be redone in ways it could not support some version 2.X scripts." }, { "code": null, "e": 81789, "s": 81585, "text": "Basically, the best way to overcome this transition is: Develop for 3.X and keep up with the latest 2.X version for legacy scripts. Currently, CentOS 7.X relies on a semi-current revision of version 2.X." }, { "code": null, "e": 81868, "s": 81789, "text": "As of this writing, the most current versions of Python are: 3.4.6 and 2.7.13." }, { "code": null, "e": 82070, "s": 81868, "text": "Don't let this confuse or draw any conclusions of Python. Setting up a Python environment is really pretty simple. With Python frameworks and libraries, this task is actually really easy to accomplish." }, { "code": null, "e": 82246, "s": 82070, "text": "Before setting up our Python environments, we need a sane environment. To start, let's make sure our CentOS install is fully updated and get some building utilities installed." }, { "code": null, "e": 82270, "s": 82246, "text": "Step 1 − Update CentOS." }, { "code": null, "e": 82300, "s": 82270, "text": "[root@CentOS]# yum -y update\n" }, { "code": null, "e": 82334, "s": 82300, "text": "Step 2 − Install build utilities." }, { "code": null, "e": 82390, "s": 82334, "text": "[root@CentOS]# yum -y groupinstall \"development tools\"\n" }, { "code": null, "e": 82429, "s": 82390, "text": "Step 3 − Install some needed packages." }, { "code": null, "e": 82507, "s": 82429, "text": "[root@CentOS]# yum install -y zlib-dev openssl-devel sqlite-devel bip2-devel\n" }, { "code": null, "e": 82570, "s": 82507, "text": "Now we need to install current Python 2.X and 3.X from source." }, { "code": null, "e": 82599, "s": 82570, "text": "Download compressed archives" }, { "code": null, "e": 82613, "s": 82599, "text": "Extract files" }, { "code": null, "e": 82633, "s": 82613, "text": "Compile source code" }, { "code": null, "e": 82712, "s": 82633, "text": "Let's start by creating a build directory for each Python install in /usr/src/" }, { "code": null, "e": 82759, "s": 82712, "text": "[root@CentOS]# mkdir -p /usr/src/pythonSource\n" }, { "code": null, "e": 82809, "s": 82759, "text": "Now let's download the source tarballs for each −" }, { "code": null, "e": 82972, "s": 82809, "text": "[root@CentOS]# wget https://www.python.org/ftp/python/2.7.13/Python-2.7.13.tar.xz\n[root@CentOS]# wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz\n" }, { "code": null, "e": 83018, "s": 82972, "text": "Now we need to extract each from the archive." }, { "code": null, "e": 83069, "s": 83018, "text": "Step 1 − Install xz-libs and extract the tarballs." }, { "code": null, "e": 83226, "s": 83069, "text": "[root@CentOS]# yum install xz-libs\n[root@CentOS python3]# xz -d ./*.xz\n[root@CentOS python3]# ls\nPython-2.7.13.tar Python-3.6.0.tar\n[root@CentOS python3]#\n" }, { "code": null, "e": 83274, "s": 83226, "text": "Step 2 − Untar each installer from its tarball." }, { "code": null, "e": 83362, "s": 83274, "text": "[root@CentOS]# tar -xvf ./Python-2.7.13.tar\n[root@CentOS]# tar -xvf ./Python-3.6.0.tar\n" }, { "code": null, "e": 83422, "s": 83362, "text": "Step 3 − Enter each directory and run the configure script." }, { "code": null, "e": 83501, "s": 83422, "text": "[root@CentOS]# ./configure --prefix=/usr/local \nroot@CentOS]# make altinstall\n" }, { "code": null, "e": 83673, "s": 83501, "text": "Note − Be sure to use altinstall and not install. This will keep CentOS and development versions of Python separated. Otherwise, you may break the functionality of CentOS." }, { "code": null, "e": 83901, "s": 83673, "text": "You will now see the compilation process begins. Grab a cup of coffee and take a 15minute break until completion. Since we installed all the needed dependencies for Python, the compilation process should complete without error." }, { "code": null, "e": 83969, "s": 83901, "text": "Let's make sure we have the latest 2.X version of Python installed." }, { "code": null, "e": 84071, "s": 83969, "text": "[root@CentOS Python-2.7.13]# /usr/local/bin/python2.7 -V \nPython 2.7.13\n[root@CentOS Python-2.7.13]#\n" }, { "code": null, "e": 84175, "s": 84071, "text": "Note − You will want to prefix the shebang line pointing to our development environment for Python 2.X." }, { "code": null, "e": 84277, "s": 84175, "text": "[root@CentOS Python-2.7.13]# cat ver.py \n#!/usr/local/bin/python2.7 \nimport sys \nprint(sys.version)\n" }, { "code": null, "e": 84397, "s": 84277, "text": "[root@CentOS Python-2.7.13]# ./ver.py \n2.7.13 (default, Jan 29 2017, 02:24:08)\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]\n" }, { "code": null, "e": 84625, "s": 84397, "text": "Just like that, we have separate Python installs for versions 2.X and 3.X. From here, we can use each and utilities such as pip and virtualenv to further ease the burden of managing Python environments and package installation." }, { "code": null, "e": 84799, "s": 84625, "text": "Ruby is a great language for both web development and Linux Administration. Ruby provides many benefits found in all the previous languages discussed: PHP, Python, and Perl." }, { "code": null, "e": 84938, "s": 84799, "text": "To install Ruby, it is best to bootstrap through the rbenv which allows the administrators to easily install and manage Ruby Environments." }, { "code": null, "e": 85135, "s": 84938, "text": "The other method for installing Ruby is the standard CentOS packages for Ruby. It is advisable to use the rbenv method with all its benefits. CentOS packages will be easier for the non-Ruby savvy." }, { "code": null, "e": 85198, "s": 85135, "text": "First, let's get some needed dependencies for rbenv installer." }, { "code": null, "e": 85207, "s": 85198, "text": "git-core" }, { "code": null, "e": 85212, "s": 85207, "text": "zlib" }, { "code": null, "e": 85223, "s": 85212, "text": "zlib-devel" }, { "code": null, "e": 85231, "s": 85223, "text": "gcc-c++" }, { "code": null, "e": 85237, "s": 85231, "text": "patch" }, { "code": null, "e": 85246, "s": 85237, "text": "readline" }, { "code": null, "e": 85261, "s": 85246, "text": "readline-devel" }, { "code": null, "e": 85275, "s": 85261, "text": "libyaml-devel" }, { "code": null, "e": 85288, "s": 85275, "text": "libffi-devel" }, { "code": null, "e": 85302, "s": 85288, "text": "openssl-devel" }, { "code": null, "e": 85307, "s": 85302, "text": "make" }, { "code": null, "e": 85314, "s": 85307, "text": "bzzip2" }, { "code": null, "e": 85323, "s": 85314, "text": "autoconf" }, { "code": null, "e": 85332, "s": 85323, "text": "automake" }, { "code": null, "e": 85340, "s": 85332, "text": "libtool" }, { "code": null, "e": 85346, "s": 85340, "text": "bison" }, { "code": null, "e": 85351, "s": 85346, "text": "curl" }, { "code": null, "e": 85364, "s": 85351, "text": "sqlite-devel" }, { "code": null, "e": 85615, "s": 85364, "text": "Most of these packages may already be installed depending on the chosen options and roles when installing CentOS. It is good to install everything we are unsure about as this can lead to less headache when installing packages requiring dependencies." }, { "code": null, "e": 85814, "s": 85615, "text": "[root@CentOS]# yum -y install git-core zlib zlib-devel gcc-c++ patch readline \nreadline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf \nautomake libtool bison curl sqlite-devel \n" }, { "code": null, "e": 85855, "s": 85814, "text": "Now as the user who will be using Ruby −" }, { "code": null, "e": 85974, "s": 85855, "text": "[rdc@CentOS ~]$ git clone https://github.com/rbenv/rbenv.git\n[rdc@CentOS ~]$ https://github.com/rbenv/ruby-build.git\n" }, { "code": null, "e": 86031, "s": 85974, "text": "ruby-build will provide installation features to rbenv −" }, { "code": null, "e": 86116, "s": 86031, "text": "Note − We need to switch to root or an administration user before running install.sh" }, { "code": null, "e": 86196, "s": 86116, "text": "[rdc@CentOS ruby-build]$ cd ~/ruby-build\n[rdc@CentOS ruby-build]# ./install.sh\n" }, { "code": null, "e": 86275, "s": 86196, "text": "Let's set our shell for rbenv and assure we have installedthe correct options." }, { "code": null, "e": 86438, "s": 86275, "text": "[rdc@CentOS ~]$ source ~/rbenv/rbenv.d/exec/gem-rehash.bash\n\n[rdc@CentOS ruby-build]$ ~/rbenv/bin/rbenv \nrbenv 1.1.0-2-g4f8925a \nUsage: rbenv <command> [<args>]\n" }, { "code": null, "e": 86471, "s": 86438, "text": "Some useful rbenv commands are −" }, { "code": null, "e": 86496, "s": 86471, "text": "Let's now install Ruby −" }, { "code": null, "e": 86550, "s": 86496, "text": "[rdc@CentOS bin]$ ~/rbenv/bin/rbenv install -v 2.2.1\n" }, { "code": null, "e": 86580, "s": 86550, "text": "After compilation completes −" }, { "code": null, "e": 86682, "s": 86580, "text": "[rdc@CentOS ~]$ ./ruby -v \nruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux] \n[rdc@CentOS ~]$\n" }, { "code": null, "e": 86777, "s": 86682, "text": "We now have a working Ruby environment with an updated and working version of Ruby 2.X branch." }, { "code": null, "e": 86978, "s": 86777, "text": "This is the most simple method. However, it can be limited by the version and gems packaged from CentOS. For serious development work, it is highly recommended to use the rbenv method to install Ruby." }, { "code": null, "e": 87043, "s": 86978, "text": "Install Ruby, needed development packages, and some common gems." }, { "code": null, "e": 87167, "s": 87043, "text": "[root@CentOS rdc]# yum install -y ruby.x86_64 ruby-devel.x86_64 ruby-\nlibs.x86_64 ruby-gem-json.x86_64 rubygem-rake.noarch\n" }, { "code": null, "e": 87234, "s": 87167, "text": "Unfortunately, we are left with somewhat outdated version of Ruby." }, { "code": null, "e": 87325, "s": 87234, "text": "[root@CentOS rdc]# ruby -v \nruby 2.0.0p648 (2015-12-16) [x86_64-linux]\n[root@CentOS rdc]#\n" }, { "code": null, "e": 87591, "s": 87325, "text": "Perl has been around for a long time. It was originally designed as a reporting language used for parsing text files. With increased popularity, Perl has added a module support or CPAN, sockets, threading, and other features needed in a powerful scripting language." }, { "code": null, "e": 87879, "s": 87591, "text": "The biggest advantage of Perl over PHP, Python, or Ruby is: it gets things done with minimal fuss. This philosophy of Perl does not always mean it gets things done the right way. However, for administration tasks on Linux, Perl is considered as the go-to choice for a scripting language." }, { "code": null, "e": 87929, "s": 87879, "text": "Some advantages of Perl over Python or Ruby are −" }, { "code": null, "e": 87954, "s": 87929, "text": "Powerful text processing" }, { "code": null, "e": 87979, "s": 87954, "text": "Powerful text processing" }, { "code": null, "e": 88119, "s": 87979, "text": "Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby)" }, { "code": null, "e": 88259, "s": 88119, "text": "Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby)" }, { "code": null, "e": 88289, "s": 88259, "text": "Perl can do anything (almost)" }, { "code": null, "e": 88319, "s": 88289, "text": "Perl can do anything (almost)" }, { "code": null, "e": 88348, "s": 88319, "text": "Some drawbacks of Perl are −" }, { "code": null, "e": 88372, "s": 88348, "text": "Syntax can be confusing" }, { "code": null, "e": 88396, "s": 88372, "text": "Syntax can be confusing" }, { "code": null, "e": 88458, "s": 88396, "text": "Coding style in Perl can be unique and bog down collaboration" }, { "code": null, "e": 88520, "s": 88458, "text": "Coding style in Perl can be unique and bog down collaboration" }, { "code": null, "e": 88555, "s": 88520, "text": "Perl is not really Object Oriented" }, { "code": null, "e": 88590, "s": 88555, "text": "Perl is not really Object Oriented" }, { "code": null, "e": 88692, "s": 88590, "text": "Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used." }, { "code": null, "e": 88794, "s": 88692, "text": "Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used." }, { "code": null, "e": 88886, "s": 88794, "text": "When deciding whether to use Perl, Python or PHP; the following questions should be asked −" }, { "code": null, "e": 88930, "s": 88886, "text": "Will this application ever need versioning?" }, { "code": null, "e": 88978, "s": 88930, "text": "Will other people ever need to modify the code?" }, { "code": null, "e": 89026, "s": 88978, "text": "Will other people need to use this application?" }, { "code": null, "e": 89101, "s": 89026, "text": "Will this application ever be used on another machine or CPU architecture?" }, { "code": null, "e": 89214, "s": 89101, "text": "If the answers to all the above are \"no\", Perl is a good choice and may speed things up in terms of end-results." }, { "code": null, "e": 89309, "s": 89214, "text": "With this mentioned, let's configure our CentOS server to use the most recent version of Perl." }, { "code": null, "e": 89547, "s": 89309, "text": "Before installing Perl, we need to understand the support for Perl. Officially, Perl is only supported far back as the last two stable versions. So, we want to be sure to keep our development environment isolated from the CentOS version." }, { "code": null, "e": 89878, "s": 89547, "text": "The reason for isolation is: if someone releases a tool in Perl to the CentOS community, more than likely it will be modified to work on Perl as shipped with CentOS. However, we also want to have the latest version installed for development purposes. Like Python, CentOS ships Perl focused on the reliability and not cutting edge." }, { "code": null, "e": 89931, "s": 89878, "text": "Let's check our current version of Perl on CentOS 7." }, { "code": null, "e": 90043, "s": 89931, "text": "[root@CentOS]# perl -v \nThis is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi\n" }, { "code": null, "e": 90141, "s": 90043, "text": "We are currently running Perl 5.16.3. The most current version as of this writing is: perl-5.24.0" }, { "code": null, "e": 90380, "s": 90141, "text": "We definitely want to upgrade our version, being able to use up-to-date Perl modules in our code. Fortunately, there is a great tool for maintaining Perl environments and keeping our CentOS version of Perl isolated. It is called perlbrew." }, { "code": null, "e": 90405, "s": 90380, "text": "Let's install Perl Brew." }, { "code": null, "e": 90778, "s": 90405, "text": "[root@CentOS]# curl -L https://install.perlbrew.pl | bash \n% Total % Received % Xferd Average Speed Time Time Time Current \n Dload Upload Total Spent Left Speed \n100 170 100 170 0 0 396 0 --:--:-- --:--:-- --:--:-- 397 \n100 1247 100 1247 0 0 1929 0 --:--:-- --:--:-- --:--:-- 1929\n" }, { "code": null, "e": 90874, "s": 90778, "text": "Now that we have Perl Brew installed, let's make an environment for the latest version of Perl." }, { "code": null, "e": 91038, "s": 90874, "text": "First, we will need the currently installed version of Perl to bootstrap the perlbrew install. Thus, let's get some needed Perl modules from the CentOS repository." }, { "code": null, "e": 91149, "s": 91038, "text": "Note − When available we always want to use CentOS Perl modules versus CPAN with our CentOS Perl installation." }, { "code": null, "e": 91198, "s": 91149, "text": "Step 1 − Install CentOS Perl Make::Maker module." }, { "code": null, "e": 91260, "s": 91198, "text": "[root@CentOS]# yum -y install perl-ExtUtils-MakeMaker.noarch\n" }, { "code": null, "e": 91305, "s": 91260, "text": "Step 2 − Install the latest version of perl." }, { "code": null, "e": 91429, "s": 91305, "text": "[root@CentOS build]# source ~/perl5/perlbrew/etc/bashrc\n[root@CentOS build]# perlbrew install -n -j4 --threads perl-5.24.1\n" }, { "code": null, "e": 91477, "s": 91429, "text": "The options we chose for our Perl install are −" }, { "code": null, "e": 91490, "s": 91477, "text": "n − No tests" }, { "code": null, "e": 91503, "s": 91490, "text": "n − No tests" }, { "code": null, "e": 91598, "s": 91503, "text": "j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU)" }, { "code": null, "e": 91693, "s": 91598, "text": "j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU)" }, { "code": null, "e": 91737, "s": 91693, "text": "threads − Enable threading support for Perl" }, { "code": null, "e": 91781, "s": 91737, "text": "threads − Enable threading support for Perl" }, { "code": null, "e": 91882, "s": 91781, "text": "After our installation has been performed successfully, let's switch to our newest Perl environment." }, { "code": null, "e": 92627, "s": 91882, "text": "[root@CentOS]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1\n\nA sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it.\n\n[root@CentOS]# perl -v\n\nThis is perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linuxthread-multi\n\n(with 1 registered patch, see perl -V for more detail)\n\nCopyright 1987-2017, Larry Wall\n\nPerl may be copied only under the terms of either the Artistic License or the GNU General\nPublic License, which may be found in the Perl 5 source kit.\n\nComplete documentation for Perl, including FAQ lists, should be found on this system \nusing \"man perl\" or \"perldoc perl\". If you have access to the Internet, point your \nbrowser at http://www.perl.org/, the Perl Home Page.\n\n[root@CentOS]#\n" }, { "code": null, "e": 92725, "s": 92627, "text": "Simple perl script printing perl version running within the context of our perlbrew environment −" }, { "code": null, "e": 92790, "s": 92725, "text": "[root@CentOS]# cat ./ver.pl \n#!/usr/bin/perl\nprint $^V . \"\\n\";\n" }, { "code": null, "e": 92846, "s": 92790, "text": "[root@CentOS]# perl ./ver.pl \nv5.24.1 \n[root@CentOS]#\n" }, { "code": null, "e": 92920, "s": 92846, "text": "Once perl is installed, we can load cpan modules with perl brew's cpanm −" }, { "code": null, "e": 92960, "s": 92920, "text": "[root@CentOS]# perl-brew install-cpanm\n" }, { "code": null, "e": 93071, "s": 92960, "text": "Now let's use the cpanm installer to make the LWP module with our current Perl version of 5.24.1 in perl brew." }, { "code": null, "e": 93131, "s": 93071, "text": "Step 1 − Switch to the context of our current Perl version." }, { "code": null, "e": 93195, "s": 93131, "text": "[root@CentOS ~]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1\n" }, { "code": null, "e": 93284, "s": 93195, "text": "A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it." }, { "code": null, "e": 93302, "s": 93284, "text": "[root@CentOS ~]#\n" }, { "code": null, "e": 93347, "s": 93302, "text": "Step 2 − Install LWP User Agent Perl Module." }, { "code": null, "e": 93410, "s": 93347, "text": "[root@CentOS ~]# ~/perl5/perlbrew/bin/cpanm -i LWP::UserAgent\n" }, { "code": null, "e": 93481, "s": 93410, "text": "Step 3 − Now let's test our Perl environment with the new CPAN module." }, { "code": null, "e": 93791, "s": 93481, "text": "[root@CentOS ~]# cat ./get_header.pl \n#!/usr/bin/perl \nuse LWP; \nmy $browser = LWP::UserAgent->new(); \nmy $response = $browser->get(\"http://www.slcc.edu/\"); \nunless(!$response->is_success) { \n print $response->header(\"Server\"); \n}\n\n[root@CentOS ~]# perl ./get_header.pl \nMicrosoft-IIS/8.5 [root@CentOS ~]#" }, { "code": null, "e": 93927, "s": 93791, "text": "There you have it! Perl Brew makes isolating perl environments a snap and can be considered as a best practice as things get with Perl." }, { "code": null, "e": 94454, "s": 93927, "text": "LDAP known as Light Weight Directory Access Protocol is a protocol used for accessing X.500 service containers within an enterprise known from a directory. Those who are familiar with Windows Server Administration can think of LDAP as being very similar in nature to Active Directory. It is even a widely used concept of intertwining Windows workstations into an OpenLDAP CentOS enterprise. On the other spectrum, a CentOS Linux workstation can share resources and participate with the basic functionality in a Windows Domain." }, { "code": null, "e": 94675, "s": 94454, "text": "Deploying LDAP on CentOS as a Directory Server Agent, Directory System Agent, or DSA (these acronyms are all one and the same) is similar to older Novell Netware installations using the Directory Tree structure with NDS." }, { "code": null, "e": 95074, "s": 94675, "text": "LDAP was basically created as an efficient way to access X.500 directories with enterprise resources. Both X.500 and LDAP share the same characteristics and are so similar that LDAP clients can access X.500 directories with some helpers. While LDAP also has its own directory server called slapd. The main difference between LDAP and DAP is, the lightweight version is designed to operate over TCP." }, { "code": null, "e": 95352, "s": 95074, "text": "While DAP uses the full OSI Model. With the advent of the Internet, TCP/IP and Ethernet prominence in networks of today, it is rare to come across a Directory Services implantation using both DAP and native X.500 enterprise directories outside specific legacy computing models." }, { "code": null, "e": 95414, "s": 95352, "text": "The main components used with openldap for CentOS Linux are −" }, { "code": null, "e": 95955, "s": 95414, "text": "Note − When naming your enterprise, it is a best practice to use the .local TLD. Using a .net or .com can cause difficulties when segregating an online and internal domain infrastructure. Imagine the extra work for a company internally using acme.com for both external and internal operations. Hence, it can be wise to have Internet resources called acme.com or acme.net. Then, the local networking enterprise resources is depicted as acme.local. This will entail configuring DNS records, but will pay in simplicity, eloquence and security." }, { "code": null, "e": 96042, "s": 95955, "text": "Install the openldap, openldap-servers, openldap-clients and migrationstools from YUM." }, { "code": null, "e": 97949, "s": 96042, "text": "[root@localhost]# yum -y install openldap openldap-servers openldap-clients\nmigration tools\n Loaded plugins: fastestmirror, langpacks\n updates\n | 3.4 kB 00:00:00\n updates/7/x86_64/primary_db\n | 2.2 MB 00:00:05\n Determining fastest mirrors\n (1/2): extras/7/x86_64/primary_db\n | 121 kB 00:00:01\n (2/2): base/7/x86_64/primary_db\n | 5.6 MB 00:00:16\n Package openldap-2.4.40-13.el7.x86_64 already installed and latest version\n Resolving Dependencies\n --> Running transaction check\n ---> Package openldap-clients.x86_64 0:2.4.40-13.el7 will be installed\n ---> Package openldap-servers.x86_64 0:2.4.40-13.el7 will be installed\n --> Finished Dependency Resolution\n base/7/x86_64/group_gz\n | 155 kB 00:00:00\n \n Dependencies Resolved\n \n=============================================================================== \n=============================================================================== \nPackage Arch\nVersion Repository Size \n=============================================================================== \n=============================================================================== \nInstalling: \nopenldap-clients x86_64\n2.4.40-13.el7 base 188 k \nopenldap-servers x86_64\n2.4.40-13.el7 base 2.1 M \n\nTransaction Summary \n=============================================================================== \n===============================================================================\nInstall 2 Packages\n\nTotal download size: 2.3 M \nInstalled size: 5.3 M \nDownloading packages:\n\nInstalled: \nopenldap-clients.x86_64 0:2.4.40-13.el7 \nopenldap-servers.x86_64 0:2.4.40-13.el7 \nComplete! \n[root@localhost]#\n" }, { "code": null, "e": 97997, "s": 97949, "text": "Now, let's start and enable the slapd service −" }, { "code": null, "e": 98075, "s": 97997, "text": "[root@centos]# systemctl start slapd \n[root@centos]# systemctl enable slapd\n" }, { "code": null, "e": 98152, "s": 98075, "text": "At this point, let's assure we have our openldap structure in /etc/openldap." }, { "code": null, "e": 98262, "s": 98152, "text": "root@localhost]# ls /etc/openldap/ \ncerts check_password.conf ldap.conf schema slapd.d\n[root@localhost]#\n" }, { "code": null, "e": 98307, "s": 98262, "text": "Then make sure our slapd service is running." }, { "code": null, "e": 98545, "s": 98307, "text": "root@centos]# netstat -antup | grep slapd\ntcp 0 0 0.0.0.0:389 0.0.0.0:* LISTEN 1641/slapd\ntcp6 0 0 :::389 :::* LISTEN 1641/slapd\n \n[root@centos]#\n" }, { "code": null, "e": 98595, "s": 98545, "text": "Next, let's configure our Open LDAP installation." }, { "code": null, "e": 98644, "s": 98595, "text": "Make sure our system ldap user has been created." }, { "code": null, "e": 98732, "s": 98644, "text": "[root@localhost]# id ldap \nuid=55(ldap) gid=55(ldap) groups=55(ldap)\n[root@localhost]#\n" }, { "code": null, "e": 98763, "s": 98732, "text": "Generate our LDAP credentials." }, { "code": null, "e": 98897, "s": 98763, "text": "[root@localhost]# slappasswd \nNew password: \nRe-enter new password: \n{SSHA}20RSyjVv6S6r43DFPeJgASDLlLoSU8g.a10\n\n[root@localhost]#\n" }, { "code": null, "e": 98941, "s": 98897, "text": "We need to save the output from slappasswd." }, { "code": null, "e": 99005, "s": 98941, "text": "Step 1 − Configure LDAP for domain and add administrative user." }, { "code": null, "e": 99116, "s": 99005, "text": "First, we want to set up our openLDAP environment. Following is a template to use with the ldapmodify command." }, { "code": null, "e": 99443, "s": 99116, "text": "dn: olcDatabase={2}hdb,cn=config \nchangetype: modify \nreplace: olcSuffix \nolcSuffix: dc=vmnet,dc=local \ndn: olcDatabase = {2}hdb,cn=config \nchangetype: modify \nreplace: olcRootDN \nolcRootDN: cn=ldapadm,dc=vmnet,dc=local \ndn: olcDatabase = {2}hdb,cn=config \nchangetype: modify \nreplace: olcRootPW \nolcRootPW: <output from slap\n" }, { "code": null, "e": 99551, "s": 99443, "text": "Make changes to: /etc/openldap/slapd.d/cn=config/olcDatabase = {1}monitor.ldif with the ldapmodify command." }, { "code": null, "e": 99945, "s": 99551, "text": "[root@localhost]# ldapmodify -Y EXTERNAL -H ldapi:/// -f /home/rdc/Documents/db.ldif \nSASL/EXTERNAL authentication started \nSASL username: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth \nSASL SSF: 0 \nmodifying entry \"olcDatabase = {2}hdb,cn=config\" \nmodifying entry \"olcDatabase = {2}hdb,cn=config\" \nmodifying entry \"olcDatabase = {2}hdb,cn=config\" \n\n[root@localhost cn=config]#\n" }, { "code": null, "e": 99990, "s": 99945, "text": "Let's check the modified LDAP configuration." }, { "code": null, "e": 100874, "s": 99990, "text": "root@linux1 ~]# vi /etc/openldap/slapd.d/cn=config/olcDatabase={2}hdb.ldif\n\n[root@centos]# cat /etc/openldap/slapd.d/cn\\=config/olcDatabase\\=\\{2\\}hdb.ldif\n # AUTO-GENERATED FILE - DO NOT EDIT!! Use ldapmodify. \n # CRC32 a163f14c\ndn: olcDatabase = {2}hdb\nobjectClass: olcDatabaseConfig\nobjectClass: olcHdbConfig\nolcDatabase: {2}hdb\nolcDbDirectory: /var/lib/ldap\nolcDbIndex: objectClass eq,pres\nolcDbIndex: ou,cn,mail,surname,givenname eq,pres,sub\nstructuralObjectClass: olcHdbConfig\nentryUUID: 1bd9aa2a-8516-1036-934b-f7eac1189139\ncreatorsName: cn=config\ncreateTimestamp: 20170212022422Z\nolcSuffix: dc=vmnet,dc=local\nolcRootDN: cn=ldapadm,dc=vmnet,dc=local\nolcRootPW:: e1NTSEF1bUVyb1VzZTRjc2dkYVdGaDY0T0k = \nentryCSN: 20170215204423.726622Z#000000#000#000000 \nmodifiersName: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth\nmodifyTimestamp: 20170215204423Z\n\n[root@centos]#\n" }, { "code": null, "e": 100941, "s": 100874, "text": "As you can see, our LDAP enterprise modifications were successful." }, { "code": null, "e": 101088, "s": 100941, "text": "Next, we want to create an self-signed ssl certificate for OpenLDAP. This will secure the communication between the enterprise server and clients." }, { "code": null, "e": 101144, "s": 101088, "text": "Step 2 − Create a self-signed certificate for OpenLDAP." }, { "code": null, "e": 101432, "s": 101144, "text": "We will use openssl to create a self-signed ssl certificate. Go to the next chapter, Create LDAP SSL Certificate with openssl for instructions to secure communications with OpenLDAP. Then when ssl certificates are configured, we will have completed our OpenLDAP enterprise configuration." }, { "code": null, "e": 101507, "s": 101432, "text": "Step 3 − Configure OpenLDAP to use secure communications with certificate." }, { "code": null, "e": 101572, "s": 101507, "text": "Create a certs.ldif file in vim with the following information −" }, { "code": null, "e": 101844, "s": 101572, "text": "dn: cn=config\nchangetype: modify\nreplace: olcTLSCertificateFile\nolcTLSCertificateFile: /etc/openldap/certs/yourGeneratedCertFile.pem\n\ndn: cn=config\nchangetype: modify\nreplace: olcTLSCertificateKeyFile\nolcTLSCertificateKeyFile: /etc/openldap/certs/youGeneratedKeyFile.pem\n" }, { "code": null, "e": 101938, "s": 101844, "text": "Next, again, use the ldapmodify command to merge the changes into the OpenLDAP configuration." }, { "code": null, "e": 102177, "s": 101938, "text": "[root@centos rdc]# ldapmodify -Y EXTERNAL -H ldapi:/// -f certs.ldif\nSASL/EXTERNAL authentication started\nSASL username: gidNumber = 0+uidNumber = 0,cn=peercred,cn=external,cn=auth\nSASL SSF: 0\nmodifying entry \"cn=config\"\n\n[root@centos]#\n" }, { "code": null, "e": 102225, "s": 102177, "text": "Finally, let's test our OpenLADP configuration." }, { "code": null, "e": 102300, "s": 102225, "text": "[root@centos]# slaptest -u \nconfig file testing succeeded \n[root@centos]#\n" }, { "code": null, "e": 102332, "s": 102300, "text": "Step 4 − Set up slapd database." }, { "code": null, "e": 102442, "s": 102332, "text": "cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG && \nchown ldap:ldap /var/lib/ldap/*\n" }, { "code": null, "e": 102471, "s": 102442, "text": "Updates the OpenLDAP Schema." }, { "code": null, "e": 102508, "s": 102471, "text": "Add the cosine and nis LDAP schemas." }, { "code": null, "e": 102720, "s": 102508, "text": "ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif\nldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif\nldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif\n" }, { "code": null, "e": 102808, "s": 102720, "text": "Finally, create the enterprise schema and add it to the current OpenLDAP configuration." }, { "code": null, "e": 102888, "s": 102808, "text": "Following is for a domain called vmnet.local with an LDAP Admin called ldapadm." }, { "code": null, "e": 103219, "s": 102888, "text": "dn: dc=vmnet,dc=local\ndc: vmnet\nobjectClass: top\nobjectClass: domain\n\ndn: cn=ldapadm ,dc=vmnet,dc=local\nobjectClass: organizationalRole\ncn: ldapadm\ndescription: LDAP Manager\n\ndn: ou = People,dc=vmnet,dc=local\nobjectClass: organizationalUnit\nou: People\n\ndn: ou = Group,dc=vmnet,dc=local \nobjectClass: organizationalUnit \nou: Group\n" }, { "code": null, "e": 103274, "s": 103219, "text": "Finally, import this into the current OpenLDAP schema." }, { "code": null, "e": 103573, "s": 103274, "text": "[root@centos]# ldapadd -x -W -D \"cn=ldapadm,dc=vmnet,dc=local\" -f ./base.ldif\n Enter LDAP Password:\nadding new entry \"dc=vmnet,dc=local\"\n\nadding new entry \"cn=ldapadm ,dc=vmnet,dc=local\"\n\nadding new entry \"ou=People,dc=vmnet,dc=local\"\n\nadding new entry \"ou=Group,dc=vmnet,dc=local\"\n\n[root@centos]#\n" }, { "code": null, "e": 103619, "s": 103573, "text": "Step 5 − Set up an OpenLDAP Enterprise Users." }, { "code": null, "e": 103763, "s": 103619, "text": "Open vim or your favorite text editor and copy the following format. This is setup for a user named \"entacct\" on the \"vmnet.local\" LDAP domain." }, { "code": null, "e": 104150, "s": 103763, "text": "dn: uid=entacct,ou=People,dc=vmnet,dc=local \nobjectClass: top\nobjectClass: account \nobjectClass: posixAccount \nobjectClass: shadowAccount \ncn: entacct \nuid: entacct \nuidNumber: 9999 \ngidNumber: 100 \nhomeDirectory: /home/enyacct \nloginShell: /bin/bash \ngecos: Enterprise User Account 001 \nuserPassword: {crypt}x \nshadowLastChange: 17058 \nshadowMin: 0 \nshadowMax: 99999 \nshadowWarning: 7\n" }, { "code": null, "e": 104214, "s": 104150, "text": "Now import the above files, as saved, into the OpenLdap Schema." }, { "code": null, "e": 104393, "s": 104214, "text": "[root@centos]# ldapadd -x -W -D \"cn=ldapadm,dc=vmnet,dc=local\" -f entuser.ldif \n Enter LDAP Password:\nadding new entry \"uid=entacct,ou=People,dc=vmnet,dc=local\" \n\n[root@centos]#\n" }, { "code": null, "e": 104484, "s": 104393, "text": "Before the users can access the LDAP Enterprise, we need to assign a password as follows −" }, { "code": null, "e": 104597, "s": 104484, "text": "ldappasswd -s password123 -W -D \"cn=ldapadm,dc=entacct,dc=local\" -x \"uid=entacct \n,ou=People,dc=vmnet,dc=local\"\n" }, { "code": null, "e": 104636, "s": 104597, "text": "-s specifies the password for the user" }, { "code": null, "e": 104692, "s": 104636, "text": "-x is the username to which password updated is applied" }, { "code": null, "e": 104760, "s": 104692, "text": "-D is the *distinguished name\" to authenticate against LDAP schema." }, { "code": null, "e": 104845, "s": 104760, "text": "Finally, before logging into the Enterprise account, let's check our OpenLDAP entry." }, { "code": null, "e": 105459, "s": 104845, "text": "[root@centos rdc]# ldapsearch -x cn=entacct -b dc=vmnet,dc=local\n # extended LDIF\n #\n # LDAPv3\n # base <dc=vmnet,dc=local> with scope subtree\n # filter: cn=entacct\n # requesting: ALL \n # \n # entacct, People, vmnet.local \ndn: uid=entacct,ou=People,dc=vmnet,dc=local \nobjectClass: top \nobjectClass: account \nobjectClass: posixAccount \nobjectClass: shadowAccount \ncn: entacct \nuid: entacct \nuidNumber: 9999 \ngidNumber: 100 \nhomeDirectory: /home/enyacct \nloginShell: /bin/bash \ngecos: Enterprise User Account 001 \nuserPassword:: e2NyeXB0fXg= \nshadowLastChange: 17058 \nshadowMin: 0 \nshadowMax: 99999 \nshadowWarning: 7\n" }, { "code": null, "e": 105672, "s": 105459, "text": "Converting things like /etc/passwd and /etc/groups to OpenLDAP authentication requires the use of migration tools. These are included in the migrationtools package. Then, installed into /usr/share/migrationtools." }, { "code": null, "e": 106497, "s": 105672, "text": "[root@centos openldap-servers]# ls -l /usr/share/migrationtools/\ntotal 128\n-rwxr-xr-x. 1 root root 2652 Jun 9 2014 migrate_aliases.pl\n-rwxr-xr-x. 1 root root 2950 Jun 9 2014 migrate_all_netinfo_offline.sh\n-rwxr-xr-x. 1 root root 2946 Jun 9 2014 migrate_all_netinfo_online.sh\n-rwxr-xr-x. 1 root root 3011 Jun 9 2014 migrate_all_nis_offline.sh\n-rwxr-xr-x. 1 root root 3006 Jun 9 2014 migrate_all_nis_online.sh\n-rwxr-xr-x. 1 root root 3164 Jun 9 2014 migrate_all_nisplus_offline.sh\n-rwxr-xr-x. 1 root root 3146 Jun 9 2014 migrate_all_nisplus_online.sh\n-rwxr-xr-x. 1 root root 5267 Jun 9 2014 migrate_all_offline.sh\n-rwxr-xr-x. 1 root root 7468 Jun 9 2014 migrate_all_online.sh\n-rwxr-xr-x. 1 root root 3278 Jun 9 2014 migrate_automount.pl\n-rwxr-xr-x. 1 root root 2608 Jun 9 2014 migrate_base.pl\n" }, { "code": null, "e": 106588, "s": 106497, "text": "Step 6 − Finally, we need to allow access to the slapd service so it can service requests." }, { "code": null, "e": 106656, "s": 106588, "text": "firewall-cmd --permanent --add-service=ldap \nfirewall-cmd --reload\n" }, { "code": null, "e": 106777, "s": 106656, "text": "Configuring LDAP client access requires the following packages on the client: openldap, open-ldap clients, and nss_ldap." }, { "code": null, "e": 106845, "s": 106777, "text": "Configuring LDAP authentication for client systems is a bit easier." }, { "code": null, "e": 106883, "s": 106845, "text": "Step 1 − Install dependent packeges −" }, { "code": null, "e": 106932, "s": 106883, "text": "# yum install -y openldap-clients nss-pam-ldapd\n" }, { "code": null, "e": 106988, "s": 106932, "text": "Step 2 − Configure LDAP authentication with authconfig." }, { "code": null, "e": 107114, "s": 106988, "text": "authconfig --enableldap --enableldapauth --ldapserver=10.25.0.1 --\nldapbasedn=\"dc=vmnet,dc=local\" --enablemkhomedir --update\n" }, { "code": null, "e": 107146, "s": 107114, "text": "Step 3 − Restart nslcd service." }, { "code": null, "e": 107172, "s": 107146, "text": "systemctl restart nslcd\n" }, { "code": null, "e": 107516, "s": 107172, "text": "TLS is the new standard for socket layer security, proceeding SSL. TLS offers better encryption standards with other security and protocol wrapper features advancing SSL. Often, the terms TLS and SSL are used interchangeably. However, as a professional CentOS Administrator, it is important to note the differences and history separating each." }, { "code": null, "e": 107792, "s": 107516, "text": "SSL goes up to version 3.0. SSL was developed and promoted as an industry standard under Netscape. After Netscape was purchased by AOL (an ISP popular in the 90's otherwise known as America Online) AOL never really promoted the change needed for security improvements to SSL." }, { "code": null, "e": 108168, "s": 107792, "text": "At version 3.1, SSL technology moved into the open systems standards and was changed to TLS. Since copyrights on SSL were still owned by AOL a new term was coined − TLS - Transport Layer Security. So it is important to acknowledge that TLS is in fact different from SSL. Especially, as older SSL technologies have known security issues and some are considered obsolete today." }, { "code": null, "e": 108326, "s": 108168, "text": "Note − This tutorial will use the term TLS when speaking of technologies 3.1 and higher. Then SSL when commenting specific to SSL technologies 3.0 and lower." }, { "code": null, "e": 108758, "s": 108326, "text": "The following table shows how TLS and SSL versioning would relate to one another. I have heard a few people speak in terms of SSL version 3.2. However, they probably got the terminology from reading a blog. As a professional administrator, we always want to use the standard terminology. Hence, while speaking SSL should be a reference to past technologies. Simple things can make a CentOS job seeker look like a seasoned CS Major." }, { "code": null, "e": 109050, "s": 108758, "text": "TLS performs two main functions important to the users of the Internet today: One, it verifies who a party is, known as authentication. Two, it offers end-to-end encryption at the transport layer for upper level protocols that lack this native feature (ftp, http, email protocols, and more)." }, { "code": null, "e": 109426, "s": 109050, "text": "The first, verifies who a party is and is important to security as end-to-end encryption. If a consumer has an encrypted connection to a website that is not authorized to take payment, financial data is still at risk. This is what every phishing site will fail to have: a properly signed TLS certificate verifying website operators are who they claim to be from a trusted CA." }, { "code": null, "e": 109705, "s": 109426, "text": "There are only two methods to get around not having a properly signed certificate: trick the user into allowing trust of a web-browser for a self-signed certificate or hope the user is not tech savvy and will not know the importance of a trusted Certificate Authority (or a CA)." }, { "code": null, "e": 110145, "s": 109705, "text": "In this tutorial, we will be using what is known as a self-signed certificate. This means, without explicitly giving this certificate the status of trusted in every web browser visiting the web-site, an error will be displayed discouraging the users from visiting the site. Then, it will make the user jump though a few actions before accessing a site with a self-signed certificate. Remember for the sake of security this is a good thing." }, { "code": null, "e": 110303, "s": 110145, "text": "openssl is the standard for open-source implementations of TLS. openssl is used on systems such as Linux, BSD distributions, OS X, and even supports Windows." }, { "code": null, "e": 110619, "s": 110303, "text": "openssl is important, as it provides transport layer security and abstracts the detailed programming of Authentication and end-to-end encryption for a developer. This is why openssl is used with almost every single open-source application using TLS. It is also installed by default on every modern version of Linux." }, { "code": null, "e": 111030, "s": 110619, "text": "By default, openssl should be installed on CentOS from at least version 5 onwards. Just to assure, let's try installing openssl via YUM. Just run install, as YUM is intelligent enough to let us know if a package is already installed. If we are running an older version of CentOS for compatibility reasons, doing a yum -y install will ensure openssl is updated against the semi-recent heart-bleed vulnerability." }, { "code": null, "e": 111112, "s": 111030, "text": "When running the installer, it was found there was actually an update to openssl." }, { "code": null, "e": 112302, "s": 111112, "text": "[root@centos]# yum -y install openssl\nResolving Dependencies\n--> Running transaction check\n---> Package openssl.x86_64 1:1.0.1e-60.el7 will be updated\n---> Package openssl.x86_64 1:1.0.1e-60.el7_3.1 will be an update\n--> Processing Dependency: openssl-libs(x86-64) = 1:1.0.1e-60.el7_3.1 for \npackage: 1:openssl-1.0.1e-60.el7_3.1.x86_64\n--> Running transaction check\n---> Package openssl-libs.x86_64 1:1.0.1e-60.el7 will be updated\n---> Package openssl-libs.x86_64 1:1.0.1e-60.el7_3.1 will be an update\n--> Finished Dependency Resolution \nDependencies Resolved\n\n===============================================================================\n=============================================================================== \n Package Arch\n Version Repository Size \n=============================================================================== \n=============================================================================== \nUpdating: \nopenssl x86_64 \n1:1.0.1e-60.el7_3.1 updates 713 k\nUpdating for dependencies:\n" }, { "code": null, "e": 112383, "s": 112302, "text": "This is a method to create a self-signed for our previous OpenLDAP installation." }, { "code": null, "e": 112430, "s": 112383, "text": "To create an self-signed OpenLDAP Certificate." }, { "code": null, "e": 113572, "s": 112430, "text": "openssl req -new -x509 -nodes -out /etc/openldap/certs/myldaplocal.pem -keyout\n/etc/openldap/certs/myldaplocal.pem -days 365\n\n[root@centos]# openssl req -new -x509 -nodes -out /etc/openldap/certs/vmnet.pem \n-keyout /etc/openldap/certs/vmnet.pem -days 365 \nGenerating a 2048 bit RSA private key\n.............................................+++\n................................................+++\nwriting new private key to '/etc/openldap/certs/vmnet.pem'\n-----\nYou are about to be asked to enter information that will be incorporated\ninto your certificate request.\nWhat you are about to enter is what is called a Distinguished Name or a DN.\nThere are quite a few fields but you can leave some blank\nFor some fields there will be a default value,\nIf you enter '.', the field will be left blank.\n-----\nCountry Name (2 letter code) [XX]:US\nState or Province Name (full name) []:Califonia\nLocality Name (eg, city) [Default City]:LA\nOrganization Name (eg, company) [Default Company Ltd]:vmnet\nOrganizational Unit Name (eg, section) []:\nCommon Name (eg, your name or your server's hostname) []:centos\nEmail Address []:bob@bobber.net\n[root@centos]#\n" }, { "code": null, "e": 113643, "s": 113572, "text": "Now our OpenLDAP certificates should be placed in /etc/openldap/certs/" }, { "code": null, "e": 113772, "s": 113643, "text": "[root@centos]# ls /etc/openldap/certs/*.pem \n/etc/openldap/certs/vmnetcert.pem /etc/openldap/certs/vmnetkey.pem\n[root@centos]#\n" }, { "code": null, "e": 113977, "s": 113772, "text": "As you can see, we have both the certificate and key installed in the /etc/openldap/certs/ directories. Finally, we need to change the permissions to each, since they are currently owned by the root user." }, { "code": null, "e": 114254, "s": 113977, "text": "[root@centos]# chown -R ldap:ldap /etc/openldap/certs/*.pem\n[root@centos]# ls -ld /etc/openldap/certs/*.pem\n-rw-r--r--. 1 ldap ldap 1395 Feb 20 10:00 /etc/openldap/certs/vmnetcert.pem \n-rw-r--r--. 1 ldap ldap 1704 Feb 20 10:00 /etc/openldap/certs/vmnetkey.pem\n[root@centos]#\n" }, { "code": null, "e": 114527, "s": 114254, "text": "In this tutorial, we will assume Apache is already installed. We did install Apache in another tutorial (configuring CentOS Firewall) and will go into advanced installation of Apache for a future tutorial. So, if you have not already installed Apache, please follow along." }, { "code": null, "e": 114590, "s": 114527, "text": "Once Apache HTTPd can be installed using the following steps −" }, { "code": null, "e": 114640, "s": 114590, "text": "Step 1 − Install mod_ssl for Apache httpd server." }, { "code": null, "e": 114742, "s": 114640, "text": "First we need to configure Apache with mod_ssl. Using the YUM package manager this is pretty simple −" }, { "code": null, "e": 114781, "s": 114742, "text": "[root@centos]# yum -y install mod_ssl\n" }, { "code": null, "e": 114857, "s": 114781, "text": "Then reload your Apache daemon to ensure Apache uses the new configuration." }, { "code": null, "e": 114896, "s": 114857, "text": "[root@centos]# systemctl reload httpd\n" }, { "code": null, "e": 114978, "s": 114896, "text": "At this point, Apache is configured to support TLS connections on the local host." }, { "code": null, "e": 115027, "s": 114978, "text": "Step 2 − Create the self-signed ssl certificate." }, { "code": null, "e": 115081, "s": 115027, "text": "First, let's configure our private TLS key directory." }, { "code": null, "e": 115164, "s": 115081, "text": "[root@centos]# mkdir /etc/ssl/private \n[root@centos]# chmod 700 /etc/ssl/private/\n" }, { "code": null, "e": 115322, "s": 115164, "text": "Note − Be sure only the root has read/write access to this directory. With world read/write access, your private key can be used to decrypt sniffed traffic. " }, { "code": null, "e": 115364, "s": 115322, "text": "Generating the certificate and key files." }, { "code": null, "e": 115927, "s": 115364, "text": "[root@centos]# sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout \n/etc/ssl/private/self-gen-apache.key -out /etc/ssl/certs/self-sign-apache.crt \nGenerating a 2048 bit RSA private key\n..........+++\n....+++\n-----\nCountry Name (2 letter code) [XX]:US\nState or Province Name (full name) []:xx\nLocality Name (eg, city) [Default City]:xxxx\nOrganization Name (eg, company) [Default Company Ltd]:VMNET\nOrganizational Unit Name (eg, section) []:\nCommon Name (eg, your name or your server's hostname) []:centos.vmnet.local\nEmail Address []:\n\n[root@centos]#\n" }, { "code": null, "e": 116022, "s": 115927, "text": "Note − You can use public IP Address of the server if you don't have a registered domain name." }, { "code": null, "e": 116061, "s": 116022, "text": "Let's take a look at our certificate −" }, { "code": null, "e": 117670, "s": 116061, "text": "[root@centos]# openssl x509 -in self-sign-apache.crt -text -noout\nCertificate:\n Data:\n Version: 3 (0x2)\n Serial Number: 17620849408802622302 (0xf489d52d94550b5e)\n Signature Algorithm: sha256WithRSAEncryption\n Issuer: C=US, ST=UT, L=xxxx, O=VMNET, CN=centos.vmnet.local\n Validity\n Not Before: Feb 24 07:07:55 2017 GMT\n Not After : Feb 24 07:07:55 2018 GMT\n Subject: C=US, ST=UT, L=xxxx, O=VMNET, CN=centos.vmnet.local\n Subject Public Key Info:\n Public Key Algorithm: rsaEncryption\n Public-Key: (2048 bit)\n Modulus:\n 00:c1:74:3e:fc:03:ca:06:95:8d:3a:0b:7e:1a:56:\n f3:8d:de:c4:7e:ee:f9:fa:79:82:bf:db:a9:6d:2a:\n 57:e5:4c:31:83:cf:92:c4:e7:16:57:59:02:9e:38:\n 47:00:cd:b8:31:b8:34:55:1c:a3:5d:cd:b4:8c:b0:\n 66:0c:0c:81:8b:7e:65:26:50:9d:b7:ab:78:95:a5:\n 31:5e:87:81:cd:43:fc:4d:00:47:5e:06:d0:cb:71:\n 9b:2a:ab:f0:90:ce:81:45:0d:ae:a8:84:80:c5:0e:\n 79:8a:c1:9b:f4:38:5d:9e:94:4e:3a:3f:bd:cc:89:\n e5:96:4a:44:f5:3d:13:20:3d:6a:c6:4d:91:be:aa:\n ef:2e:d5:81:ea:82:c6:09:4f:40:74:c1:b1:37:6c:\n ff:50:08:dc:c8:f0:67:75:12:ab:cd:8d:3e:7b:59:\n e0:83:64:5d:0c:ab:93:e2:1c:78:f0:f4:80:9e:42: \n 7d:49:57:71:a2:96:c6:b8:44:16:93:6c:62:87:0f:\n 5c:fe:df:29:89:03:6e:e5:6d:db:0a:65:b2:5e:1d:\n c8:07:3d:8a:f0:6c:7f:f3:b9:32:b4:97:f6:71:81:\n 6b:97:e3:08:bd:d6:f8:19:40:f1:15:7e:f2:fd:a5:\n 12:24:08:39:fa:b6:cc:69:4e:53:1d:7e:9a:be:4b:\n" }, { "code": null, "e": 117744, "s": 117670, "text": "Here is an explanation for each option we used with the openssl command −" }, { "code": null, "e": 117825, "s": 117744, "text": "Next, we want to create a Diffie-Heliman group for negotiating PFS with clients." }, { "code": null, "e": 117889, "s": 117825, "text": "[centos#] openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048\n" }, { "code": null, "e": 117926, "s": 117889, "text": "This will take from 5 to 15 minutes." }, { "code": null, "e": 118123, "s": 117926, "text": "Perfect Forward Secrecy − Used to secure session data in case the private key has been compromised. This will generate a key used between the client and the server that is unique for each session." }, { "code": null, "e": 118194, "s": 118123, "text": "Now, add the Perfect Forward Secrecy configuration to our certificate." }, { "code": null, "e": 118286, "s": 118194, "text": "[root@centos]# cat /etc/ssl/certs/dhparam.pem | tee -a /etc/ssl/certs/self-sign-apache.crt\n" }, { "code": null, "e": 118344, "s": 118286, "text": "We will be making changes to /etc/httpd/conf.d/ssl.conf −" }, { "code": null, "e": 118624, "s": 118344, "text": "We will make the following changes to ssl.conf. However, before we do that we should back the original file up. When making changes to a production server in an advanced text editor like vi or emcas, it is a best practice to always backup configuration files before making edits." }, { "code": null, "e": 118673, "s": 118624, "text": "[root@centos]# cp /etc/httpd/conf.d/ssl.conf ~/\n" }, { "code": null, "e": 118781, "s": 118673, "text": "Now let's continue our edits after copying a known-working copy of ssl.conf to the root of our home folder." }, { "code": null, "e": 118788, "s": 118781, "text": "Locate" }, { "code": null, "e": 118838, "s": 118788, "text": "Edit both DocumentRoot and ServerName as follows." }, { "code": null, "e": 118978, "s": 118838, "text": "\\\\# General setup for the virtual host, inherited from global configuration\nDocumentRoot \"/var/www/html\"\nServerName centos.vmnet.local:443\n" }, { "code": null, "e": 119171, "s": 118978, "text": "DocumentRoot this is the path to your default apache directory. In this folder should be a default page that will display a HTTP request asking for the default page of your web server or site." }, { "code": null, "e": 119443, "s": 119171, "text": "ServerName is the server name that can be either an ip address or the host name of the server. For TLS, it is a best practice to create a certificate with a host name. From our OpenLdap tutorial, we created a hostname of centos on the local enterprise domain: vmnet.local" }, { "code": null, "e": 119491, "s": 119443, "text": "Now we want to comment the following lines out." }, { "code": null, "e": 119865, "s": 119491, "text": "# SSL Protocol support:\n# List the enable protocol levels with which clients will be able to\n# connect. Disable SSLv2 access by default:\n ~~~~> #SSLProtocol all -SSLv2\n \n# SSL Cipher Suite:\n# List the ciphers that the client is permitted to negotiate.\n# See the mod_ssl documentation for a complete list.\n ~~~~> #SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5:!SEED:!IDEA\n" }, { "code": null, "e": 119945, "s": 119865, "text": "Then let Apache know where to find our certificate and private/public key pair." }, { "code": null, "e": 120658, "s": 119945, "text": "# Server Certificate:\n# Point SSLCertificateFile at a PEM encoded certificate. If\n# the certificate is encrypted, then you will be prompted for a\n# pass phrase. Note that a kill -HUP will prompt again. A new\n# certificate can be generated using the genkey(1) command.\n~~~~> SSLCertificateFile /etc/ssl/certs/self-sign-apache.crt\nspecify path to our private key file\n# Server Private Key:\n# If the key is not combined with the certificate, use this\n# directive to point at the key file. Keep in mind that if\n# you've both a RSA and a DSA private key you can configure\n# both in parallel (to also allow the use of DSA ciphers, etc.)\n~~~~> SSLCertificateKeyFile /etc/ssl/private/self-gen-apache.key\n" }, { "code": null, "e": 120728, "s": 120658, "text": "Finally, we need to allow inbound connections to https over port 443." }, { "code": null, "e": 120903, "s": 120728, "text": "In this chapter, we will learn a little about the background of how Apache HTTP Server came into existence and then install the most current stable version on CentOS Linux 7." }, { "code": null, "e": 121021, "s": 120903, "text": "Apache is a web server that has been around for a long time. In fact, almost as long as the existence of http itself!" }, { "code": null, "e": 121295, "s": 121021, "text": "Apache started out as a rather small project at the National Center for Supercomputing Applications also known as NCSA. In the mid-90's \"httpd\", as it was called, was by far the most popular web-server platform on the Internet, having about 90% or more of the market share." }, { "code": null, "e": 121677, "s": 121295, "text": "At this time, it was a simple project. Skilled I.T. staff known as webmaster were responsible for: maintaining web server platforms and web server software as well as both front-end and back-end site development. At the core of httpd was its ability to use custom modules known as plugins or extensions. A webmaster was also skilled enough to write patches to core server software." }, { "code": null, "e": 121853, "s": 121677, "text": "Sometime in the late-mid-90's, the senior developer and project manager for httpd left NCSA to do other things. This left the most popular web-daemon in a state of stagnation." }, { "code": null, "e": 122174, "s": 121853, "text": "Since the use of httpd was so widespread a group of seasoned httpd webmasters called for a summit reqarding the future of httpd. It was decided to coordinate and apply the best extensions and patches into a current stable release. Then, the current grand-daddy of http servers was born and christened Apache HTTP Server." }, { "code": null, "e": 122415, "s": 122174, "text": "Little Known Historical Fact − Apache was not named after a Native American Tribe of warriors. It was in fact coined and named with a twist: being made from many fixes (or patches) from many talented Computer Scientists: a patchy or Apache." }, { "code": null, "e": 122447, "s": 122415, "text": "Step 1 − Install httpd via yum." }, { "code": null, "e": 122469, "s": 122447, "text": "yum -y install httpd\n" }, { "code": null, "e": 122524, "s": 122469, "text": "At this point Apache HTTP Server will install via yum." }, { "code": null, "e": 122584, "s": 122524, "text": "Step 2 − Edit httpd.conf file specific to your httpd needs." }, { "code": null, "e": 122726, "s": 122584, "text": "With a default Apache install, the configuration file for Apache is named httpd.conf and is located in /etc/httpd/. So, let's open it in vim." }, { "code": null, "e": 122776, "s": 122726, "text": "The first few lines of httpd.conf opened in vim −" }, { "code": null, "e": 123132, "s": 122776, "text": "# \n# This is the main Apache HTTP server configuration file. It contains the \n# configuration directives that give the server its instructions.\n# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. \n# In particular, see \n# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> \n# for a discussion of each configuration directive.\n" }, { "code": null, "e": 123237, "s": 123132, "text": "We will make the following changes to allow our CentOS install to serve http requests from http port 80." }, { "code": null, "e": 123543, "s": 123237, "text": "# Listen: Allows you to bind Apache to specific IP addresses and/or\n# ports, instead of the default. See also the <VirtualHost>\n# directive.\n#\n# Change this to Listen on specific IP addresses as shown below to\n# prevent Apache from glomming onto all bound IP addresses.\n#\n#Listen 12.34.56.78:80\nListen 80\n" }, { "code": null, "e": 123790, "s": 123543, "text": "From here, we change Apache to listen on a certain port or IP Address. For example, if we want to run httpd services on an alternative port such as 8080. Or if we have our web-server configured with multiple interfaces with separate IP addresses." }, { "code": null, "e": 123993, "s": 123790, "text": "Keeps Apache from attaching to every listening daemon onto every IP Address. This is useful to stop specifying only IPv6 or IPv4 traffic. Or even binding to all network interfaces on a multi-homed host." }, { "code": null, "e": 124299, "s": 123993, "text": "#\n# Listen: Allows you to bind Apache to specific IP addresses and/or\n# ports, instead of the default. See also the <VirtualHost>\n# directive.\n#\n# Change this to Listen on specific IP addresses as shown below to\n# prevent Apache from glomming onto all bound IP addresses.\n#\nListen 10.0.0.25:80\n#Listen 80\n" }, { "code": null, "e": 124522, "s": 124299, "text": "The \"document root\" is the default directory where Apache will look for an index file to serve for requests upon visiting your sever: http://www.yoursite.com/ will retrieve and serve the index file from your document root." }, { "code": null, "e": 124762, "s": 124522, "text": "#\n# DocumentRoot: The directory out of which you will serve your\n# documents. By default, all requests are taken from this directory, but\n# symbolic links and aliases may be used to point to other locations.\n#\nDocumentRoot \"/var/www/html\"\n" }, { "code": null, "e": 124807, "s": 124762, "text": "Step 3 − Start and Enable the httpd Service." }, { "code": null, "e": 124895, "s": 124807, "text": "[root@centos rdc]# systemctl start httpd && systemctl reload httpd \n[root@centos rdc]#\n" }, { "code": null, "e": 124960, "s": 124895, "text": "Step 4 − Configure firewall to allow access to port 80 requests." }, { "code": null, "e": 125020, "s": 124960, "text": "[root@centos]# firewall-cmd --add-service=http --permanent\n" }, { "code": null, "e": 125224, "s": 125020, "text": "As touched upon briefly when configuring CentOS for use with Maria DB, there is no native MySQL package in the CentOS 7 yum repository. To account for this, we will need to add a MySQL hosted repository." }, { "code": null, "e": 125435, "s": 125224, "text": "One thing to note is MySQL will require a different set of base dependencies from MariaDB. Also using MySQL will break the concept and philosophy of CentOS: production packages designed for maximum reliability." }, { "code": null, "e": 125612, "s": 125435, "text": "So when deciding whether to use Maria or MySQL one should weigh two options: Will my current DB Schema work with Maria? What advantage does installing MySQL over Maria give me?" }, { "code": null, "e": 125810, "s": 125612, "text": "Maria components are 100% transparent to MySQL structure, with some added efficiency with better licensing. Unless a compelling reason comes along, it is advised to configure CentOS to use MariaDB." }, { "code": null, "e": 125865, "s": 125810, "text": "The biggest reasons for favoring Maria on CentOS are −" }, { "code": null, "e": 125966, "s": 125865, "text": "Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria." }, { "code": null, "e": 126067, "s": 125966, "text": "Most people will be using MariaDB. When experiencing issues you will get more assistance with Maria." }, { "code": null, "e": 126147, "s": 126067, "text": "CentOS is designed to run with Maria. Hence, Maria will offer better stability." }, { "code": null, "e": 126227, "s": 126147, "text": "CentOS is designed to run with Maria. Hence, Maria will offer better stability." }, { "code": null, "e": 126269, "s": 126227, "text": "Maria is officially supported for CentOS." }, { "code": null, "e": 126311, "s": 126269, "text": "Maria is officially supported for CentOS." }, { "code": null, "e": 126376, "s": 126311, "text": "We will want to download and install the MySQL repository from −" }, { "code": null, "e": 126439, "s": 126376, "text": "http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm" }, { "code": null, "e": 126473, "s": 126439, "text": "Step 1 − Download the Repository." }, { "code": null, "e": 126590, "s": 126473, "text": "The repository comes conveniently packaged in an rpm package for easy installation. It can be downloaded with wget −" }, { "code": null, "e": 126825, "s": 126590, "text": "[root@centos]# wget http://repo.mysql.com/mysql-community-release-el75.noarch.rpm\n --2017-02-26 03:18:36-- http://repo.mysql.com/mysql-community-release-el75.noarch.rpm\n Resolving repo.mysql.com (repo.mysql.com)... 104.86.98.130\n" }, { "code": null, "e": 126858, "s": 126825, "text": "Step 2 − Install MySQL From YUM." }, { "code": null, "e": 126916, "s": 126858, "text": "We can now use the yum package manager to install MySQL −" }, { "code": null, "e": 126960, "s": 126916, "text": "[root@centos]# yum -y install mysql-server\n" }, { "code": null, "e": 127012, "s": 126960, "text": "Step 3 − Start and Enable the MySQL Daemon Service." }, { "code": null, "e": 127090, "s": 127012, "text": "[root@centos]# systemctl start mysql \n[root@centos]# systemctl enable mysql\n" }, { "code": null, "e": 127146, "s": 127090, "text": "Step 4 − Make sure our MySQL service is up and running." }, { "code": null, "e": 127276, "s": 127146, "text": "[root@centos]# netstat -antup | grep 3306 \ntcp6 0 0 :::3306 :::* LISTEN 6572/mysqld\n[root@centos]#\n" }, { "code": null, "e": 127565, "s": 127276, "text": "Note − We will not allow any firewall rules through. It's common to have MySQL configured to use Unix Domain Sockets. This assures only the web-server of the LAMP stack, locally, can access the MySQL database, taking out a complete dimension in the attack vector at the database software." }, { "code": null, "e": 127818, "s": 127565, "text": "In order to send an email from our CentOS 7 server, we will need the setup to configure a modern Mail Transfer Agent (MTA). Mail Transfer Agent is the daemon responsible for sending outbound mail for system users or corporate Internet Domains via SMTP." }, { "code": null, "e": 128365, "s": 127818, "text": "It is worth noting, this tutorial only teaches the process of setting up the daemon for local use. We do not go into detail about advanced configuration for setting up an MTA for business operations. This is a combination of many skills including but not limited to: DNS, getting a static routable IP address that is not blacklisted, and configuring advanced security and service settings. In short, this tutorial is meant to familiarize you with the basic configuration. Do not use this tutorial for MTA configuration of an Internet facing host." }, { "code": null, "e": 128795, "s": 128365, "text": "With its combined focus on both security and the ease of administration, we have chosen Postfix as the MTA for this tutorial. The default MTA installed in the older versions of CentOS is Sendmail. Sendmail is a great MTA. However, of the author's humble opinion, Postfix hits a sweet spot when addressing the following notes for an MTA. With the most current version of CentOS, Postfix has superseded Sendmail as the default MTA." }, { "code": null, "e": 129017, "s": 128795, "text": "Postfix is a widely used and well documented MTA. It is actively maintained and developed. It requires minimal configuration in mind (this is just email) and is efficient with system resources (again, this is just email)." }, { "code": null, "e": 129068, "s": 129017, "text": "Step 1 − Install Postfix from YUM Package Manager." }, { "code": null, "e": 129107, "s": 129068, "text": "[root@centos]# yum -y install postfix\n" }, { "code": null, "e": 129147, "s": 129107, "text": "Step 2 − Configure Postfix config file." }, { "code": null, "e": 129215, "s": 129147, "text": "The Postfix configuration file is located in − /etc/postfix/main.cf" }, { "code": null, "e": 129365, "s": 129215, "text": "In a simple Postfix configuration, the following must be configured for a specific host: host name, domain, origin, inet_interfaces, and destination." }, { "code": null, "e": 129577, "s": 129365, "text": "Configure the hostname − The hostname is a fully qualified domain name of the Postfix host. In OpenLDAP chapter, we named the CentOS box: centos on the domain vmnet.local. Let’s stick with that for this chapter." }, { "code": null, "e": 129852, "s": 129577, "text": "# The myhostname parameter specifies the internet hostname of this\n# mail system. The default is to use the fully-qualified domain name\n# from gethostname(). $myhostname is used as a default value for many\n# other configuration parameters.\n#\nmyhostname = centos.vmnet.local\n" }, { "code": null, "e": 129952, "s": 129852, "text": "Configure the domain − As stated above, the domain we will be using in this tutorial is vmnet.local" }, { "code": null, "e": 130190, "s": 129952, "text": "# The mydomain parameter specifies the local internet domain name.\n# The default is to use $myhostname minus the first component.\n# $mydomain is used as a default value for many other configuration\n# parameters.\n#\nmydomain = vmnet.local\n" }, { "code": null, "e": 130342, "s": 130190, "text": "Configure the origin − For a single server and domain set up, we just need to uncomment the following sections and leave the default Postfix variables." }, { "code": null, "e": 130951, "s": 130342, "text": "# SENDING MAIL\n#\n# The myorigin parameter specifies the domain that locally-posted\n# mail appears to come from. The default is to append $myhostname,\n# which is fine for small sites. If you run a domain with multiple\n# machines, you should (1) change this to $mydomain and (2) set up\n# a domain-wide alias database that aliases each user to\n# user@that.users.mailhost.\n#\n# For the sake of consistency between sender and recipient addresses,\n# myorigin also specifies the default domain name that is appended\n# to recipient addresses that have no @domain part. \n#\nmyorigin = $myhostname\nmyorigin = $mydomain\n" }, { "code": null, "e": 131190, "s": 130951, "text": "Configure the network interfaces − We will leave Postfix listening on our single network interface and all protocols and IP Addresses associated with that interface. This is done by simply leaving the default settings enabled for Postfix." }, { "code": null, "e": 131842, "s": 131190, "text": "# The inet_interfaces parameter specifies the network interface\n# addresses that this mail system receives mail on. By default,\n# the software claims all active interfaces on the machine. The\n# parameter also controls delivery of mail to user@[ip.address].\n#\n# See also the proxy_interfaces parameter, for network addresses that\n# are forwarded to us via a proxy or network address translator.\n#\n# Note: you need to stop/start Postfix when this parameter changes. \n#\n#inet_interfaces = all\n#inet_interfaces = $myhostname\n#inet_interfaces = $myhostname, localhost\n#inet_interfaces = localhost\n# Enable IPv4, and IPv6 if supported\ninet_protocols = all\n" }, { "code": null, "e": 131887, "s": 131842, "text": "Step 3 − Configure SASL Support for Postfix." }, { "code": null, "e": 132074, "s": 131887, "text": "Without SASL Authentication support, Postfix will only allow sending email from local users. Or it will give a relaying denied error when the users send email away from the local domain." }, { "code": null, "e": 132559, "s": 132074, "text": "Note − SASL or Simple Application Security Layer Framework is a framework designed for authentication supporting different techniques amongst different Application Layer protocols. Instead of leaving authentication mechanisms up to the application layer protocol, SASL developers (and consumers) leverage current authentication protocols for higher level protocols that may not have the convenience or more secure authentication (when speaking of access to secured services) built in." }, { "code": null, "e": 132881, "s": 132559, "text": "[root@centos]# yum -y install cyrus-sasl \nLoaded plugins: fastestmirror, langpacks \nLoading mirror speeds from cached hostfile \n * base: repos.forethought.net \n * extras: repos.dfw.quadranet.com \n * updates: mirrors.tummy.com \nPackage cyrus-sasl-2.1.26-20.el7_2.x86_64 already installed and latest version\nNothing to do\n" }, { "code": null, "e": 133111, "s": 132881, "text": "smtpd_sasl_auth_enable = yes\nsmtpd_recipient_restrictions =\npermit_mynetworks,permit_sasl_authenticated,reject_unauth_destination\nsmtpd_sasl_security_options = noanonymous\nsmtpd_sasl_type = dovecot\nsmtpd_sasl_path = private/auth\n" }, { "code": null, "e": 133335, "s": 133111, "text": "##Configure SASL Options Entries:\nsmtpd_sasl_auth_enable = yes\nsmptd_recipient_restrictions =\npermit_mynetworks,permit_sasl_authenticated,reject_unauth_destination\nsmtp_sasl_type = dovecot\nsmtp_sasl_path = private/auth/etc\n" }, { "code": null, "e": 133397, "s": 133335, "text": "Step 4 − Configure FirewallD to allow incoming SMTP Services." }, { "code": null, "e": 133529, "s": 133397, "text": "[root@centos]# firewall-cmd --permanent --add-service=smtp \nsuccess\n\n[root@centos]# firewall-cmd --reload \nsuccess\n\n[root@centos]#\n" }, { "code": null, "e": 133636, "s": 133529, "text": "Now let's check to make sure our CentOS host is allowing and responding to the requests on port 25 (SMTP)." }, { "code": null, "e": 133972, "s": 133636, "text": "Nmap scan report for 172.16.223.132 \nHost is up (0.00035s latency). \nNot shown: 993 filtered ports \nPORT STATE SERVICE \n 20/tcp closed ftp-data \n 21/tcp open ftp \n 22/tcp open ssh \n 25/tcp open smtp \n 80/tcp open http \n 389/tcp open ldap \n 443/tcp open https \nMAC Address: 00:0C:29:BE:DF:5F (VMware)\n" }, { "code": null, "e": 134074, "s": 133972, "text": "As you can see, SMTP is listening and the daemon is responding to the requests from our internal LAN." }, { "code": null, "e": 134354, "s": 134074, "text": "Dovecot is a secure IMAP and POP3 Server deigned to handle incoming mail needs of a smaller to larger organization. Due to its prolific use with CentOS, we will be using Dovecot as an example of installing and configuring an incoming mail-server for CentOS and MTA SASL Provider." }, { "code": null, "e": 134622, "s": 134354, "text": "As noted previously, we will not be configuring MX records for DNS or creating secure rules allowing our services to handle mail for a domain. Hence, just setting these services up on an Internet facing host may leave leverage room for security holes w/o SPF Records." }, { "code": null, "e": 134648, "s": 134622, "text": "Step 1 − Install Dovecot." }, { "code": null, "e": 134687, "s": 134648, "text": "[root@centos]# yum -y install dovecot\n" }, { "code": null, "e": 134715, "s": 134687, "text": "Step 2 − Configure dovecot." }, { "code": null, "e": 135086, "s": 134715, "text": "The main configuration file for dovecot is located at: /etc/dovecot.conf. We will first back up the main configuration file. It is a good practice to always backup configuration files before making edits. This way id (for example) line breaks get destroyed by a text editor, and years of changes are lost. Reverting is easy as copying the current backup into production." }, { "code": null, "e": 135157, "s": 135086, "text": "# Protocols we want to be serving. \nprotocols = imap imaps pop3 pop3s\n" }, { "code": null, "e": 135222, "s": 135157, "text": "Now, we need to enable the dovecot daemon to listen on startup −" }, { "code": null, "e": 135310, "s": 135222, "text": "[root@localhost]# systemctl start dovecot \n[root@localhost]# systemctl enable dovecot\n" }, { "code": null, "e": 135427, "s": 135310, "text": "Let's make sure Dovecot is listening locally on the specified ports for: imap, pop3, imap secured, and pop3 secured." }, { "code": null, "e": 136184, "s": 135427, "text": "[root@localhost]# netstat -antup | grep dovecot \n tcp 0 0 0.0.0.0:110 0.0.0.0:* LISTEN 4368/dovecot\n tcp 0 0 0.0.0.0:143 0.0.0.0:* LISTEN 4368/dovecot\n tcp 0 0 0.0.0.0:993 0.0.0.0:* LISTEN 4368/dovecot\n tcp 0 0 0.0.0.0:995 0.0.0.0:* LISTEN 4368/dovecot\n tcp6 0 0 :::110 :::* LISTEN 4368/dovecot\n tcp6 0 0 :::143 :::* LISTEN 4368/dovecot\n tcp6 0 0 :::993 :::* LISTEN 4368/dovecot\n tcp6 0 0 :::995 :::* LISTEN 4368/dovecot\n\n[root@localhost]#\n" }, { "code": null, "e": 136256, "s": 136184, "text": "As seen, dovecot is listening on the specified ports for IPv4 and IPv4." }, { "code": null, "e": 136298, "s": 136256, "text": "Now, we need to make some firewall rules." }, { "code": null, "e": 136660, "s": 136298, "text": "[root@localhost]# firewall-cmd --permanent --add-port=110/tcp \nsuccess\n \n[root@localhost]# firewall-cmd --permanent --add-port=143/tcp \nsuccess\n \n[root@localhost]# firewall-cmd --permanent --add-port=995/tcp \nsuccess\n \n[root@localhost]# firewall-cmd --permanent --add-port=993/tcp \nsuccess\n \n[root@localhost]# firewall-cmd --reload \nsuccess\n \n[root@localhost]#\n" }, { "code": null, "e": 136760, "s": 136660, "text": "Our incoming mail sever is accepting requests for POP3, POP3s, IMAP, and IMAPs to hosts on the LAN." }, { "code": null, "e": 137139, "s": 136760, "text": "Port Scanning host: 192.168.1.143\n\n Open TCP Port: 21 ftp \n Open TCP Port: 22 ssh \n Open TCP Port: 25 smtp \n Open TCP Port: 80 http \n Open TCP Port: 110 pop3 \n Open TCP Port: 143 imap \n Open TCP Port: 443 https \n Open TCP Port: 993 imaps \n Open TCP Port: 995 pop3s \n" }, { "code": null, "e": 137537, "s": 137139, "text": "Before delving into installing FTP on CentOS, we need to learn a little about its use and security. FTP is a really efficient and well-refined protocol for transferring files between the computer systems. FTP has been used and refined for a few decades now. For transferring files efficiently over a network with latency or for sheer speed, FTP is a great choice. More so than either SAMBA or SMB." }, { "code": null, "e": 137836, "s": 137537, "text": "However, FTP does possess some security issues. Actually, some serious security issues. FTP uses a really weak plain-text authentication method. It is for this reason authenticated sessions should rely on sFTP or FTPS, where TLS is used for end-to-end encryption of the login and transfer sessions." }, { "code": null, "e": 138104, "s": 137836, "text": "With the above caveats, plain old FTP still has its use in the business environment today. The main use is, anonymous FTP file repositories. This is a situation where no authentication is warranted to download or upload files. Some examples of anonymous FTP use are −" }, { "code": null, "e": 138225, "s": 138104, "text": "Large software companies still use anonymous ftp repositories allowing Internet users to download shareware and patches." }, { "code": null, "e": 138346, "s": 138225, "text": "Large software companies still use anonymous ftp repositories allowing Internet users to download shareware and patches." }, { "code": null, "e": 138411, "s": 138346, "text": "Allowing internet users to upload and download public documents." }, { "code": null, "e": 138476, "s": 138411, "text": "Allowing internet users to upload and download public documents." }, { "code": null, "e": 138595, "s": 138476, "text": "Some applications will automatically send encrypted, archived logs for or configuration files to a repository via FTP." }, { "code": null, "e": 138714, "s": 138595, "text": "Some applications will automatically send encrypted, archived logs for or configuration files to a repository via FTP." }, { "code": null, "e": 138815, "s": 138714, "text": "Hence, as a CentOS Administrator, being able to install and configure FTP is still a designed skill." }, { "code": null, "e": 139021, "s": 138815, "text": "We will be using an FTP daemon called vsFTP, or Very Secure FTP Daemon. vsFTP has been used in development for a while. It has a reputation for being secure, easy to install and configure, and is reliable." }, { "code": null, "e": 139075, "s": 139021, "text": "Step 1 − Install vsFTPd with the YUM Package Manager." }, { "code": null, "e": 139120, "s": 139075, "text": "[root@centos]# yum -y install vsftpd.x86_64\n" }, { "code": null, "e": 139178, "s": 139120, "text": "Step 2 − Configure vsFTP to Start on Boot with systemctl." }, { "code": null, "e": 139382, "s": 139178, "text": "[root@centos]# systemctl start vsftpd \n[root@centos]# systemctl enable vsftpd \nCreated symlink from /etc/systemd/system/multi-\nuser.target.wants/vsftpd.service to /usr/lib/systemd/system/vsftpd.service.\n" }, { "code": null, "e": 139455, "s": 139382, "text": "Step 3 − Configure FirewallD to allow FTP control and transfer sessions." }, { "code": null, "e": 139539, "s": 139455, "text": "[root@centos]# firewall-cmd --add-service=ftp --permanent \nsuccess \n[root@centos]#\n" }, { "code": null, "e": 139573, "s": 139539, "text": "Assure our FTP daemon is running." }, { "code": null, "e": 139712, "s": 139573, "text": "[root@centos]# netstat -antup | grep vsftp \ntcp6 0 0 :::21 :::* LISTEN 13906/vsftpd \n[root@centos]#\n" }, { "code": null, "e": 139760, "s": 139712, "text": "Step 4 − Configure vsFTPD For Anonymous Access." }, { "code": null, "e": 139787, "s": 139760, "text": "[root@centos]# mkdir /ftp\n" }, { "code": null, "e": 139983, "s": 139787, "text": "[root@centos]# chown ftp:ftp /ftp\nSet minimal permissions for FTP root:\n\n[root@centos]# chmod -R 666 /ftp/\n\n[root@centos]# ls -ld /ftp/\ndrw-rw-rw-. 2 ftp ftp 6 Feb 27 02:01 /ftp/\n\n[root@centos]#\n" }, { "code": null, "e": 140058, "s": 139983, "text": "In this case, we gave users read/write access to the entire root FTP tree." }, { "code": null, "e": 140512, "s": 140058, "text": "[root@centos]# vim /etc/vsftpd/vsftpd.conf\n# Example config file /etc/vsftpd/vsftpd.conf\n#\n# The default compiled in settings are fairly paranoid. This sample file\n# loosens things up a bit, to make the ftp daemon more usable.\n# Please see vsftpd.conf.5 for all compiled in defaults.\n#\n# READ THIS: This example file is NOT an exhaustive list of vsftpd options.\n# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's\n# capabilities.\n" }, { "code": null, "e": 140584, "s": 140512, "text": "We will want to change the following directives in the vsftp.conf file." }, { "code": null, "e": 140655, "s": 140584, "text": "Enable Anonymous uploading by uncommenting anon_mkdir_write_enable=YES" }, { "code": null, "e": 140726, "s": 140655, "text": "Enable Anonymous uploading by uncommenting anon_mkdir_write_enable=YES" }, { "code": null, "e": 140820, "s": 140726, "text": "chown uploaded files to owned by the system ftp user\nchown_uploads = YES\nchown_username = ftp" }, { "code": null, "e": 140873, "s": 140820, "text": "chown uploaded files to owned by the system ftp user" }, { "code": null, "e": 140893, "s": 140873, "text": "chown_uploads = YES" }, { "code": null, "e": 140914, "s": 140893, "text": "chown_username = ftp" }, { "code": null, "e": 140982, "s": 140914, "text": "Change system user used by vsftp to the ftp user: nopriv_user = ftp" }, { "code": null, "e": 141050, "s": 140982, "text": "Change system user used by vsftp to the ftp user: nopriv_user = ftp" }, { "code": null, "e": 141203, "s": 141050, "text": "Set the custom banner for the user to read before signing in.\nftpd_banner = Welcome to our Anonymous FTP Repo. All connections are monitored and logged." }, { "code": null, "e": 141265, "s": 141203, "text": "Set the custom banner for the user to read before signing in." }, { "code": null, "e": 141356, "s": 141265, "text": "ftpd_banner = Welcome to our Anonymous FTP Repo. All connections are monitored and logged." }, { "code": null, "e": 141420, "s": 141356, "text": "Let's set IPv4 connections only −\nlisten = YES\nlisten_ipv6 = NO" }, { "code": null, "e": 141454, "s": 141420, "text": "Let's set IPv4 connections only −" }, { "code": null, "e": 141467, "s": 141454, "text": "listen = YES" }, { "code": null, "e": 141484, "s": 141467, "text": "listen_ipv6 = NO" }, { "code": null, "e": 141555, "s": 141484, "text": "Now, we need to restart or HUP the vsftp service to apply our changes." }, { "code": null, "e": 141596, "s": 141555, "text": "[root@centos]# systemctl restart vsftpd\n" }, { "code": null, "e": 141670, "s": 141596, "text": "Let's connect to our FTP host and make sure our FTP daemon is responding." }, { "code": null, "e": 141999, "s": 141670, "text": "[root@centos rdc]# ftp 10.0.4.34 \nConnected to localhost (10.0.4.34). \n220 Welcome to our Anonymous FTP Repo. All connections are monitored and logged. \nName (localhost:root): anonymous \n331 Please specify the password. \nPassword: \n'230 Login successful. \nRemote system type is UNIX. \nUsing binary mode to transfer files. \nftp>\n" }, { "code": null, "e": 142097, "s": 141999, "text": "When talking about remote management in CentOS as an Administrator, we will explore two methods −" }, { "code": null, "e": 142116, "s": 142097, "text": "Console Management" }, { "code": null, "e": 142131, "s": 142116, "text": "GUI Management" }, { "code": null, "e": 142597, "s": 142131, "text": "Remote Console Management means performing administration tasks from the command line via a service such as ssh. To use CentOS Linux effectively, as an Administrator, you will need to be proficient with the command line. Linux at its heart was designed to be used from the console. Even today, some system administrators prefer the power of the command and save money on the hardware by running bare-bones Linux boxes with no physical terminal and no GUI installed." }, { "code": null, "e": 142971, "s": 142597, "text": "Remote GUI Management is usually accomplished in two ways: either a remote X-Session or a GUI application layer protocol like VNC. Each has its strengths and drawbacks. However, for the most part, VNC is the best choice for Administration. It allows graphical control from other operating systems such as Windows or OS X that do not natively support the X Windows protocol." }, { "code": null, "e": 143311, "s": 142971, "text": "Using remote X Sessions is native to both X-Window's Window-Managers and DesktopManagers running on X. However, the entire X Session architecture is mostly used with Linux. Not every System Administrator will have a Linux Laptop on hand to establish a remote X Session. Therefore, it is most common to use an adapted version of VNC Server." }, { "code": null, "e": 143583, "s": 143311, "text": "The biggest drawbacks to VNC are: VNC does not natively support a multi-user environment such as remote X-Sessions. Hence, for GUI access to end-users remote XSessions would be the best choice. However, we are mainly concerned with administering a CentOS server remotely." }, { "code": null, "e": 143697, "s": 143583, "text": "We will discuss configuring VNC for multiple administrators versus a few hundred endusers with remote X-Sessions." }, { "code": null, "e": 143989, "s": 143697, "text": "ssh or Secure Shell is now the standard for remotely administering any Linux server. SSH unlike telnet uses TLS for authenticity and end-to-end encryption of communications. When properly configured an administrator can be pretty sure both their password and the server are trusted remotely." }, { "code": null, "e": 144395, "s": 143989, "text": "Before configuring SSH, lets talk a little about the basic security and least common access. When SSH is running on its default port of 22; sooner rather than later, you are going to get brute force dictionary attacks against common user names and passwords. This just comes with the territory. No matter how many hosts you add to your deny files, they will just come in from different IP addresses daily." }, { "code": null, "e": 144610, "s": 144395, "text": "With a few common rules, you can simply take some pro-active steps and let the bad guys waste their time. Following are a few rules of security to follow using SSH for remote administration on a production server −" }, { "code": null, "e": 144784, "s": 144610, "text": "Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com" }, { "code": null, "e": 144958, "s": 144784, "text": "Never use a common username or password. Usernames on the system should not be system default, or associated with the company email address like: systemadmin@yourcompany.com" }, { "code": null, "e": 145124, "s": 144958, "text": "Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH." }, { "code": null, "e": 145290, "s": 145124, "text": "Root access or administration access should not be allowed via SSH. Use a unique username and su to root or an administration account once authenticated through SSH." }, { "code": null, "e": 145480, "s": 145290, "text": "Password policy is a must: Complex SSH user passwords like: \"This&IS&a&GUD&P@ssW0rd&24&me\". Change passwords every few months to eliminate susceptibility to incremental brute force attacks." }, { "code": null, "e": 145670, "s": 145480, "text": "Password policy is a must: Complex SSH user passwords like: \"This&IS&a&GUD&P@ssW0rd&24&me\". Change passwords every few months to eliminate susceptibility to incremental brute force attacks." }, { "code": null, "e": 145914, "s": 145670, "text": "Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example." }, { "code": null, "e": 146158, "s": 145914, "text": "Disable abandoned or accounts that are unused for extended periods. If a hiring manager has a voicemail stating they will not be doing interviews for a month; that can lead to tech-savvy individuals with a lot time on their hands, for example." }, { "code": null, "e": 146476, "s": 146158, "text": "Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits." }, { "code": null, "e": 146794, "s": 146476, "text": "Watch your logs daily. As a System Administrator, dedicate at least 30-40 minutes every morning reviewing system and security logs. If asked, let everyone know you don't have the time to not be proactive. This practice will help isolate warning signs before a problem presents itself to end-users and company profits." }, { "code": null, "e": 147214, "s": 146794, "text": "Note On Linux Security − Anyone interested in Linux Administration should actively pursue current Cyber-Security news and technology. While we mostly hear about other operating systems being compromised, an insecure Linux box is a sought-after treasure for cybercriminals. With the power of Linux on a high-speed internet connection, a skilled cybercriminal can use Linux to leverage attacks on other operating systems." }, { "code": null, "e": 147270, "s": 147214, "text": "Step 1 − Install SSH Server and all dependent packages." }, { "code": null, "e": 147690, "s": 147270, "text": "[root@localhost]# yum -y install openssh-server \n'Loaded plugins: fastestmirror, langpacks \nLoading mirror speeds from cached hostfile \n* base: repos.centos.net \n* extras: repos.dfw.centos.com \n* updates: centos.centos.com \nResolving Dependencies \n --> Running transaction check \n ---> Package openssh-server.x86_64 0:6.6.1p1-33.el7_3 will be installed \n --> Finished Dependency Resolution \nDependencies Resolved\n" }, { "code": null, "e": 147750, "s": 147690, "text": "Step 2 − Make a secure regular use to add for shell access." }, { "code": null, "e": 147882, "s": 147750, "text": "[root@localhost ~]# useradd choozer \n[root@localhost ~]# usermod -c \"Remote Access\" -d /home/choozer -g users -G \nwheel -a choozer\n" }, { "code": null, "e": 148138, "s": 147882, "text": "Note − We added the new user to the wheel group enabling ability to su into root once SSH access has been authenticated. We also used a username that cannot be found in common word lists. This way, our account will not get locked out when SSH is attacked." }, { "code": null, "e": 148219, "s": 148138, "text": "The file holding configuration settings for sshd server is /etc/ssh/sshd_config." }, { "code": null, "e": 148264, "s": 148219, "text": "The portions we want to edit initially are −" }, { "code": null, "e": 148303, "s": 148264, "text": "LoginGraceTime 60m\nPermitRootLogin no\n" }, { "code": null, "e": 148340, "s": 148303, "text": "Step 3 − Reload the SSH daemon sshd." }, { "code": null, "e": 148381, "s": 148340, "text": "[root@localhost]# systemctl reload sshd\n" }, { "code": null, "e": 148623, "s": 148381, "text": "It is good to set the logout grace period to 60 minutes. Some complex administration tasks can exceed the default of 2 minutes. There is really nothing more frustrating than having SSH session timeout when configuring or researching changes." }, { "code": null, "e": 148679, "s": 148623, "text": "Step 4 − Let's try to login using the root credentials." }, { "code": null, "e": 148822, "s": 148679, "text": "bash-3.2# ssh centos.vmnet.local \nroot@centos.vmnet.local's password: \nPermission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\n" }, { "code": null, "e": 148972, "s": 148822, "text": "Step 5 − We can no longer login remotely via ssh with root credentials. So let's login to our unprivileged user account and su into the root account." }, { "code": null, "e": 149121, "s": 148972, "text": "bash-3.2# ssh chooser@centos.vmnet.local\nchoozer@centos.vmnet.local's password:\n[choozer@localhost ~]$ su root\nPassword:\n\n[root@localhost choozer]#\n" }, { "code": null, "e": 149232, "s": 149121, "text": "Step 6 − Finally, let's make sure the SSHD service loads on boot and firewalld allows outside SSH connections." }, { "code": null, "e": 149415, "s": 149232, "text": "[root@localhost]# systemctl enable sshd\n\n[root@localhost]# firewall-cmd --permanent --add-service=ssh \nsuccess\n\n[root@localhost]# firewall-cmd --reload \nsuccess\n \n[root@localhost]#\n " }, { "code": null, "e": 149630, "s": 149415, "text": "SSH is now set up and ready for remote administration. Depending on your enterprise border, the packet filtering border device may need to be configured to allow SSH remote administration outside the corporate LAN." }, { "code": null, "e": 150109, "s": 149630, "text": "There are a few ways to enable remote CentOS administration via VNC on CentOS 6 - 7. The easiest, but most limiting way is simply using a package called vino. Vino is a Virtual Network Desktop Connection application for Linux designed around the Gnome Desktop platform. Hence, it is assumed the installation was completed with Gnome Desktop. If the Gnome Desktop has not been installed, please do so before continuing. Vino will be installed with a Gnome GUI install by default." }, { "code": null, "e": 150229, "s": 150109, "text": "To configure screen sharing with Vino under Gnome, we want to go into the CentOS System Preferences for screen sharing." }, { "code": null, "e": 150276, "s": 150229, "text": "Applications->System Tools->Settings->Sharing\n" }, { "code": null, "e": 150319, "s": 150276, "text": "Notes to configuring VNC Desktop Sharing −" }, { "code": null, "e": 150520, "s": 150319, "text": "Disable New Connections must ask for access − This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop." }, { "code": null, "e": 150721, "s": 150520, "text": "Disable New Connections must ask for access − This option will require physical access to ok every connection. This option will prevent remote administration unless someone is at the physical desktop." }, { "code": null, "e": 150932, "s": 150721, "text": "Enable Require a password − This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security)." }, { "code": null, "e": 151143, "s": 150932, "text": "Enable Require a password − This is separate from the user password. It will control the access to the virtual desktop and still require the user password to access a locked desktop (this is good for security)." }, { "code": null, "e": 151352, "s": 151143, "text": "Forward UP&P Ports: If available leave disabled − Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this." }, { "code": null, "e": 151561, "s": 151352, "text": "Forward UP&P Ports: If available leave disabled − Forwarding UP&P ports will send Universal Plug and Play requests for a layer 3 device to allow VNC connections to the host automatically. We do not want this." }, { "code": null, "e": 151611, "s": 151561, "text": "Make sure vino is listening on the VNC Port 5900." }, { "code": null, "e": 151860, "s": 151611, "text": "[root@localhost]# netstat -antup | grep vino \ntcp 0 0 0.0.0.0:5900 0.0.0.0:* LISTEN 4873/vino-server\ntcp6 0 0 :::5900 :::* LISTEN 4873/vino-server\n \n[root@localhost]#\n" }, { "code": null, "e": 151928, "s": 151860, "text": "Let's now configure our Firewall to allow incoming VNC connections." }, { "code": null, "e": 152074, "s": 151928, "text": "[root@localhost]# firewall-cmd --permanent --add-port=5900/tcp \nsuccess\n\n[root@localhost]# firewall-cmd --reload \nsuccess\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 152199, "s": 152074, "text": "Finally, as you can see we are able to connect our CentOS Box and administer it with a VNC client on either Windows or OS X." }, { "code": null, "e": 152650, "s": 152199, "text": "It is just as important to obey the same rules for VNC as we set forth for SSH. Just like SSH, VNC is continually scanned across IP ranges and tested for weak passwords. It is also worth a note that leaving the default CentOS login enabled with a console timeout does help with remote VNC security. As an attacker will need the VNC and user password, make sure your screen sharing password is different and just as hard to guess as the user password." }, { "code": null, "e": 152767, "s": 152650, "text": "After entering the the VNC screen sharing password, we must also enter the user password to access a locked desktop." }, { "code": null, "e": 152902, "s": 152767, "text": "Security Note − By default, VNC is not an encrypted protocol. Hence, the VNC connection should be tunneled through SSH for encryption." }, { "code": null, "e": 153222, "s": 152902, "text": "Setting up an SSH Tunnel will provide a layer of SSH encryption to tunnel the VNC connection through. Another great feature is it uses SSH compression to add another layer of compression to the VNC GUI screen updates. More secure and faster is always a good thing when dealing with the administration of CentOS servers!" }, { "code": null, "e": 153396, "s": 153222, "text": "So from your client that will be initiating the VNC connection, let's set up a remote SSH tunnel. In this demonstration, we are using OS X. First we need to sudo -s to root." }, { "code": null, "e": 153426, "s": 153396, "text": "bash-3.2# sudo -s \npassword:\n" }, { "code": null, "e": 153502, "s": 153426, "text": "Enter the user password and we should now have root shell with a # prompt −" }, { "code": null, "e": 153513, "s": 153502, "text": "bash-3.2#\n" }, { "code": null, "e": 153547, "s": 153513, "text": "Now, let's create our SSH Tunnel." }, { "code": null, "e": 153603, "s": 153547, "text": "ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N\n" }, { "code": null, "e": 153635, "s": 153603, "text": "Let's break this command down −" }, { "code": null, "e": 153668, "s": 153635, "text": "ssh − Runs the local ssh utility" }, { "code": null, "e": 153701, "s": 153668, "text": "ssh − Runs the local ssh utility" }, { "code": null, "e": 153769, "s": 153701, "text": "-f − ssh should run in the background after the task fully executes" }, { "code": null, "e": 153837, "s": 153769, "text": "-f − ssh should run in the background after the task fully executes" }, { "code": null, "e": 153915, "s": 153837, "text": "rdc@192.168.1.143 − Remote ssh user on the CentOS server hosting VNC services" }, { "code": null, "e": 153993, "s": 153915, "text": "rdc@192.168.1.143 − Remote ssh user on the CentOS server hosting VNC services" }, { "code": null, "e": 154096, "s": 153993, "text": "-L 2200:192.168.1.143:5900 − Create our tunnel [Local Port]:[remote host]:[remote port of VNC service]" }, { "code": null, "e": 154199, "s": 154096, "text": "-L 2200:192.168.1.143:5900 − Create our tunnel [Local Port]:[remote host]:[remote port of VNC service]" }, { "code": null, "e": 154269, "s": 154199, "text": "-N tells ssh we do not wish to execute a command on the remote system" }, { "code": null, "e": 154339, "s": 154269, "text": "-N tells ssh we do not wish to execute a command on the remote system" }, { "code": null, "e": 154435, "s": 154339, "text": "bash-3.2# ssh -f rdc@192.168.1.143 -L 2200:192.168.1.143:5900 -N\nrdc@192.168.1.143's password:\n" }, { "code": null, "e": 154708, "s": 154435, "text": "After successfully entering the remote ssh user's password, our ssh tunnel is created. Now for the cool part! To connect we point our VNC client at the localhost on the port of our tunnel, in this case port 2200. Following is the configuration on Mac Laptop's VNC Client −" }, { "code": null, "e": 154756, "s": 154708, "text": "And finally, our remote VNC Desktop Connection!" }, { "code": null, "e": 155008, "s": 154756, "text": "The cool thing about SSH tunneling is it can be used for almost any protocol. SSH tunnels are commonly used to bypass egress and ingress port filtering by an ISP, as well as trick application layer IDS/IPS while evading other session layer monitoring." }, { "code": null, "e": 155148, "s": 155008, "text": "Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered)." }, { "code": null, "e": 155288, "s": 155148, "text": "Your ISP may filter port 5900 for non-business accounts but allow SSH on port 22 (or one could run SSH on any port if port 22 is filtered)." }, { "code": null, "e": 155454, "s": 155288, "text": "Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data." }, { "code": null, "e": 155620, "s": 155454, "text": "Application level IPS and IDS look at payload. For example, a common buffer overflow or SQL Injection. End-to-end SSH encryption will encrypt application layer data." }, { "code": null, "e": 155845, "s": 155620, "text": "SSH Tunneling is great tool in a Linux Administrator's toolbox for getting things done. However, as an Administrator we want to explore locking down the availability of lesser privileged users having access to SSH tunneling." }, { "code": null, "e": 156117, "s": 155845, "text": "Administration Security Note − Restricting SSH Tunneling is something that requires thought on the part of an Administrator. Assessing why users need SSH Tunneling in the first place; what users need tunneling; along with practical risk probability and worst-case impact." }, { "code": null, "e": 156318, "s": 156117, "text": "This is an advanced topic stretching outside the realm of an intermediate level primer. Research on this topic is advised for those who wish to reach the upper echelons of CentOS Linux Administration." }, { "code": null, "e": 156510, "s": 156318, "text": "The design of X-Windows in Linux is really neat compared to that of Windows. If we want to control a remote Linux box from another Linux boxm we can take advantage of mechanisms built into X." }, { "code": null, "e": 156802, "s": 156510, "text": "X-Windows (often called just \"X\"), provides the mechanism to display application windows originating from one Linux box to the display portion of X on another Linux box. So through SSH we can request an X-Windows application be forwarded to the display of another Linux box across the world!" }, { "code": null, "e": 156893, "s": 156802, "text": "To run an X Application remotely via an ssh tunnel, we just need to run a single command −" }, { "code": null, "e": 156937, "s": 156893, "text": "[root@localhost]# ssh -X rdc@192.168.1.105\n" }, { "code": null, "e": 157027, "s": 156937, "text": "The syntax is − ssh -X [user]@[host], and the host must be running ssh with a valid user." }, { "code": null, "e": 157131, "s": 157027, "text": "Following is a screenshot of GIMP running on a Ubuntu Workstation through a remote XWindows ssh tunnel." }, { "code": null, "e": 157343, "s": 157131, "text": "It is pretty simple to run applications remotely from another Linux server or workstation. It is also possible to start an entire X-Session and have the entire desktop environment remotely through a few methods." }, { "code": null, "e": 157349, "s": 157343, "text": "XDMCP" }, { "code": null, "e": 157355, "s": 157349, "text": "XDMCP" }, { "code": null, "e": 157393, "s": 157355, "text": "Headless software packages such as NX" }, { "code": null, "e": 157431, "s": 157393, "text": "Headless software packages such as NX" }, { "code": null, "e": 157522, "s": 157431, "text": "Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE" }, { "code": null, "e": 157613, "s": 157522, "text": "Configuring alternate displays and desktops in X and desktop managers such as Gnome or KDE" }, { "code": null, "e": 157809, "s": 157613, "text": "This method is most commonly used for headless servers with no physical display and really exceeds the scope of an intermediate level primer. However, it is good to know of the options available." }, { "code": null, "e": 158047, "s": 157809, "text": "There are several third party tools that can add enhanced capabilities for CentOS traffic monitoring. In this tutorial, we will focus on those that are packaged in the main CentOS distribution repositories and the Fedora EPEL repository." }, { "code": null, "e": 158467, "s": 158047, "text": "There will always be situations where an Administrator (for one reason or another) is left with only tools in the main CentOS repositories. Most utilities discussed are designed to be used by an Administrator with the shell of physical access. When traffic monitoring with an accessible web-gui, using third party utilities such as ntop-ng or Nagios is the best choice (versus re-creating such facilities from scratch)." }, { "code": null, "e": 158582, "s": 158467, "text": "For further research on both configurable web-gui solutions, following are a few links to get started on research." }, { "code": null, "e": 158589, "s": 158582, "text": "Nagios" }, { "code": null, "e": 159012, "s": 158589, "text": "Nagios has been around for a long time, therefore, it is both tried and tested. At one point it was all free and open-source, but has since advanced into an Enterprise solution with paid licensing models to support the need of Enterprise sophistication. Hence, before planning any rollouts with Nagios, make sure the open-source licensed versions will meet your needs or plan on spending with an Enterprise Budget in mind." }, { "code": null, "e": 159105, "s": 159012, "text": "Most open-source Nagios traffic monitoring software can be found at − https://www.nagios.org" }, { "code": null, "e": 159222, "s": 159105, "text": "For a summarized history of Nagious, here is the official Nagios History page: https://www.nagios.org/about/history/" }, { "code": null, "e": 159229, "s": 159222, "text": "ntopng" }, { "code": null, "e": 159533, "s": 159229, "text": "Another great tool allowing bandwidth and traffic monitoring via a web-gui is called ntopng. ntopng is similar to the Unix utility ntop, and can collect data for an entire LAN or WAN. Providing a web-gui for administration, configuration, and charting makes it easy to use for the entire IT Departments." }, { "code": null, "e": 159698, "s": 159533, "text": "Like Nagious, ntopng has both open-source and paid enterprise versions available. For more information about ntopng, please visit the website − http://www.ntop.org/" }, { "code": null, "e": 159829, "s": 159698, "text": "To access some of the needed tools for traffic monitoring, we will need to configure our CentOS system to use the EPEL Repository." }, { "code": null, "e": 160110, "s": 159829, "text": "The EPEL Repository is not officially maintained or supported by CentOS. However, it is maintained by a group of Fedora Core volunteers to address the packages commonly used by Enterprise Linux professionals not included in either CentOS, Fedora Core, or Red Hat Linux Enterprise." }, { "code": null, "e": 160118, "s": 160110, "text": "Caution" }, { "code": null, "e": 160427, "s": 160118, "text": "Remember, the EPEL Repository is not official for CentOS and may break compatibility and functionality on production servers with common dependencies. With that in mind, it is advised to always test on a non-production server running the same services as production before deploying on a system critical box." }, { "code": null, "e": 160676, "s": 160427, "text": "Really, the biggest advantage of using the EHEL Repository over any other third party repository with CentOS is that we can be sure the binaries are not tainted. It is considered a best practice to not use the repositories from an untrusted source." }, { "code": null, "e": 160791, "s": 160676, "text": "With all that said, the official EPEL Repository is so common with CentOS that it can be easily installed via YUM." }, { "code": null, "e": 161221, "s": 160791, "text": "[root@CentOS rdc]# yum -y install epel-release\n Loaded plugins: fastestmirror, langpacks\n Loading mirror speeds from cached hostfile\n * base: repo1.dal.innoscale.net\n * extras: repo1.dal.innoscale.net\n * updates: mirror.hmc.edu\nResolving Dependencies\n --> Running transaction check\n ---> Package epel-release.noarch 0:7-9 will be installed\n --> Finished Dependency Resolution\nDependencies Resolved\n--{ condensed output }--\n" }, { "code": null, "e": 161286, "s": 161221, "text": "After installing the EPEL Repository, we will want to update it." }, { "code": null, "e": 161601, "s": 161286, "text": "[root@CentOS rdc]# yum repolist \nLoaded plugins: fastestmirror, langpacks \nepel/x86_64/metalink\n| 11 kB 00:00:00 \nepel\n| 4.3 kB 00:00:00 \n(1/3): epel/x86_64/group_gz\n| 170 kB 00:00:00 \n(2/3): epel/x86_64/updateinfo\n| 753 kB 00:00:01 \n(3/3): epel/x86_64/primary_db\n--{ condensed output }--\n" }, { "code": null, "e": 161743, "s": 161601, "text": "At this point, our EPEL repository should be configured and ready to use. Let's start by installing nload for interface bandwidth monitoring." }, { "code": null, "e": 161793, "s": 161743, "text": "The tools we will focus on in this tutorial are −" }, { "code": null, "e": 161799, "s": 161793, "text": "nload" }, { "code": null, "e": 161804, "s": 161799, "text": "ntop" }, { "code": null, "e": 161811, "s": 161804, "text": "ifstst" }, { "code": null, "e": 161817, "s": 161811, "text": "iftop" }, { "code": null, "e": 161824, "s": 161817, "text": "vnstat" }, { "code": null, "e": 161833, "s": 161824, "text": "net hogs" }, { "code": null, "e": 161843, "s": 161833, "text": "Wireshark" }, { "code": null, "e": 161852, "s": 161843, "text": "TCP Dump" }, { "code": null, "e": 161863, "s": 161852, "text": "Traceroute" }, { "code": null, "e": 162050, "s": 161863, "text": "These are all standard for monitoring traffic in Linux Enterprises. The usage of each range from simple to advanced, so we will only briefly discuss tools such as Wireshark and TCP Dump." }, { "code": null, "e": 162233, "s": 162050, "text": "With our EPEL Repositories installed and configured in CentOS, we now should be able to install and use nload. This utility is designed to chart bandwidth per interface in real-time." }, { "code": null, "e": 162312, "s": 162233, "text": "Like most other basic installs nload is installed via the YUM package manager." }, { "code": null, "e": 163396, "s": 162312, "text": "[root@CentOS rdc]# yum -y install nload\nResolving Dependencies\n--> Running transaction check\n---> Package nload.x86_64 0:0.7.4-4.el7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n=============================================================================== \n=============================================================================== \n Package Arch\n Version Repository Size \n=============================================================================== \n=============================================================================== \nInstalling: \n nload x86_64\n 0.7.4-4.el7 epel 70 k \nTransaction Summary\n=============================================================================== \n=============================================================================== \nInstall 1 Package\nTotal download size: 70 k\nInstalled size: 176 k\nDownloading packages:\n--{ condensed output }--\n" }, { "code": null, "e": 163466, "s": 163396, "text": "Now we have nload installed, and using it is pretty straight forward." }, { "code": null, "e": 163499, "s": 163466, "text": "[root@CentOS rdc]# nload enp0s5\n" }, { "code": null, "e": 163671, "s": 163499, "text": "nload will monitor the specified interface. In this case, enp0s5 an Ethernet interface, in real-time from the terminal for network traffic loads and total bandwidth usage." }, { "code": null, "e": 163844, "s": 163671, "text": "As seen, nload will chart both incoming and outgoing data from the specified interface, along with providing a physical representation of the data flow with hash marks \"#\"." }, { "code": null, "e": 163941, "s": 163844, "text": "The depicted screenshot is of a simple webpage being loaded with some background daemon traffic." }, { "code": null, "e": 163986, "s": 163941, "text": "Common command line switches for nload are −" }, { "code": null, "e": 164021, "s": 163986, "text": "The standard syntax for nload is −" }, { "code": null, "e": 164050, "s": 164021, "text": "nload [options] <interface>\n" }, { "code": null, "e": 164241, "s": 164050, "text": "If no interface is specified, nload will automatically grab the first Ethernet interface. Let's try measuring the total data in/out in Megabytes and current data-transfer speeds in Megabits." }, { "code": null, "e": 164277, "s": 164241, "text": "[root@CentOS rdc]# nload -U M -u m\n" }, { "code": null, "e": 164431, "s": 164277, "text": "Data coming in/out the current interface is measured in megabits per second and each \"Ttl\" row, representing total data in/out is displayed in Megabytes." }, { "code": null, "e": 164589, "s": 164431, "text": "nload is useful for an administrator to see how much data has passed through an interface and how much data is currently coming in/out a specified interface." }, { "code": null, "e": 164738, "s": 164589, "text": "To see other interfaces without closing nload, simply use the left/right arrow keys. This will cycle through all available interfaces on the system." }, { "code": null, "e": 164821, "s": 164738, "text": "It is possible to monitor multiple interfaces simultaneously using the -m switch −" }, { "code": null, "e": 164873, "s": 164821, "text": "[root@CentOS rdc]# nload -u K -U M -m lo -m enp0s5\n" }, { "code": null, "e": 164937, "s": 164873, "text": "load monitoring two interfaces simultaneously (lo and enp0s5) −" }, { "code": null, "e": 165261, "s": 164937, "text": "systemd has changed the way system logging is managed for CentOS Linux. Instead of every daemon on the system placing logs into individual locations than using tools such as tail or grep as the primary way of sorting and filtering log entries, journald has brought a single point of administration to analyzing system logs." }, { "code": null, "e": 165349, "s": 165261, "text": "The main components behind systemd logging are − journal, jounralctl, and journald.conf" }, { "code": null, "e": 165491, "s": 165349, "text": "journald is the main logging daemon and is configured by editing journald.conf while journalctl is used to analyze events logged by journald." }, { "code": null, "e": 165578, "s": 165491, "text": "Events logged by journald include: kernel events, user processes, and daemon services." }, { "code": null, "e": 165708, "s": 165578, "text": "Before using journalctl, we need to make sure our system time is set to the correct time. To do this, we want to use timedatectl." }, { "code": null, "e": 165745, "s": 165708, "text": "Let's check the current system time." }, { "code": null, "e": 166328, "s": 165745, "text": "[root@centos rdc]# timedatectl status \nLocal time: Mon 2017-03-20 00:14:49 MDT \nUniversal time: Mon 2017-03-20 06:14:49 UTC \nRTC time: Mon 2017-03-20 06:14:49 \nTime zone: America/Denver (MDT, -0600) \nNTP enabled: yes \nNTP synchronized: yes \nRTC in local TZ: no \nDST active: yes \nLast DST change: DST began at \n Sun 2017-03-12 01:59:59 MST \n Sun 2017-03-12 03:00:00 MDT \nNext DST change: DST ends (the clock jumps one hour backwards) at \n Sun 2017-11-05 01:59:59 MDT \n Sun 2017-11-05 01:00:00 MST\n \n[root@centos rdc]#\n" }, { "code": null, "e": 166594, "s": 166328, "text": "Currently, the system is correct to the local time zone. If your system is not, let's set the correct time zone. After changing the settings, CentOS will automatically calculate the time zone offset from the current time zone, adjusting the system clock right away." }, { "code": null, "e": 166643, "s": 166594, "text": "Let's list all the time zones with timedatectl −" }, { "code": null, "e": 166823, "s": 166643, "text": "[root@centos rdc]# timedatectl list-timezones \nAfrica/Abidjan\nAfrica/Accra\nAfrica/Addis_Ababa\nAfrica/Algiers\nAfrica/Asmara\nAfrica/Bamako\nAfrica/Bangui\nAfrica/Banjul\nAfrica/Bissau\n" }, { "code": null, "e": 166952, "s": 166823, "text": "That is the contended output from timedatectl list-timezones. To find a specific local time-zone, the grep command can be used −" }, { "code": null, "e": 167065, "s": 166952, "text": "[root@centos rdc]# timedatectl list-timezones | grep -i \"america/New_York\" \nAmerica/New_York\n[root@centos rdc]#\n" }, { "code": null, "e": 167182, "s": 167065, "text": "The label used by CentOS is usually Country/Region with an underscore instead of space (New_York versus \"New York\")." }, { "code": null, "e": 167212, "s": 167182, "text": "Now let's set our time zone −" }, { "code": null, "e": 167351, "s": 167212, "text": "[root@centos rdc]# timedatectl set-timezone \"America/New_York\"\n\n[root@centos rdc]# date \nMon Mar 20 02:28:44 EDT 2017\n\n[root@centos rdc]#\n" }, { "code": null, "e": 167407, "s": 167351, "text": "Your system clock should automatically adjust the time." }, { "code": null, "e": 167460, "s": 167407, "text": "Common command line switches when using journalctl −" }, { "code": null, "e": 167650, "s": 167460, "text": "First, we will examine and configure the boot logs in CentOS Linux. The first thing you will notice is that CentOS, by default, doesn't store boot logging that is persistent across reboots." }, { "code": null, "e": 167727, "s": 167650, "text": "To check boot logs per reboot instance, we can issue the following command −" }, { "code": null, "e": 168254, "s": 167727, "text": "[root@centos rdc]# journalctl --list-boots \n-4 bca6380a31a2463aa60ba551698455b5 Sun 2017-03-19 22:01:57 MDT—Sun 2017-03-19 22:11:02 MDT\n-3 3aaa9b84f9504fa1a68db5b49c0c7208 Sun 2017-03-19 22:11:09 MDT—Sun 2017-03-19 22:15:03 MDT\n-2 f80b231272bf48ffb1d2ce9f758c5a5f Sun 2017-03-19 22:15:11 MDT—Sun 2017-03-19 22:54:06 MDT\n-1 a071c1eed09d4582a870c13be5984ed6 Sun 2017-03-19 22:54:26 MDT—Mon 2017-03-20 00:48:29 MDT\n 0 9b4e6cdb43b14a328b1fa6448bb72a56 Mon 2017-03-20 00:48:38 MDT—Mon 2017-03-20 01:07:36 MDT\n\n[root@centos rdc]# \n" }, { "code": null, "e": 168308, "s": 168254, "text": "After rebooting the system, we can see another entry." }, { "code": null, "e": 168926, "s": 168308, "text": "[root@centos rdc]# journalctl --list-boots \n-5 bca6380a31a2463aa60ba551698455b5 Sun 2017-03-19 22:01:57 MDT—Sun 2017-03-19 22:11:02 MDT\n-4 3aaa9b84f9504fa1a68db5b49c0c7208 Sun 2017-03-19 22:11:09 MDT—Sun 2017-03-19 22:15:03 MDT\n-3 f80b231272bf48ffb1d2ce9f758c5a5f Sun 2017-03-19 22:15:11 MDT—Sun 2017-03-19 22:54:06 MDT\n-2 a071c1eed09d4582a870c13be5984ed6 Sun 2017-03-19 22:54:26 MDT—Mon 2017-03-20 00:48:29 MDT\n-1 9b4e6cdb43b14a328b1fa6448bb72a56 Mon 2017-03-20 00:48:38 MDT—Mon 2017-03-20 01:09:57 MDT\n 0 aa6aaf0f0f0d4fcf924e17849593d972 Mon 2017-03-20 01:10:07 MDT—Mon 2017-03-20 01:12:44 MDT\n \n[root@centos rdc]#\n" }, { "code": null, "e": 168978, "s": 168926, "text": "Now, let's examine the last boot logging instance −" }, { "code": null, "e": 169829, "s": 168978, "text": "root@centos rdc]# journalctl -b -5 \n-- Logs begin at Sun 2017-03-19 22:01:57 MDT, end at Mon 2017-03-20 01:20:27 MDT. --\nMar 19 22:01:57 localhost.localdomain systemd-journal[97]: Runtime journal is using 8.0M \n(max allowed 108.4M\nMar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpuset\nMar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpu\nMar 19 22:01:57 localhost.localdomain kernel: Initializing cgroup subsys cpuacct\nMar 19 22:01:57 localhost.localdomain kernel: Linux version 3.10.0514.6.2.el7.x86_64 \n(builder@kbuilder.dev.\nMar 19 22:01:57 localhost.localdomain kernel: Command line: \nBOOT_IMAGE=/vmlinuz-3.10.0-514.6.2.el7.x86_64 ro\nMar 19 22:01:57 localhost.localdomain kernel: Disabled fast string operations\nMar 19 22:01:57 localhost.localdomain kernel: e820: BIOS-provided physical RAM map:\n" }, { "code": null, "e": 170118, "s": 169829, "text": "Above is the condensed output from our last boot. We could also refer back to a boot log from hours, days, weeks, months, and even years. However, by default CentOS doesn't store persistent boot logs. To enable persistently storing boot logs, we need to make a few configuration changes −" }, { "code": null, "e": 170160, "s": 170118, "text": "Make central storage points for boot logs" }, { "code": null, "e": 170204, "s": 170160, "text": "Give proper permissions to a new log folder" }, { "code": null, "e": 170251, "s": 170204, "text": "Configure journald.conf for persistent logging" }, { "code": null, "e": 170394, "s": 170251, "text": "The initial place journald will want to store persistent boot logs is /var/log/journal. Since this doesn't exist by default, let's create it −" }, { "code": null, "e": 170437, "s": 170394, "text": "[root@centos rdc]# mkdir /var/log/journal\n" }, { "code": null, "e": 170511, "s": 170437, "text": "Now, let's give the directory proper permissions journald daemon access −" }, { "code": null, "e": 170564, "s": 170511, "text": "systemd-tmpfiles --create --prefix /var/log/journal\n" }, { "code": null, "e": 170702, "s": 170564, "text": "Finally, let's tell journald it should store persistent boot logs. In vim or your favorite text editor, open /etc/systemd/jounrald.conf\"." }, { "code": null, "e": 170769, "s": 170702, "text": "# See journald.conf(5) for details. \n[Journal]=Storage=peristent\n" }, { "code": null, "e": 171020, "s": 170769, "text": "The line we are concerned with is, Storage=. First remove the comment #, then change to Storage = persistent as depicted above. Save and reboot your CentOS system and take care that there should be multiple entries when running journalctl list-boots." }, { "code": null, "e": 171352, "s": 171020, "text": "Note − A constantly changing machine-id like that from a VPS provider can cause journald to fail at storing persistent boot logs. There are many workarounds for such a scenario. It is best to peruse the current fixes posted to CentOS Admin forums, than follow the trusted advice from those who have found plausible VPS workarounds." }, { "code": null, "e": 171520, "s": 171352, "text": "To examine a specific boot log, we simply need to get each offset using journald --list-boots the offset with the -b switch. So to check the second boot log we'd use −" }, { "code": null, "e": 171538, "s": 171520, "text": "journalctl -b -2\n" }, { "code": null, "e": 171650, "s": 171538, "text": "The default for -b with no boot log offset specified will always be the current boot log after the last reboot." }, { "code": null, "e": 171724, "s": 171650, "text": "Events from journald are numbered and categorized into 7 separate types −" }, { "code": null, "e": 172142, "s": 171724, "text": "0 - emerg :: System is unusable \n1 - alert :: Action must be taken immediatly \n2 - crit :: Action is advised to be taken immediatly \n3 - err :: Error effecting functionality of application \n4 - warning :: Usually means a common issue that can affect security or usilbity \n5 - info :: logged informtation for common operations \n6 - debug :: usually disabled by default to troubleshoot functionality\n" }, { "code": null, "e": 172233, "s": 172142, "text": "Hence, if we want to see all warnings the following command can be issued via journalctl −" }, { "code": null, "e": 174582, "s": 172233, "text": "[root@centos rdc]# journalctl -p 4\n-- Logs begin at Sun 2017-03-19 22:01:57 MDT, end at Wed 2017-03-22 22:33:42 MDT. --\nMar 19 22:01:57 localhost.localdomain kernel: ACPI: RSDP 00000000000f6a10 00024\n(v02 PTLTD )\nMar 19 22:01:57 localhost.localdomain kernel: ACPI: XSDT 0000000095eea65b 0005C\n(v01 INTEL 440BX 06040000 VMW 01\nMar 19 22:01:57 localhost.localdomain kernel: ACPI: FACP 0000000095efee73 000F4\n(v04 INTEL 440BX 06040000 PTL 00\nMar 19 22:01:57 localhost.localdomain kernel: ACPI: DSDT 0000000095eec749 1272A\n(v01 PTLTD Custom 06040000 MSFT 03\nMar 19 22:01:57 localhost.localdomain kernel: ACPI: FACS 0000000095efffc0 00040\nMar 19 22:01:57 localhost.localdomain kernel: ACPI: BOOT 0000000095eec721 00028\n(v01 PTLTD $SBFTBL$ 06040000 LTP 00\nMar 19 22:01:57 localhost.localdomain kernel: ACPI: APIC 0000000095eeb8bd 00742\n(v01 PTLTD ? APIC 06040000 LTP 00 \nMar 19 22:01:57 localhost.localdomain kernel: ACPI: MCFG 0000000095eeb881 0003C\n(v01 PTLTD $PCITBL$ 06040000 LTP 00 \nMar 19 22:01:57 localhost.localdomain kernel: ACPI: SRAT 0000000095eea757 008A8\n(v02 VMWARE MEMPLUG 06040000 VMW 00 \nMar 19 22:01:57 localhost.localdomain kernel: ACPI: HPET 0000000095eea71f 00038\n(v01 VMWARE VMW HPET 06040000 VMW 00 \nMar 19 22:01:57 localhost.localdomain kernel: ACPI: WAET 0000000095eea6f7 00028\n(v01 VMWARE VMW WAET 06040000 VMW 00 \nMar 19 22:01:57 localhost.localdomain kernel: Zone ranges: \nMar 19 22:01:57 localhost.localdomain kernel: DMA [mem 0x000010000x00ffffff] \nMar 19 22:01:57 localhost.localdomain kernel: DMA32 [mem 0x010000000xffffffff] \nMar 19 22:01:57 localhost.localdomain kernel: Normal empty \nMar 19 22:01:57 localhost.localdomain kernel: Movable zone start for each node \nMar 19 22:01:57 localhost.localdomain kernel: Early memory node ranges \nMar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x000010000x0009dfff] \nMar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x001000000x95edffff] \nMar 19 22:01:57 localhost.localdomain kernel: node 0: [mem 0x95f000000x95ffffff] \nMar 19 22:01:57 localhost.localdomain kernel: Built 1 zonelists in Node order,\nmobility grouping on. Total pages: 60 \nMar 19 22:01:57 localhost.localdomain kernel: Policy zone: DMA32 \nMar 19 22:01:57 localhost.localdomain kernel: ENERGY_PERF_BIAS: Set to\n'normal', was 'performance'\n" }, { "code": null, "e": 174646, "s": 174582, "text": "The above shows all warnings for the past 4 days on the system." }, { "code": null, "e": 174982, "s": 174646, "text": "The new way of viewing and perusing logs with systemd does take little practice and research to become familiar with. However, with different output formats and particular notice to making all packaged daemon logs universal, it is worth embracing. journald offers great flexibility and efficiency over traditional log analysis methods." }, { "code": null, "e": 175216, "s": 174982, "text": "Before exploring methods particular to CentOS for deploying a standard backup plan, let's first discuss typical considerations for a standard level backup policy. The first thing we want to get accustomed to is the 3-2-1 backup rule." }, { "code": null, "e": 175971, "s": 175216, "text": "Throughout the industry, you'll often hear the term 3-2-1 backup model. This is a very good approach to live by when implementing a backup plan. 3-2-1 is defined as follows − 3 copies of data; for example, we may have the working copy; a copy put onto the CentOS server designed for redundancy using rsync; and rotated, offsite USB backups are made from data on the backup server. 2 different backup mediums. We would actually have three different backup mediums in this case: the working copy on an SSD of a laptop or workstation, the CentOS server data on a RADI6 Array, and the offsite backups put on USB drives. 1 copy of data offsite; we are rotating the USB drives offsite on a nightly basis. Another modern approach may be a cloud backup provider." }, { "code": null, "e": 176433, "s": 175971, "text": "A bare metal restore plan is simply a plan laid out by a CentOS administrator to get vital systems online with all data intact. Assuming 100% systems failure and loss of all past system hardware, an administrator must have a plan to achieve uptime with intact user-data costing minimal downtime. The monolithic kernel used in Linux actually makes bare metal restores using system images much easier than Windows. Where Windows uses a micro-kernel architecture." }, { "code": null, "e": 176801, "s": 176433, "text": "A full data restore and bare metal recovery are usually accomplished through a combination of methods including working, configured production disk-images of key operational servers, redundant backups of user data abiding by the 3-2-1 rule. Even some sensitive files that may be stored in a secure, fireproof safe with limited access to the trusted company personnel." }, { "code": null, "e": 176899, "s": 176801, "text": "A multiphase bare metal restore and data recovery plan using native CentOS tools may consist of −" }, { "code": null, "e": 176967, "s": 176899, "text": "dd to make and restore production disk-images of configured servers" }, { "code": null, "e": 177035, "s": 176967, "text": "dd to make and restore production disk-images of configured servers" }, { "code": null, "e": 177086, "s": 177035, "text": "rsync to make incremental backups of all user data" }, { "code": null, "e": 177137, "s": 177086, "text": "rsync to make incremental backups of all user data" }, { "code": null, "e": 177492, "s": 177137, "text": "tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere." }, { "code": null, "e": 177847, "s": 177492, "text": "tar & gzip to store encrypted backups of files with passwords and notes from administrators. Commonly, this can be put on a USB drive, encrypted and locked in a safe that a Senior Manager access. Also, this ensures someone else will know vital security credentials if the current administrator wins the lottery and disappears to a sunny island somewhere." }, { "code": null, "e": 177971, "s": 177847, "text": "If a system crashes due to a hardware failure or disaster, following will be the different phases of restoring operations −" }, { "code": null, "e": 178029, "s": 177971, "text": "Build a working server with a configured bare metal image" }, { "code": null, "e": 178087, "s": 178029, "text": "Build a working server with a configured bare metal image" }, { "code": null, "e": 178135, "s": 178087, "text": "Restore data to the working server from backups" }, { "code": null, "e": 178183, "s": 178135, "text": "Restore data to the working server from backups" }, { "code": null, "e": 178262, "s": 178183, "text": "Have physical access to credentials needed to perform the first two operations" }, { "code": null, "e": 178341, "s": 178262, "text": "Have physical access to credentials needed to perform the first two operations" }, { "code": null, "e": 178664, "s": 178341, "text": "rsync is a great utility for syncing directories of files either locally or to another server. rsync has been used for years by System Administrators, hence it is very refined for the purpose of backing up data. In the author's opinion, one of the best features of sync is its ability to be scripted from the command line." }, { "code": null, "e": 178722, "s": 178664, "text": "In this tutorial, we will discuss rsync in various ways −" }, { "code": null, "e": 178765, "s": 178722, "text": "Explore and talk about some common options" }, { "code": null, "e": 178786, "s": 178765, "text": "Create local backups" }, { "code": null, "e": 178817, "s": 178786, "text": "Create remote backups over SSH" }, { "code": null, "e": 178839, "s": 178817, "text": "Restore local backups" }, { "code": null, "e": 178925, "s": 178839, "text": "rsync is named for its purpose: Remote Sync and is both powerful and flexible in use." }, { "code": null, "e": 178977, "s": 178925, "text": "Following is a basic rsync remote backup over ssh −" }, { "code": null, "e": 179715, "s": 178977, "text": "MiNi:~ rdc$ rsync -aAvz --progress ./Desktop/ImportantStuff/ \nrdc@192.168.1.143:home/rdc/ Documents/RemoteStuff/\nrdc@192.168.1.143's password:\nsending incremental file list\n 6,148 100% 0.00kB/s 0:00:00 (xfr#1, to-chk=23/25)\n2017-02-14 16_26_47-002 - Veeam_Architecture001.png\n 33,144 100% 31.61MB/s 0:00:00 (xfr#2, to-chk=22/25)\nA Guide to the WordPress REST API | Toptal.pdf\n 892,406 100% 25.03MB/s 0:00:00 (xfr#3, to-chk=21/25)\nRick Cardon Technologies, LLC..webloc\n 77 100% 2.21kB/s 0:00:00 (xfr#4, to-chk=20/25)\nbackbox-4.5.1-i386.iso\n 43,188,224 1% 4.26MB/s 0:08:29\nsent 2,318,683,608 bytes received 446 bytes 7,302,941.90 bytes/sec\ntotal size is 2,327,091,863 speedup is 1.00\nMiNi:~ rdc$\n" }, { "code": null, "e": 180007, "s": 179715, "text": "The following sync sent nearly 2.3GB of data across our LAN. The beauty of rsync is it works incrementally at the block level on a file-by-file basis. This means, if we change just two characters in a 1MB text file, only one or two blocks will be transferred across the lan on the next sync!" }, { "code": null, "e": 180512, "s": 180007, "text": "Furthermore, the incremental function can be disabled in favor of more network bandwidth used for less CPU utilization. This might prove advisable if constantly copying several 10MB database files every 10 minutes on a 1Gb dedicated Backup-Lan. The reasoning is: these will always be changing and will be transmitting incrementally every 10 minutes and may tax load of the remote CPU. Since the total transfer load will not exceed 5 minutes, we may just wish to sync the database files in their entirety." }, { "code": null, "e": 180564, "s": 180512, "text": "Following are the most common switches with rsync −" }, { "code": null, "e": 180651, "s": 180564, "text": "rsync syntax:\nrsync [options] [local path] [[remote host:remote path] or [target path\n" }, { "code": null, "e": 180860, "s": 180651, "text": "My personal preference for rsync is when backing up files from a source host to a target host. For example, all the home directories for data recovery or even offsite and into the cloud for disaster recovery." }, { "code": null, "e": 180996, "s": 180860, "text": "We have already seen how to transfer files from one host to another. The same method can be used to sync directories and files locally." }, { "code": null, "e": 181074, "s": 180996, "text": "Let's make a manual incremental backup of /etc/ in our root user's directory." }, { "code": null, "e": 181146, "s": 181074, "text": "First, we need to create a directory off ~/root for the synced backup −" }, { "code": null, "e": 181190, "s": 181146, "text": "[root@localhost rdc]# mkdir /root/etc_baks\n" }, { "code": null, "e": 181236, "s": 181190, "text": "Then, assure there is enough free disk-space." }, { "code": null, "e": 181460, "s": 181236, "text": "[root@localhost rdc]# du -h --summarize /etc/ \n49M /etc/\n \n[root@localhost rdc]# df -h \nFilesystem Size Used Avail Use% Mounted on \n/dev/mapper/cl-root 43G 15G 28G 35% /\n" }, { "code": null, "e": 181513, "s": 181460, "text": "We are good for syncing our entire /etc/ directory −" }, { "code": null, "e": 181548, "s": 181513, "text": "rsync -aAvr /etc/ /root/etc_baks/\n" }, { "code": null, "e": 181577, "s": 181548, "text": "Our synced /etc/ directory −" }, { "code": null, "e": 182219, "s": 181577, "text": "[root@localhost etc_baks]# ls -l ./\ntotal 1436\ndrwxr-xr-x. 3 root root 101 Feb 1 19:40 abrt\n-rw-r--r--. 1 root root 16 Feb 1 19:51 adjtime\n-rw-r--r--. 1 root root 1518 Jun 7 2013 aliases\n-rw-r--r--. 1 root root 12288 Feb 27 19:06 aliases.db\ndrwxr-xr-x. 2 root root 51 Feb 1 19:41 alsa\ndrwxr-xr-x. 2 root root 4096 Feb 27 17:11 alternatives\n-rw-------. 1 root root 541 Mar 31 2016 anacrontab\n-rw-r--r--. 1 root root 55 Nov 4 12:29 asound.conf\n-rw-r--r--. 1 root root 1 Nov 5 14:16 at.deny\ndrwxr-xr-x. 2 root root 32 Feb 1 19:40 at-spi2\n--{ condensed output }--\n" }, { "code": null, "e": 182255, "s": 182219, "text": "Now let's do an incremental rsync −" }, { "code": null, "e": 182578, "s": 182255, "text": "[root@localhost etc_baks]# rsync -aAvr --progress /etc/ /root/etc_baks/\nsending incremental file list\n\ntest_incremental.txt \n 0 100% 0.00kB/s 0:00:00 (xfer#1, to-check=1145/1282)\n \nsent 204620 bytes received 2321 bytes 413882.00 bytes/sec\ntotal size is 80245040 speedup is 387.77\n\n[root@localhost etc_baks]#\n" }, { "code": null, "e": 182625, "s": 182578, "text": "Only our test_incremental.txt file was copied." }, { "code": null, "e": 182893, "s": 182625, "text": "Let's do our initial rsync full backup onto a server with a backup plan deployed. This example is actually backing up a folder on a Mac OS X Workstation to a CentOS server. Another great aspect of rsync is that it can be used on any platform rsync has been ported to." }, { "code": null, "e": 183647, "s": 182893, "text": "MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/\nrdc@192.168.1.143:Documents/RemoteStuff\nrdc@192.168.1.143's password:\nsending incremental file list\n./\nA Guide to the WordPress REST API | Toptal.pdf\nRick Cardon Tech LLC.webloc\nVeeamDiagram.png\nbackbox-4.5.1-i386.iso\ndhcp_admin_script_update.py\nDDWRT/\nDDWRT/.DS_Store\nDDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\nDDWRT/ddwrt_mod_notes.docx\nDDWRT/factory-to-ddwrt.bin\nopen_ldap_config_notes/\nopen_ldap_config_notes/ldap_directory_a.png\nopen_ldap_config_notes/open_ldap_notes.txt\nperl_scripts/\nperl_scripts/mysnmp.pl\nphp_scripts/\nphp_scripts/chunked.php\nphp_scripts/gettingURL.php\nsent 2,318,281,023 bytes received 336 bytes 9,720,257.27 bytes/sec\ntotal size is 2,326,636,892 speedup is 1.00\nMiNi:~ rdc$\n" }, { "code": null, "e": 183930, "s": 183647, "text": "We have now backed up a folder from a workstation onto a server running a RAID6 volume with rotated disaster recovery media stored offsite. Using rsync has given us standard 3-2-1 backup with only one server having an expensive redundant disk array and rotated differential backups." }, { "code": null, "e": 184049, "s": 183930, "text": "Now let's do another backup of the same folder using rsync after a single new file named test_file.txt has been added." }, { "code": null, "e": 184338, "s": 184049, "text": "MiNi:~ rdc$ rsync -aAvz Desktop/ImportanStuff/\nrdc@192.168.1.143:Documents/RemoteStuff \nrdc@192.168.1.143's password: \nsending incremental file list \n ./ \ntest_file.txt\n\nsent 814 bytes received 61 bytes 134.62 bytes/sec\ntotal size is 2,326,636,910 speedup is 2,659,013.61\nMiNi:~ rdc$\n" }, { "code": null, "e": 184473, "s": 184338, "text": "As you can see, only the new file was delivered to the server via rsync. The differential comparison was made on a file-by-file basis." }, { "code": null, "e": 184666, "s": 184473, "text": "A few things to note are: This only copies the new file: test_file.txt, since it was the only file with changes. rsync uses ssh. We did not ever need to use our root account on either machine." }, { "code": null, "e": 184925, "s": 184666, "text": "Simple, powerful and effective, rsync is great for backing up entire folders and directory structures. However, rsync by itself doesn't automate the process. This is where we need to dig into our toolbox and find the best, small, and simple tool for the job." }, { "code": null, "e": 185129, "s": 184925, "text": "To automate rsync backups with cronjobs, it is essential that SSH users be set up using SSH keys for authentication. This combined with cronjobs enables rsync to be done automatically at timed intervals." }, { "code": null, "e": 185234, "s": 185129, "text": "DD is a Linux utility that has been around since the dawn of the Linux kernel meeting the GNU Utilities." }, { "code": null, "e": 185560, "s": 185234, "text": "dd in simplest terms copies an image of a selected disk area. Then provides the ability to copy selected blocks of a physical disk. So unless you have backups, once dd writes over a disk, all blocks are replaced. Loss of previous data exceeds the recovery capabilities for even highly priced professional-level data-recovery." }, { "code": null, "e": 185638, "s": 185560, "text": "The entire process for making a bootable system image with dd is as follows −" }, { "code": null, "e": 185701, "s": 185638, "text": "Boot from the CentOS server with a bootable linux distribution" }, { "code": null, "e": 185756, "s": 185701, "text": "Find the designation of the bootable disk to be imaged" }, { "code": null, "e": 185812, "s": 185756, "text": "Decide location where the recovery image will be stored" }, { "code": null, "e": 185850, "s": 185812, "text": "Find the block size used on your disk" }, { "code": null, "e": 185879, "s": 185850, "text": "Start the dd image operation" }, { "code": null, "e": 186286, "s": 185879, "text": "In this tutorial, for the sake of time and simplicity, we will be creating an ISO image of the master-boot record from a CentOS virtual machine. We will then store this image offsite. In case our MBR becomes corrupted and needs to be restored, the same process can be applied to an entire bootable disk or partition. However, the time and disk space needed really goes a little overboard for this tutorial." }, { "code": null, "e": 186711, "s": 186286, "text": "It is encouraged for CentOS admins to become proficient in restoring a fully bootable disk/partition in a test environment and perform a bare metal restore. This will take a lot of pressure off when eventually one needs to complete the practice in a real life situation with Managers and a few dozen end-users counting downtime. In such a case, 10 minutes of figuring things out can seem like an eternity and make one sweat." }, { "code": null, "e": 186964, "s": 186711, "text": "Note − When using dd make sure to NOT confuse source and target volumes. You can destroy data and bootable servers by copying your backup location to a boot drive. Or possibly worse destroy data forever by copying over data at a very low level with DD." }, { "code": null, "e": 187035, "s": 186964, "text": "Following are the common command line switches and parameters for dd −" }, { "code": null, "e": 187390, "s": 187035, "text": "Note on block size − The default block size for dd is 512 bytes. This was the standard block size of lower density hard disk drives. Today's higher density HDDs have increased to 4096 byte (4kB) block sizes to allow for disks ranging from 1TB and larger. Thus, we will want to check disk block size before using dd with newer, higher capacity hard disks." }, { "code": null, "e": 187629, "s": 187390, "text": "For this tutorial, instead of working on a production server with dd, we will be using a CentOS installation running in VMWare. We will also configure VMWare to boot a bootable Linux ISO image instead of working with a bootable USB Stick." }, { "code": null, "e": 187895, "s": 187629, "text": "First, we will need to download the CentOS image entitled − CentOS Gnome ISO. This is almost 3GB and it is advised to always keep a copy for creating bootable USB thumb-drives and booting into virtual server installations for trouble-shooting and bare metal images." }, { "code": null, "e": 188067, "s": 187895, "text": "Other bootable Linux distros will work just as well. Linux Mint can be used for bootable ISOs as it has great hardware support and polished GUI disk tools for maintenance." }, { "code": null, "e": 188204, "s": 188067, "text": "CentOS GNOME Live bootable image can be downloaded from: http://buildlogs.centos.org/rolling/7/isos/x86_64/CentOS-7-x86_64-LiveGNOME.iso" }, { "code": null, "e": 188422, "s": 188204, "text": "Let's configure our VMWare Workstation installation to boot from our Linux bootable image. The steps are for VMWare on OS X. However, they are similar across VMWare Workstation on Linux, Windows, and even Virtual Box." }, { "code": null, "e": 188783, "s": 188422, "text": "Note − Using a virtual desktop solution like Virtual Box or VMWare Workstation is a great way to set up lab scenarios for learning CentOS Administration tasks. It provides the ability to install several CentOS installations, practically no hardware configuration letting the person focus on administration, and even save the server state before making changes." }, { "code": null, "e": 188907, "s": 188783, "text": "First let's configure a virtual cd-rom and attach our ISO image to boot instead of the virtual CentOS server installation −" }, { "code": null, "e": 188935, "s": 188907, "text": "Now, set the startup disk −" }, { "code": null, "e": 189104, "s": 188935, "text": "Now when booted, our virtual machine will boot from the CentOS bootable ISO image and allow access to files on the Virtual CentOS server that was previously configured." }, { "code": null, "e": 189202, "s": 189104, "text": "Let’s check our disks to see where we want to copy the MBR from (condensed output is as follows)." }, { "code": null, "e": 189624, "s": 189202, "text": "MiNt ~ # fdisk -l\nDisk /dev/sda: 60 GiB, 21474836480 bytes, 41943040 sectors\nUnits: sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\n\nDisk /dev/sdb: 20 GiB, 21474836480 bytes, 41943040 sectors\nUnits: sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\n" }, { "code": null, "e": 189798, "s": 189624, "text": "We have located both our physical disks: sda and sdb. Each has a block size of 512 bytes. So, we will now run the dd command to copy the first 512 bytes for our MBR on SDA1." }, { "code": null, "e": 189827, "s": 189798, "text": "The best way to do this is −" }, { "code": null, "e": 190058, "s": 189827, "text": "[root@mint rdc]# dd if=/dev/sda bs=512 count=1 | gzip -c >\n/mnt/sdb/images/mbr.iso.gz \n1+0 records in \n1+0 records out \n512 bytes copied, 0.000171388 s, 3.0 MB/s\n\n[root@mint rdc]# ls /mnt/sdb/ \n mbr-iso.gz\n \n[root@mint rdc]#\n" }, { "code": null, "e": 190224, "s": 190058, "text": "Just like that, we have full image of out master boot record. If we have enough room to image the boot drive, we could just as easily make a full system boot image −" }, { "code": null, "e": 190336, "s": 190224, "text": "dd if=/dev/INPUT/DEVICE-NAME-HERE conv=sync,noerror bs=4K | gzip -c >\n/mnt/sdb/boot-server-centos-image.iso.gz\n" }, { "code": null, "e": 190822, "s": 190336, "text": "The conv=sync is used when bytes must be aligned for a physical medium. In this case, dd may get an error if exact 4K alignments are not read (say... a file that is only 3K but needs to take minimum of a single 4K block on disk. Or, there is simply an error reading and the file cannot be read by dd.). Thus, dd with conv=sync,noerror will pad the 3K with trivial, but useful data to physical medium in 4K block alignments. While not presenting an error that may end a large operation." }, { "code": null, "e": 190912, "s": 190822, "text": "When working with data from disks we always want to include: conv=sync,noerror parameter." }, { "code": null, "e": 191232, "s": 190912, "text": "This is simply because the disks are not streams like TCP data. They are made up of blocks aligned to a certain size. For example, if we have 512 byte blocks, a file of only 300 bytes still needs a full 512 bytes of disk-space (possibly 2 blocks for inode information like permissions and other filesystem information)." }, { "code": null, "e": 191384, "s": 191232, "text": "gzip and tar are two utilities a CentOS administrator must become accustomed to using. They are used for a lot more than to simply decompress archives." }, { "code": null, "e": 191726, "s": 191384, "text": "Tar is an archiving utility similar to winrar on Windows. Its name Tape Archive abbreviated as tar pretty much sums up the utility. tar will take files and place them into an archive for logical convenience. Hence, instead of the dozens of files stored in /etc. we could just \"tar\" them up into an archive for backup and storage convenience." }, { "code": null, "e": 191916, "s": 191726, "text": "tar has been the standard for storing archived files on Unix and Linux for many years. Hence, using tar along with gzip or bzip is considered as a best practice for archives on each system." }, { "code": null, "e": 191996, "s": 191916, "text": "Following is a list of common command line switches and options used with tar −" }, { "code": null, "e": 192054, "s": 191996, "text": "Following is the basic syntax for creating a tar archive." }, { "code": null, "e": 192083, "s": 192054, "text": "tar -cvf [tar archive name]\n" }, { "code": null, "e": 192411, "s": 192083, "text": "Note on Compression mechanisms with tar − It is advised to stick with one of two common compression schemes when using tar: gzip and bzip2. gzip files consume less CPU resources but are usually larger in size. While bzip2 will take longer to compress, they utilize more CPU resources; but will result in a smaller end filesize." }, { "code": null, "e": 192623, "s": 192411, "text": "When using file compression, we will always want to use standard file extensions letting everyone including ourselves know (versus guess by trial and error) what compression scheme is needed to extract archives." }, { "code": null, "e": 192898, "s": 192623, "text": "When needing to possibly extract archives on a Windows box or for use on Windows, it is advised to use the .tar.tbz or .tar.gz as most the three character single extensions will confuse Windows and Windows only Administrators (however, that is sometimes the desired outcome)" }, { "code": null, "e": 192991, "s": 192898, "text": "Let's create a gzipped tar archive from our remote backups copied from the Mac Workstation −" }, { "code": null, "e": 193961, "s": 192991, "text": "[rdc@mint Documents]$ tar -cvz -f RemoteStuff.tgz ./RemoteStuff/ \n./RemoteStuff/\n./RemoteStuff/.DS_Store\n./RemoteStuff/DDWRT/\n./RemoteStuff/DDWRT/.DS_Store\n./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\n./RemoteStuff/DDWRT/ddwrt_mod_notes.docx\n./RemoteStuff/DDWRT/factory-to-ddwrt.bin\n./RemoteStuff/open_ldap_config_notes/\n./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png\n./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt\n./RemoteStuff/perl_scripts/\n./RemoteStuff/perl_scripts/mysnmp.pl\n./RemoteStuff/php_scripts/\n./RemoteStuff/php_scripts/chunked.php\n./RemoteStuff/php_scripts/gettingURL.php\n./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf\n./RemoteStuff/Rick Cardon Tech LLC.webloc\n./RemoteStuff/VeeamDiagram.png\n./RemoteStuff/backbox-4.5.1-i386.iso\n./RemoteStuff/dhcp_admin_script_update.py\n./RemoteStuff/test_file.txt\n[rdc@mint Documents]$ ls -ld RemoteStuff.tgz\n-rw-rw-r--. 1 rdc rdc 2317140451 Mar 12 06:10 RemoteStuff.tgz\n" }, { "code": null, "e": 194271, "s": 193961, "text": "Note − Instead of adding all the files directly to the archive, we archived the entire folder RemoteStuff. This is the easiest method. Simply because when extracted, the entire directory RemoteStuff is extracted with all the files inside the current working directory as ./currentWorkingDirectory/RemoteStuff/" }, { "code": null, "e": 194335, "s": 194271, "text": "Now let's extract the archive inside the /root/ home directory." }, { "code": null, "e": 195210, "s": 194335, "text": "[root@centos ~]# tar -zxvf RemoteStuff.tgz\n./RemoteStuff/\n./RemoteStuff/.DS_Store\n./RemoteStuff/DDWRT/\n./RemoteStuff/DDWRT/.DS_Store\n./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\n./RemoteStuff/DDWRT/ddwrt_mod_notes.docx\n./RemoteStuff/DDWRT/factory-to-ddwrt.bin\n./RemoteStuff/open_ldap_config_notes/\n./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png\n./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt\n./RemoteStuff/perl_scripts/\n./RemoteStuff/perl_scripts/mysnmp.pl\n./RemoteStuff/php_scripts/\n./RemoteStuff/php_scripts/chunked.php\n./RemoteStuff/php_scripts/gettingURL.php\n./RemoteStuff/A Guide to the WordPress REST API | Toptal.pdf\n./RemoteStuff/Rick Cardon Tech LLC.webloc\n./RemoteStuff/VeeamDiagram.png\n./RemoteStuff/backbox-4.5.1-i386.iso\n./RemoteStuff/dhcp_admin_script_update.py\n./RemoteStuff/test_file.txt\n[root@mint ~]# ping www.google.com\n" }, { "code": null, "e": 195329, "s": 195210, "text": "As seen above, all the files were simply extracted into the containing directory within our current working directory." }, { "code": null, "e": 195840, "s": 195329, "text": "[root@centos ~]# ls -l \ntotal 2262872 \n-rw-------. 1 root root 1752 Feb 1 19:52 anaconda-ks.cfg \ndrwxr-xr-x. 137 root root 8192 Mar 9 04:42 etc_baks \n-rw-r--r--. 1 root root 1800 Feb 2 03:14 initial-setup-ks.cfg \ndrwxr-xr-x. 6 rdc rdc 4096 Mar 10 22:20 RemoteStuff \n-rw-r--r--. 1 root root 2317140451 Mar 12 07:12 RemoteStuff.tgz \n-rw-r--r--. 1 root root 9446 Feb 25 05:09 ssl.conf [root@centos ~]#\n" }, { "code": null, "e": 196084, "s": 195840, "text": "As noted earlier, we can use either bzip2 or gzip from tar with the -j or -z command line switches. We can also use gzip to compress individual files. However, using bzip or gzip alone does not offer as many features as when combined with tar." }, { "code": null, "e": 196220, "s": 196084, "text": "When using gzip, the default action is to remove the original files, replacing each with a compressed version adding the .gz extension." }, { "code": null, "e": 196269, "s": 196220, "text": "Some common command line switches for gzip are −" }, { "code": null, "e": 196523, "s": 196269, "text": "gzip more or less works on a file-by-file basis and not on an archive basis like some Windows O/S zip utilities. The main reason for this is that tar already provides advanced archiving features. gzip is designed to provide only a compression mechanism." }, { "code": null, "e": 196687, "s": 196523, "text": "Hence, when thinking of gzip, think of a single file. When thinking of multiple files, think of tar archives. Let's now explore this with our previous tar archive." }, { "code": null, "e": 196774, "s": 196687, "text": "Note − Seasoned Linux professionals will often refer to a tarred archive as a tarball." }, { "code": null, "e": 196828, "s": 196774, "text": "Let's make another tar archive from our rsync backup." }, { "code": null, "e": 196951, "s": 196828, "text": "[root@centos Documents]# tar -cvf RemoteStuff.tar ./RemoteStuff/\n[root@centos Documents]# ls\nRemoteStuff.tar RemoteStuff/\n" }, { "code": null, "e": 197146, "s": 196951, "text": "For demonstration purposes, let's gzip the newly created tarball, and tell gzip to keep the old file. By default, without the -c option, gzip will replace the entire tar archive with a .gz file." }, { "code": null, "e": 197383, "s": 197146, "text": "[root@centos Documents]# gzip -c RemoteStuff.tar > RemoteStuff.tar.gz\n[root@centos Documents]# ls\nRemoteStuff RemoteStuff.tar RemoteStuff.tar.gz\nWe now have our original directory, our tarred directory and finally our gziped tarball.\n" }, { "code": null, "e": 197426, "s": 197383, "text": "Let's try to test the -l switch with gzip." }, { "code": null, "e": 197644, "s": 197426, "text": "[root@centos Documents]# gzip -l RemoteStuff.tar.gz \n compressed uncompressed ratio uncompressed_name \n 2317140467 2326661120 0.4% RemoteStuff.tar\n \n[root@centos Documents]#\n" }, { "code": null, "e": 197746, "s": 197644, "text": "To demonstrate how gzip differs from Windows Zip Utilities, let's run gzip on a folder of text files." }, { "code": null, "e": 197867, "s": 197746, "text": "[root@centos Documents]# ls text_files/\n file1.txt file2.txt file3.txt file4.txt file5.txt\n[root@centos Documents]#\n" }, { "code": null, "e": 197956, "s": 197867, "text": "Now let's use the -r option to recursively compress all the text files in the directory." }, { "code": null, "e": 198144, "s": 197956, "text": "[root@centos Documents]# gzip -9 -r text_files/\n\n[root@centos Documents]# ls ./text_files/\nfile1.txt.gz file2.txt.gz file3.txt.gz file4.txt.gz file5.txt.gz\n \n[root@centos Documents]#\n" }, { "code": null, "e": 198362, "s": 198144, "text": "See? Not what some may have anticipated. All the original text files were removed and each was compressed individually. Because of this behavior, it is best to think of gzip alone when needing to work in single files." }, { "code": null, "e": 198441, "s": 198362, "text": "Working with tarballs, let's extract our rsynced tarball into a new directory." }, { "code": null, "e": 199018, "s": 198441, "text": "[root@centos Documents]# tar -C /tmp -zxvf RemoteStuff.tar.gz\n./RemoteStuff/\n./RemoteStuff/.DS_Store\n./RemoteStuff/DDWRT/\n./RemoteStuff/DDWRT/.DS_Store\n./RemoteStuff/DDWRT/ddwrt-linksys-wrt1200acv2-webflash.bin\n./RemoteStuff/DDWRT/ddwrt_mod_notes.docx\n./RemoteStuff/DDWRT/factory-to-ddwrt.bin\n./RemoteStuff/open_ldap_config_notes/\n./RemoteStuff/open_ldap_config_notes/ldap_directory_a.png\n./RemoteStuff/open_ldap_config_notes/open_ldap_notes.txt\n./RemoteStuff/perl_scripts/\n./RemoteStuff/perl_scripts/mysnmp.pl\n./RemoteStuff/php_scripts/\n./RemoteStuff/php_scripts/chunked.php\n" }, { "code": null, "e": 199100, "s": 199018, "text": "As seen above, we extracted and decompressed our tarball into the /tmp directory." }, { "code": null, "e": 199163, "s": 199100, "text": "[root@centos Documents]# ls /tmp \nhsperfdata_root\nRemoteStuff\n" }, { "code": null, "e": 199450, "s": 199163, "text": "Encrypting tarball archives for storing secure documents that may need to be accessed by other employees of the organization, in case of disaster recovery, can be a tricky concept. There are basically three ways to do this: either use GnuPG, or use openssl, or use a third part utility." }, { "code": null, "e": 199923, "s": 199450, "text": "GnuPG is primarily designed for asymmetric encryption and has an identity-association in mind rather than a passphrase. True, it can be used with symmetrical encryption, but this is not the main strength of GnuPG. Thus, I would discount GnuPG for storing archives with physical security when more people than the original person may need access (like maybe a corporate manager who wants to protect against an Administrator holding all the keys to the kingdom as leverage)." }, { "code": null, "e": 200106, "s": 199923, "text": "Openssl like GnuPG can do what we want and ships with CentOS. But again, is not specifically designed to do what we want and encryption has been questioned in the security community." }, { "code": null, "e": 200427, "s": 200106, "text": "Our choice is a utility called 7zip. 7zip is a compression utility like gzip but with many more features. Like Gnu Gzip, 7zip and its standards are in the open-source community. We just need to install 7zip from our EHEL Repository (the next chapter will cover installing the Extended Enterprise Repositories in detail)." }, { "code": null, "e": 200522, "s": 200427, "text": "7zip is a simple install once our EHEL repositories have been loaded and configured in CentOS." }, { "code": null, "e": 201137, "s": 200522, "text": "[root@centos Documents]# yum -y install p7zip.x86_64 p7zip-plugins.x86_64\nLoaded plugins: fastestmirror, langpacks\nbase\n| 3.6 kB 00:00:00\nepel/x86_64/metalink\n| 13 kB 00:00:00\nepel\n| 4.3 kB 00:00:00\nextras\n| 3.4 kB 00:00:00\nupdates\n| 3.4 kB 00:00:00\n(1/2): epel/x86_64/updateinfo\n| 756 kB 00:00:04 \n(2/2):\nepel/x86_64/primary_db\n| 4.6 MB 00:00:18\nLoading mirror speeds from cached hostfile\n--> Running transaction check\n---> Package p7zip.x86_64 0:16.02-2.el7 will be installed\n---> Package p7zip-plugins.x86_64 0:16.02-2.el7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n" }, { "code": null, "e": 201243, "s": 201137, "text": "Simple as that, 7zip is installed and ready be used with 256-bit AES encryption for our tarball archives." }, { "code": null, "e": 201351, "s": 201243, "text": "Now let's use 7z to encrypt our gzipped archive with a password. The syntax for doing so is pretty simple −" }, { "code": null, "e": 201394, "s": 201351, "text": "7z a -p <output filename><input filename>\n" }, { "code": null, "e": 201462, "s": 201394, "text": "Where, a: add to archive, and -p: encrypt and prompt for passphrase" }, { "code": null, "e": 202158, "s": 201462, "text": "[root@centos Documents]# 7z a -p RemoteStuff.tgz.7z RemoteStuff.tar.gz\n\n7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21\np7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R)\nCore(TM) i5-4278U CPU @ 2.60GHz (40651),ASM,AES-NI)\nScanning the drive:\n1 file, 2317140467 bytes (2210 MiB)\n\nCreating archive: RemoteStuff.tgz.7z\n\nItems to compress: 1\n\nEnter password (will not be echoed):\nVerify password (will not be echoed) :\n\nFiles read from disk: 1\nArchive size: 2280453410 bytes (2175 MiB)\nEverything is Ok\n[root@centos Documents]# ls\nRemoteStuff RemoteStuff.tar RemoteStuff.tar.gz RemoteStuff.tgz.7z slapD\ntext_files\n\n[root@centos Documents]#\n" }, { "code": null, "e": 202239, "s": 202158, "text": "Now, we have our .7z archive that encrypts the gzipped tarball with 256-bit AES." }, { "code": null, "e": 202430, "s": 202239, "text": "Note − 7zip uses AES 256-bit encryption with an SHA-256 hash of the password and counter, repeated up to 512K times for key derivation. This should be secure enough if a complex key is used." }, { "code": null, "e": 202535, "s": 202430, "text": "The process of encrypting and recompressing the archive further can take some time with larger archives." }, { "code": null, "e": 202734, "s": 202535, "text": "7zip is an advanced offering with more features than gzip or bzip2. However, it is not as standard with CentOS or amongst the Linux world. Thus, the other utilities should be used often as possible." }, { "code": null, "e": 202785, "s": 202734, "text": "The CentOS 7 system can be updated in three ways −" }, { "code": null, "e": 202794, "s": 202785, "text": "Manually" }, { "code": null, "e": 202808, "s": 202794, "text": "Automatically" }, { "code": null, "e": 202882, "s": 202808, "text": "Update manually for major security issues and configure automatic updates" }, { "code": null, "e": 203080, "s": 202882, "text": "In a production environment, it is recommended to update manually for production servers. Or at least establish an update plan so the administrator can assure services vital to business operations." }, { "code": null, "e": 203354, "s": 203080, "text": "It is plausible a simple security update can cause recursive issues with common application that requires upgrading and reconfiguration by an Administrator. So, be weary of scheduling automatic updates in production before testing in development servers and desktops first." }, { "code": null, "e": 203522, "s": 203354, "text": "To update CentOS 7, we will want to become familiar with the yum command. yum is used to deal with package repositories in CentOS 7. yum is the tool commonly used to −" }, { "code": null, "e": 203555, "s": 203522, "text": "Update the CentOS 7 Linux System" }, { "code": null, "e": 203575, "s": 203555, "text": "Search for packages" }, { "code": null, "e": 203592, "s": 203575, "text": "Install packages" }, { "code": null, "e": 203646, "s": 203592, "text": "Detect and install required dependencies for packages" }, { "code": null, "e": 203905, "s": 203646, "text": "In order to use yum for updates, your CentOS server will need to be connected to the Internet. Most configurations will install a base system, then use yum to query the main CentOS repository for additional functionality in packages and apply system updates." }, { "code": null, "e": 204127, "s": 203905, "text": "We have already made use of yum to install a few packages. When using yum you will always need to do so as the root user. Or a user with root access. So let's search for and install an easy to use text-editor called nano." }, { "code": null, "e": 204806, "s": 204127, "text": "[root@centos rdc]# yum search nano\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.rackspace.com\n * epel: mirror.chpc.utah.edu\n * extras: repos.forethought.net \n * updates: repos.forethought.net \n====================================================================== \n N/S matched: nano \n======================================================================\nnano.x86_64 : A small text editor\nnodejs-nano.noarch : Minimalistic couchdb driver for Node.js\nperl-Time-Clock.noarch : Twenty-four hour clock object with nanosecond precision\n Name and summary matches only, use \"search all\" for everything.\n \n[root@centos rdc]#\n" }, { "code": null, "e": 204847, "s": 204806, "text": "Now, let's install the nano text editor." }, { "code": null, "e": 206132, "s": 204847, "text": "[root@centos rdc]# yum install nano\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.keystealth.org\n * epel: pubmirror1.math.uh.edu\n * extras: centos.den.host-engine.com\n * updates: repos.forethought.net\nResolving Dependencies\n--> Running transaction check\n---> Package nano.x86_64 0:2.3.1-10.el7 will be installed\n--> Finished Dependency Resolution\nDependencies Resolved\n================================================================================ \nPackage Arch\nVersion Repository Size \n================================================================================ \n Installing: \n nano x86_64\n 2.3.1-10.el7 base 440 k\n \nTransaction Summary\nInstall 1 Package\nTotal download size: 440 k\nInstalled size: 1.6 M\nIs this ok [y/d/N]: y\nDownloading packages:\nnano-2.3.1-10.el7.x86_64.rpm\n| 440 kB 00:00:00\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : nano-2.3.1-10.el7.x86_64\n1/1 \n Verifying : nano-2.3.1-10.el7.x86_64\n1/1 \nInstalled: \n nano.x86_64 0:2.3.1-10.el7\n \nComplete!\n\n[root@centos rdc]#\n" }, { "code": null, "e": 206577, "s": 206132, "text": "We have installed the nano text editor. This method, IMO, is a lot easier than searching for utilities on websites and manually running the installers. Also, repositories use digital signatures to validate packages assuring they are coming from a trusted source with yum. It is up to the administrator to validate authenticity when trusting new repositories. This is why it is considered a best practice to be weary of third party repositories." }, { "code": null, "e": 206619, "s": 206577, "text": "Yum can also be used to remove a package." }, { "code": null, "e": 206868, "s": 206619, "text": "[root@centos rdc]# yum remove nano \nLoaded plugins: fastestmirror, langpacks \nResolving Dependencies \n--> Running transaction check \n---> Package nano.x86_64 0:2.3.1-10.el7 will be erased \n--> Finished Dependency Resolution\n\nDependencies Resolved \n" }, { "code": null, "e": 206897, "s": 206868, "text": "Now let's check for updates." }, { "code": null, "e": 207762, "s": 206897, "text": "[root@centos rdc]# yum list updates\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.keystealth.org\n * epel: pubmirror1.math.uh.edu\n * extras: centos.den.host-engine.com\n * updates: repos.forethought.net\nUpdated Packages\nNetworkManager.x86_64 1:1.4.0-17.el7_3 updates\nNetworkManager-adsl.x86_64 1:1.4.0-17.el7_3 updates\nNetworkManager-glib.x86_64 1:1.4.0-17.el7_3 updates\nNetworkManager-libnm.x86_64 1:1.4.0-17.el7_3 updates\nNetworkManager-team.x86_64 1:1.4.0-17.el7_3 updates\nNetworkManager-tui.x86_64 1:1.4.0-17.el7_3 updates\nNetworkManager-wifi.x86_64 1:1.4.0-17.el7_3 updates\naudit.x86_64 2.6.5-3.el7_3.1 updates\naudit-libs.x86_64 2.6.5-3.el7_3.1 updates\naudit-libs-python.x86_64\n" }, { "code": null, "e": 207960, "s": 207762, "text": "As depicted, we have a few dozen updates pending to install. Actually, there are about 100 total updates since we have not yet configured automatic updates. Thus, let's install all pending updates." }, { "code": null, "e": 209426, "s": 207960, "text": "[root@centos rdc]# yum update\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirrors.usc.edu\n * epel: pubmirror1.math.uh.edu\n * extras: repos.forethought.net\n * updates: repos.forethought.net\nResolving Dependencies\n--> Running transaction check\n---> Package NetworkManager.x86_64 1:1.4.0-14.el7_3 will be updated\n---> Package NetworkManager.x86_64 1:1.4.0-17.el7_3 will be an update\n selinux-policy noarch 3.13.1102.el7_3.15 updates 414 k\n selinux-policy-targeted noarch 3.13.1102.el7_3.15 updates 6.4 M \n systemd x86_64 21930.el7_3.7 updates 5.2 M \n systemd-libs x86_64 21930.el7_3.7 updates 369 k \n systemd-python x86_64 21930.el7_3.7 updates 109 k \n systemd-sysv x86_64 21930.el7_3.7 updates 63 k \n tcsh x86_64 6.18.01-13.el7_3.1 updates 338 k \n tzdata noarch 2017a1.el7 updates 443 k \n tzdata-java noarch 2017a1.el7 updates 182 k \nwpa_supplicant x86_64 1:2.021.el7_3 updates 788 k \n\nTransaction Summary \n=============================================================================== \n Install 2 Packages \n Upgrade 68 Packages \nTotal size: 196 M \nTotal download size: 83 M \nIs this ok [y/d/N]:\n" }, { "code": null, "e": 209550, "s": 209426, "text": "After hitting the \"y\" key, updating of CentOS 7 will commence. The general process that yum goes through when updating is −" }, { "code": null, "e": 209578, "s": 209550, "text": "Checks the current packages" }, { "code": null, "e": 209623, "s": 209578, "text": "Looks in the repository for updated packages" }, { "code": null, "e": 209675, "s": 209623, "text": "Calculates dependencies needed for updated packages" }, { "code": null, "e": 209693, "s": 209675, "text": "Downloads updates" }, { "code": null, "e": 209710, "s": 209693, "text": "Installs updates" }, { "code": null, "e": 209758, "s": 209710, "text": "Now, let's make sure our system is up to date −" }, { "code": null, "e": 209933, "s": 209758, "text": "[root@centos rdc]# yum list updates \nLoaded plugins: fastestmirror, langpacks \nLoading mirror speeds from cached hostfile \n * updates: mirror.compevo.com\n\n[root@centos rdc]#\n" }, { "code": null, "e": 209978, "s": 209933, "text": "As you can see, there are no updates listed." }, { "code": null, "e": 210172, "s": 209978, "text": "In an Enterprise environment, as mentioned earlier, automatic updates may or may not be the preferred method of installation. Let's go over the steps for configuring automatic updates with yum." }, { "code": null, "e": 210217, "s": 210172, "text": "First, we install a package called yum-cron." }, { "code": null, "e": 210706, "s": 210217, "text": "[root@centos rdc]# yum -y install yum-cron\nInstall 1 Package\nTotal download size: 61 k\nInstalled size: 51 k\nDownloading packages:\nyum-cron-3.4.3-150.el7.centos.noarch.rpm\n| 61 kB 00:00:01\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n Installing : yum-cron-3.4.3-150.el7.centos.noarch\n1/1\n Verifying : yum-cron-3.4.3-150.el7.centos.noarch\n1/1\n\nInstalled: \n yum-cron.noarch 0:3.4.3-150.el7.centos\n \nComplete!\n\n[root@centos rdc]# \n" }, { "code": null, "e": 211001, "s": 210706, "text": "By default, yum-cron will only download updates and not install them. Whether to install updates automatically is on the Administrator. The biggest caveat is: some updates will require a system reboot. Also, some updates may require a configuration change before services are again operational." }, { "code": null, "e": 211092, "s": 211001, "text": "Updating dependencies can possibly create a recursive problem in the following situation −" }, { "code": null, "e": 211146, "s": 211092, "text": "An update is recommended by yum for a certain library" }, { "code": null, "e": 211200, "s": 211146, "text": "An update is recommended by yum for a certain library" }, { "code": null, "e": 211268, "s": 211200, "text": "The library only supports Apache Server 2.4, but we have server 2.3" }, { "code": null, "e": 211336, "s": 211268, "text": "The library only supports Apache Server 2.4, but we have server 2.3" }, { "code": null, "e": 211389, "s": 211336, "text": "Our commerce site relies on a certain version of PHP" }, { "code": null, "e": 211442, "s": 211389, "text": "Our commerce site relies on a certain version of PHP" }, { "code": null, "e": 211517, "s": 211442, "text": "The new version of Apache installed for the library requires upgrading PHP" }, { "code": null, "e": 211592, "s": 211517, "text": "The new version of Apache installed for the library requires upgrading PHP" }, { "code": null, "e": 211676, "s": 211592, "text": "Our production web applications have not yet been tested with the newer PHP version" }, { "code": null, "e": 211760, "s": 211676, "text": "Our production web applications have not yet been tested with the newer PHP version" }, { "code": null, "e": 211859, "s": 211760, "text": "Yum may go ahead and automatically upgrade Apache and PHP without notice unless configured not to." }, { "code": null, "e": 212112, "s": 211859, "text": "If all 5 scenarios play out, it can result in anything from a big headache in the morning to a possible security compromise exposing the user data. While the aforementioned example is a perfect storm of sorts, we never want such a scenario to play out." }, { "code": null, "e": 212434, "s": 212112, "text": "It is up to the Administrator for accessing possible scenarios of potential revenue loss from time needed to restore services due to possible downtime from update reboots and reconfigurations. This practice may not be conservative enough for, say, a multi-million dollar per day ecommerce site with millions of customers." }, { "code": null, "e": 212504, "s": 212434, "text": "Now let's configure yum-cron to automatically install system updates." }, { "code": null, "e": 212709, "s": 212504, "text": "[root@centos rdc]# vim /etc/yum/yum-cron.conf\n# Whether updates should be applied when they are available. Note\n# that download_updates must also be yes for the update to be applied.\napply_updates = yes\n" }, { "code": null, "e": 212824, "s": 212709, "text": "We want to change apply_updates = no to apply_updates = yes. Now let's configure the update interval for yum-cron." }, { "code": null, "e": 212996, "s": 212824, "text": "Again, whether to use automatic updates and install updates on demand can be a double edged sword and needs to be considered by an administrator for each unique situation." }, { "code": null, "e": 213444, "s": 212996, "text": "Like flavors of GNU Linux, shells come in many varieties and vary in compatibility. The default shell in CentOS is known as the Bash or Bourne Again Shell. The Bash shell is a modern day, modified version of Bourne Shell developed by Stephen Bourne. Bash was the direct replacement to the original Thompson Shell on the Unix operating system developed at Bell Labs by Ken Thompson and Dennis Ritchie (Stephen Bourne was also employed by Bell Labs)" }, { "code": null, "e": 213798, "s": 213444, "text": "Everyone has a favorite shell and each has its strengths and difficulties. But for the most part, Bash is going to be the default shell across all Linux distributions and most commonly available. With experience, everyone will want to explore and use a shell that is best for them. However at the same time, everyone will also want to master Bash shell." }, { "code": null, "e": 213857, "s": 213798, "text": "Other Linux shells include: Tcsh, Csh, Ksh, Zsh, and Fish." }, { "code": null, "e": 214370, "s": 213857, "text": "Developing skills to use any Linux shell at an expert level is extremely important to a CentOS administrator. As we mentioned previously, unlike Windows, Linux at its heart is a command line operating system. A shell is simply a user interface that allows an administrator (or user) to issue commands to the operating system. If a Linux system administrator were an airlines pilot, using the shell would be similar to taking the plane off auto-pilot and grabbing the manual controls for more maneuverable flight." }, { "code": null, "e": 214606, "s": 214370, "text": "A Linux shell, like Bash, is known in Computer Science terms as a Command Line Interpreter. Microsoft Windows also has two command line interpreters called DOS (not to be confused with the original DOS operating system) and PowerShell." }, { "code": null, "e": 214733, "s": 214606, "text": "Most modern shells like Bash provide constructs allowing more complex shell scripts to automate both common and complex tasks." }, { "code": null, "e": 214754, "s": 214733, "text": "Constructs include −" }, { "code": null, "e": 214792, "s": 214754, "text": "Script flow control (ifthen and else)" }, { "code": null, "e": 214858, "s": 214792, "text": "Logical comparison operations (greater than, less than, equality)" }, { "code": null, "e": 214864, "s": 214858, "text": "Loops" }, { "code": null, "e": 214874, "s": 214864, "text": "Variables" }, { "code": null, "e": 214940, "s": 214874, "text": "Parameters defining operation (similar to switches with commands)" }, { "code": null, "e": 215097, "s": 214940, "text": "Often when thinking about performing a task administrators ask themselves: Should I use a shell script or a scripting language such as Perl, Ruby or Python?" }, { "code": null, "e": 215202, "s": 215097, "text": "There is no set rule here. There are only typical differences between shells versus scripting languages." }, { "code": null, "e": 215426, "s": 215202, "text": "Shell allows the use of Linux commands such as sed, grep, tee, cat and all other command-line based utilities on the Linux operating system. In fact, pretty much any command line Linux utility can be scripted in your shell." }, { "code": null, "e": 215528, "s": 215426, "text": "A great example of using a shell would be a quick script to check a list of hosts for DNS resolution." }, { "code": null, "e": 215572, "s": 215528, "text": "Our simple Bash Script to check DNS names −" }, { "code": null, "e": 215671, "s": 215572, "text": "#!/bin/bash \nfor name in $(cat $1);\n do \n host $name.$2 | grep \"has address\" \n done \nexit" }, { "code": null, "e": 215714, "s": 215671, "text": "small wordlist to test DNS resolution on −" }, { "code": null, "e": 215754, "s": 215714, "text": "dns \nwww \ntest \ndev \nmail \nrdp \nremote\n" }, { "code": null, "e": 215789, "s": 215754, "text": "Output against google.com domain −" }, { "code": null, "e": 216075, "s": 215789, "text": "[rdc@centos ~]$ ./dns-check.sh dns-names.txt google.com\n-doing dns\ndns.google.com has address 172.217.6.46\n-doing www\nwww.google.com has address 172.217.6.36\n-doing test\n-doing dev\n-doing mail\ngooglemail.l.google.com has address 172.217.6.37\n-doing rdp\n-doing remote\n\n[rdc@centos ~]$\n" }, { "code": null, "e": 216323, "s": 216075, "text": "Leveraging simple Linux commands in our shell, we were able to make a simple 5-line script to audit DNS names from a word list. This would have taken some considerable time in Perl, Python, or Ruby even when using a nicely implemented DNS Library." }, { "code": null, "e": 216602, "s": 216323, "text": "A scripting language will give more control outside the shell. The above Bash script used a wrapper around the Linux host command. What if we wanted to do more and make our own application like host to interact outside the shell? This is where we would use a scripting language." }, { "code": null, "e": 216902, "s": 216602, "text": "Also, with a highly maintained scripting language we know our actions will work across different systems for the most part. Python 3.5, for example, will work on any other system running Python 3.5 with the same libraries installed. Not so, if we want to run our BASH script on both Linux and HP-UX." }, { "code": null, "e": 217226, "s": 216902, "text": "Sometimes the lines between a scripting language and a powerful shell can be blurred. It is possible to automate CentOS Linux administration tasks with Python, Perl or Ruby. Doing so is really quite commonplace. Also, affluent shell-script developers have made a simple, but otherwise functional, web-server daemon in Bash." }, { "code": null, "e": 217545, "s": 217226, "text": "With experience in scripting languages and automating tasks in shells, a CentOS administrator will be able to quickly determine where to start when needing to solve a problem. It is quite common to start a project with a shell script. Then progress to a scripting (or compiled) language as a project gets more complex." }, { "code": null, "e": 217862, "s": 217545, "text": "Also, it is ok to use both a scripting language and shell script for different parts of a project. An example could be a Perl script to scrape a website. Then, use a shell script to parse and format with sed, awk, and egrep. Finally, use a PHP script for inserting formatted data into MySQL database using a web GUI." }, { "code": null, "e": 217990, "s": 217862, "text": "With some theory behind shells, let's get started with the basic building blocks to automate tasks from a Bash shell in CentOS." }, { "code": null, "e": 218029, "s": 217990, "text": "Processing stdout to another command −" }, { "code": null, "e": 218094, "s": 218029, "text": "[rdc@centos ~]$ cat ~/output.txt | wc -l \n6039 \n[rdc@centos ~]$\n" }, { "code": null, "e": 218377, "s": 218094, "text": "Above, we have passed cat'sstoud to wc for processing with the pipe character. wc then processed the output from cat, printing the line count of output.txt to the terminal. Think of the pipe character as a \"pipe\" passing output from one command, to be processed by the next command." }, { "code": null, "e": 218460, "s": 218377, "text": "Following are the key concepts to remember when dealing with command redirection −" }, { "code": null, "e": 218647, "s": 218460, "text": "We introduced this in chapter one without really talking much about redirection or assigning redirection. When opening a terminal in Linux, your shell is seen as the default target for −" }, { "code": null, "e": 218666, "s": 218647, "text": "standard input < 0" }, { "code": null, "e": 218686, "s": 218666, "text": "standard output > 1" }, { "code": null, "e": 218703, "s": 218686, "text": "standard error 2" }, { "code": null, "e": 218730, "s": 218703, "text": "Let's see how this works −" }, { "code": null, "e": 219100, "s": 218730, "text": "[rdc@centos ~]$ lsof -ap $BASHPID -d 0,1,2 \n COMMAND PID USER **FD** TYPE DEVICE SIZE/OFF NODE NAME \n bash 13684 rdc **0u** CHR 136,0 0t0 3 /dev/pts/0 \n bash 13684 rdc **1u** CHR 136,0 0t0 3 /dev/pts/0 \n bash 13684 rdc **2u** CHR 136,0 0t0 3 /dev/pts/0\n \n[rdc@centos ~]$ \n" }, { "code": null, "e": 219414, "s": 219100, "text": "/dev/pts/0 is our pseudo terminal. CentOS Linux looks at this and thinks of our open terminal application like a real terminal with the keyboard and display plugged in through a serial interface. However, like a hypervisor abstracts hardware to an operating system /dev/pts abstracts our terminal to applications." }, { "code": null, "e": 219644, "s": 219414, "text": "From the above lsof command, we can see under the FD column that all three file-descriptors are set to our virtual terminal (0,1,2). We can now send commands, see command output, as well as any errors associated with the command." }, { "code": null, "e": 219690, "s": 219644, "text": "Following are examples for STDIN and STDOUT −" }, { "code": null, "e": 219872, "s": 219690, "text": "[root@centosLocal centos]# echo \"I am coming from Standard output or STDOUT.\" >\noutput.txt && cat output.txt\nI am coming from Standard output or STDOUT. \n[root@centosLocal centos]#\n" }, { "code": null, "e": 219943, "s": 219872, "text": "It is also possible to send both stdout and stderr to separate files −" }, { "code": null, "e": 220149, "s": 219943, "text": "bash-3.2# find / -name passwd 1> good.txt 2> err.txt\nbash-3.2# cat good.txt\n/etc/pam.d/passwd\n/etc/passwd\nbash-3.2# cat err.txt \nfind: /dev/fd/3: Not a directory\nfind: /dev/fd/4: Not a directory\nbash-3.2#\n" }, { "code": null, "e": 220336, "s": 220149, "text": "When searching the entire file system, two errors were encountered. Each were sent to a separate file for later perusal, while the results returned were placed into a separate text file." }, { "code": null, "e": 220561, "s": 220336, "text": "Sending stderr to a text file can be useful when doing things that output a lot of data to the terminal like compiling applications. This will allow for perusal of errors that could get lost from terminal scrollback history." }, { "code": null, "e": 220788, "s": 220561, "text": "One note when passing STDOUT to a text file are the differences between >> and >. The double \">>\" will append to a file, while the singular form will clobber the file and write new contents (so all previous data will be lost)." }, { "code": null, "e": 220911, "s": 220788, "text": "[root@centosLocal centos]# cat < stdin.txt\nHello,\nI am being read form Standard input, STDIN.\n\n[root@centosLocal centos]#\n" }, { "code": null, "e": 221027, "s": 220911, "text": "In the above command, the text file stdin.txt was redirected to the cat command which echoed its content to STDOUT." }, { "code": null, "e": 221205, "s": 221027, "text": "The pipe character will take the output from the first command, passing it as an input into the next command, allowing the secondary command to perform operations on the output." }, { "code": null, "e": 221262, "s": 221205, "text": "Now, let's \"pipe\" the stdout of cat to another command −" }, { "code": null, "e": 221342, "s": 221262, "text": "[root@centosLocal centos]# cat output.txt | wc -l\n2\n[root@centosLocal centos]#\n" }, { "code": null, "e": 221512, "s": 221342, "text": "Above, wc performs calculations on output from cat which was passed from the pipe. The pipe command is particularly useful when filtering the output from grep or egrep −" }, { "code": null, "e": 221618, "s": 221512, "text": "[root@centosLocal centos]# egrep \"^[0-9]{4}$\" /usr/dicts/nums | wc -l \n9000 \n[root@centosLocal centos]#\n" }, { "code": null, "e": 221760, "s": 221618, "text": "In the above command, we passed every 4 digit number to wc from a text file containing all numbers from 65535 passed through an egrep filter." }, { "code": null, "e": 221920, "s": 221760, "text": "Output can be redirected using the & character. If we want to direct the output both STDOUT and STDERR, into the same file, it can be accomplished as follows −" }, { "code": null, "e": 222132, "s": 221920, "text": "[root@centosLocal centos]# find / -name passwd > out.txt 2>&1\n[root@centosLocal centos]# cat out.txt \nfind: /dev/fd/3: Not a directory \nfind: /dev/fd/4: Not a directory \n/etc/passwd\n\n[root@centosLocal centos]#\n" }, { "code": null, "e": 222337, "s": 222132, "text": "Redirecting using the & character works like this: first, the output is redirected into out.txt. Second, STDERR or the file descriptor 2 is reassigned to the same location as STDOUT, in this case out.txt." }, { "code": null, "e": 222560, "s": 222337, "text": "Redirection is extremely useful and comes in handy while solving problems that surgace when manipulating large text-files, compiling source code, redirecting the output in shell scripts, and issuing complex Linux commands." }, { "code": null, "e": 222769, "s": 222560, "text": "While powerful, redirection can get complicated for newer CentOS Administrators. Practice, research, and occasional question to a Linux forum (such as Stack Overflow Linux) will help solve advanced solutions." }, { "code": null, "e": 222929, "s": 222769, "text": "Now that we have a good idea of how the Bash shell works, let's learn some basic constructs, commonly used, to write scripts. In this section we will explore −" }, { "code": null, "e": 222939, "s": 222929, "text": "Variables" }, { "code": null, "e": 222945, "s": 222939, "text": "Loops" }, { "code": null, "e": 222958, "s": 222945, "text": "Conditionals" }, { "code": null, "e": 222971, "s": 222958, "text": "Loop control" }, { "code": null, "e": 223000, "s": 222971, "text": "Reading and writing to files" }, { "code": null, "e": 223022, "s": 223000, "text": "Basic math operations" }, { "code": null, "e": 223399, "s": 223022, "text": "BASH can be a little tricky compared to a dedicated scripting language. Some of the biggest hang-ups in BASH scripts are from incorrectly escaping or not escaping script operations being passed to the shell. If you have looked over a script a few times and it is not working as expected, don't fret. This is common even with those who use BASH to create complex scripts daily." }, { "code": null, "e": 223616, "s": 223399, "text": "A quick search of Google or signing up at an expert Linux forum to ask a question will lead to a quick resolution. There is a very likely chance someone has come across the exact issue and it has already been solved." }, { "code": null, "e": 223945, "s": 223616, "text": "BASH scripting is a great method of quickly creating powerful scripts for everything from automating administration tasks to creating useful tools. Becoming an expert level BASH script developer takes time and practice. Hence, use BASH scripts whenever possible, it is a great tool to have in your CentOS Administration toolbox." }, { "code": null, "e": 224061, "s": 223945, "text": "Package management in CentOS can be performed in two ways: from the terminal and from the Graphical User Interface." }, { "code": null, "e": 224369, "s": 224061, "text": "More often than not a majority of a CentOS administrator's time will be using the terminal. Updating and installing packages for CentOS is no different. With this in mind, we will first explore package management in the terminal, then touch on using the graphical package management tool provided by CentOS." }, { "code": null, "e": 224632, "s": 224369, "text": "YUM is the tool provided for package management in CentOS. We have briefly touched this topic in previous chapters. In this chapter, we will be working from a clean CentOS install. We will first completely update our installation and then install an application." }, { "code": null, "e": 224932, "s": 224632, "text": "YUM has brought software installation and management in Linux a long way. YUM \"automagically” checks for out-of-date dependencies, in addition to out-of-date packages. This has really taken a load off the CentOS administrator compared to the old days of compiling every application from source-code." }, { "code": null, "e": 225228, "s": 224932, "text": "Checks for packages that can update candidates. For this tutorial, we will assume this a production system that will be facing the Internet with no production applications that needs to be tested by DevOps before upgrading the packages. Let us now install the updated candidates onto the system." }, { "code": null, "e": 226608, "s": 225228, "text": "[root@localhost rdc]# yum check-update\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com\n * updates: mirror.clarkson.edu\nNetworkManager.x86_64 1:1.4.0-19.el7_3 updates\nNetworkManager-adsl.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-glib.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-libnm.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-team.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-tui.x86_64 1:1.4.0-19.el7_3 updates \nNetworkManager-wifi.x86_64 1:1.4.0-19.el7_3 updates \naudit.x86_64 2.6.5-3.el7_3.1 updates \nvim-common.x86_64 2:7.4.160-1.el7_3.1 updates \nvim-enhanced.x86_64 2:7.4.160-1.el7_3.1 updates \nvim-filesystem.x86_64 2:7.4.160-1.el7_3.1 updates \nvim-minimal.x86_64 2:7.4.160-1.el7_3.1 updates \nwpa_supplicant.x86_64 1:2.0-21.el7_3 updates \nxfsprogs.x86_64 4.5.0-9.el7_3 updates\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 226810, "s": 226608, "text": "This will install all updated candidates making your CentOS installation current. With a new installation, this can take a little time depending on your installation and your internet connection speed." }, { "code": null, "e": 227311, "s": 226810, "text": "[root@localhost rdc]# yum update\n\nvim-minimal x86_64 2:7.4.160-1.el7_3.1 updates 436 k \nwpa_supplicant x86_64 1:2.0-21.el7_3 updates 788 k \nxfsprogs x86_64 4.5.0-9.el7_3 updates 895 k \n\nTransaction Summary \n======================================================================================\nInstall 2 Packages \nUpgrade 156 Packages \nTotal download size: 371 M\n\nIs this ok [y/d/N]:\n" }, { "code": null, "e": 227544, "s": 227311, "text": "Besides updating the CentOS system, the YUM package manager is our go-to tool for installing the software. Everything from network monitoring tools, video players, to text editors can be installed from a central repository with YUM." }, { "code": null, "e": 228043, "s": 227544, "text": "Before installing some software utilities, let's look at few YUM commands. For daily work, 90% of a CentOS Admin's usage of YUM will be with about 7 commands. We will go over each in the hope of becoming familiar with operating YUM at a proficient level for daily use. However, like most Linux utilities, YUM offers a wealth of advanced features that are always great to explore via the man page. Use man yum will always be the first step to performing unfamiliar operations with any Linux utility." }, { "code": null, "e": 228089, "s": 228043, "text": "Following are the commonly used YUM commands." }, { "code": null, "e": 228363, "s": 228089, "text": "We will now install a text-based web browser called Lynx. Before installation, we must first get the package name containing the Lynx web browser. We are not even 100% sure our default CentOS repository provides a package for the Lynx web browser, so let's search and see −" }, { "code": null, "e": 229126, "s": 228363, "text": "[root@localhost rdc]# yum search web browser\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com \n * updates: mirror.clarkson.edu \n=================================================================\nN/S matched: web, browser\n================================================================== \nicedtea-web.x86_64 : Additional Java components for OpenJDK - Java browser\nplug-in and Web Start implementation\nelinks.x86_64 : A text-mode Web browser\nfirefox.i686 : Mozilla Firefox Web browser\nfirefox.x86_64 : Mozilla Firefox Web browser\nlynx.x86_64 : A text-based Web browser\n\nFull name and summary matches only, use \"search all\" for everything.\n \n[root@localhost rdc]#\n" }, { "code": null, "e": 229243, "s": 229126, "text": "We see, CentOS does offer the Lynx web browser in the repository. Let's see some more information about the package." }, { "code": null, "e": 230134, "s": 229243, "text": "[root@localhost rdc]# lynx.x86_64\nbash: lynx.x86_64: command not found...\n[root@localhost rdc]# yum info lynx.x86_64\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com\n * updates: mirror.clarkson.edu\nAvailable Packages\nName : lynx\nArch : x86_64\nVersion : 2.8.8\nRelease : 0.3.dev15.el7\nSize : 1.4 M\nRepo : base/7/x86_64\nSummary : A text-based Web browser\nURL : http://lynx.isc.org/\nLicense : GPLv2\nDescription : Lynx is a text-based Web browser. Lynx does not display any images, \n : but it does support frames, tables, and most other HTML tags. One \n : advantage Lynx has over graphical browsers is speed; Lynx starts and\n : exits quickly and swiftly displays web pages.\n \n[root@localhost rdc]#\n" }, { "code": null, "e": 230193, "s": 230134, "text": "Nice! Version 2.8 is current enough so let's install Lynx." }, { "code": null, "e": 231827, "s": 230193, "text": "[root@localhost rdc]# yum install lynx\nLoaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\n * base: mirror.scalabledns.com\n * extras: mirror.scalabledns.com\n * updates: mirror.clarkson.edu \nResolving Dependencies\n--> Running transaction check \n---> Package lynx.x86_64 0:2.8.8-0.3.dev15.el7 will be installed \n--> Finished Dependency Resolution \nDependencies Resolved \n===============================================================================\n===============================================================================\nPackage Arch\nVersion Repository Size \n===============================================================================\n===============================================================================\nInstalling: \n lynx x86_64\n2.8.80.3.dev15.el7 base 1.4 M\n\nTransaction Summary\n===============================================================================\n===============================================================================\nInstall 1 Package\n\nTotal download size: 1.4 M \nInstalled size: 5.4 M \nIs this ok [y/d/N]: y \nDownloading packages: \nNo Presto metadata available for base\nlynx-2.8.8-0.3.dev15.el7.x86_64.rpm\n| 1.4 MB 00:00:10 \nRunning transaction check \nRunning transaction test \nTransaction test succeeded \nRunning transaction \n Installing : lynx-2.8.8-0.3.dev15.el7.x86_64\n1/1\n Verifying : lynx-2.8.8-0.3.dev15.el7.x86_64\n1/1\n\nInstalled: \n lynx.x86_64 0:2.8.8-0.3.dev15.el7\nComplete!\n\n[root@localhost rdc]# \n" }, { "code": null, "e": 231885, "s": 231827, "text": "Next, let's make sure Lynx did in fact install correctly." }, { "code": null, "e": 232039, "s": 231885, "text": "[root@localhost rdc]# yum list installed | grep -i lynx\n\nlynx.x86_64 2.8.8-0.3.dev15.el7 @base \n[root@localhost rdc]#\n" }, { "code": null, "e": 232133, "s": 232039, "text": "Great! Let's use Lynx to and see what the web looks like without \"likes\" and pretty pictures." }, { "code": null, "e": 232182, "s": 232133, "text": "[root@localhost rdc]# lynx www.tutorialpoint.in\n" }, { "code": null, "e": 232363, "s": 232182, "text": "Great, now we have a web browser for our production server that can be used without much worry into remote exploits launched over the web. This a good thing for production servers." }, { "code": null, "e": 232669, "s": 232363, "text": "We are almost completed, however first we need to set this server for developers to test applications. Thus, let's make sure they have all the tools needed for their job. We could install everything individually, but CentOS and YUM have made this a lot faster. Let's install the Development Group Package." }, { "code": null, "e": 233204, "s": 232669, "text": "[root@localhost rdc]# yum groups list \nLoaded plugins: fastestmirror, langpacks \nLoading mirror speeds from cached hostfile \n * base: mirror.scalabledns.com \n * extras: mirror.scalabledns.com \n * updates: mirror.clarkson.edu\n \nAvailable Groups: \n Compatibility Libraries \n Console Internet Tools \n Development Tools \n Graphical Administration Tools\n Legacy UNIX Compatibility \n Scientific Support \n Security Tools \n Smart Card Support \n System Administration Tools \n System Management \nDone\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 233322, "s": 233204, "text": "This is a smaller list of Package Groups provided by CentOS. Let's see what is included with the \"Development Group\"." }, { "code": null, "e": 233809, "s": 233322, "text": "[root@localhost rdc]# yum group info \"Development Tools\" \nLoaded plugins: fastestmirror, langpacks \nThere is no installed groups file. \nMaybe run: yum groups mark convert (see man yum) \nLoading mirror speeds from cached hostfile \n * base: mirror.scalabledns.com \n * extras: mirror.scalabledns.com \n * updates: mirror.clarkson.edu\n \nGroup: Development Tools \nGroup-Id: development \nDescription: A basic development environment. \nMandatory Packages: \nautoconf \nautomake \nbinutils \nbison \n" }, { "code": null, "e": 234033, "s": 233809, "text": "The first screen of output is as seen above. This entire list is rather comprehensive. However, this group will usually be needed to be installed in its entirety as time goes by. Let's install the entire Development Group." }, { "code": null, "e": 234093, "s": 234033, "text": "[root@localhost rdc]# yum groupinstall \"Development Tools\"\n" }, { "code": null, "e": 234233, "s": 234093, "text": "This will be a larger install. When completed, your server will have most development libraries and compilers for Perl, Python, C, and C++." }, { "code": null, "e": 234483, "s": 234233, "text": "Gnome Desktop provides a graphical package management tool called Software. It is fairly simple to use and straightforward. Software, the Gnome package management tool for CentOS can be found by navigating to: Applications → System Tools → Software." }, { "code": null, "e": 234755, "s": 234483, "text": "The Software Package Management Tool is divided into groups allowing the administrator to select packages for installation. While this tool is great for ease-of-use and simplicity for end-users, YUM is a lot more powerful and will probably be used more by administrators." }, { "code": null, "e": 234869, "s": 234755, "text": "Following is a screenshot of the Software Package Management Tool, not really designed for System Administrators." }, { "code": null, "e": 235380, "s": 234869, "text": "Logical Volume Management (LVM) is a method used by Linux to manage storage volumes across different physical hard disks. This is not to be confused with RAID. However, it can be thought of in a similar concept as RAID 0 or J-Bod. With LVM, it is possible to have (for example) three physical disks of 1TB each, then a logical volume of around 3TB such as /dev/sdb. Or even two logical volumes of 1.5TB, 5 volumes of 500GB, or any combination. One single disk can even be used for snapshots of Logical Volumes." }, { "code": null, "e": 235543, "s": 235380, "text": "Note − Using Logical Volumes actually increases disk I/O when configured correctly. This works in a similar fashion to RAID 0 striping data across separate disks." }, { "code": null, "e": 235829, "s": 235543, "text": "When learning about volume management with LVM, it is easier if we know what each component in LVM is. Please study the following table to get a firm grasp of each component. If you need to, use Google to study. Understanding each piece of a logical volume is important to manage them." }, { "code": null, "e": 235926, "s": 235829, "text": "A physical volume will be seen as /dev/sda, /dev/sdb; a physical disk that is detected by Linux." }, { "code": null, "e": 236199, "s": 235926, "text": "A physical partition will be a section of the disk partitioned by a disk utility such as fdisk. Keep in mind, physical partition is not recommended in most common LVM setups. Example: disk /dev/sda is partitioned to include two physical partitions: /dev/sda1 and /dev/sda1" }, { "code": null, "e": 236302, "s": 236199, "text": "If we have two physical disks of 1TB each, we can create a volume group of almost 2TB amongst the two." }, { "code": null, "e": 236421, "s": 236302, "text": "From the volume group, we can create three logical volumes each of any-size not exceeding the total volume group size." }, { "code": null, "e": 236760, "s": 236421, "text": "Before being acquainted with the latest and greatest featured tools for LVM Management in CentOS 7, we should first explore more traditional tools that have been used for Linux disk management. These tools will come handy and still have use with today's advanced LVM tools such as the System Storage Manager − lsblk, parted, and mkfs.xfs." }, { "code": null, "e": 237061, "s": 236760, "text": "Now, assuming we have added another disk or two to our system, we need to enumerate disks detected by Linux. I'd always advise enumerating disks every time before performing operations considered as destructive. lsblk is a great tool for getting disk information. Let's see what disks CentOS detects." }, { "code": null, "e": 237583, "s": 237061, "text": "[root@localhost rdc]# lsblk\nNAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT\nsda 8:0 0 20G 0 disk \n├─sda1 8:1 0 1G 0 part /boot\n└─sda2 8:2 0 19G 0 part \n ├─cl-root 253:0 0 17G 0 lvm /\n └─cl-swap 253:1 0 2G 0 lvm [SWAP]\n sdb 8:16 0 6G 0 disk \n sdc 8:32 0 4G 0 disk \n sr0 11:0 1 1024M 0 rom \n" }, { "code": null, "e": 237654, "s": 237583, "text": "As you can see, we have three disks on this system: sda, sdb, and sdc." }, { "code": null, "e": 237849, "s": 237654, "text": "Disk sda contains our working CentOS installation, so we do not want to toy around with sda. Both sdb and sdc were added to the system for this tutorial. Let's make these disks usable to CentOS." }, { "code": null, "e": 238096, "s": 237849, "text": "[root@localhost rdc]# parted /dev/sdb mklabel GPT\nWarning: The existing disk label on /dev/sdb will be destroyed and all data on this\n disk will be lost. Do you want to continue?\nYes/No? Yes \n[root@localhost rdc]#\n" }, { "code": null, "e": 238183, "s": 238096, "text": "We now have one disk labeled. Simply run the parted command in the same manner on sdc." }, { "code": null, "e": 238292, "s": 238183, "text": "We will only create a single partition on each disk. To create partitions, the parted command is used again." }, { "code": null, "e": 238366, "s": 238292, "text": "[root@localhost rdc]# parted -a opt /dev/sdb mkpart primary ext4 0% 100%\n" }, { "code": null, "e": 238446, "s": 238366, "text": "Warning − You requested a partition from 0.00B to 6442MB (sectors 0..12582911)." }, { "code": null, "e": 238521, "s": 238446, "text": "The closest location we can manage is 17.4kB to 1048kB (sectors 34..2047)." }, { "code": null, "e": 238554, "s": 238521, "text": "Is this still acceptable to you?" }, { "code": null, "e": 238565, "s": 238554, "text": "Yes/No? NO" }, { "code": null, "e": 238639, "s": 238565, "text": "[root@localhost rdc]# parted -a opt /dev/sdc mkpart primary ext4 0% 100%\n" }, { "code": null, "e": 238688, "s": 238639, "text": "Information − You may need to update /etc/fstab." }, { "code": null, "e": 239372, "s": 238688, "text": "[root@localhost rdc]# lsblk \nNAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT\nsda 8:0 0 20G 0 disk \n├─sda1 8:1 0 1G 0 part / boot\n└─sda2 8:2 0 19G 0 part \n ├─cl-root 253:0 0 17G 0 lvm /\n └─cl-swap 253:1 0 2G 0 lvm [SWAP]\nsdb 8:16 0 6G 0 disk \n└─sdb1 8:17 0 6G 0 part \n sdc 8:32 0 4G 0 disk \n└─sdc1 8:33 0 4G 0 part \nsr0 11:0 1 1024M 0 rom\n\n[root@localhost rdc]#\n" }, { "code": null, "e": 239455, "s": 239372, "text": "As you can see from lsblk output, we now have two partitions, each on sdb and sdc." }, { "code": null, "e": 239569, "s": 239455, "text": "Finally, before mounting and using any volume we need to add a file system. We will be using the XFS file system." }, { "code": null, "e": 241073, "s": 239569, "text": "root@localhost rdc]# mkfs.xfs -f /dev/sdb1\nmeta-data = /dev/sdb1 isize = 512 agcount = 4, agsize = 393088 blks\n = sectsz = 512 attr = 2, projid32bit = 1\n = crc = 1 finobt = 0, sparse = 0\ndata = bsize = 4096 blocks = 1572352, imaxpct = 25\n = sunit = 0 swidth = 0 blks\nnaming = version 2 bsize = 4096 ascii-ci = 0 ftype = 1\nlog = internal log bsize = 4096 blocks = 2560, version = 2\n = sectsz = 512 sunit = 0 blks, lazy-count = 1\nrealtime = none extsz = 4096 blocks = 0, rtextents = 0\n[root@localhost rdc]# mkfs.xfs -f /dev/sdc1\nmeta-data = /dev/sdc1 isize = 512 agcount = 4, agsize = 262016 blks\n = sectsz = 512 attr = 2, projid32bit = 1\n = crc = 1 finobt = 0, sparse = 0\ndata = bsize = 4096 blocks = 1048064, imaxpct = 25\n = sunit = 0 swidth = 0 blks\nnaming = version 2 bsize = 4096 ascii-ci = 0 ftype = 1\nlog = internal log bsize = 4096 blocks = 2560, version = 2\n = sectsz = 512 sunit = 0 blks, lazy-count = 1\nrealtime = none extsz = 4096 blocks = 0, rtextents = 0\n\n[root@localhost rdc]# \n" }, { "code": null, "e": 241130, "s": 241073, "text": "Let's check to make sure each have a usable file system." }, { "code": null, "e": 241386, "s": 241130, "text": "[root@localhost rdc]# lsblk -o NAME,FSTYPE\nNAME FSTYPE\nsda \n├─sda1 xfs\n└─sda2 LVM2_member\n ├─cl-root xfs\n └─cl-swap swap\nsdb \n└─sdb1 xfs\nsdc \n└─sdc1 xfs\nsr0\n\n[root@localhost rdc]# \n" }, { "code": null, "e": 241485, "s": 241386, "text": "Each is now using the XFS file system. Let's mount them, check the mount, and copy a file to each." }, { "code": null, "e": 241745, "s": 241485, "text": "[root@localhost rdc]# mount -o defaults /dev/sdb1 /mnt/sdb\n[root@localhost rdc]# mount -o defaults /dev/sdc1 /mnt/sdc\n\n[root@localhost ~]# touch /mnt/sdb/myFile /mnt/sdc/myFile\n[root@localhost ~]# ls /mnt/sdb /mnt/sdc\n /mnt/sdb:\n myFile\n\n /mnt/sdc:\n myFile\n" }, { "code": null, "e": 241974, "s": 241745, "text": "We have two usable disks at this point. However, they will only be usable when we mount them manually. To mount each on boot, we must edit the fstab file. Also, permissions must be set for groups needing access to the new disks." }, { "code": null, "e": 242190, "s": 241974, "text": "One of the greatest addition to CentOS 7 was the inclusion of a utility called System Storage Manager or ssm. System Storage Manager greatly simplifies the process of managing LVM pools and storage volumes on Linux." }, { "code": null, "e": 242342, "s": 242190, "text": "We will go through the process of creating a simple volume pool and logical volumes in CentOS. The first step is installing the System Storage Manager." }, { "code": null, "e": 242401, "s": 242342, "text": "[root@localhost rdc]# yum install system-storage-manager\n" }, { "code": null, "e": 242453, "s": 242401, "text": "Let's look at our disks using the ssm list command." }, { "code": null, "e": 242520, "s": 242453, "text": "As seen above, a total of three disks are installed on the system." }, { "code": null, "e": 242559, "s": 242520, "text": "/sdba1 − Hosts our CentOS installation" }, { "code": null, "e": 242598, "s": 242559, "text": "/sdba1 − Hosts our CentOS installation" }, { "code": null, "e": 242626, "s": 242598, "text": "/sdb1 − Mounted at /mnt/sdb" }, { "code": null, "e": 242654, "s": 242626, "text": "/sdb1 − Mounted at /mnt/sdb" }, { "code": null, "e": 242682, "s": 242654, "text": "/sdc1 − Mounted at /mnt/sdc" }, { "code": null, "e": 242710, "s": 242682, "text": "/sdc1 − Mounted at /mnt/sdc" }, { "code": null, "e": 242844, "s": 242710, "text": "What we want to do is make a Volume Group using two disks (sdb and sdc). Then make three 3GB Logical Volumes available to the system." }, { "code": null, "e": 242875, "s": 242844, "text": "Let's create our Volume Group." }, { "code": null, "e": 242941, "s": 242875, "text": "[root@localhost rdc]# ssm create -p NEW_POOL /dev/sdb1 /dev/sdc1\n" }, { "code": null, "e": 243074, "s": 242941, "text": "By default, ssm will create a single logical volume extending the entire 10GB of the pool. We don't want this, so let's remove this." }, { "code": null, "e": 243279, "s": 243074, "text": "[root@localhost rdc]# ssm remove /dev/NEW_POOL/lvol001\n Do you really want to remove active logical volume NEW_POOL/lvol001? [y/n]: y\n Logical volume \"lvol001\" successfully removed\n[root@localhost rdc]# \n" }, { "code": null, "e": 243328, "s": 243279, "text": "Finally, let's create the three Logical Volumes." }, { "code": null, "e": 243545, "s": 243328, "text": "[root@localhost rdc]# ssm create -n disk001 --fs xfs -s 3GB -p NEW_POOL\n[root@localhost rdc]# ssm create -n disk002 --fs xfs -s 3GB -p NEW_POOL\n[root@localhost rdc]# ssm create -n disk003 --fs xfs -s 3GB -p NEW_POOL\n" }, { "code": null, "e": 243579, "s": 243545, "text": "Now, let's check our new volumes." }, { "code": null, "e": 243667, "s": 243579, "text": "We now have three separate logical volumes spanned across two physical disk partitions." }, { "code": null, "e": 244028, "s": 243667, "text": "Logical volumes are a powerful feature now built into CentOS Linux. We have touched the surface on managing these. Mastering pools and logical volumes come with practice and extended learning from Tutorials Point. For now, you have learned the basics of LVM management in CentOS and possess the ability to create basic striped Logical Volumes on a single host." }, { "code": null, "e": 244063, "s": 244028, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 244079, "s": 244063, "text": " Mamta Tripathi" }, { "code": null, "e": 244112, "s": 244079, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 244126, "s": 244112, "text": " Lets Kode It" }, { "code": null, "e": 244161, "s": 244126, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 244178, "s": 244161, "text": " Abhilash Nelson" }, { "code": null, "e": 244213, "s": 244178, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 244230, "s": 244213, "text": " Frahaan Hussain" }, { "code": null, "e": 244265, "s": 244230, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 244293, "s": 244265, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 244326, "s": 244293, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 244366, "s": 244326, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 244373, "s": 244366, "text": " Print" }, { "code": null, "e": 244384, "s": 244373, "text": " Add Notes" } ]
C program demonstrating the concepts of strings using Pointers
An array of characters is called a string. The syntax for declaring an array is as follows − char stringname [size]; For example − char string[50]; string of length 50 characters Using single character constant − char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} Using string constants − char string[10] = "Hello":; Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’. Now, let us understand what are the arrays of pointers in C programming language. It is an array whose elements are ptrs to the base add of the string. It is declared and initialized as follows − char *a[ ] = {"one", "two", "three"}; Here, a[0] is a pointer to the base add of string "one". a[1] is a pointer to the base add of string "two". a[2] is a pointer to the base add of string "three". Following is a C program demonstrating the concepts of strings − Live Demo #include<stdio.h> #include<string.h> void main(){ //Declaring string and pointers// char *s="Meghana"; //Printing required O/p// printf("%s\n",s);//Meghana// printf("%c\n",s);//If you take %c, we should have * for string. Else you will see no output//// printf("%c\n",*s);//M because it's the character in the base address// printf("%c\n",*(s+4));//Fifth letter a because it's the character in the (base address+4)th position// printf("%c\n",*s+5);//R because it will consider character in the base address + 5 in alphabetical order// } When the above program is executed, it produces the following result − Meghana M a R Consider another example. Given below is a C program demonstrating the concepts of printing characters using the post increment and pre increment operators − Live Demo #include<stdio.h> #include<string.h> void main(){ //Declaring string and pointers// char *s="Meghana"; //Printing required O/p// printf("%s\n",s);//Meghana// printf("%c\n",++s+3);//s becomes 2nd position - 'e'. O/p is Garbage value// printf("%c\n",s+++3);//s becomes 3rd position - 'g'. O/p is Garbage value// printf("%c\n",*++s+3);//s=3 becomes incremented by 1 = 'h'.s becomes 4th position.h+3 - k is the O/p// printf("%c\n",*s+++3);//s=4 - h is the value. h=3 = k will be the O/p. S is incremented by 1 now. s=5th position// } When the above program is executed, it produces the following result − Meghana d d k k
[ { "code": null, "e": 1105, "s": 1062, "text": "An array of characters is called a string." }, { "code": null, "e": 1155, "s": 1105, "text": "The syntax for declaring an array is as follows −" }, { "code": null, "e": 1179, "s": 1155, "text": "char stringname [size];" }, { "code": null, "e": 1241, "s": 1179, "text": "For example − char string[50]; string of length 50 characters" }, { "code": null, "e": 1275, "s": 1241, "text": "Using single character constant −" }, { "code": null, "e": 1326, "s": 1275, "text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}" }, { "code": null, "e": 1351, "s": 1326, "text": "Using string constants −" }, { "code": null, "e": 1379, "s": 1351, "text": "char string[10] = \"Hello\":;" }, { "code": null, "e": 1477, "s": 1379, "text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’." }, { "code": null, "e": 1559, "s": 1477, "text": "Now, let us understand what are the arrays of pointers in C programming language." }, { "code": null, "e": 1629, "s": 1559, "text": "It is an array whose elements are ptrs to the base add of the string." }, { "code": null, "e": 1673, "s": 1629, "text": "It is declared and initialized as follows −" }, { "code": null, "e": 1711, "s": 1673, "text": "char *a[ ] = {\"one\", \"two\", \"three\"};" }, { "code": null, "e": 1768, "s": 1711, "text": "Here, a[0] is a pointer to the base add of string \"one\"." }, { "code": null, "e": 1823, "s": 1768, "text": " a[1] is a pointer to the base add of string \"two\"." }, { "code": null, "e": 1880, "s": 1823, "text": " a[2] is a pointer to the base add of string \"three\"." }, { "code": null, "e": 1945, "s": 1880, "text": "Following is a C program demonstrating the concepts of strings −" }, { "code": null, "e": 1956, "s": 1945, "text": " Live Demo" }, { "code": null, "e": 2520, "s": 1956, "text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring string and pointers//\n char *s=\"Meghana\";\n //Printing required O/p//\n printf(\"%s\\n\",s);//Meghana//\n printf(\"%c\\n\",s);//If you take %c, we should have * for string. Else you\n will see no output////\n printf(\"%c\\n\",*s);//M because it's the character in the base address//\n printf(\"%c\\n\",*(s+4));//Fifth letter a because it's the character in the (base address+4)th position//\n printf(\"%c\\n\",*s+5);//R because it will consider character in the base address + 5 in alphabetical order//\n}" }, { "code": null, "e": 2591, "s": 2520, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2605, "s": 2591, "text": "Meghana\nM\na\nR" }, { "code": null, "e": 2631, "s": 2605, "text": "Consider another example." }, { "code": null, "e": 2763, "s": 2631, "text": "Given below is a C program demonstrating the concepts of printing characters using the post increment and pre increment operators −" }, { "code": null, "e": 2774, "s": 2763, "text": " Live Demo" }, { "code": null, "e": 3331, "s": 2774, "text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring string and pointers//\n char *s=\"Meghana\";\n //Printing required O/p//\n printf(\"%s\\n\",s);//Meghana//\n printf(\"%c\\n\",++s+3);//s becomes 2nd position - 'e'. O/p is Garbage value//\n printf(\"%c\\n\",s+++3);//s becomes 3rd position - 'g'. O/p is Garbage value//\n printf(\"%c\\n\",*++s+3);//s=3 becomes incremented by 1 = 'h'.s becomes 4th\n position.h+3 - k is the O/p//\n printf(\"%c\\n\",*s+++3);//s=4 - h is the value. h=3 = k will be the O/p. S is incremented by 1 now. s=5th position//\n}" }, { "code": null, "e": 3402, "s": 3331, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3418, "s": 3402, "text": "Meghana\nd\nd\nk\nk" } ]
Plotting live data with Matplotlib | by Thiago Carvalho | Towards Data Science
Whether you’re working with a sensor, continually pulling data from an API, or have a file that’s often updated, you may want to analyze your data in real-time. This article will explore a simple way to use functions to animate our plots with Matplotlib’s FuncAnimation. The data for this first example is from the OS, and to retrieve this information, we’ll use psutil. pip install psutil We’ll handle the data with deques, but you can adapt the example to work with most collections, like dictionaries, data frames, lists, or others. By the end of the article, I’ll quickly show another example with Pandas and Geopandas. import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.animation import FuncAnimationimport psutilimport collections Let’s start with collecting and storing the data. We’ll define two deques filled with zeros. cpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))print("CPU: {}".format(cpu))print("Memory: {}".format(ram)) Then we’ll create a function to update the deques with new data. It’ll remove the last value of each deque and append a new one. def my_function(): cpu.popleft() cpu.append(psutil.cpu_percent(interval=1)) ram.popleft() ram.append(psutil.virtual_memory().percent)cpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# testmy_function()my_function()my_function()print("CPU: {}".format(cpu))print("Memory: {}".format(ram)) Now we can define the figure and subplots. Besides updating the deques, our function will also need to add this data to our chart. # function to update the datadef my_function(): cpu.popleft() cpu.append(psutil.cpu_percent(interval=1)) ax.plot(cpu) ram.popleft() ram.append(psutil.virtual_memory().percent) ax1.plot(ram)# start collections with zeroscpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# define and adjust figurefig = plt.figure(figsize=(12,6), facecolor='#DEDEDE')ax = plt.subplot(121)ax1 = plt.subplot(122)ax.set_facecolor('#DEDEDE')ax1.set_facecolor('#DEDEDE')# testmy_function()plt.show() When we add FuncAnimation, it’ll repeatedly call our function to refresh the chart. But when we use .plot() multiple times on the same axis, it won’t update the line but rather plot new ones. It’s hard to append to a line that’s already plotted, and other types of visualization like maps, bars, and pie charts, can be even more challenging to update. A more straightforward solution is to clear the axis before plotting and draw a new plot at every iteration. Adding axis.cla() to our function will give us that result. That way, we don’t need to worry about texts, annotations, or other elements of our chart either. Every time we plot, the axis will reset, and the function will draw everything again. # function to update the datadef my_function(): # get data cpu.popleft() cpu.append(psutil.cpu_percent(interval=1)) ram.popleft() ram.append(psutil.virtual_memory().percent) # clear axis ax.cla() ax1.cla() # plot cpu ax.plot(cpu) ax.scatter(len(cpu)-1, cpu[-1]) ax.text(len(cpu)-1, cpu[-1]+2, "{}%".format(cpu[-1])) ax.set_ylim(0,100) # plot memory ax1.plot(ram) ax1.scatter(len(ram)-1, ram[-1]) ax1.text(len(ram)-1, ram[-1]+2, "{}%".format(ram[-1])) ax1.set_ylim(0,100)# start collections with zeroscpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# define and adjust figurefig = plt.figure(figsize=(12,6), facecolor='#DEDEDE')ax = plt.subplot(121)ax1 = plt.subplot(122)ax.set_facecolor('#DEDEDE')ax1.set_facecolor('#DEDEDE')# testmy_function()my_function()my_function()plt.show() We have everything we need to make our chart come to life. Now we can add FuncAnimation and pass our figure and function as parameters. ani = FuncAnimation(fig, my_function, interval=1000) When we defined the figure, we assigned it to a variable called fig. A different approach would be to skip that and rely on the default figure created by Matplotlib. Replacing the first parameter for plt.gcf(), which will automatically get the current figure for us. Note that we also set an interval of 1,000 milliseconds at FuncAnimation. We’re not required to put it. By default, it’ll call the function every 200 milliseconds. Since we already have an interval, we can also remove the one from .cpu_percent(). Without getting into too much detail about psutil, when we don’t set the interval, it will calculate from the last time the function was called — Which means the first value it returns will be zero. After that, it’ll work as before. Lastly, FuncAnimation will call our function and use frames as the first argument. Since we won’t define any custom values for this parameter, it will work as a counter, passing the iterations count. The only thing we have to do is make sure our function can receive this argument, even if we’re not using it. # function to update the datadef my_function(i): # get data cpu.popleft() cpu.append(psutil.cpu_percent()) ram.popleft() ram.append(psutil.virtual_memory().percent) # clear axis ax.cla() ax1.cla() # plot cpu ax.plot(cpu) ax.scatter(len(cpu)-1, cpu[-1]) ax.text(len(cpu)-1, cpu[-1]+2, "{}%".format(cpu[-1])) ax.set_ylim(0,100) # plot memory ax1.plot(ram) ax1.scatter(len(ram)-1, ram[-1]) ax1.text(len(ram)-1, ram[-1]+2, "{}%".format(ram[-1])) ax1.set_ylim(0,100)# start collections with zeroscpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# define and adjust figurefig = plt.figure(figsize=(12,6), facecolor='#DEDEDE')ax = plt.subplot(121)ax1 = plt.subplot(122)ax.set_facecolor('#DEDEDE')ax1.set_facecolor('#DEDEDE')# animateani = FuncAnimation(fig, my_function, interval=1000)plt.show() It’s alive! In the next example, we’ll use Pandas and Openpyxl to read an Excel file and Geopandas to plot a map. When we change something in the Excel file and save it, the plot should reflect the difference. import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.animation import FuncAnimationimport pandas as pdimport geopandas as gpd# function to update the datadef my_function(i): # get data try: df = pd.read_excel('w.xlsx', engine='openpyxl') except: print('error reading file') # merge with world map world_values = world.merge(df, how='right', on='name', copy=True) # clear axis ax.cla() ax1.cla() # plot map world_values.plot(column='Val', ax=ax1, cmap='coolwarm_r', edgecolors='black', linewidths=0.5, alpha=0.8) # remove spines and ticks ax1.spines['left'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['top'].set_visible(False) ax1.spines['bottom'].set_visible(False) ax1.set_yticks([]) ax1.set_xticks([]) # get records with a value higher than 0.97 alert = world_values[world_values['Val'] > 0.97] alert = alert.sort_values('Val', ascending=False) # plot bars ax.bar(alert.name, alert.Val, color='#E9493C', alpha=0.8) # limits, labels, and spines ax.set_ylim(0.9, 1) ax.set_xticklabels(alert.name, fontsize=11) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False)# world mapworld = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))# define and adjust figurefig, (ax, ax1) = plt.subplots(2, 1, figsize=(16,12), facecolor='#707576', gridspec_kw={'height_ratios': [1, 3]})ax.set_facecolor('#707576')ax1.set_facecolor('#707576')# animateani = FuncAnimation(fig, my_function, interval=500)fig.tight_layout()plt.show() Animations with Matplotlib can appear intimidating, but they’re relatively straightforward. Different data sources and visualizations may impose unique challenges, but overall the process is the same. You define a function to systematically update your chart and use FuncAnimation to do it repeatedly. You can find the code for this article here. I’ve also added another example in this repository for plotting a clock with Matplotlib. Thanks for reading my article. I hope you enjoyed it.
[ { "code": null, "e": 333, "s": 172, "text": "Whether you’re working with a sensor, continually pulling data from an API, or have a file that’s often updated, you may want to analyze your data in real-time." }, { "code": null, "e": 443, "s": 333, "text": "This article will explore a simple way to use functions to animate our plots with Matplotlib’s FuncAnimation." }, { "code": null, "e": 543, "s": 443, "text": "The data for this first example is from the OS, and to retrieve this information, we’ll use psutil." }, { "code": null, "e": 562, "s": 543, "text": "pip install psutil" }, { "code": null, "e": 708, "s": 562, "text": "We’ll handle the data with deques, but you can adapt the example to work with most collections, like dictionaries, data frames, lists, or others." }, { "code": null, "e": 796, "s": 708, "text": "By the end of the article, I’ll quickly show another example with Pandas and Geopandas." }, { "code": null, "e": 923, "s": 796, "text": "import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.animation import FuncAnimationimport psutilimport collections" }, { "code": null, "e": 1016, "s": 923, "text": "Let’s start with collecting and storing the data. We’ll define two deques filled with zeros." }, { "code": null, "e": 1150, "s": 1016, "text": "cpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))print(\"CPU: {}\".format(cpu))print(\"Memory: {}\".format(ram))" }, { "code": null, "e": 1279, "s": 1150, "text": "Then we’ll create a function to update the deques with new data. It’ll remove the last value of each deque and append a new one." }, { "code": null, "e": 1603, "s": 1279, "text": "def my_function(): cpu.popleft() cpu.append(psutil.cpu_percent(interval=1)) ram.popleft() ram.append(psutil.virtual_memory().percent)cpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# testmy_function()my_function()my_function()print(\"CPU: {}\".format(cpu))print(\"Memory: {}\".format(ram))" }, { "code": null, "e": 1734, "s": 1603, "text": "Now we can define the figure and subplots. Besides updating the deques, our function will also need to add this data to our chart." }, { "code": null, "e": 2252, "s": 1734, "text": "# function to update the datadef my_function(): cpu.popleft() cpu.append(psutil.cpu_percent(interval=1)) ax.plot(cpu) ram.popleft() ram.append(psutil.virtual_memory().percent) ax1.plot(ram)# start collections with zeroscpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# define and adjust figurefig = plt.figure(figsize=(12,6), facecolor='#DEDEDE')ax = plt.subplot(121)ax1 = plt.subplot(122)ax.set_facecolor('#DEDEDE')ax1.set_facecolor('#DEDEDE')# testmy_function()plt.show()" }, { "code": null, "e": 2336, "s": 2252, "text": "When we add FuncAnimation, it’ll repeatedly call our function to refresh the chart." }, { "code": null, "e": 2444, "s": 2336, "text": "But when we use .plot() multiple times on the same axis, it won’t update the line but rather plot new ones." }, { "code": null, "e": 2604, "s": 2444, "text": "It’s hard to append to a line that’s already plotted, and other types of visualization like maps, bars, and pie charts, can be even more challenging to update." }, { "code": null, "e": 2713, "s": 2604, "text": "A more straightforward solution is to clear the axis before plotting and draw a new plot at every iteration." }, { "code": null, "e": 2773, "s": 2713, "text": "Adding axis.cla() to our function will give us that result." }, { "code": null, "e": 2957, "s": 2773, "text": "That way, we don’t need to worry about texts, annotations, or other elements of our chart either. Every time we plot, the axis will reset, and the function will draw everything again." }, { "code": null, "e": 3818, "s": 2957, "text": "# function to update the datadef my_function(): # get data cpu.popleft() cpu.append(psutil.cpu_percent(interval=1)) ram.popleft() ram.append(psutil.virtual_memory().percent) # clear axis ax.cla() ax1.cla() # plot cpu ax.plot(cpu) ax.scatter(len(cpu)-1, cpu[-1]) ax.text(len(cpu)-1, cpu[-1]+2, \"{}%\".format(cpu[-1])) ax.set_ylim(0,100) # plot memory ax1.plot(ram) ax1.scatter(len(ram)-1, ram[-1]) ax1.text(len(ram)-1, ram[-1]+2, \"{}%\".format(ram[-1])) ax1.set_ylim(0,100)# start collections with zeroscpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# define and adjust figurefig = plt.figure(figsize=(12,6), facecolor='#DEDEDE')ax = plt.subplot(121)ax1 = plt.subplot(122)ax.set_facecolor('#DEDEDE')ax1.set_facecolor('#DEDEDE')# testmy_function()my_function()my_function()plt.show()" }, { "code": null, "e": 3877, "s": 3818, "text": "We have everything we need to make our chart come to life." }, { "code": null, "e": 3954, "s": 3877, "text": "Now we can add FuncAnimation and pass our figure and function as parameters." }, { "code": null, "e": 4007, "s": 3954, "text": "ani = FuncAnimation(fig, my_function, interval=1000)" }, { "code": null, "e": 4076, "s": 4007, "text": "When we defined the figure, we assigned it to a variable called fig." }, { "code": null, "e": 4274, "s": 4076, "text": "A different approach would be to skip that and rely on the default figure created by Matplotlib. Replacing the first parameter for plt.gcf(), which will automatically get the current figure for us." }, { "code": null, "e": 4438, "s": 4274, "text": "Note that we also set an interval of 1,000 milliseconds at FuncAnimation. We’re not required to put it. By default, it’ll call the function every 200 milliseconds." }, { "code": null, "e": 4521, "s": 4438, "text": "Since we already have an interval, we can also remove the one from .cpu_percent()." }, { "code": null, "e": 4754, "s": 4521, "text": "Without getting into too much detail about psutil, when we don’t set the interval, it will calculate from the last time the function was called — Which means the first value it returns will be zero. After that, it’ll work as before." }, { "code": null, "e": 4954, "s": 4754, "text": "Lastly, FuncAnimation will call our function and use frames as the first argument. Since we won’t define any custom values for this parameter, it will work as a counter, passing the iterations count." }, { "code": null, "e": 5064, "s": 4954, "text": "The only thing we have to do is make sure our function can receive this argument, even if we’re not using it." }, { "code": null, "e": 5932, "s": 5064, "text": "# function to update the datadef my_function(i): # get data cpu.popleft() cpu.append(psutil.cpu_percent()) ram.popleft() ram.append(psutil.virtual_memory().percent) # clear axis ax.cla() ax1.cla() # plot cpu ax.plot(cpu) ax.scatter(len(cpu)-1, cpu[-1]) ax.text(len(cpu)-1, cpu[-1]+2, \"{}%\".format(cpu[-1])) ax.set_ylim(0,100) # plot memory ax1.plot(ram) ax1.scatter(len(ram)-1, ram[-1]) ax1.text(len(ram)-1, ram[-1]+2, \"{}%\".format(ram[-1])) ax1.set_ylim(0,100)# start collections with zeroscpu = collections.deque(np.zeros(10))ram = collections.deque(np.zeros(10))# define and adjust figurefig = plt.figure(figsize=(12,6), facecolor='#DEDEDE')ax = plt.subplot(121)ax1 = plt.subplot(122)ax.set_facecolor('#DEDEDE')ax1.set_facecolor('#DEDEDE')# animateani = FuncAnimation(fig, my_function, interval=1000)plt.show()" }, { "code": null, "e": 5944, "s": 5932, "text": "It’s alive!" }, { "code": null, "e": 6142, "s": 5944, "text": "In the next example, we’ll use Pandas and Openpyxl to read an Excel file and Geopandas to plot a map. When we change something in the Excel file and save it, the plot should reflect the difference." }, { "code": null, "e": 7791, "s": 6142, "text": "import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.animation import FuncAnimationimport pandas as pdimport geopandas as gpd# function to update the datadef my_function(i): # get data try: df = pd.read_excel('w.xlsx', engine='openpyxl') except: print('error reading file') # merge with world map world_values = world.merge(df, how='right', on='name', copy=True) # clear axis ax.cla() ax1.cla() # plot map world_values.plot(column='Val', ax=ax1, cmap='coolwarm_r', edgecolors='black', linewidths=0.5, alpha=0.8) # remove spines and ticks ax1.spines['left'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['top'].set_visible(False) ax1.spines['bottom'].set_visible(False) ax1.set_yticks([]) ax1.set_xticks([]) # get records with a value higher than 0.97 alert = world_values[world_values['Val'] > 0.97] alert = alert.sort_values('Val', ascending=False) # plot bars ax.bar(alert.name, alert.Val, color='#E9493C', alpha=0.8) # limits, labels, and spines ax.set_ylim(0.9, 1) ax.set_xticklabels(alert.name, fontsize=11) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False)# world mapworld = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))# define and adjust figurefig, (ax, ax1) = plt.subplots(2, 1, figsize=(16,12), facecolor='#707576', gridspec_kw={'height_ratios': [1, 3]})ax.set_facecolor('#707576')ax1.set_facecolor('#707576')# animateani = FuncAnimation(fig, my_function, interval=500)fig.tight_layout()plt.show()" }, { "code": null, "e": 7883, "s": 7791, "text": "Animations with Matplotlib can appear intimidating, but they’re relatively straightforward." }, { "code": null, "e": 8093, "s": 7883, "text": "Different data sources and visualizations may impose unique challenges, but overall the process is the same. You define a function to systematically update your chart and use FuncAnimation to do it repeatedly." }, { "code": null, "e": 8138, "s": 8093, "text": "You can find the code for this article here." }, { "code": null, "e": 8227, "s": 8138, "text": "I’ve also added another example in this repository for plotting a clock with Matplotlib." } ]
Predicting house value using regression analysis | by Bhavesh Patel | Towards Data Science
Machine learning model Regression analysis is a basic method used in statistical analysis of data. It’s a statistical method which allows estimating the relationships among variables. One needs to identify dependent variable which will vary based on the value of the independent variable. For example, the value of the house (dependent variable) varies based on square feet of the house (independent variable). Regression analysis is very useful tool in predictive analytics. E(Y | X) = f(X, β) It is easy to understand with a graph (source: Wikipedia) Y = f(X) = β0 + β1 * X β0 is the intercept of the line β1 is the slope of the line Linear regression algorithm is used to predict the relationship(line) among data points. There can be many different (linear or nonlinear) ways to define the relationship. In the linear model, it is based on the intercept and the slope. To find out the most optimal relationship, we need to train the model with the data. Before applying the linear regression model, we should determine whether or not there is a relationship between the variables of interest. A scatterplot is a good starting point to help in determining the strength of the relationship between two variables. The correlation coefficient is a valuable measure of association between variables. Its value varies between -1 (weak relationship) and 1 (strong relationship). Once we determine that there is a relationship between variables, next step is to identify best-fitting relationship (line) between the variables. The most common method is the Residual Sum of Squares (RSS). This method calculates the difference between observed data (actual value) and its vertical distance from the proposed best-fitting line (predicted value). It squares each difference and adds all of them. The MSE (Mean Squared Error) is a quality measure for the estimator by dividing RSS by total observed data points. It is always a non-negative number. Values closer to zero represent a smaller error. The RMSE (Root Mean Squared Error) is the square root of the MSE. The RMSE is a measure of the average deviation of the estimates from the observed values. This is easier to observe compare to MSE, which can be a large number. RMSE (Square root of MSE) = √ (MSE) The additional number of variables will add more dimension to the model. Y = f(X) = β0 + β1 * X1 + β1 * X2 + β1 * X3 PythonGraphlabS Frame (similar to Pandas Data Frame) Python Graphlab S Frame (similar to Pandas Data Frame) House data of Seattle, Washington area is used. It contains following columns and around 21,000 rows. Id : date : price : bedrooms : bathrooms : sqft_living sqft_lot : floors : waterfront : view : condition : grade : sqft_above : sqft_basement : yr_built : yr_renovated : zipcode : lat : long : sqft_living : sqft_lot > homesales = graphlab.SFrame(‘home_data.gl’)> homesales We need to understand if there is a relationship between two variables. Let’s pick the housing price and square feet of living. > homesales.show(view=”Scatter Plot”, x=”sqft_living”, y=”price”) We can observe that there is a relationship between square feet of living area and housing price. Let’s observer the data using the Boxplot with error lines to understand price by zip code. > homesales.show(view=’BoxWhisker Plot’, x=’zipcode’, y=’price’) It is always good idea to explore and understand the surrounding data. Graphlab has a nice way to show the data statistics. > my_features = [‘bedrooms’, ‘bathrooms’, ‘sqft_living’, ‘sqft_lot’, ‘floors’, ‘zipcode’] The first step is to get training data set and test data set. Let’s use 80% as training data and remaining 20% for testing. > train_data, test_data = homesales.random_split(0.8, seed=0) Let’s build regression model with one variable for sq ft and store the results. The dependent variable price is what the model will need to predict. > sqft_model = graphlab.linear_regression.create(train_data, target=’price’, features=[‘sqft_living’], validation_set=None) We can plot the model values along with actual values using matplotlib. > plt.plot(test_data[‘sqft_living’],test_data[‘price’],’.’, test_data[‘sqft_living’],sqft_model.predict(test_data),’-’) Blue dots represents the test data displaying relationship between house price and square feet of living area. Green line shows the prediction of the home price (dependent variable) for given square feet using the “sqft_model” linear regression model we built. Let’s pick a house and predict its value using the “sqft_model”. > house2 = homesales[homesales[‘id’]==’5309101200']> house2 Now let’s predict the house value using the “sqft_model”. > print sqft_model.predict(house2) [629584.8197281545] It predicted value of $629,584 which is very close to actual value of $620,000. While our model worked reasonably well, there is a gap between predicted value and actual value. > print sqft_model.evaluate(test_data) {‘max_error’: 4143550.8825285938, ‘rmse’: 255191.02870527358} The “max_error” is due to the outlier. It is displayed in the upper right corner in the matplot visualization. The model has error value based on RMSE of $255,191.
[ { "code": null, "e": 195, "s": 172, "text": "Machine learning model" }, { "code": null, "e": 648, "s": 195, "text": "Regression analysis is a basic method used in statistical analysis of data. It’s a statistical method which allows estimating the relationships among variables. One needs to identify dependent variable which will vary based on the value of the independent variable. For example, the value of the house (dependent variable) varies based on square feet of the house (independent variable). Regression analysis is very useful tool in predictive analytics." }, { "code": null, "e": 667, "s": 648, "text": "E(Y | X) = f(X, β)" }, { "code": null, "e": 725, "s": 667, "text": "It is easy to understand with a graph (source: Wikipedia)" }, { "code": null, "e": 748, "s": 725, "text": "Y = f(X) = β0 + β1 * X" }, { "code": null, "e": 780, "s": 748, "text": "β0 is the intercept of the line" }, { "code": null, "e": 808, "s": 780, "text": "β1 is the slope of the line" }, { "code": null, "e": 1130, "s": 808, "text": "Linear regression algorithm is used to predict the relationship(line) among data points. There can be many different (linear or nonlinear) ways to define the relationship. In the linear model, it is based on the intercept and the slope. To find out the most optimal relationship, we need to train the model with the data." }, { "code": null, "e": 1548, "s": 1130, "text": "Before applying the linear regression model, we should determine whether or not there is a relationship between the variables of interest. A scatterplot is a good starting point to help in determining the strength of the relationship between two variables. The correlation coefficient is a valuable measure of association between variables. Its value varies between -1 (weak relationship) and 1 (strong relationship)." }, { "code": null, "e": 1961, "s": 1548, "text": "Once we determine that there is a relationship between variables, next step is to identify best-fitting relationship (line) between the variables. The most common method is the Residual Sum of Squares (RSS). This method calculates the difference between observed data (actual value) and its vertical distance from the proposed best-fitting line (predicted value). It squares each difference and adds all of them." }, { "code": null, "e": 2388, "s": 1961, "text": "The MSE (Mean Squared Error) is a quality measure for the estimator by dividing RSS by total observed data points. It is always a non-negative number. Values closer to zero represent a smaller error. The RMSE (Root Mean Squared Error) is the square root of the MSE. The RMSE is a measure of the average deviation of the estimates from the observed values. This is easier to observe compare to MSE, which can be a large number." }, { "code": null, "e": 2424, "s": 2388, "text": "RMSE (Square root of MSE) = √ (MSE)" }, { "code": null, "e": 2497, "s": 2424, "text": "The additional number of variables will add more dimension to the model." }, { "code": null, "e": 2541, "s": 2497, "text": "Y = f(X) = β0 + β1 * X1 + β1 * X2 + β1 * X3" }, { "code": null, "e": 2594, "s": 2541, "text": "PythonGraphlabS Frame (similar to Pandas Data Frame)" }, { "code": null, "e": 2601, "s": 2594, "text": "Python" }, { "code": null, "e": 2610, "s": 2601, "text": "Graphlab" }, { "code": null, "e": 2649, "s": 2610, "text": "S Frame (similar to Pandas Data Frame)" }, { "code": null, "e": 2751, "s": 2649, "text": "House data of Seattle, Washington area is used. It contains following columns and around 21,000 rows." }, { "code": null, "e": 2967, "s": 2751, "text": "Id : date : price : bedrooms : bathrooms : sqft_living sqft_lot : floors : waterfront : view : condition : grade : sqft_above : sqft_basement : yr_built : yr_renovated : zipcode : lat : long : sqft_living : sqft_lot" }, { "code": null, "e": 3024, "s": 2967, "text": "> homesales = graphlab.SFrame(‘home_data.gl’)> homesales" }, { "code": null, "e": 3152, "s": 3024, "text": "We need to understand if there is a relationship between two variables. Let’s pick the housing price and square feet of living." }, { "code": null, "e": 3218, "s": 3152, "text": "> homesales.show(view=”Scatter Plot”, x=”sqft_living”, y=”price”)" }, { "code": null, "e": 3316, "s": 3218, "text": "We can observe that there is a relationship between square feet of living area and housing price." }, { "code": null, "e": 3408, "s": 3316, "text": "Let’s observer the data using the Boxplot with error lines to understand price by zip code." }, { "code": null, "e": 3473, "s": 3408, "text": "> homesales.show(view=’BoxWhisker Plot’, x=’zipcode’, y=’price’)" }, { "code": null, "e": 3597, "s": 3473, "text": "It is always good idea to explore and understand the surrounding data. Graphlab has a nice way to show the data statistics." }, { "code": null, "e": 3687, "s": 3597, "text": "> my_features = [‘bedrooms’, ‘bathrooms’, ‘sqft_living’, ‘sqft_lot’, ‘floors’, ‘zipcode’]" }, { "code": null, "e": 3811, "s": 3687, "text": "The first step is to get training data set and test data set. Let’s use 80% as training data and remaining 20% for testing." }, { "code": null, "e": 3873, "s": 3811, "text": "> train_data, test_data = homesales.random_split(0.8, seed=0)" }, { "code": null, "e": 4022, "s": 3873, "text": "Let’s build regression model with one variable for sq ft and store the results. The dependent variable price is what the model will need to predict." }, { "code": null, "e": 4146, "s": 4022, "text": "> sqft_model = graphlab.linear_regression.create(train_data, target=’price’, features=[‘sqft_living’], validation_set=None)" }, { "code": null, "e": 4218, "s": 4146, "text": "We can plot the model values along with actual values using matplotlib." }, { "code": null, "e": 4338, "s": 4218, "text": "> plt.plot(test_data[‘sqft_living’],test_data[‘price’],’.’, test_data[‘sqft_living’],sqft_model.predict(test_data),’-’)" }, { "code": null, "e": 4599, "s": 4338, "text": "Blue dots represents the test data displaying relationship between house price and square feet of living area. Green line shows the prediction of the home price (dependent variable) for given square feet using the “sqft_model” linear regression model we built." }, { "code": null, "e": 4664, "s": 4599, "text": "Let’s pick a house and predict its value using the “sqft_model”." }, { "code": null, "e": 4724, "s": 4664, "text": "> house2 = homesales[homesales[‘id’]==’5309101200']> house2" }, { "code": null, "e": 4782, "s": 4724, "text": "Now let’s predict the house value using the “sqft_model”." }, { "code": null, "e": 4817, "s": 4782, "text": "> print sqft_model.predict(house2)" }, { "code": null, "e": 4837, "s": 4817, "text": "[629584.8197281545]" }, { "code": null, "e": 4917, "s": 4837, "text": "It predicted value of $629,584 which is very close to actual value of $620,000." }, { "code": null, "e": 5014, "s": 4917, "text": "While our model worked reasonably well, there is a gap between predicted value and actual value." }, { "code": null, "e": 5053, "s": 5014, "text": "> print sqft_model.evaluate(test_data)" }, { "code": null, "e": 5115, "s": 5053, "text": "{‘max_error’: 4143550.8825285938, ‘rmse’: 255191.02870527358}" } ]
Convert Floats to Integers in a Pandas DataFrame - GeeksforGeeks
20 Aug, 2020 Let us see how to convert float to integer in a Pandas DataFrame. We will be using the astype() method to do this. It can also be done using the apply() method. Method 1: Using DataFrame.astype() method First of all we will create a DataFrame: # importing the libraryimport pandas as pd # creating a DataFramelist = [['Anton Yelchin', 36, 75.2, 54280.20], ['Yul Brynner', 38, 74.32, 34280.30], ['Lev Gorn', 31, 70.56, 84280.50], ['Alexander Godunov', 34, 80.30, 44280.80], ['Oleg Taktarov', 40, 100.03, 45280.30], ['Dmitriy Pevtsov', 33, 72.99, 70280.25], ['Alexander Petrov', 42, 85.84, 25280.75]]df = pd.DataFrame(list, columns =['Name', 'Age', 'Weight', 'Salary'])display(df) Output : Example 1 : Converting one column from float to int using DataFrame.astype() # displaying the datatypesdisplay(df.dtypes) # converting 'Weight' from float to intdf['Weight'] = df['Weight'].astype(int) # displaying the datatypesdisplay(df.dtypes) Output : Example 2: Converting more than one column from float to int using DataFrame.astype() # displaying the datatypesdisplay(df.dtypes) # converting 'Weight' and 'Salary' from float to intdf = df.astype({"Weight":'int', "Salary":'int'}) # displaying the datatypesdisplay(df.dtypes) Output : Method 2: Using DataFrame.apply() method First of all we will create a DataFrame. # importing the moduleimport pandas as pd # creating a DataFramelist = [[15, 2.5, 100.22], [20, 4.5, 50.21], [25, 5.2, 80.55], [45, 5.8, 48.86], [40, 6.3, 70.99], [41, 6.4, 90.25], [51, 2.3, 111.90]]df = pd.DataFrame(list, columns = ['Field_1', 'Field_2', 'Field_3'], index = ['a', 'b', 'c', 'd', 'e', 'f', 'g'])display(df) Output : Example 1: Converting a single column from float to int using DataFrame.apply(np.int64) # importing the moduleimport numpy as np # displaying the datatypesdisplay(df.dtypes) # converting 'Field_2' from float to intdf['Field_2'] = df['Field_2'].apply(np.int64) # displaying the datatypesdisplay(df.dtypes) Output : Example 2: Converting multiple columns from float to int using DataFrame.apply(np.int64) # displaying the datatypesdisplay(df.dtypes) # converting 'Field_2' and 'Field_3' from float to intdf['Field_2'] = df['Field_2'].apply(np.int64)df['Field_3'] = df['Field_3'].apply(np.int64) # displaying the datatypesdisplay(df.dtypes) Output : Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 24064, "s": 24036, "text": "\n20 Aug, 2020" }, { "code": null, "e": 24225, "s": 24064, "text": "Let us see how to convert float to integer in a Pandas DataFrame. We will be using the astype() method to do this. It can also be done using the apply() method." }, { "code": null, "e": 24267, "s": 24225, "text": "Method 1: Using DataFrame.astype() method" }, { "code": null, "e": 24308, "s": 24267, "text": "First of all we will create a DataFrame:" }, { "code": "# importing the libraryimport pandas as pd # creating a DataFramelist = [['Anton Yelchin', 36, 75.2, 54280.20], ['Yul Brynner', 38, 74.32, 34280.30], ['Lev Gorn', 31, 70.56, 84280.50], ['Alexander Godunov', 34, 80.30, 44280.80], ['Oleg Taktarov', 40, 100.03, 45280.30], ['Dmitriy Pevtsov', 33, 72.99, 70280.25], ['Alexander Petrov', 42, 85.84, 25280.75]]df = pd.DataFrame(list, columns =['Name', 'Age', 'Weight', 'Salary'])display(df)", "e": 24790, "s": 24308, "text": null }, { "code": null, "e": 24799, "s": 24790, "text": "Output :" }, { "code": null, "e": 24876, "s": 24799, "text": "Example 1 : Converting one column from float to int using DataFrame.astype()" }, { "code": "# displaying the datatypesdisplay(df.dtypes) # converting 'Weight' from float to intdf['Weight'] = df['Weight'].astype(int) # displaying the datatypesdisplay(df.dtypes)", "e": 25047, "s": 24876, "text": null }, { "code": null, "e": 25056, "s": 25047, "text": "Output :" }, { "code": null, "e": 25142, "s": 25056, "text": "Example 2: Converting more than one column from float to int using DataFrame.astype()" }, { "code": "# displaying the datatypesdisplay(df.dtypes) # converting 'Weight' and 'Salary' from float to intdf = df.astype({\"Weight\":'int', \"Salary\":'int'}) # displaying the datatypesdisplay(df.dtypes)", "e": 25336, "s": 25142, "text": null }, { "code": null, "e": 25345, "s": 25336, "text": "Output :" }, { "code": null, "e": 25386, "s": 25345, "text": "Method 2: Using DataFrame.apply() method" }, { "code": null, "e": 25427, "s": 25386, "text": "First of all we will create a DataFrame." }, { "code": "# importing the moduleimport pandas as pd # creating a DataFramelist = [[15, 2.5, 100.22], [20, 4.5, 50.21], [25, 5.2, 80.55], [45, 5.8, 48.86], [40, 6.3, 70.99], [41, 6.4, 90.25], [51, 2.3, 111.90]]df = pd.DataFrame(list, columns = ['Field_1', 'Field_2', 'Field_3'], index = ['a', 'b', 'c', 'd', 'e', 'f', 'g'])display(df)", "e": 25793, "s": 25427, "text": null }, { "code": null, "e": 25802, "s": 25793, "text": "Output :" }, { "code": null, "e": 25890, "s": 25802, "text": "Example 1: Converting a single column from float to int using DataFrame.apply(np.int64)" }, { "code": "# importing the moduleimport numpy as np # displaying the datatypesdisplay(df.dtypes) # converting 'Field_2' from float to intdf['Field_2'] = df['Field_2'].apply(np.int64) # displaying the datatypesdisplay(df.dtypes)", "e": 26110, "s": 25890, "text": null }, { "code": null, "e": 26119, "s": 26110, "text": "Output :" }, { "code": null, "e": 26208, "s": 26119, "text": "Example 2: Converting multiple columns from float to int using DataFrame.apply(np.int64)" }, { "code": "# displaying the datatypesdisplay(df.dtypes) # converting 'Field_2' and 'Field_3' from float to intdf['Field_2'] = df['Field_2'].apply(np.int64)df['Field_3'] = df['Field_3'].apply(np.int64) # displaying the datatypesdisplay(df.dtypes)", "e": 26445, "s": 26208, "text": null }, { "code": null, "e": 26454, "s": 26445, "text": "Output :" }, { "code": null, "e": 26478, "s": 26454, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26501, "s": 26478, "text": "Python Pandas-exercise" }, { "code": null, "e": 26515, "s": 26501, "text": "Python-pandas" }, { "code": null, "e": 26522, "s": 26515, "text": "Python" }, { "code": null, "e": 26620, "s": 26522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26629, "s": 26620, "text": "Comments" }, { "code": null, "e": 26642, "s": 26629, "text": "Old Comments" }, { "code": null, "e": 26674, "s": 26642, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26709, "s": 26674, "text": "Read a file line by line in Python" }, { "code": null, "e": 26731, "s": 26709, "text": "Enumerate() in Python" }, { "code": null, "e": 26761, "s": 26731, "text": "Iterate over a list in Python" }, { "code": null, "e": 26803, "s": 26761, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26846, "s": 26803, "text": "Python program to convert a list to string" }, { "code": null, "e": 26883, "s": 26846, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26909, "s": 26883, "text": "Python String | replace()" }, { "code": null, "e": 26953, "s": 26909, "text": "Reading and Writing to text files in Python" } ]
count() function in PHP
The count() function counts elements in an array, or properties in an object. It returns the number of elements in an array. count(arr, mode) arr − The specified array. arr − The specified array. mode − Specifies the mode. Possible values are 0 or 1. 0: Do not count all the elements, 1: Count all the elements. mode − Specifies the mode. Possible values are 0 or 1. 0: Do not count all the elements, 1: Count all the elements. The count() function returns the number of elements in an array − The following is an example − Live Demo <?php $products = array("Electronics","Footwear"); echo count($products); ?> 2
[ { "code": null, "e": 1187, "s": 1062, "text": "The count() function counts elements in an array, or properties in an object. It returns the number of elements in an array." }, { "code": null, "e": 1205, "s": 1187, "text": "count(arr, mode)\n" }, { "code": null, "e": 1232, "s": 1205, "text": "arr − The specified array." }, { "code": null, "e": 1259, "s": 1232, "text": "arr − The specified array." }, { "code": null, "e": 1375, "s": 1259, "text": "mode − Specifies the mode. Possible values are 0 or 1. 0: Do not count all the elements, 1: Count all the elements." }, { "code": null, "e": 1491, "s": 1375, "text": "mode − Specifies the mode. Possible values are 0 or 1. 0: Do not count all the elements, 1: Count all the elements." }, { "code": null, "e": 1557, "s": 1491, "text": "The count() function returns the number of elements in an array −" }, { "code": null, "e": 1587, "s": 1557, "text": "The following is an example −" }, { "code": null, "e": 1598, "s": 1587, "text": " Live Demo" }, { "code": null, "e": 1678, "s": 1598, "text": "<?php\n $products = array(\"Electronics\",\"Footwear\"); echo count($products);\n?>" }, { "code": null, "e": 1681, "s": 1678, "text": "2\n" } ]
DAX Information - ISLOGICAL function
Checks whether a value is a logical value (TRUE or FALSE), and returns TRUE or FALSE. ISLOGICAL (<value>) value The value that you want to test. TRUE or FALSE. = ISLOGICAL (5>4) returns TRUE. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2087, "s": 2001, "text": "Checks whether a value is a logical value (TRUE or FALSE), and returns TRUE or FALSE." }, { "code": null, "e": 2109, "s": 2087, "text": "ISLOGICAL (<value>) \n" }, { "code": null, "e": 2115, "s": 2109, "text": "value" }, { "code": null, "e": 2148, "s": 2115, "text": "The value that you want to test." }, { "code": null, "e": 2163, "s": 2148, "text": "TRUE or FALSE." }, { "code": null, "e": 2196, "s": 2163, "text": "= ISLOGICAL (5>4) returns TRUE. " }, { "code": null, "e": 2231, "s": 2196, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2245, "s": 2231, "text": " Abhay Gadiya" }, { "code": null, "e": 2278, "s": 2245, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2292, "s": 2278, "text": " Randy Minder" }, { "code": null, "e": 2327, "s": 2292, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2341, "s": 2327, "text": " Randy Minder" }, { "code": null, "e": 2348, "s": 2341, "text": " Print" }, { "code": null, "e": 2359, "s": 2348, "text": " Add Notes" } ]
Consul - Architecture
The architecture diagram for consul working in one datacenter can be best described as shown below − As we can observe, there are three different servers, which are managed by Consul. The working architecture works by the using raft algorithm, which helps us in electing a leader out of the three different servers. These servers are then labelled according to the tags such as Follower and Leader. As the name suggests, the follower is responsible for following the decisions of the leader. All these three servers are further connected with each other for any communication. Each server interacts with its own client using the concept of RPC. The Communication between the Clients is possible due to Gossip Protocol as mentioned below. The Communication with the internet facility can be made available using TCP or gossip method of communication. This communication is in direct contact with any of the three servers. Raft is a consensus algorithm for managing a replicated log. It relies on the principle of CAP Theorem, which states that in the presence of a network partition, one has to choose between consistency and availability. Not all the three fundamentals of the CAP Theorem can be achieved at any given point of time. One has to tradeoff for any two of them at the best. A Raft Cluster contains several servers, usually in the odd number count. For example, if we have five servers, it will allow the system to tolerate two failures. At any given time, each server is in one of the three states: Leader, Follower, or Candidate. In a normal operation, there is exactly one leader and all of the other servers are followers. These followers are in a passive state, i.e. they issue no requests on their own, but simply respond to requests from leaders and the candidate. The following illustration describes the workflow model using which the raft algorithm works − Since the Consul's version 0.7.1, there has been an introduction of separate key value data. The KV command is used to interact with the Consul's key-value store via the command line. It exposes top-level commands for Inserting, Updating, Reading and Deleting from the store. To get the Key/Value object store, we call the KV method available for the consul client − kv := consul.KV() The KVPair Structure is used to represent a single key/value entry. We can view the structure of Consul KV Pair in the following program. type KVPair struct { Key string CreateIndex uint64 ModifyIndex uint64 LockIndex uint64 Flags uint64 Value []byte Session string } Here, the various structures mentioned in the above code can be defined as follows − Key − It is a slash URL name. For example – sites/1/domain. Key − It is a slash URL name. For example – sites/1/domain. CreateIndex − Index number assigned when the key was first created. CreateIndex − Index number assigned when the key was first created. ModifyIndex − Index number assigned when the key was last updated. ModifyIndex − Index number assigned when the key was last updated. LockIndex − Index number created when a new lock acquired on the key/value entry LockIndex − Index number created when a new lock acquired on the key/value entry Flags − It can be used by the app to set the custom value. Flags − It can be used by the app to set the custom value. Value − It is a byte array of maximum 512kb. Value − It is a byte array of maximum 512kb. Session − It can be set after creating a session object. Session − It can be set after creating a session object. There are two types of protocol in Consul, which are called as − Consensus Protocol and Gossip Protocol Let us now understand them in detail. Consensus protocol is used by Consul to provide Consistency as described by the CAP Theorem. This protocol is based on the Raft Algorithm. When implementing Consensus protocol, the Raft Algorithm is used where raft nodes are always in any one of the three states: Follower, Candidate or Leader. The gossip protocol can be used to manage membership, send and receive messages across the cluster. In consul, the usage of gossip protocol occurs in two ways, WAN (Wireless Area Network) and LAN (Local Area Network). There are three known libraries, which can implement a Gossip Algorithm to discover nodes in a peer-to-peer network − teknek-gossip − It works with UDP and is written in Java. teknek-gossip − It works with UDP and is written in Java. gossip-python − It utilizes the TCP stack and it is possible to share data via the constructed network as well. gossip-python − It utilizes the TCP stack and it is possible to share data via the constructed network as well. Smudge − It is written in Go and uses UDP to exchange status information. Smudge − It is written in Go and uses UDP to exchange status information. Gossip protocols have also been used for achieving and maintaining a distributed database consistency or with other types of data in consistent states, counting the number of nodes in a network of unknown size, spreading news robustly, organizing nodes, etc. The RPC can be denoted as the short form for Remote Procedure Calls. It is a protocol that one program uses to request a service from another program. This protocol can be located in another computer on a network without having to acknowledge the networking details. The real beauty of using RPC in Consul is that, it helps us avoid the latency issues which most of the discovery service tools did have some time ago. Before RPC, Consul used to have only TCP and UDP based connections, which were good with most systems, but not in the case of distributed systems. RPC solves such problems by reducing the time-period of transfer of packet information from one place to another. In this area, GRPC by Google is a great tool to look forward in case one wishes to observe benchmarks and compare performance. 140 Lectures 20 hours Juan Galvan 86 Lectures 6.5 hours John Colley Print Add Notes Bookmark this page
[ { "code": null, "e": 1903, "s": 1802, "text": "The architecture diagram for consul working in one datacenter can be best described as shown below −" }, { "code": null, "e": 2379, "s": 1903, "text": "As we can observe, there are three different servers, which are managed by Consul. The working architecture works by the using raft algorithm, which helps us in electing a leader out of the three different servers. These servers are then labelled according to the tags such as Follower and Leader. As the name suggests, the follower is responsible for following the decisions of the leader. All these three servers are further connected with each other for any communication." }, { "code": null, "e": 2723, "s": 2379, "text": "Each server interacts with its own client using the concept of RPC. The Communication between the Clients is possible due to Gossip Protocol as mentioned below. The Communication with the internet facility can be made available using TCP or gossip method of communication. This communication is in direct contact with any of the three servers." }, { "code": null, "e": 3088, "s": 2723, "text": "Raft is a consensus algorithm for managing a replicated log. It relies on the principle of CAP Theorem, which states that in the presence of a network partition, one has to choose between consistency and availability. Not all the three fundamentals of the CAP Theorem can be achieved at any given point of time. One has to tradeoff for any two of them at the best." }, { "code": null, "e": 3585, "s": 3088, "text": "A Raft Cluster contains several servers, usually in the odd number count. For example, if we have five servers, it will allow the system to tolerate two failures. At any given time, each server is in one of the three states: Leader, Follower, or Candidate. In a normal operation, there is exactly one leader and all of the other servers are followers. These followers are in a passive state, i.e. they issue no requests on their own, but simply respond to requests from leaders and the candidate." }, { "code": null, "e": 3680, "s": 3585, "text": "The following illustration describes the workflow model using which the raft algorithm works −" }, { "code": null, "e": 4047, "s": 3680, "text": "Since the Consul's version 0.7.1, there has been an introduction of separate key value data. The KV command is used to interact with the Consul's key-value store via the command line. It exposes top-level commands for Inserting, Updating, Reading and Deleting from the store. To get the Key/Value object store, we call the KV method available for the consul client −" }, { "code": null, "e": 4066, "s": 4047, "text": "kv := consul.KV()\n" }, { "code": null, "e": 4204, "s": 4066, "text": "The KVPair Structure is used to represent a single key/value entry. We can view the structure of Consul KV Pair in the following program." }, { "code": null, "e": 4355, "s": 4204, "text": "type KVPair struct {\n Key string\n CreateIndex uint64\n ModifyIndex uint64\n LockIndex uint64\n Flags uint64\n Value []byte\n Session string\n}" }, { "code": null, "e": 4440, "s": 4355, "text": "Here, the various structures mentioned in the above code can be defined as follows −" }, { "code": null, "e": 4500, "s": 4440, "text": "Key − It is a slash URL name. For example – sites/1/domain." }, { "code": null, "e": 4560, "s": 4500, "text": "Key − It is a slash URL name. For example – sites/1/domain." }, { "code": null, "e": 4628, "s": 4560, "text": "CreateIndex − Index number assigned when the key was first created." }, { "code": null, "e": 4696, "s": 4628, "text": "CreateIndex − Index number assigned when the key was first created." }, { "code": null, "e": 4763, "s": 4696, "text": "ModifyIndex − Index number assigned when the key was last updated." }, { "code": null, "e": 4830, "s": 4763, "text": "ModifyIndex − Index number assigned when the key was last updated." }, { "code": null, "e": 4911, "s": 4830, "text": "LockIndex − Index number created when a new lock acquired on the key/value entry" }, { "code": null, "e": 4992, "s": 4911, "text": "LockIndex − Index number created when a new lock acquired on the key/value entry" }, { "code": null, "e": 5051, "s": 4992, "text": "Flags − It can be used by the app to set the custom value." }, { "code": null, "e": 5110, "s": 5051, "text": "Flags − It can be used by the app to set the custom value." }, { "code": null, "e": 5155, "s": 5110, "text": "Value − It is a byte array of maximum 512kb." }, { "code": null, "e": 5200, "s": 5155, "text": "Value − It is a byte array of maximum 512kb." }, { "code": null, "e": 5257, "s": 5200, "text": "Session − It can be set after creating a session object." }, { "code": null, "e": 5314, "s": 5257, "text": "Session − It can be set after creating a session object." }, { "code": null, "e": 5379, "s": 5314, "text": "There are two types of protocol in Consul, which are called as −" }, { "code": null, "e": 5402, "s": 5379, "text": "Consensus Protocol and" }, { "code": null, "e": 5418, "s": 5402, "text": "Gossip Protocol" }, { "code": null, "e": 5456, "s": 5418, "text": "Let us now understand them in detail." }, { "code": null, "e": 5751, "s": 5456, "text": "Consensus protocol is used by Consul to provide Consistency as described by the CAP Theorem. This protocol is based on the Raft Algorithm. When implementing Consensus protocol, the Raft Algorithm is used where raft nodes are always in any one of the three states: Follower, Candidate or Leader." }, { "code": null, "e": 6087, "s": 5751, "text": "The gossip protocol can be used to manage membership, send and receive messages across the cluster. In consul, the usage of gossip protocol occurs in two ways, WAN (Wireless Area Network) and LAN (Local Area Network). There are three known libraries, which can implement a Gossip Algorithm to discover nodes in a peer-to-peer network −" }, { "code": null, "e": 6145, "s": 6087, "text": "teknek-gossip − It works with UDP and is written in Java." }, { "code": null, "e": 6203, "s": 6145, "text": "teknek-gossip − It works with UDP and is written in Java." }, { "code": null, "e": 6315, "s": 6203, "text": "gossip-python − It utilizes the TCP stack and it is possible to share data via the constructed network as well." }, { "code": null, "e": 6427, "s": 6315, "text": "gossip-python − It utilizes the TCP stack and it is possible to share data via the constructed network as well." }, { "code": null, "e": 6501, "s": 6427, "text": "Smudge − It is written in Go and uses UDP to exchange status information." }, { "code": null, "e": 6575, "s": 6501, "text": "Smudge − It is written in Go and uses UDP to exchange status information." }, { "code": null, "e": 6834, "s": 6575, "text": "Gossip protocols have also been used for achieving and maintaining a distributed database consistency or with other types of data in consistent states, counting the number of nodes in a network of unknown size, spreading news robustly, organizing nodes, etc." }, { "code": null, "e": 7101, "s": 6834, "text": "The RPC can be denoted as the short form for Remote Procedure Calls. It is a protocol that one program uses to request a service from another program. This protocol can be located in another computer on a network without having to acknowledge the networking details." }, { "code": null, "e": 7640, "s": 7101, "text": "The real beauty of using RPC in Consul is that, it helps us avoid the latency issues which most of the discovery service tools did have some time ago. Before RPC, Consul used to have only TCP and UDP based connections, which were good with most systems, but not in the case of distributed systems. RPC solves such problems by reducing the time-period of transfer of packet information from one place to another. In this area, GRPC by Google is a great tool to look forward in case one wishes to observe benchmarks and compare performance." }, { "code": null, "e": 7675, "s": 7640, "text": "\n 140 Lectures \n 20 hours \n" }, { "code": null, "e": 7688, "s": 7675, "text": " Juan Galvan" }, { "code": null, "e": 7723, "s": 7688, "text": "\n 86 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7736, "s": 7723, "text": " John Colley" }, { "code": null, "e": 7743, "s": 7736, "text": " Print" }, { "code": null, "e": 7754, "s": 7743, "text": " Add Notes" } ]
Add Text to ggplot2 Plot in R - GeeksforGeeks
30 May, 2021 In this article, we are going to see how to add Text to the ggplot2 plot in R Programming Language. To do this annotate() is used. It is useful for adding small annotations (such as text labels) or if you have your data in vectors, and for some reason don’t want to put them in a data frame. Syntax: annotate(geom,x = NULL,y = NULL, xmin = NULL, xmax = NULL, ymin = NULL, ymax = NULL, xend = NULL, yend = NULL, ..., na.rm = FALSE) Parameters: geom: name of geom to use for annotation x, y, xmin, ymin, xmax, ymax, xend, yend: positioning aesthetics – you must specify at least one of these. ...: Other arguments passed on to layer(). These are often aesthetics, used to set an aesthetic to a fixed value, like color = “red” or size = 3. na.rm: If FALSE, the default, missing values are removed with a warning. Example: R library("ggplot2") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(4,3,2,5,1))gfg_data gfg_plot<- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot + annotate("text", x = 4, y = 3, label = "GeeksForGeeks") Output: To annotate multiple test elements to the ggplot2 plot user needs to call annotate() function of the ggplot2 package multiple times with the required parameters in the R programming language. Example: R library("ggplot2") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(4,3,2,5,1))gfg_data gfg_plot<- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot + annotate("text", x = 1.2, y = 5, label = "GeeksForGeeks") + annotate("text", x = 4.7, y = 1, label = "GeeksForGeeks") Output: To modify the color and the size of the text added to the ggplot2 plot using annotate() function, the user needs to add col and size as the arguments of the annotate function from the ggplot2 package and specify the required parameter into this function and this will lead to the change in the size and the color of the text added to ggplot2 plot in the R programming language. Example: R library("ggplot2") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(4,3,2,5,1)) gfg_data gfg_plot<- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot + annotate("text", x = 2, y = 5, label = "GeeksForGeeks", col = "green", size = 10) + annotate("text", x = 4.7, y = 1, label = "GeeksForGeeks", col = "green", size = 5) Output: Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to Change Axis Scales in R Plots? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? R - if statement How to filter R dataframe by multiple conditions? Plot mean and standard deviation using ggplot2 in R Time Series Analysis in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n30 May, 2021" }, { "code": null, "e": 26587, "s": 26487, "text": "In this article, we are going to see how to add Text to the ggplot2 plot in R Programming Language." }, { "code": null, "e": 26779, "s": 26587, "text": "To do this annotate() is used. It is useful for adding small annotations (such as text labels) or if you have your data in vectors, and for some reason don’t want to put them in a data frame." }, { "code": null, "e": 26787, "s": 26779, "text": "Syntax:" }, { "code": null, "e": 26918, "s": 26787, "text": "annotate(geom,x = NULL,y = NULL, xmin = NULL, xmax = NULL, ymin = NULL, ymax = NULL, xend = NULL, yend = NULL, ..., na.rm = FALSE)" }, { "code": null, "e": 26930, "s": 26918, "text": "Parameters:" }, { "code": null, "e": 26971, "s": 26930, "text": "geom: name of geom to use for annotation" }, { "code": null, "e": 27078, "s": 26971, "text": "x, y, xmin, ymin, xmax, ymax, xend, yend: positioning aesthetics – you must specify at least one of these." }, { "code": null, "e": 27224, "s": 27078, "text": "...: Other arguments passed on to layer(). These are often aesthetics, used to set an aesthetic to a fixed value, like color = “red” or size = 3." }, { "code": null, "e": 27297, "s": 27224, "text": "na.rm: If FALSE, the default, missing values are removed with a warning." }, { "code": null, "e": 27306, "s": 27297, "text": "Example:" }, { "code": null, "e": 27308, "s": 27306, "text": "R" }, { "code": "library(\"ggplot2\") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(4,3,2,5,1))gfg_data gfg_plot<- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot + annotate(\"text\", x = 4, y = 3, label = \"GeeksForGeeks\")", "e": 27579, "s": 27308, "text": null }, { "code": null, "e": 27587, "s": 27579, "text": "Output:" }, { "code": null, "e": 27779, "s": 27587, "text": "To annotate multiple test elements to the ggplot2 plot user needs to call annotate() function of the ggplot2 package multiple times with the required parameters in the R programming language." }, { "code": null, "e": 27788, "s": 27779, "text": "Example:" }, { "code": null, "e": 27790, "s": 27788, "text": "R" }, { "code": "library(\"ggplot2\") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(4,3,2,5,1))gfg_data gfg_plot<- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot + annotate(\"text\", x = 1.2, y = 5, label = \"GeeksForGeeks\") + annotate(\"text\", x = 4.7, y = 1, label = \"GeeksForGeeks\") ", "e": 28127, "s": 27790, "text": null }, { "code": null, "e": 28135, "s": 28127, "text": "Output:" }, { "code": null, "e": 28513, "s": 28135, "text": "To modify the color and the size of the text added to the ggplot2 plot using annotate() function, the user needs to add col and size as the arguments of the annotate function from the ggplot2 package and specify the required parameter into this function and this will lead to the change in the size and the color of the text added to ggplot2 plot in the R programming language." }, { "code": null, "e": 28522, "s": 28513, "text": "Example:" }, { "code": null, "e": 28524, "s": 28522, "text": "R" }, { "code": "library(\"ggplot2\") gfg_data <- data.frame(x = c(1,2,3,4,5), y = c(4,3,2,5,1)) gfg_data gfg_plot<- ggplot(gfg_data, aes(x, y)) + geom_point() gfg_plot + annotate(\"text\", x = 2, y = 5, label = \"GeeksForGeeks\", col = \"green\", size = 10) + annotate(\"text\", x = 4.7, y = 1, label = \"GeeksForGeeks\", col = \"green\", size = 5) ", "e": 28953, "s": 28524, "text": null }, { "code": null, "e": 28961, "s": 28953, "text": "Output:" }, { "code": null, "e": 28968, "s": 28961, "text": "Picked" }, { "code": null, "e": 28977, "s": 28968, "text": "R-ggplot" }, { "code": null, "e": 28988, "s": 28977, "text": "R Language" }, { "code": null, "e": 29086, "s": 28988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29138, "s": 29086, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29173, "s": 29138, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29231, "s": 29173, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29269, "s": 29231, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29312, "s": 29269, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29361, "s": 29312, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29378, "s": 29361, "text": "R - if statement" }, { "code": null, "e": 29428, "s": 29378, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29480, "s": 29428, "text": "Plot mean and standard deviation using ggplot2 in R" } ]
How to remove multiple selected items in listbox in Tkinter? - GeeksforGeeks
02 Feb, 2021 Prerequisite: Tkinter, Listbox in Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we will learn how to remove multiple selected checkboxes in Listbox Using Tkinter in Python. Let’s Understand step by step implementation:- 1. Create Normal Tkinter Window Python3 from tkinter import * root = Tk()root.geometry("200x200") root.mainloop() Output: 2. Add Listbox using Listbox() method Syntax: Listbox(root, bg, fg, bd, height, width, font, ..) Python3 # Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set Geometryroot.geometry("200x200") # Add Listboxlistbox = Listbox(root, selectmode=MULTIPLE)listbox.pack() # Listbox Items Listitems = ["Apple", "Orange", "Grapes", "Banana", "Mango"] # Iterate Through Items list for item in items: listbox.insert(END, item) Button(root, text="delete").pack() # Execute Tkinterroot.mainloop() Output: 3. Remove Selected Item From Listbox Get a List of selected Items from Listbox using the curselection() method. Iterate through all list and remove item using delete() method Below is the implementation:- Python3 # Import Modulefrom tkinter import * # Function will remove selected Listbox itemsdef remove_item(): selected_checkboxs = listbox.curselection() for selected_checkbox in selected_checkboxs[::-1]: listbox.delete(selected_checkbox) # Create Objectroot = Tk() # Set Geometryroot.geometry("200x200") # Add Listboxlistbox = Listbox(root, selectmode=MULTIPLE)listbox.pack() # Listbox Items Listitems = ["Apple", "Orange", "Grapes", "Banana", "Mango"] # Iterate Through Items list for item in items: listbox.insert(END, item) Button(root, text="delete", command=remove_item).pack() # Execute Tkinterroot.mainloop() Output: Picked Python-tkinter 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": "\n02 Feb, 2021" }, { "code": null, "e": 25689, "s": 25647, "text": "Prerequisite: Tkinter, Listbox in Tkinter" }, { "code": null, "e": 25993, "s": 25689, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications." }, { "code": null, "e": 26103, "s": 25993, "text": "In this article, we will learn how to remove multiple selected checkboxes in Listbox Using Tkinter in Python." }, { "code": null, "e": 26150, "s": 26103, "text": "Let’s Understand step by step implementation:-" }, { "code": null, "e": 26182, "s": 26150, "text": "1. Create Normal Tkinter Window" }, { "code": null, "e": 26190, "s": 26182, "text": "Python3" }, { "code": "from tkinter import * root = Tk()root.geometry(\"200x200\") root.mainloop()", "e": 26266, "s": 26190, "text": null }, { "code": null, "e": 26274, "s": 26266, "text": "Output:" }, { "code": null, "e": 26312, "s": 26274, "text": "2. Add Listbox using Listbox() method" }, { "code": null, "e": 26321, "s": 26312, "text": "Syntax: " }, { "code": null, "e": 26373, "s": 26321, "text": "Listbox(root, bg, fg, bd, height, width, font, ..) " }, { "code": null, "e": 26381, "s": 26373, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Set Geometryroot.geometry(\"200x200\") # Add Listboxlistbox = Listbox(root, selectmode=MULTIPLE)listbox.pack() # Listbox Items Listitems = [\"Apple\", \"Orange\", \"Grapes\", \"Banana\", \"Mango\"] # Iterate Through Items list for item in items: listbox.insert(END, item) Button(root, text=\"delete\").pack() # Execute Tkinterroot.mainloop()", "e": 26785, "s": 26381, "text": null }, { "code": null, "e": 26793, "s": 26785, "text": "Output:" }, { "code": null, "e": 26830, "s": 26793, "text": "3. Remove Selected Item From Listbox" }, { "code": null, "e": 26905, "s": 26830, "text": "Get a List of selected Items from Listbox using the curselection() method." }, { "code": null, "e": 26968, "s": 26905, "text": "Iterate through all list and remove item using delete() method" }, { "code": null, "e": 26998, "s": 26968, "text": "Below is the implementation:-" }, { "code": null, "e": 27006, "s": 26998, "text": "Python3" }, { "code": "# Import Modulefrom tkinter import * # Function will remove selected Listbox itemsdef remove_item(): selected_checkboxs = listbox.curselection() for selected_checkbox in selected_checkboxs[::-1]: listbox.delete(selected_checkbox) # Create Objectroot = Tk() # Set Geometryroot.geometry(\"200x200\") # Add Listboxlistbox = Listbox(root, selectmode=MULTIPLE)listbox.pack() # Listbox Items Listitems = [\"Apple\", \"Orange\", \"Grapes\", \"Banana\", \"Mango\"] # Iterate Through Items list for item in items: listbox.insert(END, item) Button(root, text=\"delete\", command=remove_item).pack() # Execute Tkinterroot.mainloop()", "e": 27640, "s": 27006, "text": null }, { "code": null, "e": 27648, "s": 27640, "text": "Output:" }, { "code": null, "e": 27655, "s": 27648, "text": "Picked" }, { "code": null, "e": 27670, "s": 27655, "text": "Python-tkinter" }, { "code": null, "e": 27677, "s": 27670, "text": "Python" }, { "code": null, "e": 27775, "s": 27677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27807, "s": 27775, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27849, "s": 27807, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27891, "s": 27849, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27947, "s": 27891, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27974, "s": 27947, "text": "Python Classes and Objects" }, { "code": null, "e": 28005, "s": 27974, "text": "Python | os.path.join() method" }, { "code": null, "e": 28034, "s": 28005, "text": "Create a directory in Python" }, { "code": null, "e": 28056, "s": 28034, "text": "Defaultdict in Python" }, { "code": null, "e": 28092, "s": 28056, "text": "Python | Pandas dataframe.groupby()" } ]
Python | sympy.prime() method - GeeksforGeeks
26 Aug, 2019 With the help of sympy.prime() method, we can find the nth prime, with the primes indexed as prime(1) = 2, prime(2) = 3, etc. Syntax: prime(n) Parameter:n – It denotes the nth prime number. Returns: Returns the nth prime number. Example #1: # import sympy from sympy import prime n = 5 # Use prime() method nth_prime = prime(n) print("The {}th prime is {}".format(n, nth_prime)) Output: The 5th prime is 11 Example #2: # import sympy from sympy import prime n = 23 # Use prime() method nth_prime = prime(n) print("The {}rd prime is {}".format(n, nth_prime)) Output: The 23rd prime is 83 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n26 Aug, 2019" }, { "code": null, "e": 25791, "s": 25665, "text": "With the help of sympy.prime() method, we can find the nth prime, with the primes indexed as prime(1) = 2, prime(2) = 3, etc." }, { "code": null, "e": 25808, "s": 25791, "text": "Syntax: prime(n)" }, { "code": null, "e": 25855, "s": 25808, "text": "Parameter:n – It denotes the nth prime number." }, { "code": null, "e": 25894, "s": 25855, "text": "Returns: Returns the nth prime number." }, { "code": null, "e": 25906, "s": 25894, "text": "Example #1:" }, { "code": "# import sympy from sympy import prime n = 5 # Use prime() method nth_prime = prime(n) print(\"The {}th prime is {}\".format(n, nth_prime)) ", "e": 26054, "s": 25906, "text": null }, { "code": null, "e": 26062, "s": 26054, "text": "Output:" }, { "code": null, "e": 26083, "s": 26062, "text": "The 5th prime is 11\n" }, { "code": null, "e": 26095, "s": 26083, "text": "Example #2:" }, { "code": "# import sympy from sympy import prime n = 23 # Use prime() method nth_prime = prime(n) print(\"The {}rd prime is {}\".format(n, nth_prime)) ", "e": 26250, "s": 26095, "text": null }, { "code": null, "e": 26258, "s": 26250, "text": "Output:" }, { "code": null, "e": 26280, "s": 26258, "text": "The 23rd prime is 83\n" }, { "code": null, "e": 26286, "s": 26280, "text": "SymPy" }, { "code": null, "e": 26293, "s": 26286, "text": "Python" }, { "code": null, "e": 26391, "s": 26293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26423, "s": 26391, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26465, "s": 26423, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26507, "s": 26465, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26563, "s": 26507, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26590, "s": 26563, "text": "Python Classes and Objects" }, { "code": null, "e": 26621, "s": 26590, "text": "Python | os.path.join() method" }, { "code": null, "e": 26650, "s": 26621, "text": "Create a directory in Python" }, { "code": null, "e": 26672, "s": 26650, "text": "Defaultdict in Python" }, { "code": null, "e": 26711, "s": 26672, "text": "Python | Get unique values from a list" } ]
Batch Script - SUBST
This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment. Subst [driveletter] @echo off Subst p: P: will be assigned as the drive letter for the current folder. Print Add Notes Bookmark this page
[ { "code": null, "e": 2286, "s": 2169, "text": "This batch command assigns a drive letter to a local folder, displays current assignments, or removes an assignment." }, { "code": null, "e": 2307, "s": 2286, "text": "Subst [driveletter]\n" }, { "code": null, "e": 2327, "s": 2307, "text": "@echo off \nSubst p:" }, { "code": null, "e": 2391, "s": 2327, "text": "P: will be assigned as the drive letter for the current folder." }, { "code": null, "e": 2398, "s": 2391, "text": " Print" }, { "code": null, "e": 2409, "s": 2398, "text": " Add Notes" } ]
Sorting a vector in C++
Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements. Quicksort(), mergesort() can also be used, as per requirement. Begin Decalre v of vector type. Initialize some values into v in array pattern. Print “Elements before sorting”. for (const auto &i: v) print all the values of variable i. Print “Elements after sorting”. Call sort(v.begin(), v.end()) function to sort all the elements of the v vector. for (const auto &i: v) print all the values of variable i. End. This is a simple example of sorting a vector in c++: Live Demo #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 }; cout<<"Elements before sorting"<<endl; for (const auto &i: v) cout << i << ' '<<endl; cout<<"Elements after sorting"<<endl; sort(v.begin(), v.end()); for (const auto &i: v) cout << i << ' '<<endl; return 0; } Elements before sorting 10 9 8 6 7 2 5 1 Elements after sorting 1 2 5 6 7 8 9 10
[ { "code": null, "e": 1344, "s": 1062, "text": "Sorting a vector in C++ can be done by using std::sort(). It is defined in<algorithm> header. To get a stable sort std::stable_sort is used. It is exactly like sort() but maintains the relative order of equal elements. Quicksort(), mergesort() can also be used, as per requirement." }, { "code": null, "e": 1729, "s": 1344, "text": "Begin\n Decalre v of vector type.\n Initialize some values into v in array pattern.\n Print “Elements before sorting”.\n for (const auto &i: v)\n print all the values of variable i.\n Print “Elements after sorting”.\n Call sort(v.begin(), v.end()) function to sort all the elements of the v vector.\n for (const auto &i: v)\n print all the values of variable i.\nEnd." }, { "code": null, "e": 1782, "s": 1729, "text": "This is a simple example of sorting a vector in c++:" }, { "code": null, "e": 1793, "s": 1782, "text": " Live Demo" }, { "code": null, "e": 2179, "s": 1793, "text": "#include <iostream>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main() {\n vector<int> v = { 10, 9, 8, 6, 7, 2, 5, 1 };\n cout<<\"Elements before sorting\"<<endl;\n for (const auto &i: v)\n cout << i << ' '<<endl;\n cout<<\"Elements after sorting\"<<endl;\n sort(v.begin(), v.end());\n for (const auto &i: v)\n cout << i << ' '<<endl;\n return 0;\n}" }, { "code": null, "e": 2260, "s": 2179, "text": "Elements before sorting\n10\n9\n8\n6\n7\n2\n5\n1\nElements after sorting\n1\n2\n5\n6\n7\n8\n9\n10" } ]
Format percentage with MessageFormat class in Java
To format message with percentage fillers in Java, we use the MessageFormat class. The MessageFormat class gives us a way to produce concatenated messages which are not dependent on the language. The MessageFormat class extends the Serializable and Cloneable interfaces. Declaration - The java.text.MessageFormat class is declared as follows − public class MessageFormat extends Format The MessageFormat.format(pattern, params) method formats the message and fills in the missing parts using the objects in the params array matching up the argument numbers and the array indices. The format method has two arguments, a pattern and an array of arguments. The pattern contains placeholder in {} curly braces which have a index that indicate the position in the array where the value of the argument is stored, a number argument indicating that the filler is a number and a percent parameter indicating that the number is percent representing percentage. They are as follows − String message = MessageFormat.format("{0,number,percent} passed and {1,number,percent} failed", obj); Let us see a program to format the message with percentage fillers − Live Demo import java.text.MessageFormat; public class Example { public static void main(String[] args) throws Exception { Object[] obj = new Object[] { new Double(40.56), new Double(59.44)}; String message = MessageFormat.format("{0,number,percent} passed and {1,number,percent} ailed", obj); System.out.println(message); } } The output is as follows − 4,056% passed and 5,944% failed
[ { "code": null, "e": 1333, "s": 1062, "text": "To format message with percentage fillers in Java, we use the MessageFormat class. The MessageFormat class gives us a way to produce concatenated messages which are not dependent on the language. The MessageFormat class extends the Serializable and Cloneable interfaces." }, { "code": null, "e": 1406, "s": 1333, "text": "Declaration - The java.text.MessageFormat class is declared as follows −" }, { "code": null, "e": 1448, "s": 1406, "text": "public class MessageFormat extends Format" }, { "code": null, "e": 1643, "s": 1448, "text": "The MessageFormat.format(pattern, params) method formats the message and fills in the missing parts using the objects in the params array matching up the argument numbers and the array indices." }, { "code": null, "e": 2037, "s": 1643, "text": "The format method has two arguments, a pattern and an array of arguments. The pattern contains placeholder in {} curly braces which have a index that indicate the position in the array where the value of the argument is stored, a number argument indicating that the filler is a number and a percent parameter indicating that the number is percent representing percentage. They are as follows −" }, { "code": null, "e": 2140, "s": 2037, "text": "String message = MessageFormat.format(\"{0,number,percent} passed and {1,number,percent} failed\", obj);" }, { "code": null, "e": 2209, "s": 2140, "text": "Let us see a program to format the message with percentage fillers −" }, { "code": null, "e": 2220, "s": 2209, "text": " Live Demo" }, { "code": null, "e": 2561, "s": 2220, "text": "import java.text.MessageFormat;\npublic class Example {\n public static void main(String[] args) throws Exception {\n Object[] obj = new Object[] { new Double(40.56), new Double(59.44)};\n String message = MessageFormat.format(\"{0,number,percent} passed and {1,number,percent} ailed\", obj);\n System.out.println(message);\n }\n}" }, { "code": null, "e": 2588, "s": 2561, "text": "The output is as follows −" }, { "code": null, "e": 2620, "s": 2588, "text": "4,056% passed and 5,944% failed" } ]
Python - CGI Programming
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA. The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. The current version is CGI/1.1 and CGI/1.2 is under progress. To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL. Your browser contacts the HTTP web server and demands for the URL, i.e., filename. Your browser contacts the HTTP web server and demands for the URL, i.e., filename. Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file. Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file. Web browser takes response from web server and displays either the received file or error message. Web browser takes response from web server and displays either the received file or error message. However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc. Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well. By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file − <Directory "/var/www/cgi-bin"> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> <Directory "/var/www/cgi-bin"> Options All </Directory> Here, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc. Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable. #!/usr/bin/python print "Content-type:text/html\r\n\r\n" print '<html>' print '<head>' print '<title>Hello World - First CGI Program</title>' print '</head>' print '<body>' print '<h2>Hello World! This is my first CGI program</h2>' print '</body>' print '</html>' If you click hello.py, then this produces the following output − This hello.py script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen. By now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS. The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form − HTTP Field Name: Field Content For Example Content-type: text/html\r\n\r\n There are few other important HTTP headers, which you will use frequently in your CGI Programming. Content-type: A MIME string defining the format of the file being returned. Example is Content-type:text/html Expires: Date The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT. Location: URL The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file. Last-modified: Date The date of last modification of the resource. Content-length: N The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. Set-Cookie: String Set the cookie passed through the string All the CGI programs have access to the following environment variables. These variables play an important role while writing any CGI program. CONTENT_TYPE The data type of the content. Used when the client is sending attached content to the server. For example, file upload. CONTENT_LENGTH The length of the query information. It is available only for POST requests. HTTP_COOKIE Returns the set cookies in the form of key & value pair. HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. It is name of the web browser. PATH_INFO The path for the CGI script. QUERY_STRING The URL-encoded information that is sent with GET method request. REMOTE_ADDR The IP address of the remote host making the request. This is useful logging or for authentication. REMOTE_HOST The fully qualified name of the host making the request. If this information is not available, then REMOTE_ADDR can be used to get IR address. REQUEST_METHOD The method used to make the request. The most common methods are GET and POST. SCRIPT_FILENAME The full path to the CGI script. SCRIPT_NAME The name of the CGI script. SERVER_NAME The server's hostname or IP Address SERVER_SOFTWARE The name and version of the software the server is running. Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment #!/usr/bin/python import os print "Content-type: text/html\r\n\r\n"; print "<font size=+1>Environment</font><\br>"; for param in os.environ.keys(): print "<b>%20s</b>: %s<\br>" % (param, os.environ[param]) You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently, browser uses two methods two pass this information to web server. These methods are GET Method and POST Method. The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows − http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2 The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be sent in a request string. The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable. You can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method. Here is a simple URL, which passes two values to hello_get.py program using GET method. Below is hello_get.py script to handle input given by web browser. We are going to use cgi module, which makes it very easy to access passed information − #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello - Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (first_name, last_name) print "</body>" print "</html>" This would generate the following result − This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input. <form action = "/cgi-bin/hello_get.py" method = "get"> First Name: <input type = "text" name = "first_name"> <br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> Here is the actual output of the above form, you enter First and Last Name and then click submit button to see the result. A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input. Below is same hello_get.py script which handles GET as well as POST method. #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello - Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (first_name, last_name) print "</body>" print "</html>" Let us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input. <form action = "/cgi-bin/hello_get.py" method = "post"> First Name: <input type = "text" name = "first_name"><br /> Last Name: <input type = "text" name = "last_name" /> <input type = "submit" value = "Submit" /> </form> Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result. Checkboxes are used when more than one option is required to be selected. Here is example HTML code for a form with two checkboxes − <form action = "/cgi-bin/checkbox.cgi" method = "POST" target = "_blank"> <input type = "checkbox" name = "maths" value = "on" /> Maths <input type = "checkbox" name = "physics" value = "on" /> Physics <input type = "submit" value = "Select Subject" /> </form> The result of this code is the following form − Below is checkbox.cgi script to handle input given by web browser for checkbox button. #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields if form.getvalue('maths'): math_flag = "ON" else: math_flag = "OFF" if form.getvalue('physics'): physics_flag = "ON" else: physics_flag = "OFF" print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Checkbox - Third CGI Program</title>" print "</head>" print "<body>" print "<h2> CheckBox Maths is : %s</h2>" % math_flag print "<h2> CheckBox Physics is : %s</h2>" % physics_flag print "</body>" print "</html>" Radio Buttons are used when only one option is required to be selected. Here is example HTML code for a form with two radio buttons − <form action = "/cgi-bin/radiobutton.py" method = "post" target = "_blank"> <input type = "radio" name = "subject" value = "maths" /> Maths <input type = "radio" name = "subject" value = "physics" /> Physics <input type = "submit" value = "Select Subject" /> </form> The result of this code is the following form − Below is radiobutton.py script to handle input given by web browser for radio button − #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields if form.getvalue('subject'): subject = form.getvalue('subject') else: subject = "Not set" print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Radio - Fourth CGI Program</title>" print "</head>" print "<body>" print "<h2> Selected Subject is %s</h2>" % subject print "</body>" print "</html>" TEXTAREA element is used when multiline text has to be passed to the CGI Program. Here is example HTML code for a form with a TEXTAREA box − <form action = "/cgi-bin/textarea.py" method = "post" target = "_blank"> <textarea name = "textcontent" cols = "40" rows = "4"> Type your text here... </textarea> <input type = "submit" value = "Submit" /> </form> The result of this code is the following form − Below is textarea.cgi script to handle input given by web browser − #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields if form.getvalue('textcontent'): text_content = form.getvalue('textcontent') else: text_content = "Not entered" print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>"; print "<title>Text Area - Fifth CGI Program</title>" print "</head>" print "<body>" print "<h2> Entered Text Content is %s</h2>" % text_content print "</body>" Drop Down Box is used when we have many options available but only one or two will be selected. Here is example HTML code for a form with one drop down box − <form action = "/cgi-bin/dropdown.py" method = "post" target = "_blank"> <select name = "dropdown"> <option value = "Maths" selected>Maths</option> <option value = "Physics">Physics</option> </select> <input type = "submit" value = "Submit"/> </form> The result of this code is the following form − Below is dropdown.py script to handle input given by web browser. #!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields if form.getvalue('dropdown'): subject = form.getvalue('dropdown') else: subject = "Not entered" print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Dropdown Box - Sixth CGI Program</title>" print "</head>" print "<body>" print "<h2> Selected Subject is %s</h2>" % subject print "</body>" print "</html>" HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. How to maintain user's session information across all the web pages? In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics. Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored. Cookies are a plain text data record of 5 variable-length fields − Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. Domain − The domain name of your site. Domain − The domain name of your site. Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page. Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. Name=Value − Cookies are set and retrieved in the form of key and value pairs. Name=Value − Cookies are set and retrieved in the form of key and value pairs. It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows − #!/usr/bin/python print "Set-Cookie:UserID = XYZ;\r\n" print "Set-Cookie:Password = XYZ123;\r\n" print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT";\r\n" print "Set-Cookie:Domain = www.tutorialspoint.com;\r\n" print "Set-Cookie:Path = /perl;\n" print "Content-type:text/html\r\n\r\n" ...........Rest of the HTML Content.... From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n. It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form − key1 = value1;key2 = value2;key3 = value3.... Here is an example of how to retrieve cookies. #!/usr/bin/python # Import modules for CGI handling from os import environ import cgi, cgitb if environ.has_key('HTTP_COOKIE'): for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')): (key, value ) = split(cookie, '='); if key == "UserID": user_id = value if key == "Password": password = value print "User ID = %s" % user_id print "Password = %s" % password This produces the following result for the cookies set by above script − User ID = XYZ Password = XYZ123 To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a "Browse" button. <html> <body> <form enctype = "multipart/form-data" action = "save_file.py" method = "post"> <p>File: <input type = "file" name = "filename" /></p> <p><input type = "submit" value = "Upload" /></p> </form> </body> </html> The result of this code is the following form − File: Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server. Here is the script save_file.py to handle file upload − #!/usr/bin/python import cgi, os import cgitb; cgitb.enable() form = cgi.FieldStorage() # Get filename here. fileitem = form['filename'] # Test if the file was uploaded if fileitem.filename: # strip leading path from file name to avoid # directory traversal attacks fn = os.path.basename(fileitem.filename) open('/tmp/' + fn, 'wb').write(fileitem.file.read()) message = 'The file "' + fn + '" was uploaded successfully' else: message = 'No file was uploaded' print """\ Content-Type: text/html\n <html> <body> <p>%s</p> </body> </html> """ % (message,) If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine. fn = os.path.basename(fileitem.filename.replace("\\", "/" )) Sometimes, it is desired that you want to give option where a user can click a link and it will pop up a "File Download" dialogue box to the user instead of displaying actual content. This is very easy and can be achieved through HTTP header. This HTTP header is be different from the header mentioned in previous section. For example, if you want make a FileName file downloadable from a given link, then its syntax is as follows − #!/usr/bin/python # HTTP Header print "Content-Type:application/octet-stream; name = \"FileName\"\r\n"; print "Content-Disposition: attachment; filename = \"FileName\"\r\n\n"; # Actual File Content will go here. fo = open("foo.txt", "rb") str = fo.read(); print str # Close opend file fo.close() Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us 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": 2441, "s": 2244, "text": "The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA." }, { "code": null, "e": 2583, "s": 2441, "text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers." }, { "code": null, "e": 2725, "s": 2583, "text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers." }, { "code": null, "e": 2787, "s": 2725, "text": "The current version is CGI/1.1 and CGI/1.2 is under progress." }, { "code": null, "e": 2849, "s": 2787, "text": "The current version is CGI/1.1 and CGI/1.2 is under progress." }, { "code": null, "e": 2974, "s": 2849, "text": "To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL." }, { "code": null, "e": 3057, "s": 2974, "text": "Your browser contacts the HTTP web server and demands for the URL, i.e., filename." }, { "code": null, "e": 3140, "s": 3057, "text": "Your browser contacts the HTTP web server and demands for the URL, i.e., filename." }, { "code": null, "e": 3328, "s": 3140, "text": "Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file." }, { "code": null, "e": 3516, "s": 3328, "text": "Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file." }, { "code": null, "e": 3615, "s": 3516, "text": "Web browser takes response from web server and displays either the received file or error message." }, { "code": null, "e": 3714, "s": 3615, "text": "Web browser takes response from web server and displays either the received file or error message." }, { "code": null, "e": 4159, "s": 3714, "text": "However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc." }, { "code": null, "e": 4586, "s": 4159, "text": "Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well." }, { "code": null, "e": 4812, "s": 4586, "text": "By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file −" }, { "code": null, "e": 4992, "s": 4812, "text": "<Directory \"/var/www/cgi-bin\">\n AllowOverride None\n Options ExecCGI\n Order allow,deny\n Allow from all\n</Directory>\n\n<Directory \"/var/www/cgi-bin\">\nOptions All\n</Directory>" }, { "code": null, "e": 5132, "s": 4992, "text": "Here, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc." }, { "code": null, "e": 5417, "s": 5132, "text": "Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable." }, { "code": null, "e": 5682, "s": 5417, "text": "#!/usr/bin/python\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint '<html>'\nprint '<head>'\nprint '<title>Hello World - First CGI Program</title>'\nprint '</head>'\nprint '<body>'\nprint '<h2>Hello World! This is my first CGI program</h2>'\nprint '</body>'\nprint '</html>'" }, { "code": null, "e": 5747, "s": 5682, "text": "If you click hello.py, then this produces the following output −" }, { "code": null, "e": 6077, "s": 5747, "text": "This hello.py script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\\r\\n\\r\\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen." }, { "code": null, "e": 6292, "s": 6077, "text": "By now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS." }, { "code": null, "e": 6463, "s": 6292, "text": "The line Content-type:text/html\\r\\n\\r\\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form −" }, { "code": null, "e": 6540, "s": 6463, "text": "HTTP Field Name: Field Content\n\nFor Example\nContent-type: text/html\\r\\n\\r\\n\n" }, { "code": null, "e": 6639, "s": 6540, "text": "There are few other important HTTP headers, which you will use frequently in your CGI Programming." }, { "code": null, "e": 6653, "s": 6639, "text": "Content-type:" }, { "code": null, "e": 6749, "s": 6653, "text": "A MIME string defining the format of the file being returned. Example is Content-type:text/html" }, { "code": null, "e": 6763, "s": 6749, "text": "Expires: Date" }, { "code": null, "e": 6939, "s": 6763, "text": "The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT." }, { "code": null, "e": 6953, "s": 6939, "text": "Location: URL" }, { "code": null, "e": 7066, "s": 6953, "text": "The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file." }, { "code": null, "e": 7086, "s": 7066, "text": "Last-modified: Date" }, { "code": null, "e": 7133, "s": 7086, "text": "The date of last modification of the resource." }, { "code": null, "e": 7151, "s": 7133, "text": "Content-length: N" }, { "code": null, "e": 7279, "s": 7151, "text": "The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file." }, { "code": null, "e": 7298, "s": 7279, "text": "Set-Cookie: String" }, { "code": null, "e": 7339, "s": 7298, "text": "Set the cookie passed through the string" }, { "code": null, "e": 7482, "s": 7339, "text": "All the CGI programs have access to the following environment variables. These variables play an important role while writing any CGI program." }, { "code": null, "e": 7495, "s": 7482, "text": "CONTENT_TYPE" }, { "code": null, "e": 7615, "s": 7495, "text": "The data type of the content. Used when the client is sending attached content to the server. For example, file upload." }, { "code": null, "e": 7630, "s": 7615, "text": "CONTENT_LENGTH" }, { "code": null, "e": 7707, "s": 7630, "text": "The length of the query information. It is available only for POST requests." }, { "code": null, "e": 7719, "s": 7707, "text": "HTTP_COOKIE" }, { "code": null, "e": 7776, "s": 7719, "text": "Returns the set cookies in the form of key & value pair." }, { "code": null, "e": 7792, "s": 7776, "text": "HTTP_USER_AGENT" }, { "code": null, "e": 7926, "s": 7792, "text": "The User-Agent request-header field contains information about the user agent originating the request. It is name of the web browser." }, { "code": null, "e": 7936, "s": 7926, "text": "PATH_INFO" }, { "code": null, "e": 7965, "s": 7936, "text": "The path for the CGI script." }, { "code": null, "e": 7978, "s": 7965, "text": "QUERY_STRING" }, { "code": null, "e": 8044, "s": 7978, "text": "The URL-encoded information that is sent with GET method request." }, { "code": null, "e": 8056, "s": 8044, "text": "REMOTE_ADDR" }, { "code": null, "e": 8156, "s": 8056, "text": "The IP address of the remote host making the request. This is useful logging or for authentication." }, { "code": null, "e": 8168, "s": 8156, "text": "REMOTE_HOST" }, { "code": null, "e": 8311, "s": 8168, "text": "The fully qualified name of the host making the request. If this information is not available, then REMOTE_ADDR can be used to get IR address." }, { "code": null, "e": 8326, "s": 8311, "text": "REQUEST_METHOD" }, { "code": null, "e": 8405, "s": 8326, "text": "The method used to make the request. The most common methods are GET and POST." }, { "code": null, "e": 8421, "s": 8405, "text": "SCRIPT_FILENAME" }, { "code": null, "e": 8454, "s": 8421, "text": "The full path to the CGI script." }, { "code": null, "e": 8466, "s": 8454, "text": "SCRIPT_NAME" }, { "code": null, "e": 8494, "s": 8466, "text": "The name of the CGI script." }, { "code": null, "e": 8506, "s": 8494, "text": "SERVER_NAME" }, { "code": null, "e": 8542, "s": 8506, "text": "The server's hostname or IP Address" }, { "code": null, "e": 8558, "s": 8542, "text": "SERVER_SOFTWARE" }, { "code": null, "e": 8618, "s": 8558, "text": "The name and version of the software the server is running." }, { "code": null, "e": 8729, "s": 8618, "text": "Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment" }, { "code": null, "e": 8940, "s": 8729, "text": "#!/usr/bin/python\n\nimport os\n\nprint \"Content-type: text/html\\r\\n\\r\\n\";\nprint \"<font size=+1>Environment</font><\\br>\";\nfor param in os.environ.keys():\n print \"<b>%20s</b>: %s<\\br>\" % (param, os.environ[param])" }, { "code": null, "e": 9218, "s": 8940, "text": "You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently, browser uses two methods two pass this information to web server. These methods are GET Method and POST Method." }, { "code": null, "e": 9381, "s": 9218, "text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows −" }, { "code": null, "e": 9443, "s": 9381, "text": "http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2\n" }, { "code": null, "e": 9933, "s": 9443, "text": "The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be sent in a request string. The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable." }, { "code": null, "e": 10091, "s": 9933, "text": "You can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method." }, { "code": null, "e": 10179, "s": 10091, "text": "Here is a simple URL, which passes two values to hello_get.py program using GET method." }, { "code": null, "e": 10334, "s": 10179, "text": "Below is hello_get.py script to handle input given by web browser. We are going to use cgi module, which makes it very easy to access passed information −" }, { "code": null, "e": 10813, "s": 10334, "text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\"" }, { "code": null, "e": 10856, "s": 10813, "text": "This would generate the following result −" }, { "code": null, "e": 10980, "s": 10856, "text": "This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input." }, { "code": null, "e": 11203, "s": 10980, "text": "<form action = \"/cgi-bin/hello_get.py\" method = \"get\">\nFirst Name: <input type = \"text\" name = \"first_name\"> <br />\n\nLast Name: <input type = \"text\" name = \"last_name\" />\n<input type = \"submit\" value = \"Submit\" />\n</form>" }, { "code": null, "e": 11326, "s": 11203, "text": "Here is the actual output of the above form, you enter First and Last Name and then click submit button to see the result." }, { "code": null, "e": 11663, "s": 11326, "text": "A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input." }, { "code": null, "e": 11739, "s": 11663, "text": "Below is same hello_get.py script which handles GET as well as POST method." }, { "code": null, "e": 12218, "s": 11739, "text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\"" }, { "code": null, "e": 12375, "s": 12218, "text": "Let us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input." }, { "code": null, "e": 12597, "s": 12375, "text": "<form action = \"/cgi-bin/hello_get.py\" method = \"post\">\nFirst Name: <input type = \"text\" name = \"first_name\"><br />\nLast Name: <input type = \"text\" name = \"last_name\" />\n\n<input type = \"submit\" value = \"Submit\" />\n</form>" }, { "code": null, "e": 12720, "s": 12597, "text": "Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result." }, { "code": null, "e": 12794, "s": 12720, "text": "Checkboxes are used when more than one option is required to be selected." }, { "code": null, "e": 12853, "s": 12794, "text": "Here is example HTML code for a form with two checkboxes −" }, { "code": null, "e": 13114, "s": 12853, "text": "<form action = \"/cgi-bin/checkbox.cgi\" method = \"POST\" target = \"_blank\">\n<input type = \"checkbox\" name = \"maths\" value = \"on\" /> Maths\n<input type = \"checkbox\" name = \"physics\" value = \"on\" /> Physics\n<input type = \"submit\" value = \"Select Subject\" />\n</form>" }, { "code": null, "e": 13162, "s": 13114, "text": "The result of this code is the following form −" }, { "code": null, "e": 13249, "s": 13162, "text": "Below is checkbox.cgi script to handle input given by web browser for checkbox button." }, { "code": null, "e": 13862, "s": 13249, "text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('maths'):\n math_flag = \"ON\"\nelse:\n math_flag = \"OFF\"\n\nif form.getvalue('physics'):\n physics_flag = \"ON\"\nelse:\n physics_flag = \"OFF\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Checkbox - Third CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> CheckBox Maths is : %s</h2>\" % math_flag\nprint \"<h2> CheckBox Physics is : %s</h2>\" % physics_flag\nprint \"</body>\"\nprint \"</html>\"" }, { "code": null, "e": 13934, "s": 13862, "text": "Radio Buttons are used when only one option is required to be selected." }, { "code": null, "e": 13996, "s": 13934, "text": "Here is example HTML code for a form with two radio buttons −" }, { "code": null, "e": 14263, "s": 13996, "text": "<form action = \"/cgi-bin/radiobutton.py\" method = \"post\" target = \"_blank\">\n<input type = \"radio\" name = \"subject\" value = \"maths\" /> Maths\n<input type = \"radio\" name = \"subject\" value = \"physics\" /> Physics\n<input type = \"submit\" value = \"Select Subject\" />\n</form>" }, { "code": null, "e": 14311, "s": 14263, "text": "The result of this code is the following form −" }, { "code": null, "e": 14398, "s": 14311, "text": "Below is radiobutton.py script to handle input given by web browser for radio button −" }, { "code": null, "e": 14888, "s": 14398, "text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('subject'):\n subject = form.getvalue('subject')\nelse:\n subject = \"Not set\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Radio - Fourth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\"" }, { "code": null, "e": 14970, "s": 14888, "text": "TEXTAREA element is used when multiline text has to be passed to the CGI Program." }, { "code": null, "e": 15029, "s": 14970, "text": "Here is example HTML code for a form with a TEXTAREA box −" }, { "code": null, "e": 15243, "s": 15029, "text": "<form action = \"/cgi-bin/textarea.py\" method = \"post\" target = \"_blank\">\n<textarea name = \"textcontent\" cols = \"40\" rows = \"4\">\nType your text here...\n</textarea>\n<input type = \"submit\" value = \"Submit\" />\n</form>" }, { "code": null, "e": 15291, "s": 15243, "text": "The result of this code is the following form −" }, { "code": null, "e": 15359, "s": 15291, "text": "Below is textarea.cgi script to handle input given by web browser −" }, { "code": null, "e": 15868, "s": 15359, "text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('textcontent'):\n text_content = form.getvalue('textcontent')\nelse:\n text_content = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\";\nprint \"<title>Text Area - Fifth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Entered Text Content is %s</h2>\" % text_content\nprint \"</body>\"" }, { "code": null, "e": 15964, "s": 15868, "text": "Drop Down Box is used when we have many options available but only one or two will be selected." }, { "code": null, "e": 16026, "s": 15964, "text": "Here is example HTML code for a form with one drop down box −" }, { "code": null, "e": 16277, "s": 16026, "text": "<form action = \"/cgi-bin/dropdown.py\" method = \"post\" target = \"_blank\">\n<select name = \"dropdown\">\n<option value = \"Maths\" selected>Maths</option>\n<option value = \"Physics\">Physics</option>\n</select>\n<input type = \"submit\" value = \"Submit\"/>\n</form>" }, { "code": null, "e": 16325, "s": 16277, "text": "The result of this code is the following form −" }, { "code": null, "e": 16391, "s": 16325, "text": "Below is dropdown.py script to handle input given by web browser." }, { "code": null, "e": 16893, "s": 16391, "text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('dropdown'):\n subject = form.getvalue('dropdown')\nelse:\n subject = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Dropdown Box - Sixth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\"" }, { "code": null, "e": 17167, "s": 16893, "text": "HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. How to maintain user's session information across all the web pages?" }, { "code": null, "e": 17376, "s": 17167, "text": "In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics." }, { "code": null, "e": 17726, "s": 17376, "text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored." }, { "code": null, "e": 17793, "s": 17726, "text": "Cookies are a plain text data record of 5 variable-length fields −" }, { "code": null, "e": 17913, "s": 17793, "text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser." }, { "code": null, "e": 18033, "s": 17913, "text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser." }, { "code": null, "e": 18072, "s": 18033, "text": "Domain − The domain name of your site." }, { "code": null, "e": 18111, "s": 18072, "text": "Domain − The domain name of your site." }, { "code": null, "e": 18259, "s": 18111, "text": "Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page." }, { "code": null, "e": 18407, "s": 18259, "text": "Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page." }, { "code": null, "e": 18570, "s": 18407, "text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists." }, { "code": null, "e": 18733, "s": 18570, "text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists." }, { "code": null, "e": 18812, "s": 18733, "text": "Name=Value − Cookies are set and retrieved in the form of key and value pairs." }, { "code": null, "e": 18891, "s": 18812, "text": "Name=Value − Cookies are set and retrieved in the form of key and value pairs." }, { "code": null, "e": 19109, "s": 18891, "text": "It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows −" }, { "code": null, "e": 19446, "s": 19109, "text": "#!/usr/bin/python\n\nprint \"Set-Cookie:UserID = XYZ;\\r\\n\"\nprint \"Set-Cookie:Password = XYZ123;\\r\\n\"\nprint \"Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT\";\\r\\n\"\nprint \"Set-Cookie:Domain = www.tutorialspoint.com;\\r\\n\"\nprint \"Set-Cookie:Path = /perl;\\n\"\nprint \"Content-type:text/html\\r\\n\\r\\n\"\n...........Rest of the HTML Content...." }, { "code": null, "e": 19556, "s": 19446, "text": "From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies." }, { "code": null, "e": 19723, "s": 19556, "text": "It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line \"Content-type:text/html\\r\\n\\r\\n." }, { "code": null, "e": 19867, "s": 19723, "text": "It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form −" }, { "code": null, "e": 19914, "s": 19867, "text": "key1 = value1;key2 = value2;key3 = value3....\n" }, { "code": null, "e": 19961, "s": 19914, "text": "Here is an example of how to retrieve cookies." }, { "code": null, "e": 20371, "s": 19961, "text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nfrom os import environ\nimport cgi, cgitb\n\nif environ.has_key('HTTP_COOKIE'):\n for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):\n (key, value ) = split(cookie, '=');\n if key == \"UserID\":\n user_id = value\n\n if key == \"Password\":\n password = value\n\nprint \"User ID = %s\" % user_id\nprint \"Password = %s\" % password" }, { "code": null, "e": 20444, "s": 20371, "text": "This produces the following result for the cookies set by above script −" }, { "code": null, "e": 20477, "s": 20444, "text": "User ID = XYZ\nPassword = XYZ123\n" }, { "code": null, "e": 20629, "s": 20477, "text": "To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a \"Browse\" button." }, { "code": null, "e": 20885, "s": 20629, "text": "<html>\n<body>\n <form enctype = \"multipart/form-data\" \n action = \"save_file.py\" method = \"post\">\n <p>File: <input type = \"file\" name = \"filename\" /></p>\n <p><input type = \"submit\" value = \"Upload\" /></p>\n </form>\n</body>\n</html>" }, { "code": null, "e": 20933, "s": 20885, "text": "The result of this code is the following form −" }, { "code": null, "e": 20940, "s": 20933, "text": "File: " }, { "code": null, "e": 21076, "s": 20940, "text": "Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server." }, { "code": null, "e": 21132, "s": 21076, "text": "Here is the script save_file.py to handle file upload −" }, { "code": null, "e": 21720, "s": 21132, "text": "#!/usr/bin/python\n\nimport cgi, os\nimport cgitb; cgitb.enable()\n\nform = cgi.FieldStorage()\n\n# Get filename here.\nfileitem = form['filename']\n\n# Test if the file was uploaded\nif fileitem.filename:\n # strip leading path from file name to avoid \n # directory traversal attacks\n fn = os.path.basename(fileitem.filename)\n open('/tmp/' + fn, 'wb').write(fileitem.file.read())\n\n message = 'The file \"' + fn + '\" was uploaded successfully'\n \nelse:\n message = 'No file was uploaded'\n \nprint \"\"\"\\\nContent-Type: text/html\\n\n<html>\n<body>\n <p>%s</p>\n</body>\n</html>\n\"\"\" % (message,)" }, { "code": null, "e": 21906, "s": 21720, "text": "If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine." }, { "code": null, "e": 21968, "s": 21906, "text": "fn = os.path.basename(fileitem.filename.replace(\"\\\\\", \"/\" ))\n" }, { "code": null, "e": 22291, "s": 21968, "text": "Sometimes, it is desired that you want to give option where a user can click a link and it will pop up a \"File Download\" dialogue box to the user instead of displaying actual content. This is very easy and can be achieved through HTTP header. This HTTP header is be different from the header mentioned in previous section." }, { "code": null, "e": 22401, "s": 22291, "text": "For example, if you want make a FileName file downloadable from a given link, then its syntax is as follows −" }, { "code": null, "e": 22701, "s": 22401, "text": "#!/usr/bin/python\n\n# HTTP Header\nprint \"Content-Type:application/octet-stream; name = \\\"FileName\\\"\\r\\n\";\nprint \"Content-Disposition: attachment; filename = \\\"FileName\\\"\\r\\n\\n\";\n\n# Actual File Content will go here.\nfo = open(\"foo.txt\", \"rb\")\n\nstr = fo.read();\nprint str\n\n# Close opend file\nfo.close()" }, { "code": null, "e": 22785, "s": 22701, "text": "Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us" }, { "code": null, "e": 22822, "s": 22785, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 22838, "s": 22822, "text": " Malhar Lathkar" }, { "code": null, "e": 22871, "s": 22838, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 22890, "s": 22871, "text": " Arnab Chakraborty" }, { "code": null, "e": 22925, "s": 22890, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 22947, "s": 22925, "text": " In28Minutes Official" }, { "code": null, "e": 22981, "s": 22947, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 23009, "s": 22981, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 23044, "s": 23009, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 23058, "s": 23044, "text": " Lets Kode It" }, { "code": null, "e": 23091, "s": 23058, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 23108, "s": 23091, "text": " Abhilash Nelson" }, { "code": null, "e": 23115, "s": 23108, "text": " Print" }, { "code": null, "e": 23126, "s": 23115, "text": " Add Notes" } ]
Font Awesome - Brand icons
This chapter explains the usage of Font Awesome Brand icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below. <html> <head> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"> <style> i.custom {font-size: 2em; color: gray;} </style> </head> <body> <i class = "fa fa-adjust custom"></i> </body> </html> The following table shows the usage and the results of Font Awesome Brand icons. Replace the <body> tag of the above program with the code given in the table to get the respective outputs − 26 Lectures 2 hours Neha Gupta 20 Lectures 2 hours Asif Hussain 43 Lectures 5 hours Sharad Kumar 411 Lectures 38.5 hours In28Minutes Official 71 Lectures 10 hours Chaand Sheikh 207 Lectures 33 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2742, "s": 2566, "text": "This chapter explains the usage of Font Awesome Brand icons. Assume that custom is the CSS class name where we defined the size and color, as shown in the example given below." }, { "code": null, "e": 3053, "s": 2742, "text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n\n <style>\n i.custom {font-size: 2em; color: gray;}\n </style>\n\t\t\n </head>\n\t\n <body>\n <i class = \"fa fa-adjust custom\"></i>\n </body>\n\t\n</html>" }, { "code": null, "e": 3243, "s": 3053, "text": "The following table shows the usage and the results of Font Awesome Brand icons. Replace the <body> tag of the above program with the code given in the table to get the respective outputs −" }, { "code": null, "e": 3276, "s": 3243, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3288, "s": 3276, "text": " Neha Gupta" }, { "code": null, "e": 3321, "s": 3288, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3335, "s": 3321, "text": " Asif Hussain" }, { "code": null, "e": 3368, "s": 3335, "text": "\n 43 Lectures \n 5 hours \n" }, { "code": null, "e": 3382, "s": 3368, "text": " Sharad Kumar" }, { "code": null, "e": 3419, "s": 3382, "text": "\n 411 Lectures \n 38.5 hours \n" }, { "code": null, "e": 3441, "s": 3419, "text": " In28Minutes Official" }, { "code": null, "e": 3475, "s": 3441, "text": "\n 71 Lectures \n 10 hours \n" }, { "code": null, "e": 3490, "s": 3475, "text": " Chaand Sheikh" }, { "code": null, "e": 3525, "s": 3490, "text": "\n 207 Lectures \n 33 hours \n" }, { "code": null, "e": 3553, "s": 3525, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3560, "s": 3553, "text": " Print" }, { "code": null, "e": 3571, "s": 3560, "text": " Add Notes" } ]
PyQt5 QSpinBox - Setting size increment - GeeksforGeeks
28 May, 2020 In this article we will see how we can set the size increment of spin box or not. Size increment is used when spin box size is changeable with the main window size. Base size is used to calculate a proper spin box size if the spin box defines sizeIncrement. By default, for a newly-created spin box, this property contains a size with zero width and height. Below is the formula for getting new spin box size when main window get bigger. width = baseSize().width() + i * sizeIncrement().width() height = baseSize().height() + j * sizeIncrement().height() Here i, j are the size increment in the main window In order to do this we use setSizeIncrement method with the spin box object. Syntax : spin_box.setSizeIncrement(base, height) Argument : It takes two integer as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 9) # setting prefix to spin self.spin.setPrefix("PREFIX ") # setting suffix to spin self.spin.setSuffix(" SUFFIX") # setting size increment self.spin.setSizeIncrement(10, 10) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n28 May, 2020" }, { "code": null, "e": 24259, "s": 23901, "text": "In this article we will see how we can set the size increment of spin box or not. Size increment is used when spin box size is changeable with the main window size. Base size is used to calculate a proper spin box size if the spin box defines sizeIncrement. By default, for a newly-created spin box, this property contains a size with zero width and height." }, { "code": null, "e": 24339, "s": 24259, "text": "Below is the formula for getting new spin box size when main window get bigger." }, { "code": null, "e": 24510, "s": 24339, "text": "width = baseSize().width() + i * sizeIncrement().width()\nheight = baseSize().height() + j * sizeIncrement().height()\n\nHere i, j are the size increment in the main window\n" }, { "code": null, "e": 24587, "s": 24510, "text": "In order to do this we use setSizeIncrement method with the spin box object." }, { "code": null, "e": 24636, "s": 24587, "text": "Syntax : spin_box.setSizeIncrement(base, height)" }, { "code": null, "e": 24680, "s": 24636, "text": "Argument : It takes two integer as argument" }, { "code": null, "e": 24705, "s": 24680, "text": "Return : It returns None" }, { "code": null, "e": 24733, "s": 24705, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 250, 40) # setting range to the spin box self.spin.setRange(0, 9) # setting prefix to spin self.spin.setPrefix(\"PREFIX \") # setting suffix to spin self.spin.setSuffix(\" SUFFIX\") # setting size increment self.spin.setSizeIncrement(10, 10) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 25849, "s": 24733, "text": null }, { "code": null, "e": 25858, "s": 25849, "text": "Output :" }, { "code": null, "e": 25878, "s": 25858, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 25889, "s": 25878, "text": "Python-gui" }, { "code": null, "e": 25901, "s": 25889, "text": "Python-PyQt" }, { "code": null, "e": 25908, "s": 25901, "text": "Python" }, { "code": null, "e": 26006, "s": 25908, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26015, "s": 26006, "text": "Comments" }, { "code": null, "e": 26028, "s": 26015, "text": "Old Comments" }, { "code": null, "e": 26060, "s": 26028, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26116, "s": 26060, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26158, "s": 26116, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26200, "s": 26158, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26236, "s": 26200, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26258, "s": 26236, "text": "Defaultdict in Python" }, { "code": null, "e": 26297, "s": 26258, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26324, "s": 26297, "text": "Python Classes and Objects" }, { "code": null, "e": 26355, "s": 26324, "text": "Python | os.path.join() method" } ]
Display an Icon from Image Sprite using CSS
The main advantage of using image sprite is to reduce the number of http requests that makes our site’s load time faster. Following is the code for displaying an icon from image sprite using CSS − Live Demo <!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .twitter,.facebook { background: url(sprites_64.png) no-repeat; display:inline-block; width: 64px; height: 64px; margin:10px 4px; } .facebook { background-position: 0 -148px; } </style> </head> <body> <h1>Image Sprite example</h1> <a class="twitter"></a> <a class="facebook"></a> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1184, "s": 1062, "text": "The main advantage of using image sprite is to reduce the number of http requests that makes our site’s load time faster." }, { "code": null, "e": 1259, "s": 1184, "text": "Following is the code for displaying an icon from image sprite using CSS −" }, { "code": null, "e": 1270, "s": 1259, "text": " Live Demo" }, { "code": null, "e": 1696, "s": 1270, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n}\n.twitter,.facebook {\n background: url(sprites_64.png) no-repeat;\n display:inline-block;\n width: 64px;\n height: 64px;\n margin:10px 4px;\n}\n.facebook {\n background-position: 0 -148px;\n}\n</style>\n</head>\n<body>\n<h1>Image Sprite example</h1>\n<a class=\"twitter\"></a>\n<a class=\"facebook\"></a>\n</body>\n</html>" }, { "code": null, "e": 1747, "s": 1696, "text": "The above code will produce the following output −" } ]
How does one remove a Docker image?
If you have been using Docker for quite a long time now, you might have several unused images already existing in your local machine. These images might be previously downloaded older versions, or simply an image that you downloaded for testing. These images take up a lot of space unnecessarily and reduce the overall performance and experience. Moreover, they are several unused, dangling images as well. It’s always better to remove these older images which will help you to keep track of all your useful images in a better way. Docker allows you to remove images quite easily and through many different commands. You can use the Docker rmi command, Docker images rm command, or even Docker image prune commands to do so. Additionally, Docker allows you to use several options along with these commands to remove images strategically. In this article, we will discuss all the popular and most frequently used commands that will allow you to delete images quite easily. As already discussed, there are several commands that can be used interchangeably to remove one or more Docker images from your system. Let’s start from the very basic one. $ docker image rm [OPTIONS] IMAGE [IMAGE...] You can also use several options along with this command. Below are the most useful ones. --force - You can use this option to forcefully remove images. --no-prune - If you don’t want to delete untagged images, you can use this option. Please note that you can only remove those images that don’t have a container associated with it. If you try to remove such an image, it will throw an error. To override this default behaviour, you can use the --force option to delete images forcefully. For example, if you want to delete a fedora image with tag 24, you can do so using the following command. $ docker image rm fedora:24 To check whether an image has a container associated with it, you can list all the containers using any one of the following two commands. $ docker ps -a $ docker container ls -a If you find any container associated with that image, you can either stop and remove the container or remove it forcefully. $ docker stop <container-name> $ docker rm <container-name> Or $ docker rm -f <container-name> After removing the container, you can now proceed with deleting the image. Delete Images using a shorter command You can also use the other shorter command mentioned below to delete an image. $ docker rmi [OPTIONS] IMAGE [IMAGE...] If you don’t want to check for containers before removing an image, you can use the force option to remove it. $ docker rmi -f <image-name> Also, if you want to remove more than one image together, you can directly mention the image IDs or image names of all these images separated by spaces. $ docker rmi -f myimage1 myimage2 myimage2 You can also use the Docker image prune command to delete all the dangling images. $ docker image prune [OPTIONS] You can use several options such as - --all - To delete all the unused and dangling images as well. --filter - To provide filters to remove only certain specific images. --force - To prune images forcefully. For example, if you want to remove all the unused images from your system, you can use the following command. $ docker image prune --all If you want to delete all the Docker images together, this is a great way to do it. There is also another way to delete all the images simultaneously. You can use a sub-command along with the Docker rmi command. Consider the command below. $ docker rmi -f $(docker images -aq) Here, we have used the force option along with the Docker rmi command as a parent command. Instead of mentioning the image IDs or names, we have used a subcommand that lists the image IDs of all the images using the all and quiet options. To sum up, in this article, we have discussed why it is a good practice to remove unused or dangling images periodically. We discussed how to delete images using three different commands along with several options. We also discussed how to remove more than one or all the images simultaneously. We hope that you will now be able to remove Docker images quite easily.
[ { "code": null, "e": 1469, "s": 1062, "text": "If you have been using Docker for quite a long time now, you might have several unused images already existing in your local machine. These images might be previously downloaded older versions, or simply an image that you downloaded for testing. These images take up a lot of space unnecessarily and reduce the overall performance and experience. Moreover, they are several unused, dangling images as well." }, { "code": null, "e": 1900, "s": 1469, "text": "It’s always better to remove these older images which will help you to keep track of all your useful images in a better way. Docker allows you to remove images quite easily and through many different commands. You can use the Docker rmi command, Docker images rm command, or even Docker image prune commands to do so. Additionally, Docker allows you to use several options along with these commands to remove images strategically." }, { "code": null, "e": 2034, "s": 1900, "text": "In this article, we will discuss all the popular and most frequently used commands that will allow you to delete images quite easily." }, { "code": null, "e": 2207, "s": 2034, "text": "As already discussed, there are several commands that can be used interchangeably to remove one or more Docker images from your system. Let’s start from the very basic one." }, { "code": null, "e": 2252, "s": 2207, "text": "$ docker image rm [OPTIONS] IMAGE [IMAGE...]" }, { "code": null, "e": 2342, "s": 2252, "text": "You can also use several options along with this command. Below are the most useful ones." }, { "code": null, "e": 2405, "s": 2342, "text": "--force - You can use this option to forcefully remove images." }, { "code": null, "e": 2488, "s": 2405, "text": "--no-prune - If you don’t want to delete untagged images, you can use this option." }, { "code": null, "e": 2742, "s": 2488, "text": "Please note that you can only remove those images that don’t have a container associated with it. If you try to remove such an image, it will throw an error. To override this default behaviour, you can use the --force option to delete images forcefully." }, { "code": null, "e": 2848, "s": 2742, "text": "For example, if you want to delete a fedora image with tag 24, you can do so using the following command." }, { "code": null, "e": 2876, "s": 2848, "text": "$ docker image rm fedora:24" }, { "code": null, "e": 3015, "s": 2876, "text": "To check whether an image has a container associated with it, you can list all the containers using any one of the following two commands." }, { "code": null, "e": 3030, "s": 3015, "text": "$ docker ps -a" }, { "code": null, "e": 3056, "s": 3030, "text": "$ docker container ls -a\n" }, { "code": null, "e": 3180, "s": 3056, "text": "If you find any container associated with that image, you can either stop and remove the container or remove it forcefully." }, { "code": null, "e": 3211, "s": 3180, "text": "$ docker stop <container-name>" }, { "code": null, "e": 3240, "s": 3211, "text": "$ docker rm <container-name>" }, { "code": null, "e": 3243, "s": 3240, "text": "Or" }, { "code": null, "e": 3275, "s": 3243, "text": "$ docker rm -f <container-name>" }, { "code": null, "e": 3350, "s": 3275, "text": "After removing the container, you can now proceed with deleting the image." }, { "code": null, "e": 3388, "s": 3350, "text": "Delete Images using a shorter command" }, { "code": null, "e": 3467, "s": 3388, "text": "You can also use the other shorter command mentioned below to delete an image." }, { "code": null, "e": 3508, "s": 3467, "text": "$ docker rmi [OPTIONS] IMAGE [IMAGE...]\n" }, { "code": null, "e": 3619, "s": 3508, "text": "If you don’t want to check for containers before removing an image, you can use the force option to remove it." }, { "code": null, "e": 3648, "s": 3619, "text": "$ docker rmi -f <image-name>" }, { "code": null, "e": 3801, "s": 3648, "text": "Also, if you want to remove more than one image together, you can directly mention the image IDs or image names of all these images separated by spaces." }, { "code": null, "e": 3844, "s": 3801, "text": "$ docker rmi -f myimage1 myimage2 myimage2" }, { "code": null, "e": 3927, "s": 3844, "text": "You can also use the Docker image prune command to delete all the dangling images." }, { "code": null, "e": 3958, "s": 3927, "text": "$ docker image prune [OPTIONS]" }, { "code": null, "e": 3996, "s": 3958, "text": "You can use several options such as -" }, { "code": null, "e": 4058, "s": 3996, "text": "--all - To delete all the unused and dangling images as well." }, { "code": null, "e": 4128, "s": 4058, "text": "--filter - To provide filters to remove only certain specific images." }, { "code": null, "e": 4166, "s": 4128, "text": "--force - To prune images forcefully." }, { "code": null, "e": 4276, "s": 4166, "text": "For example, if you want to remove all the unused images from your system, you can use the following command." }, { "code": null, "e": 4304, "s": 4276, "text": "$ docker image prune --all\n" }, { "code": null, "e": 4544, "s": 4304, "text": "If you want to delete all the Docker images together, this is a great way to do it. There is also another way to delete all the images simultaneously. You can use a sub-command along with the Docker rmi command. Consider the command below." }, { "code": null, "e": 4581, "s": 4544, "text": "$ docker rmi -f $(docker images -aq)" }, { "code": null, "e": 4820, "s": 4581, "text": "Here, we have used the force option along with the Docker rmi command as a parent command. Instead of mentioning the image IDs or names, we have used a subcommand that lists the image IDs of all the images using the all and quiet options." }, { "code": null, "e": 5187, "s": 4820, "text": "To sum up, in this article, we have discussed why it is a good practice to remove unused or dangling images periodically. We discussed how to delete images using three different commands along with several options. We also discussed how to remove more than one or all the images simultaneously. We hope that you will now be able to remove Docker images quite easily." } ]
Jump Game in Python
Suppose we have an array of non-negative integers; we are initially positioned at the first index of the array. Each element in the given array represents out maximum jump length at that position. We have to determine if we are able to reach the last index or not. So if the array is like [2,3,1,1,4], then the output will be true. This is like jump one step from position 0 to 1, then three step from position 1 to the end. Let us see the steps − n := length of array A – 1 for i := n – 1, down to -1if A[i] + i > n, then n := i if A[i] + i > n, then n := i return true when n = 0, otherwise false Let us see the following implementation to get better understanding − Live Demo class Solution(object): def canJump(self, nums): n = len(nums)-1 for i in range(n-1,-1,-1): if nums[i] + i>=n: n = i return n ==0 ob1 = Solution() print(ob1.canJump([2,3,1,1,4])) [2,3,1,1,4] True
[ { "code": null, "e": 1487, "s": 1062, "text": "Suppose we have an array of non-negative integers; we are initially positioned at the first index of the array. Each element in the given array represents out maximum jump length at that position. We have to determine if we are able to reach the last index or not. So if the array is like [2,3,1,1,4], then the output will be true. This is like jump one step from position 0 to 1, then three step from position 1 to the end." }, { "code": null, "e": 1510, "s": 1487, "text": "Let us see the steps −" }, { "code": null, "e": 1537, "s": 1510, "text": "n := length of array A – 1" }, { "code": null, "e": 1592, "s": 1537, "text": "for i := n – 1, down to -1if A[i] + i > n, then n := i" }, { "code": null, "e": 1621, "s": 1592, "text": "if A[i] + i > n, then n := i" }, { "code": null, "e": 1661, "s": 1621, "text": "return true when n = 0, otherwise false" }, { "code": null, "e": 1731, "s": 1661, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1742, "s": 1731, "text": " Live Demo" }, { "code": null, "e": 1963, "s": 1742, "text": "class Solution(object):\n def canJump(self, nums):\n n = len(nums)-1\n for i in range(n-1,-1,-1):\n if nums[i] + i>=n:\n n = i\n return n ==0\nob1 = Solution()\nprint(ob1.canJump([2,3,1,1,4]))" }, { "code": null, "e": 1975, "s": 1963, "text": "[2,3,1,1,4]" }, { "code": null, "e": 1980, "s": 1975, "text": "True" } ]
Remove Trailing Zero in MySQL?
Use trim() function to remove trailing zeroz in MySQL. Following is the syntax − select trim(yourColumnName)+0 As anyAliasName from yourTableName; Let us first create a table − mysql> create table removeTrailingZero -> ( -> Number DECIMAL(10,4) -> ); Query OK, 0 rows affected (0.83 sec) Following is the query to insert some records in the table using insert command − mysql> insert into removeTrailingZero values(10.789); Query OK, 1 row affected (0.19 sec) mysql> insert into removeTrailingZero values(89.90); Query OK, 1 row affected (0.18 sec) mysql> insert into removeTrailingZero values(8999.70); Query OK, 1 row affected (0.20 sec) mysql> insert into removeTrailingZero values(0.40); Query OK, 1 row affected (0.23 sec) mysql> insert into removeTrailingZero values(0.0); Query OK, 1 row affected (0.16 sec) Following is the query to display all records from the table using select statement − mysql> select * from removeTrailingZero; This will produce the following output − +-----------+ | Number | +-----------+ | 10.7890 | | 89.9000 | | 8999.7000 | | 0.4000 | | 0.0000 | +-----------+ 5 rows in set (0.00 sec) Following is the query to remove trailing zeros − mysql> select trim(Number)+0 As WithoutTrailingZero from removeTrailingZero; This will produce the following output − +---------------------+ | WithoutTrailingZero | +---------------------+ | 10.789 | | 89.9 | | 8999.7 | | 0.4 | | 0 | +---------------------+ 5 rows in set (0.00 sec
[ { "code": null, "e": 1143, "s": 1062, "text": "Use trim() function to remove trailing zeroz in MySQL. Following is the syntax −" }, { "code": null, "e": 1209, "s": 1143, "text": "select trim(yourColumnName)+0 As anyAliasName from yourTableName;" }, { "code": null, "e": 1239, "s": 1209, "text": "Let us first create a table −" }, { "code": null, "e": 1359, "s": 1239, "text": "mysql> create table removeTrailingZero\n -> (\n -> Number DECIMAL(10,4)\n -> );\nQuery OK, 0 rows affected (0.83 sec)" }, { "code": null, "e": 1441, "s": 1359, "text": "Following is the query to insert some records in the table using insert command −" }, { "code": null, "e": 1890, "s": 1441, "text": "mysql> insert into removeTrailingZero values(10.789);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into removeTrailingZero values(89.90);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into removeTrailingZero values(8999.70);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into removeTrailingZero values(0.40);\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into removeTrailingZero values(0.0);\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1976, "s": 1890, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 2017, "s": 1976, "text": "mysql> select * from removeTrailingZero;" }, { "code": null, "e": 2058, "s": 2017, "text": "This will produce the following output −" }, { "code": null, "e": 2209, "s": 2058, "text": "+-----------+\n| Number |\n+-----------+\n| 10.7890 |\n| 89.9000 |\n| 8999.7000 |\n| 0.4000 |\n| 0.0000 |\n+-----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2259, "s": 2209, "text": "Following is the query to remove trailing zeros −" }, { "code": null, "e": 2336, "s": 2259, "text": "mysql> select trim(Number)+0 As WithoutTrailingZero from removeTrailingZero;" }, { "code": null, "e": 2377, "s": 2336, "text": "This will produce the following output −" }, { "code": null, "e": 2617, "s": 2377, "text": "+---------------------+\n| WithoutTrailingZero |\n+---------------------+\n| 10.789 |\n| 89.9 |\n| 8999.7 |\n| 0.4 |\n| 0 |\n+---------------------+\n5 rows in set (0.00 sec" } ]
Find all good indices in the given Array - GeeksforGeeks
26 May, 2021 Given an array A[] of integers. The task is to print all indices of this array such that after removing the ith element from the array, the array becomes a good array.Note: An array is good if there is an element in the array that equals to the sum of all other elements. 1-based indexing is considered for the array. Examples: Input : A[] = { 8, 3, 5, 2 } Output : 1 4 Explanation: A[] = [8, 3, 5, 2] If you remove A[1], the array will look like [3, 5, 2] and it is good, since 5 = 3+2. If you remove A[4], the array will look like [8, 3, 5] and it is good, since 8 = 3+5. Hence the nice indices are 1 and 4.Input : A[] = { 2, 2, 2 } Output : 1 2 3 Removing any element at any indices will make array good. Approach: Create a hash of array A[] which store frequency of each element and a variable sum having sum of each element of A.Iterate the array, remove the element at index i for each .After removing an element the sum of remaining array is K, where K = sum – A[i].We have to find an element K/2 in the remaining array to make it good. Let K = K/2 for now.Now the remaining array will be good if and only if below conditions holds true. If A[i] == K and hash(K) > 1 OR If A[i] != K and hash(K) > 0.Print all such indices i. Create a hash of array A[] which store frequency of each element and a variable sum having sum of each element of A. Iterate the array, remove the element at index i for each . After removing an element the sum of remaining array is K, where K = sum – A[i]. We have to find an element K/2 in the remaining array to make it good. Let K = K/2 for now. Now the remaining array will be good if and only if below conditions holds true. If A[i] == K and hash(K) > 1 OR If A[i] != K and hash(K) > 0. If A[i] == K and hash(K) > 1 OR If A[i] != K and hash(K) > 0. Print all such indices i. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to find all good indices// in the given array #include <bits/stdc++.h>using namespace std; // Function to find all good indices// in the given arrayvoid niceIndices(int A[], int n){ int sum = 0; // hash to store frequency // of each element map<int, int> m; // Storing frequency of each element // and calculating sum simultaneously for (int i = 0; i < n; ++i) { m[A[i]]++; sum += A[i]; } for (int i = 0; i < n; ++i) { int k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (m.find(k) != m.end()) { if ((A[i] == k && m[k] > 1) || (A[i] != k)) // print good indices cout << (i + 1) << " "; } } }} // Driver Codeint main(){ int A[] = { 8, 3, 5, 2 }; int n = sizeof(A) / sizeof(A[0]); niceIndices(A, n); return 0;} // Java program to find all good indices// in the given arrayimport java.util.*;class Solution{ // Function to find all good indices// in the given arraystatic void niceIndices(int A[], int n){ int sum = 0; // hash to store frequency // of each element Map<Integer, Integer> m=new HashMap<Integer, Integer>(); // Storing frequency of each element // and calculating sum simultaneously for (int i = 0; i < n; ++i) { m.put(A[i],(m.get(A[i])==null)?0:m.get(A[i])+1); sum += A[i]; } for (int i = 0; i < n; ++i) { int k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (m.containsKey(k)) { if ((A[i] == k && m.get(k) > 1) || (A[i] != k)) // print good indices System.out.print( (i + 1) +" "); } } }} // Driver Codepublic static void main(String args[]){ int A[] = { 8, 3, 5, 2 }; int n = A.length; niceIndices(A, n); }}//contributed by Arnab Kundu # Python3 program to find all good# indices in the given arrayfrom collections import defaultdict # Function to find all good indices# in the given arraydef niceIndices(A, n): Sum = 0 # hash to store frequency # of each element m = defaultdict(lambda:0) # Storing frequency of each element # and calculating sum simultaneously for i in range(n): m[A[i]] += 1 Sum += A[i] for i in range(n): k = Sum - A[i] if k % 2 == 0: k = k >> 1 # check if array is good after # removing i-th index element if k in m: if ((A[i] == k and m[k] > 1) or (A[i] != k)): # print good indices print((i + 1), end = " ") # Driver Code if __name__ == "__main__": A = [8, 3, 5, 2] n = len(A) niceIndices(A, n) # This code is contributed by Rituraj Jain // C# program to find all good indices// in the given arrayusing System;using System.Collections.Generic; class GFG{ // Function to find all good indices// in the given arraystatic void niceIndices(int []A, int n){ int sum = 0; // hash to store frequency // of each element Dictionary<int,int> mp = new Dictionary<int,int>(); // Storing frequency of each element // and calculating sum simultaneously for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(A[i])) { var val = mp[A[i]]; mp.Remove(A[i]); mp.Add(A[i], val + 1); sum += A[i]; } else { mp.Add(A[i], 0); sum += A[i]; } } for (int i = 0; i < n; ++i) { int k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (mp.ContainsKey(k)) { if ((A[i] == k && mp[k] > 1) || (A[i] != k)) // print good indices Console.Write( (i + 1) +" "); } } }} // Driver Codepublic static void Main(String []args){ int []A = { 8, 3, 5, 2 }; int n = A.Length; niceIndices(A, n); }} /* This code is contributed by PrinciRaj1992 */ <script> // Javascript program to find all good indices// in the given array // Function to find all good indices// in the given arrayfunction niceIndices(A, n){ var sum = 0; // hash to store frequency // of each element var m = new Map(); // Storing frequency of each element // and calculating sum simultaneously for (var i = 0; i < n; ++i) { if(m.has(A[i])) m.set(A[i], m.get(A[i])+1) else m.set(A[i], 1) sum += A[i]; } for (var i = 0; i < n; ++i) { var k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (m.has(k)) { if ((A[i] == k && m.get(k) > 1) || (A[i] != k)) // print good indices document.write(i + 1 + " "); } } }} // Driver Codevar A = [8, 3, 5, 2];var n = A.length;niceIndices(A, n); // This code is contributed by importantly.</script> 1 4 Time Complexity: O(N*log(N)) andrew1234 rituraj_jain princiraj1992 importantly cpp-map frequency-counting Hash Arrays Mathematical Arrays Hash Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Building Heap from Array Reversal algorithm for array rotation Program to find sum of elements in a given array 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": 24796, "s": 24768, "text": "\n26 May, 2021" }, { "code": null, "e": 24971, "s": 24796, "text": "Given an array A[] of integers. The task is to print all indices of this array such that after removing the ith element from the array, the array becomes a good array.Note: " }, { "code": null, "e": 25070, "s": 24971, "text": "An array is good if there is an element in the array that equals to the sum of all other elements." }, { "code": null, "e": 25116, "s": 25070, "text": "1-based indexing is considered for the array." }, { "code": null, "e": 25128, "s": 25116, "text": "Examples: " }, { "code": null, "e": 25510, "s": 25128, "text": "Input : A[] = { 8, 3, 5, 2 } Output : 1 4 Explanation: A[] = [8, 3, 5, 2] If you remove A[1], the array will look like [3, 5, 2] and it is good, since 5 = 3+2. If you remove A[4], the array will look like [8, 3, 5] and it is good, since 8 = 3+5. Hence the nice indices are 1 and 4.Input : A[] = { 2, 2, 2 } Output : 1 2 3 Removing any element at any indices will make array good. " }, { "code": null, "e": 25524, "s": 25512, "text": "Approach: " }, { "code": null, "e": 26038, "s": 25524, "text": "Create a hash of array A[] which store frequency of each element and a variable sum having sum of each element of A.Iterate the array, remove the element at index i for each .After removing an element the sum of remaining array is K, where K = sum – A[i].We have to find an element K/2 in the remaining array to make it good. Let K = K/2 for now.Now the remaining array will be good if and only if below conditions holds true. If A[i] == K and hash(K) > 1 OR If A[i] != K and hash(K) > 0.Print all such indices i." }, { "code": null, "e": 26155, "s": 26038, "text": "Create a hash of array A[] which store frequency of each element and a variable sum having sum of each element of A." }, { "code": null, "e": 26215, "s": 26155, "text": "Iterate the array, remove the element at index i for each ." }, { "code": null, "e": 26296, "s": 26215, "text": "After removing an element the sum of remaining array is K, where K = sum – A[i]." }, { "code": null, "e": 26388, "s": 26296, "text": "We have to find an element K/2 in the remaining array to make it good. Let K = K/2 for now." }, { "code": null, "e": 26531, "s": 26388, "text": "Now the remaining array will be good if and only if below conditions holds true. If A[i] == K and hash(K) > 1 OR If A[i] != K and hash(K) > 0." }, { "code": null, "e": 26593, "s": 26531, "text": "If A[i] == K and hash(K) > 1 OR If A[i] != K and hash(K) > 0." }, { "code": null, "e": 26619, "s": 26593, "text": "Print all such indices i." }, { "code": null, "e": 26668, "s": 26619, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 26672, "s": 26668, "text": "C++" }, { "code": null, "e": 26677, "s": 26672, "text": "Java" }, { "code": null, "e": 26685, "s": 26677, "text": "Python3" }, { "code": null, "e": 26688, "s": 26685, "text": "C#" }, { "code": null, "e": 26699, "s": 26688, "text": "Javascript" }, { "code": "// C++ program to find all good indices// in the given array #include <bits/stdc++.h>using namespace std; // Function to find all good indices// in the given arrayvoid niceIndices(int A[], int n){ int sum = 0; // hash to store frequency // of each element map<int, int> m; // Storing frequency of each element // and calculating sum simultaneously for (int i = 0; i < n; ++i) { m[A[i]]++; sum += A[i]; } for (int i = 0; i < n; ++i) { int k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (m.find(k) != m.end()) { if ((A[i] == k && m[k] > 1) || (A[i] != k)) // print good indices cout << (i + 1) << \" \"; } } }} // Driver Codeint main(){ int A[] = { 8, 3, 5, 2 }; int n = sizeof(A) / sizeof(A[0]); niceIndices(A, n); return 0;}", "e": 27679, "s": 26699, "text": null }, { "code": "// Java program to find all good indices// in the given arrayimport java.util.*;class Solution{ // Function to find all good indices// in the given arraystatic void niceIndices(int A[], int n){ int sum = 0; // hash to store frequency // of each element Map<Integer, Integer> m=new HashMap<Integer, Integer>(); // Storing frequency of each element // and calculating sum simultaneously for (int i = 0; i < n; ++i) { m.put(A[i],(m.get(A[i])==null)?0:m.get(A[i])+1); sum += A[i]; } for (int i = 0; i < n; ++i) { int k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (m.containsKey(k)) { if ((A[i] == k && m.get(k) > 1) || (A[i] != k)) // print good indices System.out.print( (i + 1) +\" \"); } } }} // Driver Codepublic static void main(String args[]){ int A[] = { 8, 3, 5, 2 }; int n = A.length; niceIndices(A, n); }}//contributed by Arnab Kundu", "e": 28800, "s": 27679, "text": null }, { "code": "# Python3 program to find all good# indices in the given arrayfrom collections import defaultdict # Function to find all good indices# in the given arraydef niceIndices(A, n): Sum = 0 # hash to store frequency # of each element m = defaultdict(lambda:0) # Storing frequency of each element # and calculating sum simultaneously for i in range(n): m[A[i]] += 1 Sum += A[i] for i in range(n): k = Sum - A[i] if k % 2 == 0: k = k >> 1 # check if array is good after # removing i-th index element if k in m: if ((A[i] == k and m[k] > 1) or (A[i] != k)): # print good indices print((i + 1), end = \" \") # Driver Code if __name__ == \"__main__\": A = [8, 3, 5, 2] n = len(A) niceIndices(A, n) # This code is contributed by Rituraj Jain", "e": 29756, "s": 28800, "text": null }, { "code": "// C# program to find all good indices// in the given arrayusing System;using System.Collections.Generic; class GFG{ // Function to find all good indices// in the given arraystatic void niceIndices(int []A, int n){ int sum = 0; // hash to store frequency // of each element Dictionary<int,int> mp = new Dictionary<int,int>(); // Storing frequency of each element // and calculating sum simultaneously for (int i = 0 ; i < n; i++) { if(mp.ContainsKey(A[i])) { var val = mp[A[i]]; mp.Remove(A[i]); mp.Add(A[i], val + 1); sum += A[i]; } else { mp.Add(A[i], 0); sum += A[i]; } } for (int i = 0; i < n; ++i) { int k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (mp.ContainsKey(k)) { if ((A[i] == k && mp[k] > 1) || (A[i] != k)) // print good indices Console.Write( (i + 1) +\" \"); } } }} // Driver Codepublic static void Main(String []args){ int []A = { 8, 3, 5, 2 }; int n = A.Length; niceIndices(A, n); }} /* This code is contributed by PrinciRaj1992 */", "e": 31122, "s": 29756, "text": null }, { "code": "<script> // Javascript program to find all good indices// in the given array // Function to find all good indices// in the given arrayfunction niceIndices(A, n){ var sum = 0; // hash to store frequency // of each element var m = new Map(); // Storing frequency of each element // and calculating sum simultaneously for (var i = 0; i < n; ++i) { if(m.has(A[i])) m.set(A[i], m.get(A[i])+1) else m.set(A[i], 1) sum += A[i]; } for (var i = 0; i < n; ++i) { var k = sum - A[i]; if (k % 2 == 0) { k = k >> 1; // check if array is good after // removing i-th index element if (m.has(k)) { if ((A[i] == k && m.get(k) > 1) || (A[i] != k)) // print good indices document.write(i + 1 + \" \"); } } }} // Driver Codevar A = [8, 3, 5, 2];var n = A.length;niceIndices(A, n); // This code is contributed by importantly.</script>", "e": 32141, "s": 31122, "text": null }, { "code": null, "e": 32145, "s": 32141, "text": "1 4" }, { "code": null, "e": 32177, "s": 32147, "text": "Time Complexity: O(N*log(N)) " }, { "code": null, "e": 32188, "s": 32177, "text": "andrew1234" }, { "code": null, "e": 32201, "s": 32188, "text": "rituraj_jain" }, { "code": null, "e": 32215, "s": 32201, "text": "princiraj1992" }, { "code": null, "e": 32227, "s": 32215, "text": "importantly" }, { "code": null, "e": 32235, "s": 32227, "text": "cpp-map" }, { "code": null, "e": 32254, "s": 32235, "text": "frequency-counting" }, { "code": null, "e": 32259, "s": 32254, "text": "Hash" }, { "code": null, "e": 32266, "s": 32259, "text": "Arrays" }, { "code": null, "e": 32279, "s": 32266, "text": "Mathematical" }, { "code": null, "e": 32286, "s": 32279, "text": "Arrays" }, { "code": null, "e": 32291, "s": 32286, "text": "Hash" }, { "code": null, "e": 32304, "s": 32291, "text": "Mathematical" }, { "code": null, "e": 32402, "s": 32304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32427, "s": 32402, "text": "Window Sliding Technique" }, { "code": null, "e": 32447, "s": 32427, "text": "Trapping Rain Water" }, { "code": null, "e": 32472, "s": 32447, "text": "Building Heap from Array" }, { "code": null, "e": 32510, "s": 32472, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 32559, "s": 32510, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 32589, "s": 32559, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 32649, "s": 32589, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32664, "s": 32649, "text": "C++ Data Types" }, { "code": null, "e": 32707, "s": 32664, "text": "Set in C++ Standard Template Library (STL)" } ]
B-Spline Curve in Computer Graphics - GeeksforGeeks
22 Jan, 2021 Prerequisite – Bezier Curve Concept of B-spline curve came to resolve the disadvantages having by Bezier curve, as we all know that both curves are parametric in nature. In Bezier curve we face a problem, when we change any of the control point respective location the whole curve shape gets change. But here in B-spline curve, the only a specific segment of the curve-shape gets changes or affected by the changing of the corresponding location of the control points. In the B-spline curve, the control points impart local control over the curve-shape rather than the global control like Bezier-curve. B-spline curve shape before changing the position of control point P1 – B-spline curve shape after changing the position of control point P1 – You can see in the above figure that only the segment-1st shape as we have only changed the control point P1, and the shape of segment-2nd remains intact. B-spline Curve :As we see above that the B-splines curves are independent of the number of control points and made up of joining the several segments smoothly, where each segment shape is decided by some specific control points that come in that region of segment. Consider a curve given below – Attributes of this curve are – We have “n+1” control points in the above, so, n+1=8, so n=7. Let’s assume that the order of this curve is ‘k’, so the curve that we get will be of a polynomial degree of “k-1”. Conventionally it’s said that the value of ‘k’ must be in the range: 2 ≤ k ≤ n+1. So, let us assume k=4, so the curve degree will be k-1 = 3. The total number of segments for this curve will be calculated through the following formula –Total no. of seg = n – k + 2 = 7 – 4 + 2 = 5. Knots in B-spline Curve : The point between two segments of a curve that joins each other such points are known as knots in B-spline curve. In the case of the cubic polynomial degree curve, the knots are “n+4”. But in other common cases, we have “n+k+1” knots. So, for the above curve, the total knots vectors will be – Total knots = n+k+1 = 7 + 4 + 1 = 12 These knot vectors could be of three types – Uniform (periodic) Open-Uniform Non-Uniform B-spline Curve Equation : The equation of the spline-curve is as follows – Where Pi, k, t correspondingly represents the control points, degree, parameter of the curve. And following are some conditions for xi are as follows – Some cases of Basis function : Properties of B-spline Curve : Each basis function has 0 or +ve value for all parameters. Each basis function has one maximum value except for k=1. The degree of B-spline curve polynomial does not depend on the number of control points which makes it more reliable to use than Bezier curve. B-spline curve provides the local control through control points over each segment of the curve. The sum of basis functions for a given parameter is one. computer-graphics Technical Scripter 2020 Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to write Regular Expressions? fgets() and gets() in C language Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move) Recursive Functions Association Rule Software Engineering | Prototyping Model Java Math min() method with Examples Set add() method in Java with Examples Find all factors of a natural number | Set 1 OOPs | Object Oriented Design
[ { "code": null, "e": 24538, "s": 24510, "text": "\n22 Jan, 2021" }, { "code": null, "e": 24566, "s": 24538, "text": "Prerequisite – Bezier Curve" }, { "code": null, "e": 25007, "s": 24566, "text": "Concept of B-spline curve came to resolve the disadvantages having by Bezier curve, as we all know that both curves are parametric in nature. In Bezier curve we face a problem, when we change any of the control point respective location the whole curve shape gets change. But here in B-spline curve, the only a specific segment of the curve-shape gets changes or affected by the changing of the corresponding location of the control points." }, { "code": null, "e": 25141, "s": 25007, "text": "In the B-spline curve, the control points impart local control over the curve-shape rather than the global control like Bezier-curve." }, { "code": null, "e": 25214, "s": 25141, "text": "B-spline curve shape before changing the position of control point P1 – " }, { "code": null, "e": 25286, "s": 25214, "text": "B-spline curve shape after changing the position of control point P1 – " }, { "code": null, "e": 25441, "s": 25286, "text": "You can see in the above figure that only the segment-1st shape as we have only changed the control point P1, and the shape of segment-2nd remains intact." }, { "code": null, "e": 25738, "s": 25441, "text": "B-spline Curve :As we see above that the B-splines curves are independent of the number of control points and made up of joining the several segments smoothly, where each segment shape is decided by some specific control points that come in that region of segment. Consider a curve given below – " }, { "code": null, "e": 25769, "s": 25738, "text": "Attributes of this curve are –" }, { "code": null, "e": 25831, "s": 25769, "text": "We have “n+1” control points in the above, so, n+1=8, so n=7." }, { "code": null, "e": 26089, "s": 25831, "text": "Let’s assume that the order of this curve is ‘k’, so the curve that we get will be of a polynomial degree of “k-1”. Conventionally it’s said that the value of ‘k’ must be in the range: 2 ≤ k ≤ n+1. So, let us assume k=4, so the curve degree will be k-1 = 3." }, { "code": null, "e": 26229, "s": 26089, "text": "The total number of segments for this curve will be calculated through the following formula –Total no. of seg = n – k + 2 = 7 – 4 + 2 = 5." }, { "code": null, "e": 26549, "s": 26229, "text": "Knots in B-spline Curve : The point between two segments of a curve that joins each other such points are known as knots in B-spline curve. In the case of the cubic polynomial degree curve, the knots are “n+4”. But in other common cases, we have “n+k+1” knots. So, for the above curve, the total knots vectors will be –" }, { "code": null, "e": 26586, "s": 26549, "text": "Total knots = n+k+1 = 7 + 4 + 1 = 12" }, { "code": null, "e": 26631, "s": 26586, "text": "These knot vectors could be of three types –" }, { "code": null, "e": 26650, "s": 26631, "text": "Uniform (periodic)" }, { "code": null, "e": 26663, "s": 26650, "text": "Open-Uniform" }, { "code": null, "e": 26675, "s": 26663, "text": "Non-Uniform" }, { "code": null, "e": 26750, "s": 26675, "text": "B-spline Curve Equation : The equation of the spline-curve is as follows –" }, { "code": null, "e": 26844, "s": 26750, "text": "Where Pi, k, t correspondingly represents the control points, degree, parameter of the curve." }, { "code": null, "e": 26902, "s": 26844, "text": "And following are some conditions for xi are as follows –" }, { "code": null, "e": 26935, "s": 26904, "text": "Some cases of Basis function :" }, { "code": null, "e": 26968, "s": 26937, "text": "Properties of B-spline Curve :" }, { "code": null, "e": 27027, "s": 26968, "text": "Each basis function has 0 or +ve value for all parameters." }, { "code": null, "e": 27085, "s": 27027, "text": "Each basis function has one maximum value except for k=1." }, { "code": null, "e": 27228, "s": 27085, "text": "The degree of B-spline curve polynomial does not depend on the number of control points which makes it more reliable to use than Bezier curve." }, { "code": null, "e": 27325, "s": 27228, "text": "B-spline curve provides the local control through control points over each segment of the curve." }, { "code": null, "e": 27382, "s": 27325, "text": "The sum of basis functions for a given parameter is one." }, { "code": null, "e": 27400, "s": 27382, "text": "computer-graphics" }, { "code": null, "e": 27424, "s": 27400, "text": "Technical Scripter 2020" }, { "code": null, "e": 27429, "s": 27424, "text": "Misc" }, { "code": null, "e": 27434, "s": 27429, "text": "Misc" }, { "code": null, "e": 27439, "s": 27434, "text": "Misc" }, { "code": null, "e": 27537, "s": 27439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27571, "s": 27537, "text": "How to write Regular Expressions?" }, { "code": null, "e": 27604, "s": 27571, "text": "fgets() and gets() in C language" }, { "code": null, "e": 27685, "s": 27604, "text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)" }, { "code": null, "e": 27705, "s": 27685, "text": "Recursive Functions" }, { "code": null, "e": 27722, "s": 27705, "text": "Association Rule" }, { "code": null, "e": 27763, "s": 27722, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 27800, "s": 27763, "text": "Java Math min() method with Examples" }, { "code": null, "e": 27839, "s": 27800, "text": "Set add() method in Java with Examples" }, { "code": null, "e": 27884, "s": 27839, "text": "Find all factors of a natural number | Set 1" } ]
Bitonic Sort in C++
The bitonic sort is a parallel sorting algorithm that is created for best implementation and has optimum usage with hardware and parallel processor array. It is not the most effective one though as compared to the merge sort. But it is good for parallel implementation. This is due to the predefined comparison sequence which makes comparisons independent of data that are to be sorted. For bitonic sort to work effectively the number of elements should be in a specific type of quantity i.e. the order 2^n. One major part of the bitonic sort is the bitonic sequence which is a sequence whose elements value first increases and then decreases. Bitonic sequence is an array arr[0 ... (n-1)] if there is an index value i within the range 0 to n-1. For which the value of arr[i] is greatest in the array. i.e. arr[0] <= arr[1] ... <= arr[i] and arr[i] >= arr[i+1] ... >= aar[n-1] Bitonic sequence can be rotated back to bitonic sequence. Bitonic sequence can be rotated back to bitonic sequence. A sequence with elements in increasing and decreasing order is a bitonic sequence. A sequence with elements in increasing and decreasing order is a bitonic sequence. For creating a bitonic sequence, we will create two sub-sequences, one with ascending elements and other with descending elements. For example, let’s see the sequence arr[] and convert the following sequence to a bitonic sequence. arr[] = {3, 4, 1, 9, 2, 7, 5, 6} First, we will make pairs of elements and then create a bitonic sequence of these in such a way that one is in ascending order and the other is in descending order and so on. For our array, let’s create pairs in bitonic sequence. arr[] = {(3, 4), (1, 9), (2, 7), (5, 6)} // creating bitonic sequence pairs... arr[] = {(3, 4), (9, 1), (2, 7), (6, 5)} Then, we will create pairs of these pairs. i.e 4 elements bitonic sequence and compare elements with are a 2 distance [i.e. i with i+2]. arr[] = {(3, 4, 9, 1), (2, 7, 6, 5)} Ascending bitonic in first set will be created as − (3, 4, 9, 1) : comparing two distant elements. (3, 1, 9, 4) : Now, check adjacent elements. (1, 3, 4, 9) -> ascending bitonic sequence. Descending bitonic in second set will be created as − (2, 7, 6, 5) : comparing two distant elements. (6, 7, 2, 5) : Now, check adjacent elements. (7, 6, 5, 2) -> descending bitonic sequence. At the end, we will get the bitonic sequence of size 8. 1, 3, 4, 9, 7, 6, 5, 2 Now, since we have learned about the bitonic sequence. We will know about the Bitonic Sorting. To sort a bitonic sequence using bitonic sorting using these steps − Step 1 − Create a bitonic sequence. Step 2 − Now, we have a bitonic sequence with one part in increasing order and others in decreasing order. Step 3 − We will compare and swap the first elements of both halves. Then second, third, fourth elements for them. Step 4 − We will compare and swap, every second element of the sequence. Step 5 − At last, we will compare and swap adjacent elements of the sequence. Step 6 − After all swaps, we will get the sorted array. Program to show the implementation of Bitonic Sort − Live Demo #include<iostream> using namespace std; void bitonicSeqMerge(int a[], int start, int BseqSize, int direction) { if (BseqSize>1){ int k = BseqSize/2; for (int i=start; i<start+k; i++) if (direction==(a[i]>a[i+k])) swap(a[i],a[i+k]); bitonicSeqMerge(a, start, k, direction); bitonicSeqMerge(a, start+k, k, direction); } } void bitonicSortrec(int a[],int start, int BseqSize, int direction) { if (BseqSize>1){ int k = BseqSize/2; bitonicSortrec(a, start, k, 1); bitonicSortrec(a, start+k, k, 0); bitonicSeqMerge(a,start, BseqSize, direction); } } void bitonicSort(int a[], int size, int up) { bitonicSortrec(a, 0, size, up); } int main() { int a[]= {5, 10, 51, 8, 1, 9, 6, 22}; int size = sizeof(a)/sizeof(a[0]); printf("Original array: \n"); for (int i=0; i<size; i++) printf("%d\t", a[i]); bitonicSort(a, size, 1); printf("\nSorted array: \n"); for (int i=0; i<size; i++) printf("%d\t", a[i]); return 0; } Original array: 5 10 51 8 1 9 6 22 Sorted array: 1 5 6 8 9 10 22 51
[ { "code": null, "e": 1217, "s": 1062, "text": "The bitonic sort is a parallel sorting algorithm that is created for best implementation and has optimum usage with hardware and parallel processor array." }, { "code": null, "e": 1449, "s": 1217, "text": "It is not the most effective one though as compared to the merge sort. But it is good for parallel implementation. This is due to the predefined comparison sequence which makes comparisons independent of data that are to be sorted." }, { "code": null, "e": 1570, "s": 1449, "text": "For bitonic sort to work effectively the number of elements should be in a specific type of quantity i.e. the order 2^n." }, { "code": null, "e": 1706, "s": 1570, "text": "One major part of the bitonic sort is the bitonic sequence which is a sequence whose elements value first increases and then decreases." }, { "code": null, "e": 1869, "s": 1706, "text": "Bitonic sequence is an array arr[0 ... (n-1)] if there is an index value i within the range 0 to n-1. For which the value of arr[i] is greatest in the array. i.e." }, { "code": null, "e": 1939, "s": 1869, "text": "arr[0] <= arr[1] ... <= arr[i] and arr[i] >= arr[i+1] ... >= aar[n-1]" }, { "code": null, "e": 1997, "s": 1939, "text": "Bitonic sequence can be rotated back to bitonic sequence." }, { "code": null, "e": 2055, "s": 1997, "text": "Bitonic sequence can be rotated back to bitonic sequence." }, { "code": null, "e": 2138, "s": 2055, "text": "A sequence with elements in increasing and decreasing order is a bitonic sequence." }, { "code": null, "e": 2221, "s": 2138, "text": "A sequence with elements in increasing and decreasing order is a bitonic sequence." }, { "code": null, "e": 2352, "s": 2221, "text": "For creating a bitonic sequence, we will create two sub-sequences, one with ascending elements and other with descending elements." }, { "code": null, "e": 2452, "s": 2352, "text": "For example, let’s see the sequence arr[] and convert the following sequence to a bitonic sequence." }, { "code": null, "e": 2485, "s": 2452, "text": "arr[] = {3, 4, 1, 9, 2, 7, 5, 6}" }, { "code": null, "e": 2660, "s": 2485, "text": "First, we will make pairs of elements and then create a bitonic sequence of these in such a way that one is in ascending order and the other is in descending order and so on." }, { "code": null, "e": 2715, "s": 2660, "text": "For our array, let’s create pairs in bitonic sequence." }, { "code": null, "e": 2835, "s": 2715, "text": "arr[] = {(3, 4), (1, 9), (2, 7), (5, 6)}\n// creating bitonic sequence pairs...\narr[] = {(3, 4), (9, 1), (2, 7), (6, 5)}" }, { "code": null, "e": 2972, "s": 2835, "text": "Then, we will create pairs of these pairs. i.e 4 elements bitonic sequence and compare elements with are a 2 distance [i.e. i with i+2]." }, { "code": null, "e": 3009, "s": 2972, "text": "arr[] = {(3, 4, 9, 1), (2, 7, 6, 5)}" }, { "code": null, "e": 3061, "s": 3009, "text": "Ascending bitonic in first set will be created as −" }, { "code": null, "e": 3197, "s": 3061, "text": "(3, 4, 9, 1) : comparing two distant elements.\n(3, 1, 9, 4) : Now, check adjacent elements.\n(1, 3, 4, 9) -> ascending bitonic sequence." }, { "code": null, "e": 3251, "s": 3197, "text": "Descending bitonic in second set will be created as −" }, { "code": null, "e": 3388, "s": 3251, "text": "(2, 7, 6, 5) : comparing two distant elements.\n(6, 7, 2, 5) : Now, check adjacent elements.\n(7, 6, 5, 2) -> descending bitonic sequence." }, { "code": null, "e": 3444, "s": 3388, "text": "At the end, we will get the bitonic sequence of size 8." }, { "code": null, "e": 3467, "s": 3444, "text": "1, 3, 4, 9, 7, 6, 5, 2" }, { "code": null, "e": 3562, "s": 3467, "text": "Now, since we have learned about the bitonic sequence. We will know about the Bitonic Sorting." }, { "code": null, "e": 3631, "s": 3562, "text": "To sort a bitonic sequence using bitonic sorting using these steps −" }, { "code": null, "e": 3667, "s": 3631, "text": "Step 1 − Create a bitonic sequence." }, { "code": null, "e": 3774, "s": 3667, "text": "Step 2 − Now, we have a bitonic sequence with one part in increasing order and others in decreasing order." }, { "code": null, "e": 3889, "s": 3774, "text": "Step 3 − We will compare and swap the first elements of both halves. Then second, third, fourth elements for them." }, { "code": null, "e": 3962, "s": 3889, "text": "Step 4 − We will compare and swap, every second element of the sequence." }, { "code": null, "e": 4040, "s": 3962, "text": "Step 5 − At last, we will compare and swap adjacent elements of the sequence." }, { "code": null, "e": 4096, "s": 4040, "text": "Step 6 − After all swaps, we will get the sorted array." }, { "code": null, "e": 4149, "s": 4096, "text": "Program to show the implementation of Bitonic Sort −" }, { "code": null, "e": 4160, "s": 4149, "text": " Live Demo" }, { "code": null, "e": 5170, "s": 4160, "text": "#include<iostream>\nusing namespace std;\nvoid bitonicSeqMerge(int a[], int start, int BseqSize, int direction) {\n if (BseqSize>1){\n int k = BseqSize/2;\n for (int i=start; i<start+k; i++)\n if (direction==(a[i]>a[i+k]))\n swap(a[i],a[i+k]);\n bitonicSeqMerge(a, start, k, direction);\n bitonicSeqMerge(a, start+k, k, direction);\n }\n}\nvoid bitonicSortrec(int a[],int start, int BseqSize, int direction) {\n if (BseqSize>1){\n int k = BseqSize/2;\n bitonicSortrec(a, start, k, 1);\n bitonicSortrec(a, start+k, k, 0);\n bitonicSeqMerge(a,start, BseqSize, direction);\n }\n}\nvoid bitonicSort(int a[], int size, int up) {\n bitonicSortrec(a, 0, size, up);\n}\nint main() {\n int a[]= {5, 10, 51, 8, 1, 9, 6, 22};\n int size = sizeof(a)/sizeof(a[0]);\n printf(\"Original array: \\n\");\n for (int i=0; i<size; i++)\n printf(\"%d\\t\", a[i]);\n bitonicSort(a, size, 1);\n printf(\"\\nSorted array: \\n\");\n for (int i=0; i<size; i++)\n printf(\"%d\\t\", a[i]);\n return 0;\n}" }, { "code": null, "e": 5238, "s": 5170, "text": "Original array:\n5 10 51 8 1 9 6 22\nSorted array:\n1 5 6 8 9 10 22 51" } ]
How to loop through HTML elements without using forEach() loop in JavaScript ? - GeeksforGeeks
07 Apr, 2021 In this article, we will learn how to loop through HTML elements without using the forEach() method. Approach 1: Using the for loop: The HTML elements can be iterated by using the regular JavaScript for loop. The number of elements to be iterated can be found using the length property. The for loop has three parts, initialization, condition expression, and increment/decrement expression. Each of the items can be accessed by using square brackets with their respective index. Syntax: for (let i = 0; i < elements.length; i++) { console.log(elements[i]); } Example: HTML <!DOCTYPE html> <html> <body> <!-- HTML elements to iterate --> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <p>This is paragraph 3.</p> <script type="text/javascript"> // Get the elements to be iterated let htmlElements = document.getElementsByTagName("p"); // Use a regular for-loop for (let i = 0; i < htmlElements.length; i++) { // Print the current element console.log(htmlElements[i]); } </script> </body> </html> Output: Approach 2: Using the While loop: The HTML elements can be iterated by using a regular JavaScript while loop. The number of elements can be found using the length property. A temporary value is used to keep track of the current iteration by checking it in the condition expression. Each of the items can then be accessed by using square brackets with their respective index. Syntax: let i = 0; while(i < elements.length) { console.log(elements[i]); i++; } Example: HTML <!DOCTYPE html> <html> <body> <!-- HTML elements to iterate --> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <p>This is paragraph 3.</p> <script type="text/javascript"> // Get the elements to be iterated let htmlElements = document.getElementsByTagName("p"); // Define a variable to keep track // of the current iteration let i = 0; // Check if the current value // is lesser than total elements while (i < htmlElements.length) { // Print the current element console.log(htmlElements[i]); // Increment the value i++; } </script> </body> </html> Output: Approach 3: Using the ‘for.....of’ statement: The for...of statement can be used to loop over values of an iterable object. It includes objects like an Array, Map, Set, or HTML elements. A temporary variable holds the current value during the execution of the loop, which can then be used in the body of the loop. Syntax: for (element of elements) { console.log(element); } Example: HTML <!DOCTYPE html> <html> <body> <!-- HTML elements to iterate --> <p>This is paragraph 1.</p> <p>This is paragraph 2.</p> <p>This is paragraph 3.</p> <script type="text/javascript"> // Get the elements to be iterated let HTMLelements = document.getElementsByTagName("p"); // Use the for...of statement to get // the values for (elem of HTMLelements) { // Print the current element console.log(elem); } </script> </body> </html> 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 JavaScript-Questions Picked HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a web page using HTML and CSS Angular File Upload Form validation using jQuery DOM (Document Object Model) How to auto-resize an image to fit a div container using CSS? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? Make a div horizontally scrollable using CSS How to place text on image using HTML and CSS?
[ { "code": null, "e": 24968, "s": 24937, "text": " \n07 Apr, 2021\n" }, { "code": null, "e": 25069, "s": 24968, "text": "In this article, we will learn how to loop through HTML elements without using the forEach() method." }, { "code": null, "e": 25447, "s": 25069, "text": "Approach 1: Using the for loop: The HTML elements can be iterated by using the regular JavaScript for loop. The number of elements to be iterated can be found using the length property. The for loop has three parts, initialization, condition expression, and increment/decrement expression. Each of the items can be accessed by using square brackets with their respective index." }, { "code": null, "e": 25455, "s": 25447, "text": "Syntax:" }, { "code": null, "e": 25532, "s": 25455, "text": "for (let i = 0; i < elements.length; i++) {\n console.log(elements[i]);\n}\n" }, { "code": null, "e": 25543, "s": 25534, "text": "Example:" }, { "code": null, "e": 25548, "s": 25543, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n \n<body> \n \n <!-- HTML elements to iterate -->\n <p>This is paragraph 1.</p> \n <p>This is paragraph 2.</p> \n <p>This is paragraph 3.</p> \n \n <script type=\"text/javascript\"> \n \n // Get the elements to be iterated \n let htmlElements = \n document.getElementsByTagName(\"p\"); \n \n // Use a regular for-loop \n for (let i = 0; i < htmlElements.length; i++) { \n \n // Print the current element \n console.log(htmlElements[i]); \n } \n </script> \n</body> \n \n</html> \n\n\n\n\n\n", "e": 26145, "s": 25558, "text": null }, { "code": null, "e": 26153, "s": 26145, "text": "Output:" }, { "code": null, "e": 26528, "s": 26153, "text": "Approach 2: Using the While loop: The HTML elements can be iterated by using a regular JavaScript while loop. The number of elements can be found using the length property. A temporary value is used to keep track of the current iteration by checking it in the condition expression. Each of the items can then be accessed by using square brackets with their respective index." }, { "code": null, "e": 26536, "s": 26528, "text": "Syntax:" }, { "code": null, "e": 26617, "s": 26536, "text": "let i = 0;\nwhile(i < elements.length) {\n console.log(elements[i]);\n i++;\n}" }, { "code": null, "e": 26626, "s": 26617, "text": "Example:" }, { "code": null, "e": 26631, "s": 26626, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n \n<body> \n \n <!-- HTML elements to iterate -->\n <p>This is paragraph 1.</p> \n <p>This is paragraph 2.</p> \n <p>This is paragraph 3.</p> \n \n <script type=\"text/javascript\"> \n \n // Get the elements to be iterated \n let htmlElements = \n document.getElementsByTagName(\"p\"); \n \n // Define a variable to keep track \n // of the current iteration \n let i = 0; \n \n // Check if the current value \n // is lesser than total elements \n while (i < htmlElements.length) { \n \n // Print the current element \n console.log(htmlElements[i]); \n \n // Increment the value \n i++; \n } \n </script> \n</body> \n \n</html> \n\n\n\n\n\n", "e": 27421, "s": 26641, "text": null }, { "code": null, "e": 27429, "s": 27421, "text": "Output:" }, { "code": null, "e": 27743, "s": 27429, "text": "Approach 3: Using the ‘for.....of’ statement: The for...of statement can be used to loop over values of an iterable object. It includes objects like an Array, Map, Set, or HTML elements. A temporary variable holds the current value during the execution of the loop, which can then be used in the body of the loop." }, { "code": null, "e": 27751, "s": 27743, "text": "Syntax:" }, { "code": null, "e": 27807, "s": 27751, "text": "for (element of elements) {\n console.log(element);\n}" }, { "code": null, "e": 27816, "s": 27807, "text": "Example:" }, { "code": null, "e": 27821, "s": 27816, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n \n<body> \n \n <!-- HTML elements to iterate -->\n <p>This is paragraph 1.</p> \n <p>This is paragraph 2.</p> \n <p>This is paragraph 3.</p> \n \n <script type=\"text/javascript\"> \n \n // Get the elements to be iterated \n let HTMLelements = \n document.getElementsByTagName(\"p\"); \n \n // Use the for...of statement to get \n // the values \n for (elem of HTMLelements) { \n \n // Print the current element \n console.log(elem); \n } \n </script> \n</body> \n \n</html> \n\n\n\n\n\n", "e": 28422, "s": 27831, "text": null }, { "code": null, "e": 28430, "s": 28422, "text": "Output:" }, { "code": null, "e": 28567, "s": 28430, "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": 28584, "s": 28567, "text": "\nHTML-Questions\n" }, { "code": null, "e": 28607, "s": 28584, "text": "\nJavaScript-Questions\n" }, { "code": null, "e": 28616, "s": 28607, "text": "\nPicked\n" }, { "code": null, "e": 28623, "s": 28616, "text": "\nHTML\n" }, { "code": null, "e": 28828, "s": 28623, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28852, "s": 28828, "text": "REST API (Introduction)" }, { "code": null, "e": 28889, "s": 28852, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28909, "s": 28889, "text": "Angular File Upload" }, { "code": null, "e": 28938, "s": 28909, "text": "Form validation using jQuery" }, { "code": null, "e": 28966, "s": 28938, "text": "DOM (Document Object Model)" }, { "code": null, "e": 29028, "s": 28966, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 29070, "s": 29028, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 29117, "s": 29070, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 29162, "s": 29117, "text": "Make a div horizontally scrollable using CSS" } ]
Can we create an object of an abstract class in Java?
No, we can't create an object of an abstract class. But we can create a reference variable of an abstract class. The reference variable is used to refer to the objects of derived classes (subclasses of abstract class). An abstract class means hiding the implementation and showing the function definition to the user is known as Abstract class. A Java abstract class can have instance methods that implement a default behavior if we know the requirement and partially implementation we can go for an abstract class. Live Demo abstract class Diagram { double dim1; double dim2; Diagram(double a, double b) { dim1 = a; dim2 = b; } // area is now an abstract method abstract double area(); } class Rectangle extends Diagram { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Diagram { Triangle(double a, double b) { super(a, b); } // override area for triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } public class Test { public static void main(String args[]) { // Diagram d = new Diagram(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Diagram diagRef; // This is OK, no object is created diagRef = r; System.out.println("Area of Rectangle is: " + diagRef.area()); diagRef = t; System.out.println("Area of Triangle is:" + diagRef.area()); } } In the above example, we cannot create the object of type Diagram but we can create a reference variable of type Diagram. Here we created a reference variable of type Diagram and the Diagram class reference variable is used to refer to the objects of the class Rectangle and Triangle. Inside Area for Rectangle. Area of Rectangle is: 45.0 Inside Area for Triangle. Area of Triangle is:40.0
[ { "code": null, "e": 1281, "s": 1062, "text": "No, we can't create an object of an abstract class. But we can create a reference variable of an abstract class. The reference variable is used to refer to the objects of derived classes (subclasses of abstract class)." }, { "code": null, "e": 1578, "s": 1281, "text": "An abstract class means hiding the implementation and showing the function definition to the user is known as Abstract class. A Java abstract class can have instance methods that implement a default behavior if we know the requirement and partially implementation we can go for an abstract class." }, { "code": null, "e": 1588, "s": 1578, "text": "Live Demo" }, { "code": null, "e": 2699, "s": 1588, "text": "abstract class Diagram {\n double dim1;\n double dim2;\n Diagram(double a, double b) {\n dim1 = a;\n dim2 = b;\n }\n // area is now an abstract method\n abstract double area();\n}\nclass Rectangle extends Diagram {\n Rectangle(double a, double b) {\n super(a, b);\n }\n // override area for rectangle\n double area() {\n System.out.println(\"Inside Area for Rectangle.\");\n return dim1 * dim2;\n }\n}\nclass Triangle extends Diagram {\n Triangle(double a, double b) {\n super(a, b);\n }\n // override area for triangle\n double area() {\n System.out.println(\"Inside Area for Triangle.\");\n return dim1 * dim2 / 2;\n }\n}\npublic class Test {\n public static void main(String args[]) {\n // Diagram d = new Diagram(10, 10); // illegal now\n Rectangle r = new Rectangle(9, 5);\n Triangle t = new Triangle(10, 8);\n Diagram diagRef; // This is OK, no object is created\n diagRef = r;\n System.out.println(\"Area of Rectangle is: \" + diagRef.area());\n diagRef = t;\n System.out.println(\"Area of Triangle is:\" + diagRef.area());\n }\n}" }, { "code": null, "e": 2984, "s": 2699, "text": "In the above example, we cannot create the object of type Diagram but we can create a reference variable of type Diagram. Here we created a reference variable of type Diagram and the Diagram class reference variable is used to refer to the objects of the class Rectangle and Triangle." }, { "code": null, "e": 3089, "s": 2984, "text": "Inside Area for Rectangle.\nArea of Rectangle is: 45.0\nInside Area for Triangle.\nArea of Triangle is:40.0" } ]
What are the undecidable problems in TOC?
The problems for which we can’t construct an algorithm that can answer the problem correctly in the infinite time are termed as Undecidable Problems in the theory of computation (TOC). A problem is undecidable if there is no Turing machine that will always halt an infinite amount of time to answer as ‘yes’ or ‘no’. Examples The examples of undecidable problems are explained below. Here, CFG refers to Context Free Grammar. Whether two CFG L and M equal − Since, we cannot determine all the strings of any CFG, we can predict that two CFG are equal or not. Whether two CFG L and M equal − Since, we cannot determine all the strings of any CFG, we can predict that two CFG are equal or not. Given a context-free language, there is no Turing machine (TM) that will always halt an infinite amount of time and give an answer to whether language is ambiguous or not. Given a context-free language, there is no Turing machine (TM) that will always halt an infinite amount of time and give an answer to whether language is ambiguous or not. Given two context-free languages, there is no Turing machine that will always halt an infinite amount of time and give an answer whether two context-free languages are equal or not. Given two context-free languages, there is no Turing machine that will always halt an infinite amount of time and give an answer whether two context-free languages are equal or not. Whether CFG will generate all possible strings of the input alphabet (∑*) is undecidable. Whether CFG will generate all possible strings of the input alphabet (∑*) is undecidable. Halting Problem The Halting problem is the most famous of the undecidable problems. Consider the code num=1; while(num=0) { num=num+1; } It counts up forever since it will never equal 0. This is an example of the halting problem. Note: Every context-free language is decidable. Some of the other undecidable problems are: Totality problem − It decide whether an arbitrary TM halts on all inputs. This is equivalent to the problem of whether a program can ever enter an infinite loop, for any input. It differs from the halting problem, which asks whether it enters an infinite loop for a particular input. Equivalence problem − It decide whether two TMs accept the same language. This is equivalent to the problem of whether two programs compute the same output for every input.
[ { "code": null, "e": 1247, "s": 1062, "text": "The problems for which we can’t construct an algorithm that can answer the problem correctly in the infinite time are termed as Undecidable Problems in the theory of computation (TOC)." }, { "code": null, "e": 1379, "s": 1247, "text": "A problem is undecidable if there is no Turing machine that will always halt an infinite amount of time to answer as ‘yes’ or ‘no’." }, { "code": null, "e": 1388, "s": 1379, "text": "Examples" }, { "code": null, "e": 1488, "s": 1388, "text": "The examples of undecidable problems are explained below. Here, CFG refers to Context Free Grammar." }, { "code": null, "e": 1621, "s": 1488, "text": "Whether two CFG L and M equal − Since, we cannot determine all the strings of any CFG, we can predict that two CFG are equal or not." }, { "code": null, "e": 1754, "s": 1621, "text": "Whether two CFG L and M equal − Since, we cannot determine all the strings of any CFG, we can predict that two CFG are equal or not." }, { "code": null, "e": 1926, "s": 1754, "text": "Given a context-free language, there is no Turing machine (TM) that will always halt an infinite amount of time and give an answer to whether language is ambiguous or not." }, { "code": null, "e": 2098, "s": 1926, "text": "Given a context-free language, there is no Turing machine (TM) that will always halt an infinite amount of time and give an answer to whether language is ambiguous or not." }, { "code": null, "e": 2280, "s": 2098, "text": "Given two context-free languages, there is no Turing machine that will always halt an infinite amount of time and give an answer whether two context-free languages are equal or not." }, { "code": null, "e": 2462, "s": 2280, "text": "Given two context-free languages, there is no Turing machine that will always halt an infinite amount of time and give an answer whether two context-free languages are equal or not." }, { "code": null, "e": 2552, "s": 2462, "text": "Whether CFG will generate all possible strings of the input alphabet (∑*) is undecidable." }, { "code": null, "e": 2642, "s": 2552, "text": "Whether CFG will generate all possible strings of the input alphabet (∑*) is undecidable." }, { "code": null, "e": 2658, "s": 2642, "text": "Halting Problem" }, { "code": null, "e": 2726, "s": 2658, "text": "The Halting problem is the most famous of the undecidable problems." }, { "code": null, "e": 2744, "s": 2726, "text": "Consider the code" }, { "code": null, "e": 2782, "s": 2744, "text": "num=1;\nwhile(num=0)\n{\n num=num+1;\n}" }, { "code": null, "e": 2875, "s": 2782, "text": "It counts up forever since it will never equal 0. This is an example of the halting problem." }, { "code": null, "e": 2923, "s": 2875, "text": "Note: Every context-free language is decidable." }, { "code": null, "e": 2967, "s": 2923, "text": "Some of the other undecidable problems are:" }, { "code": null, "e": 3251, "s": 2967, "text": "Totality problem − It decide whether an arbitrary TM halts on all inputs. This is equivalent to the problem of whether a program can ever enter an infinite loop, for any input. It differs from the halting problem, which asks whether it enters an infinite loop for a particular input." }, { "code": null, "e": 3424, "s": 3251, "text": "Equivalence problem − It decide whether two TMs accept the same language. This is equivalent to the problem of whether two programs compute the same output for every input." } ]
Create an Exception Logging Decorator in Python - GeeksforGeeks
08 May, 2020 Prerequisites: Decorators in Python, Logging in Python Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice. Logging is a standard process an application to follow to store the process in a log file that would help to analyze/debug in the future/unexpected situations. For a logger, we have different levels of logging a message. As the article is limited to exception logging, we will go with the ‘INFO’ level log message which helps us to check if the code is working as expected. If there is an exception, it will store exception into the log file using logger object logger.exception(“some exception raised”) Below is the implementation. import loggingfrom functools import wraps def create_logger(): #create a logger object logger = logging.getLogger('exc_logger') logger.setLevel(logging.INFO) #create a file to store all the # logged exceptions logfile = logging.FileHandler('exc_logger.log') fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter(fmt) logfile.setFormatter(formatter) logger.addHandler(logfile) return logger logger = create_logger() # you will find a log file# created in a given pathprint(logger) def exception(logger): # logger is the logging object # exception is the decorator objects # that logs every exception into log file def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: issue = "exception in "+func.__name__+"\n" issue = issue+"-------------------------\ ------------------------------------------------\n" logger.exception(issue) raise return wrapper return decorator @exception(logger)def divideStrByInt(): return "krishna"/7 # Driver Codeif __name__ == '__main__': divideStrByInt() Output: Python Decorators 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 drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n08 May, 2020" }, { "code": null, "e": 24347, "s": 24292, "text": "Prerequisites: Decorators in Python, Logging in Python" }, { "code": null, "e": 24802, "s": 24347, "text": "Logging helps you to keep track of the program/application you run. It stores the outputs/errors/messages/exceptions anything you want to store. Program executions can be debugged with the help of print statements during the runtime of code. But the code is not elegant and not a good practice. Logging is a standard process an application to follow to store the process in a log file that would help to analyze/debug in the future/unexpected situations." }, { "code": null, "e": 25146, "s": 24802, "text": "For a logger, we have different levels of logging a message. As the article is limited to exception logging, we will go with the ‘INFO’ level log message which helps us to check if the code is working as expected. If there is an exception, it will store exception into the log file using logger object logger.exception(“some exception raised”)" }, { "code": null, "e": 25175, "s": 25146, "text": "Below is the implementation." }, { "code": "import loggingfrom functools import wraps def create_logger(): #create a logger object logger = logging.getLogger('exc_logger') logger.setLevel(logging.INFO) #create a file to store all the # logged exceptions logfile = logging.FileHandler('exc_logger.log') fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter(fmt) logfile.setFormatter(formatter) logger.addHandler(logfile) return logger logger = create_logger() # you will find a log file# created in a given pathprint(logger) def exception(logger): # logger is the logging object # exception is the decorator objects # that logs every exception into log file def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: issue = \"exception in \"+func.__name__+\"\\n\" issue = issue+\"-------------------------\\ ------------------------------------------------\\n\" logger.exception(issue) raise return wrapper return decorator @exception(logger)def divideStrByInt(): return \"krishna\"/7 # Driver Codeif __name__ == '__main__': divideStrByInt() ", "e": 26552, "s": 25175, "text": null }, { "code": null, "e": 26560, "s": 26552, "text": "Output:" }, { "code": null, "e": 26578, "s": 26560, "text": "Python Decorators" }, { "code": null, "e": 26585, "s": 26578, "text": "Python" }, { "code": null, "e": 26683, "s": 26585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26715, "s": 26683, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26771, "s": 26715, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26813, "s": 26771, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26868, "s": 26813, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26910, "s": 26868, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26932, "s": 26910, "text": "Defaultdict in Python" }, { "code": null, "e": 26971, "s": 26932, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27002, "s": 26971, "text": "Python | os.path.join() method" }, { "code": null, "e": 27031, "s": 27002, "text": "Create a directory in Python" } ]
How to call a method after a delay in Swift(iOS)?
In this post, we will be seeing how you can delay a method call using Swift. Here we will be seeing how you can achieve the same in two ways, So let’s get started, We will be seeing both the example in Playground, Step 1 − Open Xcode → New Playground. In the first approach, we will be using asyncAfter(deadline: execute:) instance method, which Schedules a work item for execution at the specified time and returns immediately. You can read more about it here https://developer.apple.com/documentation/dispatch/dispatchqueue/2300020-asyncafter Step 2 − Copy the below code in Playground and run, func functionOne() { let delayTime = DispatchTime.now() + 3.0 print("one") DispatchQueue.main.asyncAfter(deadline: delayTime, execute: { hello() }) } func hello() { print("text") } functionOne() Here we are creating one function functionOne, where first we are declaring delay time which is 3 Seconds. Then we are using asyncAfter where we are giving the delay time as a parameter and asking to execute hello() function after 3 seconds. If we run the above program first “one” prints then after 3 seconds “text” prints. In the second approach, we are going to use NSTimer, You can copy the below code in your Xcode→Single View application class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("one") Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.hello), userInfo: nil, repeats: false) } @objc func hello() { print("text") } } Run the application, you will see the same output, one is printed and after 3 seconds text is printed.
[ { "code": null, "e": 1204, "s": 1062, "text": "In this post, we will be seeing how you can delay a method call using Swift. Here we will be seeing how you can achieve the same in two ways," }, { "code": null, "e": 1226, "s": 1204, "text": "So let’s get started," }, { "code": null, "e": 1276, "s": 1226, "text": "We will be seeing both the example in Playground," }, { "code": null, "e": 1314, "s": 1276, "text": "Step 1 − Open Xcode → New Playground." }, { "code": null, "e": 1491, "s": 1314, "text": "In the first approach, we will be using asyncAfter(deadline: execute:) instance method, which Schedules a work item for execution at the specified time and returns immediately." }, { "code": null, "e": 1607, "s": 1491, "text": "You can read more about it here https://developer.apple.com/documentation/dispatch/dispatchqueue/2300020-asyncafter" }, { "code": null, "e": 1659, "s": 1607, "text": "Step 2 − Copy the below code in Playground and run," }, { "code": null, "e": 1875, "s": 1659, "text": "func functionOne() {\n let delayTime = DispatchTime.now() + 3.0\n print(\"one\")\n DispatchQueue.main.asyncAfter(deadline: delayTime, execute: {\n hello()\n })\n}\nfunc hello() {\n print(\"text\")\n} functionOne()" }, { "code": null, "e": 2117, "s": 1875, "text": "Here we are creating one function functionOne, where first we are declaring delay time which is 3 Seconds. Then we are using asyncAfter where we are giving the delay time as a parameter and asking to execute hello() function after 3 seconds." }, { "code": null, "e": 2200, "s": 2117, "text": "If we run the above program first “one” prints then after 3 seconds “text” prints." }, { "code": null, "e": 2253, "s": 2200, "text": "In the second approach, we are going to use NSTimer," }, { "code": null, "e": 2319, "s": 2253, "text": "You can copy the below code in your Xcode→Single View application" }, { "code": null, "e": 2626, "s": 2319, "text": "class ViewController: UIViewController {\n override func viewDidLoad() {\n super.viewDidLoad()\n print(\"one\")\n Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(ViewController.hello), userInfo: nil, repeats: false)\n }\n @objc func hello() {\n print(\"text\")\n }\n}" }, { "code": null, "e": 2729, "s": 2626, "text": "Run the application, you will see the same output, one is printed and after 3 seconds text is printed." } ]
How To Convert Python Dictionary To JSON?
08 Nov, 2021 JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.Note: For more information, refer to Read, Write and Parse JSON using Python Function Used: json.dumps() json.dump() Syntax: json.dumps(dict, indent)Parameters: dictionary – name of dictionary which should be converted to JSON object. indent – defines the number of units for indentation Syntax: json.dump(dict, file_pointer)Parameters: dictionary – name of dictionary which should be converted to JSON object. file pointer – pointer of the file opened in write or append mode. Example 1: Python3 import json # Data to be written dictionary ={ "id": "04", "name": "sunil", "department": "HR"} # Serializing json json_object = json.dumps(dictionary, indent = 4) print(json_object) { "id": "04", "name": "sunil", "department": "HR" } Output: { "department": "HR", "id": "04", "name": "sunil" } Example 2: Python3 import json # Data to be writtendictionary ={ "name" : "sathiyajith", "rollno" : 56, "cgpa" : 8.6, "phonenumber" : "9976770500"} with open("sample.json", "w") as outfile: json.dump(dictionary, outfile) Output: sagar0719kumar prachisoda1234 Python json-programs Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Nov, 2021" }, { "code": null, "e": 552, "s": 28, "text": "JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.Note: For more information, refer to Read, Write and Parse JSON using Python " }, { "code": null, "e": 569, "s": 552, "text": "Function Used: " }, { "code": null, "e": 584, "s": 569, "text": "json.dumps() " }, { "code": null, "e": 598, "s": 584, "text": "json.dump() " }, { "code": null, "e": 644, "s": 598, "text": "Syntax: json.dumps(dict, indent)Parameters: " }, { "code": null, "e": 720, "s": 644, "text": "dictionary – name of dictionary which should be converted to JSON object. " }, { "code": null, "e": 775, "s": 720, "text": "indent – defines the number of units for indentation " }, { "code": null, "e": 826, "s": 775, "text": "Syntax: json.dump(dict, file_pointer)Parameters: " }, { "code": null, "e": 902, "s": 826, "text": "dictionary – name of dictionary which should be converted to JSON object. " }, { "code": null, "e": 971, "s": 902, "text": "file pointer – pointer of the file opened in write or append mode. " }, { "code": null, "e": 984, "s": 973, "text": "Example 1:" }, { "code": null, "e": 992, "s": 984, "text": "Python3" }, { "code": "import json # Data to be written dictionary ={ \"id\": \"04\", \"name\": \"sunil\", \"department\": \"HR\"} # Serializing json json_object = json.dumps(dictionary, indent = 4) print(json_object)", "e": 1194, "s": 992, "text": null }, { "code": null, "e": 1258, "s": 1194, "text": "{\n \"id\": \"04\",\n \"name\": \"sunil\",\n \"department\": \"HR\"\n}" }, { "code": null, "e": 1266, "s": 1258, "text": "Output:" }, { "code": null, "e": 1330, "s": 1266, "text": "{\n \"department\": \"HR\",\n \"id\": \"04\",\n \"name\": \"sunil\"\n}" }, { "code": null, "e": 1341, "s": 1330, "text": "Example 2:" }, { "code": null, "e": 1349, "s": 1341, "text": "Python3" }, { "code": "import json # Data to be writtendictionary ={ \"name\" : \"sathiyajith\", \"rollno\" : 56, \"cgpa\" : 8.6, \"phonenumber\" : \"9976770500\"} with open(\"sample.json\", \"w\") as outfile: json.dump(dictionary, outfile)", "e": 1572, "s": 1349, "text": null }, { "code": null, "e": 1581, "s": 1572, "text": "Output: " }, { "code": null, "e": 1596, "s": 1581, "text": "sagar0719kumar" }, { "code": null, "e": 1611, "s": 1596, "text": "prachisoda1234" }, { "code": null, "e": 1632, "s": 1611, "text": "Python json-programs" }, { "code": null, "e": 1644, "s": 1632, "text": "Python-json" }, { "code": null, "e": 1651, "s": 1644, "text": "Python" } ]
Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
07 Jul, 2022 Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pairs of vertices. There are different methods to check the connectivity of directed graph but one of the optimized method is Kosaraju’s DFS based simple algorithm. Kosaraju’s BFS based simple algorithm also work on the same principle as DFS based algorithm does. Following is Kosaraju’s BFS based simple algorithm that does two BFS traversals of graph: 1) Initialize all vertices as not visited. 2) Do a BFS traversal of graph starting from any arbitrary vertex v. If BFS traversal doesn’t visit all vertices, then return false. 3) Reverse all edges (or find transpose or reverse of graph) 4) Mark all vertices as not visited in reversed graph. 5) Again do a BFS traversal of reversed graph starting from same vertex v (Same as step 2). If BFS traversal doesn’t visit all vertices, then return false. Otherwise, return true. The idea is again simple if every node can be reached from a vertex v, and every node can reach same vertex v, then the graph is strongly connected. In step 2, we check if all vertices are reachable from v. In step 5, we check if all vertices can reach v (In reversed graph, if all vertices are reachable from v, then all vertices can reach v in original graph). Explanation with some examples: Example 1 : Given a directed to check if it is strongly connected or not. step 1: Starting with vertex 2 BFS obtained is 2 3 4 0 1 step 2: After reversing the given graph we got listed graph. step 3: Again after starting with vertex 2 the BFS is 2 1 4 0 3 step 4: No vertex in both case (step 1 & step 3) remains unvisited. step 5: So, given graph is strongly connected. Example 2 : Given a directed to check if it is strongly connected or not. step 1: Starting with vertex 2 BFS obtained is 2 3 4 step 2: After reversing the given graph we got listed graph. step 3: Again after starting with vertex 2 the BFS is 2 1 0 step 4: vertex 0, 1 in original graph and 3, 4 in reverse graph remains unvisited. step 5: So, given graph is not strongly connected. Following is the implementation of above algorithm. C++ Python3 // C++ program to check if a given directed graph// is strongly connected or not with BFS use#include <bits/stdc++.h>using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // An array of adjacency lists // A recursive function to print DFS starting from v void BFSUtil(int v, bool visited[]);public: // Constructor and Destructor Graph(int V) { this->V = V; adj = new list<int>[V];} ~Graph() { delete [] adj; } // Method to add an edge void addEdge(int v, int w); // The main function that returns true if the // graph is strongly connected, otherwise false bool isSC(); // Function that returns reverse (or transpose) // of this graph Graph getTranspose();}; // A recursive function to print DFS starting from vvoid Graph::BFSUtil(int v, bool visited[]){ // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[v] = true; queue.push_back(v); // 'i' will be used to get all adjacent vertices // of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue v = queue.front(); queue.pop_front(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it for (i = adj[v].begin(); i != adj[v].end(); ++i) { if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } }} // Function that returns reverse (or transpose) of this graphGraph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) g.adj[*i].push_back(v); } return g;} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // The main function that returns true if graph// is strongly connectedbool Graph::isSC(){ // Step 1: Mark all the vertices as not // visited (For first BFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do BFS traversal starting // from first vertex. BFSUtil(0, visited); // If BFS traversal doesn’t visit all // vertices, then return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not // visited (For second BFS) for(int i = 0; i < V; i++) visited[i] = false; // Step 5: Do BFS for reversed graph // starting from first vertex. // Starting Vertex must be same starting // point of first DFS gr.BFSUtil(0, visited); // If all vertices are not visited in // second DFS, then return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver program to test above functionsint main(){ // Create graphs given in the above diagrams Graph g1(5); g1.addEdge(0, 1); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.addEdge(3, 0); g1.addEdge(2, 4); g1.addEdge(4, 2); g1.isSC()? cout << "Yes\n" : cout << "No\n"; Graph g2(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); g2.isSC()? cout << "Yes\n" : cout << "No\n"; return 0;} # Python3 program to check if a given directed graph# is strongly connected or not with BFS usefrom collections import deque # A recursive function to print DFS starting from vdef BFSUtil(adj, v, visited): # Create a queue for BFS queue = deque() # Mark the current node as visited # and enqueue it visited[v] = True queue.append(v) # 'i' will be used to get all adjacent # vertices of a vertex while (len(queue) > 0): # Dequeue a vertex from queue v = queue.popleft() #print(v) #queue.pop_front() # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in adj[v]: if (visited[i] == False): visited[i] = True queue.append(i) return visited # Function that returns reverse# (or transpose) of this graphdef getTranspose(adj, V): g = [[] for i in range(V)] for v in range(V): # Recur for all the vertices adjacent to # this vertex # list<int>::iterator i for i in adj[v]: g[i].append(v) return g def addEdge(adj, v, w): # Add w to v’s list. adj[v].append(w) return adj # The main function that returns True if graph# is strongly connecteddef isSC(adj, V): # Step 1: Mark all the vertices as not # visited (For first BFS) visited = [False]*V # Step 2: Do BFS traversal starting # from first vertex. visited = BFSUtil(adj, 0, visited) # print(visited) # If BFS traversal doesn’t visit all # vertices, then return false. for i in range(V): if (visited[i] == False): return False # Step 3: Create a reversed graph adj = getTranspose(adj, V) # Step 4: Mark all the vertices as not # visited (For second BFS) for i in range(V): visited[i] = False # Step 5: Do BFS for reversed graph # starting from first vertex. # Starting Vertex must be same starting # point of first DFS visited = BFSUtil(adj, 0, visited) # If all vertices are not visited in # second DFS, then return false for i in range(V): if (visited[i] == False): return False return True # Driver codeif __name__ == '__main__': # Create graphs given in the above diagrams g1 = [[] for i in range(5)] g1 = addEdge(g1, 0, 1) g1 = addEdge(g1, 1, 2) g1 = addEdge(g1, 2, 3) g1 = addEdge(g1, 3, 0) g1 = addEdge(g1, 2, 4) g1 = addEdge(g1, 4, 2) #print(g1) print("Yes" if isSC(g1, 5) else "No") g2 = [[] for i in range(4)] g2 = addEdge(g2, 0, 1) g2 = addEdge(g2, 1, 2) g2 = addEdge(g2, 2, 3) print("Yes" if isSC(g2, 4) else "No") # This code is contributed by mohit kumar 29 Yes No Time Complexity: Time complexity of above implementation is same as Breadth First Search which is O(V+E) if the graph is represented using adjacency matrix representation. Can we improve further? The above approach requires two traversals of graph. We can find whether a graph is strongly connected or not in one traversal using Tarjan’s Algorithm to find Strongly Connected Components. This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. mohit kumar 29 anikaseth98 akshaysingh98088 simmytarika5 surinderdawra388 hardikkoriintern graph-connectivity Graph Graph 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": 375, "s": 54, "text": "Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pairs of vertices. There are different methods to check the connectivity of directed graph but one of the optimized method is Kosaraju’s DFS based simple algorithm. " }, { "code": null, "e": 475, "s": 375, "text": "Kosaraju’s BFS based simple algorithm also work on the same principle as DFS based algorithm does. " }, { "code": null, "e": 1063, "s": 475, "text": "Following is Kosaraju’s BFS based simple algorithm\nthat does two BFS traversals of graph:\n1) Initialize all vertices as not visited.\n\n2) Do a BFS traversal of graph starting from \n any arbitrary vertex v. If BFS traversal \n doesn’t visit all vertices, then return false.\n\n3) Reverse all edges (or find transpose or reverse \n of graph)\n\n4) Mark all vertices as not visited in reversed graph.\n\n5) Again do a BFS traversal of reversed graph starting\n from same vertex v (Same as step 2). If BFS traversal\n doesn’t visit all vertices, then return false. \n Otherwise, return true." }, { "code": null, "e": 1426, "s": 1063, "text": "The idea is again simple if every node can be reached from a vertex v, and every node can reach same vertex v, then the graph is strongly connected. In step 2, we check if all vertices are reachable from v. In step 5, we check if all vertices can reach v (In reversed graph, if all vertices are reachable from v, then all vertices can reach v in original graph)." }, { "code": null, "e": 1459, "s": 1426, "text": "Explanation with some examples: " }, { "code": null, "e": 1534, "s": 1459, "text": "Example 1 : Given a directed to check if it is strongly connected or not. " }, { "code": null, "e": 1591, "s": 1534, "text": "step 1: Starting with vertex 2 BFS obtained is 2 3 4 0 1" }, { "code": null, "e": 1653, "s": 1591, "text": "step 2: After reversing the given graph we got listed graph. " }, { "code": null, "e": 1717, "s": 1653, "text": "step 3: Again after starting with vertex 2 the BFS is 2 1 4 0 3" }, { "code": null, "e": 1785, "s": 1717, "text": "step 4: No vertex in both case (step 1 & step 3) remains unvisited." }, { "code": null, "e": 1832, "s": 1785, "text": "step 5: So, given graph is strongly connected." }, { "code": null, "e": 1845, "s": 1832, "text": "Example 2 : " }, { "code": null, "e": 1908, "s": 1845, "text": "Given a directed to check if it is strongly connected or not. " }, { "code": null, "e": 1962, "s": 1908, "text": "step 1: Starting with vertex 2 BFS obtained is 2 3 4 " }, { "code": null, "e": 2024, "s": 1962, "text": "step 2: After reversing the given graph we got listed graph. " }, { "code": null, "e": 2085, "s": 2024, "text": "step 3: Again after starting with vertex 2 the BFS is 2 1 0 " }, { "code": null, "e": 2168, "s": 2085, "text": "step 4: vertex 0, 1 in original graph and 3, 4 in reverse graph remains unvisited." }, { "code": null, "e": 2219, "s": 2168, "text": "step 5: So, given graph is not strongly connected." }, { "code": null, "e": 2272, "s": 2219, "text": "Following is the implementation of above algorithm. " }, { "code": null, "e": 2276, "s": 2272, "text": "C++" }, { "code": null, "e": 2284, "s": 2276, "text": "Python3" }, { "code": "// C++ program to check if a given directed graph// is strongly connected or not with BFS use#include <bits/stdc++.h>using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // An array of adjacency lists // A recursive function to print DFS starting from v void BFSUtil(int v, bool visited[]);public: // Constructor and Destructor Graph(int V) { this->V = V; adj = new list<int>[V];} ~Graph() { delete [] adj; } // Method to add an edge void addEdge(int v, int w); // The main function that returns true if the // graph is strongly connected, otherwise false bool isSC(); // Function that returns reverse (or transpose) // of this graph Graph getTranspose();}; // A recursive function to print DFS starting from vvoid Graph::BFSUtil(int v, bool visited[]){ // Create a queue for BFS list<int> queue; // Mark the current node as visited and enqueue it visited[v] = true; queue.push_back(v); // 'i' will be used to get all adjacent vertices // of a vertex list<int>::iterator i; while (!queue.empty()) { // Dequeue a vertex from queue v = queue.front(); queue.pop_front(); // Get all adjacent vertices of the dequeued vertex s // If a adjacent has not been visited, then mark it // visited and enqueue it for (i = adj[v].begin(); i != adj[v].end(); ++i) { if (!visited[*i]) { visited[*i] = true; queue.push_back(*i); } } }} // Function that returns reverse (or transpose) of this graphGraph Graph::getTranspose(){ Graph g(V); for (int v = 0; v < V; v++) { // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) g.adj[*i].push_back(v); } return g;} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // The main function that returns true if graph// is strongly connectedbool Graph::isSC(){ // Step 1: Mark all the vertices as not // visited (For first BFS) bool visited[V]; for (int i = 0; i < V; i++) visited[i] = false; // Step 2: Do BFS traversal starting // from first vertex. BFSUtil(0, visited); // If BFS traversal doesn’t visit all // vertices, then return false. for (int i = 0; i < V; i++) if (visited[i] == false) return false; // Step 3: Create a reversed graph Graph gr = getTranspose(); // Step 4: Mark all the vertices as not // visited (For second BFS) for(int i = 0; i < V; i++) visited[i] = false; // Step 5: Do BFS for reversed graph // starting from first vertex. // Starting Vertex must be same starting // point of first DFS gr.BFSUtil(0, visited); // If all vertices are not visited in // second DFS, then return false for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver program to test above functionsint main(){ // Create graphs given in the above diagrams Graph g1(5); g1.addEdge(0, 1); g1.addEdge(1, 2); g1.addEdge(2, 3); g1.addEdge(3, 0); g1.addEdge(2, 4); g1.addEdge(4, 2); g1.isSC()? cout << \"Yes\\n\" : cout << \"No\\n\"; Graph g2(4); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.addEdge(2, 3); g2.isSC()? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 5759, "s": 2284, "text": null }, { "code": "# Python3 program to check if a given directed graph# is strongly connected or not with BFS usefrom collections import deque # A recursive function to print DFS starting from vdef BFSUtil(adj, v, visited): # Create a queue for BFS queue = deque() # Mark the current node as visited # and enqueue it visited[v] = True queue.append(v) # 'i' will be used to get all adjacent # vertices of a vertex while (len(queue) > 0): # Dequeue a vertex from queue v = queue.popleft() #print(v) #queue.pop_front() # Get all adjacent vertices of the # dequeued vertex s. If a adjacent # has not been visited, then mark it # visited and enqueue it for i in adj[v]: if (visited[i] == False): visited[i] = True queue.append(i) return visited # Function that returns reverse# (or transpose) of this graphdef getTranspose(adj, V): g = [[] for i in range(V)] for v in range(V): # Recur for all the vertices adjacent to # this vertex # list<int>::iterator i for i in adj[v]: g[i].append(v) return g def addEdge(adj, v, w): # Add w to v’s list. adj[v].append(w) return adj # The main function that returns True if graph# is strongly connecteddef isSC(adj, V): # Step 1: Mark all the vertices as not # visited (For first BFS) visited = [False]*V # Step 2: Do BFS traversal starting # from first vertex. visited = BFSUtil(adj, 0, visited) # print(visited) # If BFS traversal doesn’t visit all # vertices, then return false. for i in range(V): if (visited[i] == False): return False # Step 3: Create a reversed graph adj = getTranspose(adj, V) # Step 4: Mark all the vertices as not # visited (For second BFS) for i in range(V): visited[i] = False # Step 5: Do BFS for reversed graph # starting from first vertex. # Starting Vertex must be same starting # point of first DFS visited = BFSUtil(adj, 0, visited) # If all vertices are not visited in # second DFS, then return false for i in range(V): if (visited[i] == False): return False return True # Driver codeif __name__ == '__main__': # Create graphs given in the above diagrams g1 = [[] for i in range(5)] g1 = addEdge(g1, 0, 1) g1 = addEdge(g1, 1, 2) g1 = addEdge(g1, 2, 3) g1 = addEdge(g1, 3, 0) g1 = addEdge(g1, 2, 4) g1 = addEdge(g1, 4, 2) #print(g1) print(\"Yes\" if isSC(g1, 5) else \"No\") g2 = [[] for i in range(4)] g2 = addEdge(g2, 0, 1) g2 = addEdge(g2, 1, 2) g2 = addEdge(g2, 2, 3) print(\"Yes\" if isSC(g2, 4) else \"No\") # This code is contributed by mohit kumar 29", "e": 8588, "s": 5759, "text": null }, { "code": null, "e": 8595, "s": 8588, "text": "Yes\nNo" }, { "code": null, "e": 8767, "s": 8595, "text": "Time Complexity: Time complexity of above implementation is same as Breadth First Search which is O(V+E) if the graph is represented using adjacency matrix representation." }, { "code": null, "e": 8982, "s": 8767, "text": "Can we improve further? The above approach requires two traversals of graph. We can find whether a graph is strongly connected or not in one traversal using Tarjan’s Algorithm to find Strongly Connected Components." }, { "code": null, "e": 9294, "s": 8982, "text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 9309, "s": 9294, "text": "mohit kumar 29" }, { "code": null, "e": 9321, "s": 9309, "text": "anikaseth98" }, { "code": null, "e": 9338, "s": 9321, "text": "akshaysingh98088" }, { "code": null, "e": 9351, "s": 9338, "text": "simmytarika5" }, { "code": null, "e": 9368, "s": 9351, "text": "surinderdawra388" }, { "code": null, "e": 9385, "s": 9368, "text": "hardikkoriintern" }, { "code": null, "e": 9404, "s": 9385, "text": "graph-connectivity" }, { "code": null, "e": 9410, "s": 9404, "text": "Graph" }, { "code": null, "e": 9416, "s": 9410, "text": "Graph" } ]
Lodash _.fromQuery() Method
30 Sep, 2020 The Lodash _.fromQuery() method is used to convert the given URL Query String into an equivalent JavaScript object. Syntax: _.fromQuery( URL_Query); Parameters: This method accepts a single parameter as mentioned above and described below: URL_Query: This method takes a URL Query String to convert into JavaScript object. Return Value: This method returns the equivalent JavaScript Object. Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib –save. Example 1: Javascript // Defining lodash contrib variable var _ = require('lodash-contrib'); var s = _.fromQuery("https://geeksforgeeks.org/path/to/page?name=ferret&color=purple"); console.log("The generated JavaScript Object is : ", s); Output: The generated JavaScript Object is : Object { color: "purple" , https://geeksforgeeks.org/path/to/page?name: "ferret" } Example 2: Javascript // Defining lodash contrib variable var _ = require('lodash-contrib'); var s = _.fromQuery("https://practice.geeksforgeeks.org/courses/?ref=gfg_header"); console.log("The generated JavaScript Object is : ", s); Output: The generated JavaScript Object is : Object {https://practice.geeksforgeeks.org/courses/?ref: "gfg_header"} JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Lodash _.groupBy() Method JavaScript | Promises Difference Between PUT and PATCH Request Remove elements from a JavaScript Array Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript REST API (Introduction) How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2020" }, { "code": null, "e": 144, "s": 28, "text": "The Lodash _.fromQuery() method is used to convert the given URL Query String into an equivalent JavaScript object." }, { "code": null, "e": 152, "s": 144, "text": "Syntax:" }, { "code": null, "e": 177, "s": 152, "text": "_.fromQuery( URL_Query);" }, { "code": null, "e": 268, "s": 177, "text": "Parameters: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 351, "s": 268, "text": "URL_Query: This method takes a URL Query String to convert into JavaScript object." }, { "code": null, "e": 419, "s": 351, "text": "Return Value: This method returns the equivalent JavaScript Object." }, { "code": null, "e": 615, "s": 419, "text": "Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using npm install lodash-contrib –save." }, { "code": null, "e": 626, "s": 615, "text": "Example 1:" }, { "code": null, "e": 637, "s": 626, "text": "Javascript" }, { "code": "// Defining lodash contrib variable var _ = require('lodash-contrib'); var s = _.fromQuery(\"https://geeksforgeeks.org/path/to/page?name=ferret&color=purple\"); console.log(\"The generated JavaScript Object is : \", s);", "e": 860, "s": 637, "text": null }, { "code": null, "e": 868, "s": 860, "text": "Output:" }, { "code": null, "e": 989, "s": 868, "text": "The generated JavaScript Object is :\nObject {\ncolor: \"purple\" ,\nhttps://geeksforgeeks.org/path/to/page?name: \"ferret\"\n}\n" }, { "code": null, "e": 1000, "s": 989, "text": "Example 2:" }, { "code": null, "e": 1011, "s": 1000, "text": "Javascript" }, { "code": "// Defining lodash contrib variable var _ = require('lodash-contrib'); var s = _.fromQuery(\"https://practice.geeksforgeeks.org/courses/?ref=gfg_header\"); console.log(\"The generated JavaScript Object is : \", s);", "e": 1228, "s": 1011, "text": null }, { "code": null, "e": 1236, "s": 1228, "text": "Output:" }, { "code": null, "e": 1345, "s": 1236, "text": "The generated JavaScript Object is :\nObject {https://practice.geeksforgeeks.org/courses/?ref: \"gfg_header\"}\n" }, { "code": null, "e": 1363, "s": 1345, "text": "JavaScript-Lodash" }, { "code": null, "e": 1374, "s": 1363, "text": "JavaScript" }, { "code": null, "e": 1391, "s": 1374, "text": "Web Technologies" }, { "code": null, "e": 1489, "s": 1391, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1550, "s": 1489, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1576, "s": 1550, "text": "Lodash _.groupBy() Method" }, { "code": null, "e": 1598, "s": 1576, "text": "JavaScript | Promises" }, { "code": null, "e": 1639, "s": 1598, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 1679, "s": 1639, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1712, "s": 1679, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1774, "s": 1712, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1835, "s": 1774, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1859, "s": 1835, "text": "REST API (Introduction)" } ]
Python | Dictionary has_key()
12 Apr, 2022 Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair. Note: has_key() method was removed in Python 3. Use the in operator instead. In Python Dictionary, has_key() method returns true if specified key is present in the dictionary, else returns false. Syntax: dict.has_key(key)Parameters: key – This is the Key to be searched in the dictionary. Returns: Method returns true if a given key is available in the dictionary, otherwise it returns a false. Example #1: Python # Python program to show working# of has_key() method in Dictionary # Dictionary with three itemsDictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # Dictionary to be checkedprint("Dictionary to be checked: ")print(Dictionary1) # Use of has_key() to check# for presence of a key in Dictionaryprint(Dictionary1.has_key('A'))print(Dictionary1.has_key('For')) Output: Dictionary to be checked: {'A': 'Geeks', 'C': 'Geeks', 'B': 'For'} True False Example #2: Python # Python program to show working# of has_key() method in Dictionary # Dictionary with three itemsDictionary2 = {1: 'Welcome', 2: 'To', 3: 'Geeks'} # Dictionary to be checkedprint("Dictionary to be checked: ")print(Dictionary2) # Use of has_key() to check# for presence of a key in Dictionaryprint(Dictionary2.has_key(1))print(Dictionary2.has_key('To')) Output: Dictionary to be checked: {1: 'Welcome', 2: 'To', 3: 'Geeks'} True False Note : dict.has_key() has removed from Python 3.x has_key() has been removed in Python 3. in operator is used to check whether a specified key is present or not in a Dictionary. Example: Python3 # Python Program to search a key in Dictionary# Using in operator dictionary = {1: "Geeks", 2: "For", 3: "Geeks"} print("Dictionary: {}".format(dictionary)) # Return True if Present.if 1 in dictionary: # or "dictionary.keys()" print(dictionary[1])else: print("{} is Absent".format(1)) # Return False if not Present.if 5 in dictionary.keys(): print(dictionary[5])else: print("{} is Absent".format(5)) Output: Dictionary: {1:"Geeks",2:"For",3:"Geeks"} Geeks 5 is Absent Vikku_Sharma victorbitman nagulans python-dict Python-dict-functions Python python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2022" }, { "code": null, "e": 239, "s": 28, "text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair." }, { "code": null, "e": 316, "s": 239, "text": "Note: has_key() method was removed in Python 3. Use the in operator instead." }, { "code": null, "e": 436, "s": 316, "text": "In Python Dictionary, has_key() method returns true if specified key is present in the dictionary, else returns false. " }, { "code": null, "e": 473, "s": 436, "text": "Syntax: dict.has_key(key)Parameters:" }, { "code": null, "e": 529, "s": 473, "text": "key – This is the Key to be searched in the dictionary." }, { "code": null, "e": 635, "s": 529, "text": "Returns: Method returns true if a given key is available in the dictionary, otherwise it returns a false." }, { "code": null, "e": 649, "s": 635, "text": "Example #1: " }, { "code": null, "e": 656, "s": 649, "text": "Python" }, { "code": "# Python program to show working# of has_key() method in Dictionary # Dictionary with three itemsDictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'} # Dictionary to be checkedprint(\"Dictionary to be checked: \")print(Dictionary1) # Use of has_key() to check# for presence of a key in Dictionaryprint(Dictionary1.has_key('A'))print(Dictionary1.has_key('For'))", "e": 1017, "s": 656, "text": null }, { "code": null, "e": 1026, "s": 1017, "text": "Output: " }, { "code": null, "e": 1105, "s": 1026, "text": "Dictionary to be checked: \n{'A': 'Geeks', 'C': 'Geeks', 'B': 'For'}\nTrue\nFalse" }, { "code": null, "e": 1119, "s": 1105, "text": "Example #2: " }, { "code": null, "e": 1126, "s": 1119, "text": "Python" }, { "code": "# Python program to show working# of has_key() method in Dictionary # Dictionary with three itemsDictionary2 = {1: 'Welcome', 2: 'To', 3: 'Geeks'} # Dictionary to be checkedprint(\"Dictionary to be checked: \")print(Dictionary2) # Use of has_key() to check# for presence of a key in Dictionaryprint(Dictionary2.has_key(1))print(Dictionary2.has_key('To'))", "e": 1479, "s": 1126, "text": null }, { "code": null, "e": 1488, "s": 1479, "text": "Output: " }, { "code": null, "e": 1562, "s": 1488, "text": "Dictionary to be checked: \n{1: 'Welcome', 2: 'To', 3: 'Geeks'}\nTrue\nFalse" }, { "code": null, "e": 1612, "s": 1562, "text": "Note : dict.has_key() has removed from Python 3.x" }, { "code": null, "e": 1740, "s": 1612, "text": "has_key() has been removed in Python 3. in operator is used to check whether a specified key is present or not in a Dictionary." }, { "code": null, "e": 1751, "s": 1740, "text": "Example: " }, { "code": null, "e": 1759, "s": 1751, "text": "Python3" }, { "code": "# Python Program to search a key in Dictionary# Using in operator dictionary = {1: \"Geeks\", 2: \"For\", 3: \"Geeks\"} print(\"Dictionary: {}\".format(dictionary)) # Return True if Present.if 1 in dictionary: # or \"dictionary.keys()\" print(dictionary[1])else: print(\"{} is Absent\".format(1)) # Return False if not Present.if 5 in dictionary.keys(): print(dictionary[5])else: print(\"{} is Absent\".format(5))", "e": 2172, "s": 1759, "text": null }, { "code": null, "e": 2181, "s": 2172, "text": "Output: " }, { "code": null, "e": 2242, "s": 2181, "text": "Dictionary: {1:\"Geeks\",2:\"For\",3:\"Geeks\"}\nGeeks\n5 is Absent " }, { "code": null, "e": 2255, "s": 2242, "text": "Vikku_Sharma" }, { "code": null, "e": 2268, "s": 2255, "text": "victorbitman" }, { "code": null, "e": 2277, "s": 2268, "text": "nagulans" }, { "code": null, "e": 2289, "s": 2277, "text": "python-dict" }, { "code": null, "e": 2311, "s": 2289, "text": "Python-dict-functions" }, { "code": null, "e": 2318, "s": 2311, "text": "Python" }, { "code": null, "e": 2330, "s": 2318, "text": "python-dict" } ]
CSS | Display property
28 Jun, 2022 The Display property in CSS defines how the components(div, hyperlink, heading, etc) are going to be placed on the web page. As the name suggests, this property is used to define the display of the different parts of a web page. Syntax: display: value; Property values Few important values are described below with the example.Block: This property is used as the default property of div. This property places the div one after another vertically. The height and width of the div can be changed using the block property if the width is not mentioned, then the div under block property will take up the width of the container.Example: HTML <!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #geeks1{ height: 100px; width: 200px; background: teal; display: block; } #geeks2{ height: 100px; width: 200px; background: cyan; display: block; } #geeks3{ height: 100px; width: 200px; background: green; display: block; } .gfg { margin-left:20px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:30px; } .main { margin:50px; text-align:center; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">display: block; property</div> <div class = "main"> <div id="geeks1">Block 1 </div> <div id="geeks2">Block 2</div> <div id="geeks3">Block 3</div> </div> </body> </html> Output: Inline: This property is the default property of anchor tags. This is used to place the div inline i.e. in a horizontal manner. The inline display property ignores the height and the width set by the user. Example: HTML <!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #main{ height: 200px; width: 200px; background: teal; display: inline; } #main1{ height: 200px; width: 200px; background: cyan; display: inline; } #main2{ height: 200px; width: 200px; background: green; display: inline; } .gfg { margin-left:20px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:30px; } .main { margin:50px; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">display: inline; property</div> <div class = "main"> <div id="main"> BLOCK 1 </div> <div id="main1"> BLOCK 2</div> <div id="main2">BLOCK 3 </div> </div> </body></html> Output: Inline-block: This features uses the both properties mentioned above, block and inline. So, this property aligns the div inline but the difference is it can edit the height and the width of block. Basically, this will align the div both in block and inline fashion.Example: html <!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #main{ height: 100px; width: 200px; background: teal; display: inline-block; } #main1{ height: 100px; width: 200px; background: cyan; display: inline-block; } #main2{ height: 100px; width: 200px; background: green; display: inline-block; } .gfg { margin-left:200px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:210px; } .main { margin:50px; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">display: Inline-block; property</div> <div class = "main"> <div id="main"> BLOCK 1 </div> <div id="main1"> BLOCK 2</div> <div id="main2">BLOCK 3 </div> </div> </body></html> Output: None: This property hides the div or the container which use this property. Using it on one of the div it will make working clear. Example: html <!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #main{ height: 100px; width: 200px; background: teal; display: block; } #main1{ height: 100px; width: 200px; background: cyan; display: none; } #main2{ height: 100px; width: 200px; background: green; display: block; } .gfg { margin-left:20px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:20px; } .main { margin:50px; } </style> </head> <body> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">display: none; property</div> <div class = "main"> <div id="main"> BLOCK 1 </div> <div id="main1"> BLOCK 2</div> <div id="main2">BLOCK 3 </div> </div> </body></html> Output: Supported Browsers: The browsers supported by the Display property are listed below: Google Chrome 1.0 Edge 12.0 Internet Explorer 4.0 Firefox 1.0 Opera 7.0 Safari 1.0 skyridetim geeksr3ap CSS-Properties Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jun, 2022" }, { "code": null, "e": 292, "s": 53, "text": "The Display property in CSS defines how the components(div, hyperlink, heading, etc) are going to be placed on the web page. As the name suggests, this property is used to define the display of the different parts of a web page. Syntax: " }, { "code": null, "e": 308, "s": 292, "text": "display: value;" }, { "code": null, "e": 326, "s": 308, "text": "Property values " }, { "code": null, "e": 692, "s": 326, "text": "Few important values are described below with the example.Block: This property is used as the default property of div. This property places the div one after another vertically. The height and width of the div can be changed using the block property if the width is not mentioned, then the div under block property will take up the width of the container.Example: " }, { "code": null, "e": 697, "s": 692, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #geeks1{ height: 100px; width: 200px; background: teal; display: block; } #geeks2{ height: 100px; width: 200px; background: cyan; display: block; } #geeks3{ height: 100px; width: 200px; background: green; display: block; } .gfg { margin-left:20px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:30px; } .main { margin:50px; text-align:center; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">display: block; property</div> <div class = \"main\"> <div id=\"geeks1\">Block 1 </div> <div id=\"geeks2\">Block 2</div> <div id=\"geeks3\">Block 3</div> </div> </body> </html> ", "e": 1976, "s": 697, "text": null }, { "code": null, "e": 1986, "s": 1976, "text": "Output: " }, { "code": null, "e": 2203, "s": 1986, "text": "Inline: This property is the default property of anchor tags. This is used to place the div inline i.e. in a horizontal manner. The inline display property ignores the height and the width set by the user. Example: " }, { "code": null, "e": 2208, "s": 2203, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #main{ height: 200px; width: 200px; background: teal; display: inline; } #main1{ height: 200px; width: 200px; background: cyan; display: inline; } #main2{ height: 200px; width: 200px; background: green; display: inline; } .gfg { margin-left:20px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:30px; } .main { margin:50px; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">display: inline; property</div> <div class = \"main\"> <div id=\"main\"> BLOCK 1 </div> <div id=\"main1\"> BLOCK 2</div> <div id=\"main2\">BLOCK 3 </div> </div> </body></html> ", "e": 3457, "s": 2208, "text": null }, { "code": null, "e": 3467, "s": 3457, "text": "Output: " }, { "code": null, "e": 3743, "s": 3467, "text": "Inline-block: This features uses the both properties mentioned above, block and inline. So, this property aligns the div inline but the difference is it can edit the height and the width of block. Basically, this will align the div both in block and inline fashion.Example: " }, { "code": null, "e": 3748, "s": 3743, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #main{ height: 100px; width: 200px; background: teal; display: inline-block; } #main1{ height: 100px; width: 200px; background: cyan; display: inline-block; } #main2{ height: 100px; width: 200px; background: green; display: inline-block; } .gfg { margin-left:200px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:210px; } .main { margin:50px; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">display: Inline-block; property</div> <div class = \"main\"> <div id=\"main\"> BLOCK 1 </div> <div id=\"main1\"> BLOCK 2</div> <div id=\"main2\">BLOCK 3 </div> </div> </body></html> ", "e": 5019, "s": 3748, "text": null }, { "code": null, "e": 5029, "s": 5019, "text": "Output: " }, { "code": null, "e": 5171, "s": 5029, "text": "None: This property hides the div or the container which use this property. Using it on one of the div it will make working clear. Example: " }, { "code": null, "e": 5176, "s": 5171, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS | Display property</title> <style> #main{ height: 100px; width: 200px; background: teal; display: block; } #main1{ height: 100px; width: 200px; background: cyan; display: none; } #main2{ height: 100px; width: 200px; background: green; display: block; } .gfg { margin-left:20px; font-size:42px; font-weight:bold; color:#009900; } .geeks { font-size:25px; margin-left:20px; } .main { margin:50px; } </style> </head> <body> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">display: none; property</div> <div class = \"main\"> <div id=\"main\"> BLOCK 1 </div> <div id=\"main1\"> BLOCK 2</div> <div id=\"main2\">BLOCK 3 </div> </div> </body></html> ", "e": 6415, "s": 5176, "text": null }, { "code": null, "e": 6425, "s": 6415, "text": "Output: " }, { "code": null, "e": 6512, "s": 6425, "text": "Supported Browsers: The browsers supported by the Display property are listed below: " }, { "code": null, "e": 6530, "s": 6512, "text": "Google Chrome 1.0" }, { "code": null, "e": 6540, "s": 6530, "text": "Edge 12.0" }, { "code": null, "e": 6562, "s": 6540, "text": "Internet Explorer 4.0" }, { "code": null, "e": 6574, "s": 6562, "text": "Firefox 1.0" }, { "code": null, "e": 6584, "s": 6574, "text": "Opera 7.0" }, { "code": null, "e": 6595, "s": 6584, "text": "Safari 1.0" }, { "code": null, "e": 6608, "s": 6597, "text": "skyridetim" }, { "code": null, "e": 6618, "s": 6608, "text": "geeksr3ap" }, { "code": null, "e": 6633, "s": 6618, "text": "CSS-Properties" }, { "code": null, "e": 6640, "s": 6633, "text": "Picked" }, { "code": null, "e": 6644, "s": 6640, "text": "CSS" }, { "code": null, "e": 6649, "s": 6644, "text": "HTML" }, { "code": null, "e": 6666, "s": 6649, "text": "Web Technologies" }, { "code": null, "e": 6671, "s": 6666, "text": "HTML" }, { "code": null, "e": 6769, "s": 6671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6817, "s": 6769, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 6879, "s": 6817, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6929, "s": 6879, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 6987, "s": 6929, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 7037, "s": 6987, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 7085, "s": 7037, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 7147, "s": 7085, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7197, "s": 7147, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7221, "s": 7197, "text": "REST API (Introduction)" } ]
Trie | (Insert and Search)
25 Jun, 2022 Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to optimal limit (key length). If we store keys in a binary search tree, a well balanced BST will need time proportional to M * log N, where M is the maximum string length and N is the number of keys in the tree. Using Trie, we can search the key in O(M) time. However, the penalty is on Trie storage requirements (Please refer to Applications of Trie for more details) Every node of Trie consists of multiple branches. Each branch represents a possible character of keys. We need to mark the last node of every key as the end of the word node. A Trie node field isEndOfWord is used to distinguish the node as the end of the word node. A simple structure to represent nodes of the English alphabet can be as follows, // Trie node struct TrieNode { struct TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is true if the node // represents end of a word bool isEndOfWord; }; Inserting a key into Trie is a simple approach. Every character of the input key is inserted as an individual Trie node. Note that the children is an array of pointers (or references) to next level trie nodes. The key character acts as an index to the array children. If the input key is new or an extension of the existing key, we need to construct non-existing nodes of the key, and mark the end of the word for the last node. If the input key is a prefix of the existing key in Trie, we simply mark the last node of the key as the end of a word. The key length determines Trie depth. Searching for a key is similar to an insert operation, however, we only compare the characters and move down. The search can terminate due to the end of a string or lack of key in the trie. In the former case, if the isEndofWord field of the last node is true, then the key exists in the trie. In the second case, the search terminates without examining all the characters of the key, since the key is not present in the trie.The following picture explains the construction of trie using keys given in the example below, root / \ \ t a b | | | h n y | | \ | e s y e / | | i r w | | | r e e | r In the picture, every character is of type trie_node_t. For example, the root is of type trie_node_t, and it’s children a, b and t are filled, all other nodes of root will be NULL. Similarly, “a” at the next level is having only one child (“n”), all other children are NULL. The leaf nodes are in blue. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Insert and search costs O(key_length), however, the memory requirements of Trie is O(ALPHABET_SIZE * key_length * N) where N is the number of keys in Trie. There are efficient representations of trie nodes (e.g. compressed trie, ternary search tree, etc.) to minimize the memory requirements of the trie. C++ C Java Python3 C# Javascript PHP // C++ implementation of search and insert// operations on Trie#include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just// marks leaf nodevoid insert(struct TrieNode *root, string key){ struct TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true;} // Returns true if key presents in trie, else// falsebool search(struct TrieNode *root, string key){ struct TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl->isEndOfWord);} // Driverint main(){ // Input keys (use only 'a' through 'z' // and lower case) string keys[] = {"the", "a", "there", "answer", "any", "by", "bye", "their" }; int n = sizeof(keys)/sizeof(keys[0]); struct TrieNode *root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); // Search for different keys search(root, "the")? cout << "Yes\n" : cout << "No\n"; search(root, "these")? cout << "Yes\n" : cout << "No\n"; search(root, "their")? cout << "Yes\n" : cout << "No\n"; search(root, "thaw")? cout << "Yes\n" : cout << "No\n"; return 0;} // C implementation of search and insert operations// on Trie#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdbool.h> #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = NULL; pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode)); if (pNode) { int i; pNode->isEndOfWord = false; for (i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just marks leaf nodevoid insert(struct TrieNode *root, const char *key){ int level; int length = strlen(key); int index; struct TrieNode *pCrawl = root; for (level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true;} // Returns true if key presents in trie, else falsebool search(struct TrieNode *root, const char *key){ int level; int length = strlen(key); int index; struct TrieNode *pCrawl = root; for (level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl->isEndOfWord);} // Driverint main(){ // Input keys (use only 'a' through 'z' and lower case) char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; char output[][32] = {"Not present in trie", "Present in trie"}; struct TrieNode *root = getNode(); // Construct trie int i; for (i = 0; i < ARRAY_SIZE(keys); i++) insert(root, keys[i]); // Search for different keys printf("%s --- %s\n", "the", output[search(root, "the")] ); printf("%s --- %s\n", "these", output[search(root, "these")] ); printf("%s --- %s\n", "their", output[search(root, "their")] ); printf("%s --- %s\n", "thaw", output[search(root, "thaw")] ); return 0;} // Java implementation of search and insert operations// on Triepublic class Trie { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word boolean isEndOfWord; TrieNode(){ isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, // just marks leaf node static void insert(String key) { int level; int length = key.length(); int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true; } // Returns true if key presents in trie, else false static boolean search(String key) { int level; int length = key.length(); int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl.isEndOfWord); } // Driver public static void main(String args[]) { // Input keys (use only 'a' through 'z' and lower case) String keys[] = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; String output[] = {"Not present in trie", "Present in trie"}; root = new TrieNode(); // Construct trie int i; for (i = 0; i < keys.length ; i++) insert(keys[i]); // Search for different keys if(search("the") == true) System.out.println("the --- " + output[1]); else System.out.println("the --- " + output[0]); if(search("these") == true) System.out.println("these --- " + output[1]); else System.out.println("these --- " + output[0]); if(search("their") == true) System.out.println("their --- " + output[1]); else System.out.println("their --- " + output[0]); if(search("thaw") == true) System.out.println("thaw --- " + output[1]); else System.out.println("thaw --- " + output[0]); }}// This code is contributed by Sumit Ghosh # Python program for insert and search# operation in a Trie class TrieNode: # Trie node class def __init__(self): self.children = [None]*26 # isEndOfWord is True if node represent the end of the word self.isEndOfWord = False class Trie: # Trie data structure class def __init__(self): self.root = self.getNode() def getNode(self): # Returns new trie node (initialized to NULLs) return TrieNode() def _charToIndex(self,ch): # private helper function # Converts key current character into index # use only 'a' through 'z' and lower case return ord(ch)-ord('a') def insert(self,key): # If not present, inserts key into trie # If the key is prefix of trie node, # just marks leaf node pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) # if current character is not present if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] # mark last node as leaf pCrawl.isEndOfWord = True def search(self, key): # Search key in the trie # Returns true if key presents # in trie, else false pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl.isEndOfWord # driver functiondef main(): # Input keys (use only 'a' through 'z' and lower case) keys = ["the","a","there","anaswe","any", "by","their"] output = ["Not present in trie", "Present in trie"] # Trie object t = Trie() # Construct trie for key in keys: t.insert(key) # Search for different keys print("{} ---- {}".format("the",output[t.search("the")])) print("{} ---- {}".format("these",output[t.search("these")])) print("{} ---- {}".format("their",output[t.search("their")])) print("{} ---- {}".format("thaw",output[t.search("thaw")])) if __name__ == '__main__': main() # This code is contributed by Atul Kumar (www.facebook.com/atul.kr.007) // C# implementation of search and // insert operations on Trieusing System; public class Trie { // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // trie node class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word public bool isEndOfWord; public TrieNode() { isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, // just marks leaf node static void insert(String key) { int level; int length = key.Length; int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true; } // Returns true if key // presents in trie, else false static bool search(String key) { int level; int length = key.Length; int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key[level] - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl.isEndOfWord); } // Driver public static void Main() { // Input keys (use only 'a' // through 'z' and lower case) String []keys = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; String []output = {"Not present in trie", "Present in trie"}; root = new TrieNode(); // Construct trie int i; for (i = 0; i < keys.Length ; i++) insert(keys[i]); // Search for different keys if(search("the") == true) Console.WriteLine("the --- " + output[1]); else Console.WriteLine("the --- " + output[0]); if(search("these") == true) Console.WriteLine("these --- " + output[1]); else Console.WriteLine("these --- " + output[0]); if(search("their") == true) Console.WriteLine("their --- " + output[1]); else Console.WriteLine("their --- " + output[0]); if(search("thaw") == true) Console.WriteLine("thaw --- " + output[1]); else Console.WriteLine("thaw --- " + output[0]); }} /* This code contributed by PrinciRaj1992 */ <script>// Javascript implementation of search and insert operations// on Trie // Alphabet size (# of symbols)let ALPHABET_SIZE = 26; // trie nodeclass TrieNode{ constructor() { this.isEndOfWord = false; this.children = new Array(ALPHABET_SIZE); for (let i = 0; i < ALPHABET_SIZE; i++) this.children[i] = null; }} let root; // If not present, inserts key into trie // If the key is prefix of trie node, // just marks leaf nodefunction insert(key){ let level; let length = key.length; let index; let pCrawl = root; for (level = 0; level < length; level++) { index = key[level].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true;} // Returns true if key presents in trie, else falsefunction search(key){ let level; let length = key.length; let index; let pCrawl = root; for (level = 0; level < length; level++) { index = key[level].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl.isEndOfWord);} // Driver // Input keys (use only 'a' through 'z' and lower case)let keys = ["the", "a", "there", "answer", "any", "by", "bye", "their"]; let output = ["Not present in trie", "Present in trie"]; root = new TrieNode(); // Construct trielet i;for (i = 0; i < keys.length ; i++) insert(keys[i]); // Search for different keysif(search("the") == true) document.write("the --- " + output[1]+"<br>");else document.write("the --- " + output[0]+"<br>"); if(search("these") == true) document.write("these --- " + output[1]+"<br>");else document.write("these --- " + output[0]+"<br>"); if(search("their") == true) document.write("their --- " + output[1]+"<br>");else document.write("their --- " + output[0]+"<br>"); if(search("thaw") == true) document.write("thaw --- " + output[1]+"<br>");else document.write("thaw --- " + output[0]+"<br>"); // This code is contributed by patel2127</script> <?php# PHP program for insert and search operation in a Trie# Trie node classclass TrieNode { public $isEnd = false; public $children = [];} class Trie { # Trie data structure class public $node = null; //Initializing trie public function __construct() { $this->node = new TrieNode(); } // Inserts a word into the trie. public function insert($word) { $count = strlen($word); $node = $this->node; for ($i = 0; $i < $count; $i++) { $char = $word[$i]; if (array_key_exists($char, $node->children)) { $node = $node->children[$char]; continue; } $node->children[$char] = new TrieNode(); $node = $node->children[$char]; } $node->isEnd = true; } // Returns if the word is in the trie. public function search($word): bool { $count = strlen($word); $node = $this->node; for ($i = 0; $i < $count; $i++) { $char = $word[$i]; if (!array_key_exists($char, $node->children)) { return false; } $node = $node->children[$char]; } return $node->isEnd; } } $keys = array("the","a","there","answer","any","by","their"); # Trie object $t = new Trie(); # Constructing trie foreach ($keys as $key) { $t->insert($key); } # Searching different words print ($t->search("the")==1)?("Yes"):("No"); echo(' '); print ($t->search("this")==1)?("Yes"):("No"); echo(' '); print ($t->search("they")==1)?("Yes"):("No"); echo(' '); print ($t->search("thaw")==1)?("Yes"):("No"); # This code is contributed by Sajal Aggarwal. ?> Output : the --- Present in trie these --- Not present in trie their --- Present in trie thaw --- Not present in trie NOTE : In video, isEndOfWord is referred as isLeaf.Related Articles: Trie Delete Displaying content of Trie Applications of Trie Auto-complete feature using Trie Minimum Word Break Sorting array of strings (or words) using Trie Pattern Searching using a Trie of all Suffixes Practice Problems : Trie Search and InsertTrie DeleteUnique rows in a binary matrixCount of distinct substringsWord Boggle Trie Search and Insert Trie Delete Unique rows in a binary matrix Count of distinct substrings Word Boggle Recent Articles on TrieThis article is contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 jarretchng02 jeetkaria patel2127 amartyaghoshgfg kiriti93 aggarwalsajal19 Amazon D-E-Shaw FactSet Trie Advanced Data Structure Amazon D-E-Shaw FactSet Trie Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. AVL Tree | Set 1 (Insertion) LRU Cache Implementation Introduction of B-Tree Agents in Artificial Intelligence Red-Black Tree | Set 1 (Introduction) Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) AVL Tree | Set 2 (Deletion) Disjoint Set Data Structures Difference between B tree and B+ tree
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jun, 2022" }, { "code": null, "e": 531, "s": 54, "text": "Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to optimal limit (key length). If we store keys in a binary search tree, a well balanced BST will need time proportional to M * log N, where M is the maximum string length and N is the number of keys in the tree. Using Trie, we can search the key in O(M) time. However, the penalty is on Trie storage requirements (Please refer to Applications of Trie for more details) " }, { "code": null, "e": 1643, "s": 531, "text": "Every node of Trie consists of multiple branches. Each branch represents a possible character of keys. We need to mark the last node of every key as the end of the word node. A Trie node field isEndOfWord is used to distinguish the node as the end of the word node. A simple structure to represent nodes of the English alphabet can be as follows, // Trie node struct TrieNode { struct TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is true if the node // represents end of a word bool isEndOfWord; }; Inserting a key into Trie is a simple approach. Every character of the input key is inserted as an individual Trie node. Note that the children is an array of pointers (or references) to next level trie nodes. The key character acts as an index to the array children. If the input key is new or an extension of the existing key, we need to construct non-existing nodes of the key, and mark the end of the word for the last node. If the input key is a prefix of the existing key in Trie, we simply mark the last node of the key as the end of a word. The key length determines Trie depth. " }, { "code": null, "e": 2166, "s": 1643, "text": "Searching for a key is similar to an insert operation, however, we only compare the characters and move down. The search can terminate due to the end of a string or lack of key in the trie. In the former case, if the isEndofWord field of the last node is true, then the key exists in the trie. In the second case, the search terminates without examining all the characters of the key, since the key is not present in the trie.The following picture explains the construction of trie using keys given in the example below, " }, { "code": null, "e": 2541, "s": 2166, "text": " root\n / \\ \\\n t a b\n | | |\n h n y\n | | \\ |\n e s y e\n / | |\n i r w\n | | |\n r e e\n |\n r" }, { "code": null, "e": 2845, "s": 2541, "text": "In the picture, every character is of type trie_node_t. For example, the root is of type trie_node_t, and it’s children a, b and t are filled, all other nodes of root will be NULL. Similarly, “a” at the next level is having only one child (“n”), all other children are NULL. The leaf nodes are in blue. " }, { "code": null, "e": 2854, "s": 2845, "text": "Chapters" }, { "code": null, "e": 2881, "s": 2854, "text": "descriptions off, selected" }, { "code": null, "e": 2931, "s": 2881, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 2954, "s": 2931, "text": "captions off, selected" }, { "code": null, "e": 2962, "s": 2954, "text": "English" }, { "code": null, "e": 2986, "s": 2962, "text": "This is a modal window." }, { "code": null, "e": 3055, "s": 2986, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 3077, "s": 3055, "text": "End of dialog window." }, { "code": null, "e": 3383, "s": 3077, "text": "Insert and search costs O(key_length), however, the memory requirements of Trie is O(ALPHABET_SIZE * key_length * N) where N is the number of keys in Trie. There are efficient representations of trie nodes (e.g. compressed trie, ternary search tree, etc.) to minimize the memory requirements of the trie. " }, { "code": null, "e": 3389, "s": 3385, "text": "C++" }, { "code": null, "e": 3391, "s": 3389, "text": "C" }, { "code": null, "e": 3396, "s": 3391, "text": "Java" }, { "code": null, "e": 3404, "s": 3396, "text": "Python3" }, { "code": null, "e": 3407, "s": 3404, "text": "C#" }, { "code": null, "e": 3418, "s": 3407, "text": "Javascript" }, { "code": null, "e": 3422, "s": 3418, "text": "PHP" }, { "code": "// C++ implementation of search and insert// operations on Trie#include <bits/stdc++.h>using namespace std; const int ALPHABET_SIZE = 26; // trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just// marks leaf nodevoid insert(struct TrieNode *root, string key){ struct TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true;} // Returns true if key presents in trie, else// falsebool search(struct TrieNode *root, string key){ struct TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl->isEndOfWord);} // Driverint main(){ // Input keys (use only 'a' through 'z' // and lower case) string keys[] = {\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\" }; int n = sizeof(keys)/sizeof(keys[0]); struct TrieNode *root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, keys[i]); // Search for different keys search(root, \"the\")? cout << \"Yes\\n\" : cout << \"No\\n\"; search(root, \"these\")? cout << \"Yes\\n\" : cout << \"No\\n\"; search(root, \"their\")? cout << \"Yes\\n\" : cout << \"No\\n\"; search(root, \"thaw\")? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 5570, "s": 3422, "text": null }, { "code": "// C implementation of search and insert operations// on Trie#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdbool.h> #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) // Alphabet size (# of symbols)#define ALPHABET_SIZE (26) // Converts key current character into index// use only 'a' through 'z' and lower case#define CHAR_TO_INDEX(c) ((int)c - (int)'a') // trie nodestruct TrieNode{ struct TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord;}; // Returns new trie node (initialized to NULLs)struct TrieNode *getNode(void){ struct TrieNode *pNode = NULL; pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode)); if (pNode) { int i; pNode->isEndOfWord = false; for (i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode;} // If not present, inserts key into trie// If the key is prefix of trie node, just marks leaf nodevoid insert(struct TrieNode *root, const char *key){ int level; int length = strlen(key); int index; struct TrieNode *pCrawl = root; for (level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true;} // Returns true if key presents in trie, else falsebool search(struct TrieNode *root, const char *key){ int level; int length = strlen(key); int index; struct TrieNode *pCrawl = root; for (level = 0; level < length; level++) { index = CHAR_TO_INDEX(key[level]); if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl->isEndOfWord);} // Driverint main(){ // Input keys (use only 'a' through 'z' and lower case) char keys[][8] = {\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\"}; char output[][32] = {\"Not present in trie\", \"Present in trie\"}; struct TrieNode *root = getNode(); // Construct trie int i; for (i = 0; i < ARRAY_SIZE(keys); i++) insert(root, keys[i]); // Search for different keys printf(\"%s --- %s\\n\", \"the\", output[search(root, \"the\")] ); printf(\"%s --- %s\\n\", \"these\", output[search(root, \"these\")] ); printf(\"%s --- %s\\n\", \"their\", output[search(root, \"their\")] ); printf(\"%s --- %s\\n\", \"thaw\", output[search(root, \"thaw\")] ); return 0;}", "e": 8157, "s": 5570, "text": null }, { "code": "// Java implementation of search and insert operations// on Triepublic class Trie { // Alphabet size (# of symbols) static final int ALPHABET_SIZE = 26; // trie node static class TrieNode { TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word boolean isEndOfWord; TrieNode(){ isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, // just marks leaf node static void insert(String key) { int level; int length = key.length(); int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true; } // Returns true if key presents in trie, else false static boolean search(String key) { int level; int length = key.length(); int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key.charAt(level) - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl.isEndOfWord); } // Driver public static void main(String args[]) { // Input keys (use only 'a' through 'z' and lower case) String keys[] = {\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\"}; String output[] = {\"Not present in trie\", \"Present in trie\"}; root = new TrieNode(); // Construct trie int i; for (i = 0; i < keys.length ; i++) insert(keys[i]); // Search for different keys if(search(\"the\") == true) System.out.println(\"the --- \" + output[1]); else System.out.println(\"the --- \" + output[0]); if(search(\"these\") == true) System.out.println(\"these --- \" + output[1]); else System.out.println(\"these --- \" + output[0]); if(search(\"their\") == true) System.out.println(\"their --- \" + output[1]); else System.out.println(\"their --- \" + output[0]); if(search(\"thaw\") == true) System.out.println(\"thaw --- \" + output[1]); else System.out.println(\"thaw --- \" + output[0]); }}// This code is contributed by Sumit Ghosh", "e": 11055, "s": 8157, "text": null }, { "code": "# Python program for insert and search# operation in a Trie class TrieNode: # Trie node class def __init__(self): self.children = [None]*26 # isEndOfWord is True if node represent the end of the word self.isEndOfWord = False class Trie: # Trie data structure class def __init__(self): self.root = self.getNode() def getNode(self): # Returns new trie node (initialized to NULLs) return TrieNode() def _charToIndex(self,ch): # private helper function # Converts key current character into index # use only 'a' through 'z' and lower case return ord(ch)-ord('a') def insert(self,key): # If not present, inserts key into trie # If the key is prefix of trie node, # just marks leaf node pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) # if current character is not present if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] # mark last node as leaf pCrawl.isEndOfWord = True def search(self, key): # Search key in the trie # Returns true if key presents # in trie, else false pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl.isEndOfWord # driver functiondef main(): # Input keys (use only 'a' through 'z' and lower case) keys = [\"the\",\"a\",\"there\",\"anaswe\",\"any\", \"by\",\"their\"] output = [\"Not present in trie\", \"Present in trie\"] # Trie object t = Trie() # Construct trie for key in keys: t.insert(key) # Search for different keys print(\"{} ---- {}\".format(\"the\",output[t.search(\"the\")])) print(\"{} ---- {}\".format(\"these\",output[t.search(\"these\")])) print(\"{} ---- {}\".format(\"their\",output[t.search(\"their\")])) print(\"{} ---- {}\".format(\"thaw\",output[t.search(\"thaw\")])) if __name__ == '__main__': main() # This code is contributed by Atul Kumar (www.facebook.com/atul.kr.007)", "e": 13445, "s": 11055, "text": null }, { "code": "// C# implementation of search and // insert operations on Trieusing System; public class Trie { // Alphabet size (# of symbols) static readonly int ALPHABET_SIZE = 26; // trie node class TrieNode { public TrieNode[] children = new TrieNode[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word public bool isEndOfWord; public TrieNode() { isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) children[i] = null; } }; static TrieNode root; // If not present, inserts key into trie // If the key is prefix of trie node, // just marks leaf node static void insert(String key) { int level; int length = key.Length; int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key[level] - 'a'; if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true; } // Returns true if key // presents in trie, else false static bool search(String key) { int level; int length = key.Length; int index; TrieNode pCrawl = root; for (level = 0; level < length; level++) { index = key[level] - 'a'; if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl.isEndOfWord); } // Driver public static void Main() { // Input keys (use only 'a' // through 'z' and lower case) String []keys = {\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\"}; String []output = {\"Not present in trie\", \"Present in trie\"}; root = new TrieNode(); // Construct trie int i; for (i = 0; i < keys.Length ; i++) insert(keys[i]); // Search for different keys if(search(\"the\") == true) Console.WriteLine(\"the --- \" + output[1]); else Console.WriteLine(\"the --- \" + output[0]); if(search(\"these\") == true) Console.WriteLine(\"these --- \" + output[1]); else Console.WriteLine(\"these --- \" + output[0]); if(search(\"their\") == true) Console.WriteLine(\"their --- \" + output[1]); else Console.WriteLine(\"their --- \" + output[0]); if(search(\"thaw\") == true) Console.WriteLine(\"thaw --- \" + output[1]); else Console.WriteLine(\"thaw --- \" + output[0]); }} /* This code contributed by PrinciRaj1992 */", "e": 16347, "s": 13445, "text": null }, { "code": "<script>// Javascript implementation of search and insert operations// on Trie // Alphabet size (# of symbols)let ALPHABET_SIZE = 26; // trie nodeclass TrieNode{ constructor() { this.isEndOfWord = false; this.children = new Array(ALPHABET_SIZE); for (let i = 0; i < ALPHABET_SIZE; i++) this.children[i] = null; }} let root; // If not present, inserts key into trie // If the key is prefix of trie node, // just marks leaf nodefunction insert(key){ let level; let length = key.length; let index; let pCrawl = root; for (level = 0; level < length; level++) { index = key[level].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) pCrawl.children[index] = new TrieNode(); pCrawl = pCrawl.children[index]; } // mark last node as leaf pCrawl.isEndOfWord = true;} // Returns true if key presents in trie, else falsefunction search(key){ let level; let length = key.length; let index; let pCrawl = root; for (level = 0; level < length; level++) { index = key[level].charCodeAt(0) - 'a'.charCodeAt(0); if (pCrawl.children[index] == null) return false; pCrawl = pCrawl.children[index]; } return (pCrawl.isEndOfWord);} // Driver // Input keys (use only 'a' through 'z' and lower case)let keys = [\"the\", \"a\", \"there\", \"answer\", \"any\", \"by\", \"bye\", \"their\"]; let output = [\"Not present in trie\", \"Present in trie\"]; root = new TrieNode(); // Construct trielet i;for (i = 0; i < keys.length ; i++) insert(keys[i]); // Search for different keysif(search(\"the\") == true) document.write(\"the --- \" + output[1]+\"<br>\");else document.write(\"the --- \" + output[0]+\"<br>\"); if(search(\"these\") == true) document.write(\"these --- \" + output[1]+\"<br>\");else document.write(\"these --- \" + output[0]+\"<br>\"); if(search(\"their\") == true) document.write(\"their --- \" + output[1]+\"<br>\");else document.write(\"their --- \" + output[0]+\"<br>\"); if(search(\"thaw\") == true) document.write(\"thaw --- \" + output[1]+\"<br>\");else document.write(\"thaw --- \" + output[0]+\"<br>\"); // This code is contributed by patel2127</script>", "e": 18740, "s": 16347, "text": null }, { "code": "<?php# PHP program for insert and search operation in a Trie# Trie node classclass TrieNode { public $isEnd = false; public $children = [];} class Trie { # Trie data structure class public $node = null; //Initializing trie public function __construct() { $this->node = new TrieNode(); } // Inserts a word into the trie. public function insert($word) { $count = strlen($word); $node = $this->node; for ($i = 0; $i < $count; $i++) { $char = $word[$i]; if (array_key_exists($char, $node->children)) { $node = $node->children[$char]; continue; } $node->children[$char] = new TrieNode(); $node = $node->children[$char]; } $node->isEnd = true; } // Returns if the word is in the trie. public function search($word): bool { $count = strlen($word); $node = $this->node; for ($i = 0; $i < $count; $i++) { $char = $word[$i]; if (!array_key_exists($char, $node->children)) { return false; } $node = $node->children[$char]; } return $node->isEnd; } } $keys = array(\"the\",\"a\",\"there\",\"answer\",\"any\",\"by\",\"their\"); # Trie object $t = new Trie(); # Constructing trie foreach ($keys as $key) { $t->insert($key); } # Searching different words print ($t->search(\"the\")==1)?(\"Yes\"):(\"No\"); echo(' '); print ($t->search(\"this\")==1)?(\"Yes\"):(\"No\"); echo(' '); print ($t->search(\"they\")==1)?(\"Yes\"):(\"No\"); echo(' '); print ($t->search(\"thaw\")==1)?(\"Yes\"):(\"No\"); # This code is contributed by Sajal Aggarwal. ?>", "e": 20477, "s": 18740, "text": null }, { "code": null, "e": 20486, "s": 20477, "text": "Output :" }, { "code": null, "e": 20595, "s": 20486, "text": "the --- Present in trie\nthese --- Not present in trie\ntheir --- Present in trie\nthaw --- Not present in trie" }, { "code": null, "e": 20668, "s": 20597, "text": "NOTE : In video, isEndOfWord is referred as isLeaf.Related Articles: " }, { "code": null, "e": 20680, "s": 20668, "text": "Trie Delete" }, { "code": null, "e": 20707, "s": 20680, "text": "Displaying content of Trie" }, { "code": null, "e": 20728, "s": 20707, "text": "Applications of Trie" }, { "code": null, "e": 20761, "s": 20728, "text": "Auto-complete feature using Trie" }, { "code": null, "e": 20780, "s": 20761, "text": "Minimum Word Break" }, { "code": null, "e": 20827, "s": 20780, "text": "Sorting array of strings (or words) using Trie" }, { "code": null, "e": 20874, "s": 20827, "text": "Pattern Searching using a Trie of all Suffixes" }, { "code": null, "e": 20896, "s": 20874, "text": "Practice Problems : " }, { "code": null, "e": 20999, "s": 20896, "text": "Trie Search and InsertTrie DeleteUnique rows in a binary matrixCount of distinct substringsWord Boggle" }, { "code": null, "e": 21022, "s": 20999, "text": "Trie Search and Insert" }, { "code": null, "e": 21034, "s": 21022, "text": "Trie Delete" }, { "code": null, "e": 21065, "s": 21034, "text": "Unique rows in a binary matrix" }, { "code": null, "e": 21094, "s": 21065, "text": "Count of distinct substrings" }, { "code": null, "e": 21106, "s": 21094, "text": "Word Boggle" }, { "code": null, "e": 21293, "s": 21106, "text": "Recent Articles on TrieThis article is contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 21309, "s": 21295, "text": "princiraj1992" }, { "code": null, "e": 21322, "s": 21309, "text": "jarretchng02" }, { "code": null, "e": 21332, "s": 21322, "text": "jeetkaria" }, { "code": null, "e": 21342, "s": 21332, "text": "patel2127" }, { "code": null, "e": 21358, "s": 21342, "text": "amartyaghoshgfg" }, { "code": null, "e": 21367, "s": 21358, "text": "kiriti93" }, { "code": null, "e": 21383, "s": 21367, "text": "aggarwalsajal19" }, { "code": null, "e": 21390, "s": 21383, "text": "Amazon" }, { "code": null, "e": 21399, "s": 21390, "text": "D-E-Shaw" }, { "code": null, "e": 21407, "s": 21399, "text": "FactSet" }, { "code": null, "e": 21412, "s": 21407, "text": "Trie" }, { "code": null, "e": 21436, "s": 21412, "text": "Advanced Data Structure" }, { "code": null, "e": 21443, "s": 21436, "text": "Amazon" }, { "code": null, "e": 21452, "s": 21443, "text": "D-E-Shaw" }, { "code": null, "e": 21460, "s": 21452, "text": "FactSet" }, { "code": null, "e": 21465, "s": 21460, "text": "Trie" }, { "code": null, "e": 21563, "s": 21465, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21592, "s": 21563, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 21617, "s": 21592, "text": "LRU Cache Implementation" }, { "code": null, "e": 21640, "s": 21617, "text": "Introduction of B-Tree" }, { "code": null, "e": 21674, "s": 21640, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 21712, "s": 21674, "text": "Red-Black Tree | Set 1 (Introduction)" }, { "code": null, "e": 21752, "s": 21712, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 21794, "s": 21752, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 21822, "s": 21794, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 21851, "s": 21822, "text": "Disjoint Set Data Structures" } ]
Python - Tkinter Canvas
The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas. Here is the simple syntax to create this widget − w = Canvas ( master, option=value, ... ) master − This represents the parent window. master − This represents the parent window. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. bd Border width in pixels. Default is 2. bg Normal background color. confine If true (the default), the canvas cannot be scrolled outside of the scrollregion. cursor Cursor used in the canvas like arrow, circle, dot etc. height Size of the canvas in the Y dimension. highlightcolor Color shown in the focus highlight. relief Relief specifies the type of the border. Some of the values are SUNKEN, RAISED, GROOVE, and RIDGE. scrollregion A tuple (w, n, e, s) that defines over how large an area the canvas can be scrolled, where w is the left side, n the top, e the right side, and s the bottom. width Size of the canvas in the X dimension. xscrollincrement If you set this option to some positive dimension, the canvas can be positioned only on multiples of that distance, and the value will be used for scrolling by scrolling units, such as when the user clicks on the arrows at the ends of a scrollbar. xscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the horizontal scrollbar. yscrollincrement Works like xscrollincrement, but governs vertical movement. yscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the vertical scrollbar. The Canvas widget can support the following standard items − arc − Creates an arc item, which can be a chord, a pieslice or a simple arc. coord = 10, 50, 240, 210 arc = canvas.create_arc(coord, start=0, extent=150, fill="blue") image − Creates an image item, which can be an instance of either the BitmapImage or the PhotoImage classes. filename = PhotoImage(file = "sunshine.gif") image = canvas.create_image(50, 50, anchor=NE, image=filename) line − Creates a line item. line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, options) oval − Creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval. oval = canvas.create_oval(x0, y0, x1, y1, options) polygon − Creates a polygon item that must have at least three vertices. oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options) Try the following example yourself − import Tkinter top = Tkinter.Tk() C = Tkinter.Canvas(top, bg="blue", height=250, width=300) coord = 10, 50, 240, 210 arc = C.create_arc(coord, start=0, extent=150, fill="red") C.pack() top.mainloop() When the above code is executed, it produces the following result −
[ { "code": null, "e": 2528, "s": 2378, "text": "The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets or frames on a Canvas." }, { "code": null, "e": 2578, "s": 2528, "text": "Here is the simple syntax to create this widget −" }, { "code": null, "e": 2620, "s": 2578, "text": "w = Canvas ( master, option=value, ... )\n" }, { "code": null, "e": 2664, "s": 2620, "text": "master − This represents the parent window." }, { "code": null, "e": 2708, "s": 2664, "text": "master − This represents the parent window." }, { "code": null, "e": 2848, "s": 2708, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 2988, "s": 2848, "text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas." }, { "code": null, "e": 2991, "s": 2988, "text": "bd" }, { "code": null, "e": 3029, "s": 2991, "text": "Border width in pixels. Default is 2." }, { "code": null, "e": 3032, "s": 3029, "text": "bg" }, { "code": null, "e": 3057, "s": 3032, "text": "Normal background color." }, { "code": null, "e": 3065, "s": 3057, "text": "confine" }, { "code": null, "e": 3147, "s": 3065, "text": "If true (the default), the canvas cannot be scrolled outside of the scrollregion." }, { "code": null, "e": 3154, "s": 3147, "text": "cursor" }, { "code": null, "e": 3209, "s": 3154, "text": "Cursor used in the canvas like arrow, circle, dot etc." }, { "code": null, "e": 3216, "s": 3209, "text": "height" }, { "code": null, "e": 3255, "s": 3216, "text": "Size of the canvas in the Y dimension." }, { "code": null, "e": 3270, "s": 3255, "text": "highlightcolor" }, { "code": null, "e": 3306, "s": 3270, "text": "Color shown in the focus highlight." }, { "code": null, "e": 3313, "s": 3306, "text": "relief" }, { "code": null, "e": 3412, "s": 3313, "text": "Relief specifies the type of the border. Some of the values are SUNKEN, RAISED, GROOVE, and RIDGE." }, { "code": null, "e": 3425, "s": 3412, "text": "scrollregion" }, { "code": null, "e": 3583, "s": 3425, "text": "A tuple (w, n, e, s) that defines over how large an area the canvas can be scrolled, where w is the left side, n the top, e the right side, and s the bottom." }, { "code": null, "e": 3589, "s": 3583, "text": "width" }, { "code": null, "e": 3628, "s": 3589, "text": "Size of the canvas in the X dimension." }, { "code": null, "e": 3645, "s": 3628, "text": "xscrollincrement" }, { "code": null, "e": 3893, "s": 3645, "text": "If you set this option to some positive dimension, the canvas can be positioned only on multiples of that distance, and the value will be used for scrolling by scrolling units, such as when the user clicks on the arrows at the ends of a scrollbar." }, { "code": null, "e": 3908, "s": 3893, "text": "xscrollcommand" }, { "code": null, "e": 4009, "s": 3908, "text": "If the canvas is scrollable, this attribute should be the .set() method of the horizontal scrollbar." }, { "code": null, "e": 4026, "s": 4009, "text": "yscrollincrement" }, { "code": null, "e": 4086, "s": 4026, "text": "Works like xscrollincrement, but governs vertical movement." }, { "code": null, "e": 4101, "s": 4086, "text": "yscrollcommand" }, { "code": null, "e": 4200, "s": 4101, "text": "If the canvas is scrollable, this attribute should be the .set() method of the vertical scrollbar." }, { "code": null, "e": 4261, "s": 4200, "text": "The Canvas widget can support the following standard items −" }, { "code": null, "e": 4338, "s": 4261, "text": "arc − Creates an arc item, which can be a chord, a pieslice or a simple arc." }, { "code": null, "e": 4429, "s": 4338, "text": "coord = 10, 50, 240, 210\narc = canvas.create_arc(coord, start=0, extent=150, fill=\"blue\")\n" }, { "code": null, "e": 4538, "s": 4429, "text": "image − Creates an image item, which can be an instance of either the BitmapImage or the PhotoImage classes." }, { "code": null, "e": 4647, "s": 4538, "text": "filename = PhotoImage(file = \"sunshine.gif\")\nimage = canvas.create_image(50, 50, anchor=NE, image=filename)\n" }, { "code": null, "e": 4675, "s": 4647, "text": "line − Creates a line item." }, { "code": null, "e": 4740, "s": 4675, "text": "line = canvas.create_line(x0, y0, x1, y1, ..., xn, yn, options)\n" }, { "code": null, "e": 4917, "s": 4740, "text": "oval − Creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval." }, { "code": null, "e": 4969, "s": 4917, "text": "oval = canvas.create_oval(x0, y0, x1, y1, options)\n" }, { "code": null, "e": 5042, "s": 4969, "text": "polygon − Creates a polygon item that must have at least three vertices." }, { "code": null, "e": 5107, "s": 5042, "text": "oval = canvas.create_polygon(x0, y0, x1, y1,...xn, yn, options)\n" }, { "code": null, "e": 5144, "s": 5107, "text": "Try the following example yourself −" }, { "code": null, "e": 5348, "s": 5144, "text": "import Tkinter\n\ntop = Tkinter.Tk()\n\nC = Tkinter.Canvas(top, bg=\"blue\", height=250, width=300)\n\ncoord = 10, 50, 240, 210\narc = C.create_arc(coord, start=0, extent=150, fill=\"red\")\n\nC.pack()\ntop.mainloop()" } ]
Spatial Resolution (down sampling and up sampling) in image processing
12 Dec, 2021 A digital image is a two-dimensional array of size M x N where M is the number of rows and N is the number of columns in the array. A digital image is made up of a finite number of discrete picture elements called a pixel. The location of each pixel is given by coordinates (x, y) and the value of each pixel is given by intensity value f. Hence, the elements in a digital image can be represented by f(x, y). The term spatial resolution corresponds to the total number of pixels in the given image. If the number of pixels is more, then the resolution of the image is more. In the down-sampling technique, the number of pixels in the given image is reduced depending on the sampling frequency. Due to this, the resolution and size of the image decrease. The number of pixels in the down-sampled image can be increased by using up-sampling interpolation techniques. The up-sampling technique increases the resolution as well as the size of the image. Some commonly used up-sampling techniques are Nearest neighbor interpolation Bilinear interpolation Cubic interpolation In this article, we have implemented upsampling using Nearest neighbor interpolation by replicating rows and columns. As the sampling rate increases, artifacts will be seen in the reconstructed image. However, by using bilinear interpolation or cubic interpolation, a better quality of the reconstructed image can be attained. Both Down sampling and Up Sampling can be illustrated in grayscale for better understandings because while reading images using OpenCV, some color values are manipulated, So we are going to convert the original input image into a black and white image. The below program depicts the down sampled and up sampled representation of a given image: Python3 # Import cv2, matplotlib, numpyimport cv2import matplotlib.pyplot as pltimport numpy as np # Read the original image and know its typeimg1 = cv2.imread('g4g.png', 0) # Obtain the size of the original image[m, n] = img1.shapeprint('Image Shape:', m, n) # Show original imageprint('Original Image:')plt.imshow(img1, cmap="gray") # Down sampling # Assign a down sampling rate# Here we are down sampling the# image by 4f = 4 # Create a matrix of all zeros for# downsampled valuesimg2 = np.zeros((m//f, n//f), dtype=np.int) # Assign the down sampled values from the original# image according to the down sampling frequency.# For example, if the down sampling rate f=2, take# pixel values from alternate rows and columns# and assign them in the matrix created abovefor i in range(0, m, f): for j in range(0, n, f): try: img2[i//f][j//f] = img1[i][j] except IndexError: pass # Show down sampled imageprint('Down Sampled Image:')plt.imshow(img2, cmap="gray") # Up sampling # Create matrix of zeros to store the upsampled imageimg3 = np.zeros((m, n), dtype=np.int)# new sizefor i in range(0, m-1, f): for j in range(0, n-1, f): img3[i, j] = img2[i//f][j//f] # Nearest neighbour interpolation-Replication# Replicating rows for i in range(1, m-(f-1), f): for j in range(0, n-(f-1)): img3[i:i+(f-1), j] = img3[i-1, j] # Replicating columnsfor i in range(0, m-1): for j in range(1, n-1, f): img3[i, j:j+(f-1)] = img3[i, j-1] # Plot the up sampled imageprint('Up Sampled Image:')plt.imshow(img3, cmap="gray") Input: Output: gabaa406 Image-Processing Python-OpenCV Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Dec, 2021" }, { "code": null, "e": 440, "s": 28, "text": "A digital image is a two-dimensional array of size M x N where M is the number of rows and N is the number of columns in the array. A digital image is made up of a finite number of discrete picture elements called a pixel. The location of each pixel is given by coordinates (x, y) and the value of each pixel is given by intensity value f. Hence, the elements in a digital image can be represented by f(x, y). " }, { "code": null, "e": 605, "s": 440, "text": "The term spatial resolution corresponds to the total number of pixels in the given image. If the number of pixels is more, then the resolution of the image is more." }, { "code": null, "e": 785, "s": 605, "text": "In the down-sampling technique, the number of pixels in the given image is reduced depending on the sampling frequency. Due to this, the resolution and size of the image decrease." }, { "code": null, "e": 981, "s": 785, "text": "The number of pixels in the down-sampled image can be increased by using up-sampling interpolation techniques. The up-sampling technique increases the resolution as well as the size of the image." }, { "code": null, "e": 1027, "s": 981, "text": "Some commonly used up-sampling techniques are" }, { "code": null, "e": 1058, "s": 1027, "text": "Nearest neighbor interpolation" }, { "code": null, "e": 1081, "s": 1058, "text": "Bilinear interpolation" }, { "code": null, "e": 1101, "s": 1081, "text": "Cubic interpolation" }, { "code": null, "e": 1303, "s": 1101, "text": "In this article, we have implemented upsampling using Nearest neighbor interpolation by replicating rows and columns. As the sampling rate increases, artifacts will be seen in the reconstructed image. " }, { "code": null, "e": 1682, "s": 1303, "text": "However, by using bilinear interpolation or cubic interpolation, a better quality of the reconstructed image can be attained. Both Down sampling and Up Sampling can be illustrated in grayscale for better understandings because while reading images using OpenCV, some color values are manipulated, So we are going to convert the original input image into a black and white image." }, { "code": null, "e": 1773, "s": 1682, "text": "The below program depicts the down sampled and up sampled representation of a given image:" }, { "code": null, "e": 1781, "s": 1773, "text": "Python3" }, { "code": "# Import cv2, matplotlib, numpyimport cv2import matplotlib.pyplot as pltimport numpy as np # Read the original image and know its typeimg1 = cv2.imread('g4g.png', 0) # Obtain the size of the original image[m, n] = img1.shapeprint('Image Shape:', m, n) # Show original imageprint('Original Image:')plt.imshow(img1, cmap=\"gray\") # Down sampling # Assign a down sampling rate# Here we are down sampling the# image by 4f = 4 # Create a matrix of all zeros for# downsampled valuesimg2 = np.zeros((m//f, n//f), dtype=np.int) # Assign the down sampled values from the original# image according to the down sampling frequency.# For example, if the down sampling rate f=2, take# pixel values from alternate rows and columns# and assign them in the matrix created abovefor i in range(0, m, f): for j in range(0, n, f): try: img2[i//f][j//f] = img1[i][j] except IndexError: pass # Show down sampled imageprint('Down Sampled Image:')plt.imshow(img2, cmap=\"gray\") # Up sampling # Create matrix of zeros to store the upsampled imageimg3 = np.zeros((m, n), dtype=np.int)# new sizefor i in range(0, m-1, f): for j in range(0, n-1, f): img3[i, j] = img2[i//f][j//f] # Nearest neighbour interpolation-Replication# Replicating rows for i in range(1, m-(f-1), f): for j in range(0, n-(f-1)): img3[i:i+(f-1), j] = img3[i-1, j] # Replicating columnsfor i in range(0, m-1): for j in range(1, n-1, f): img3[i, j:j+(f-1)] = img3[i, j-1] # Plot the up sampled imageprint('Up Sampled Image:')plt.imshow(img3, cmap=\"gray\")", "e": 3350, "s": 1781, "text": null }, { "code": null, "e": 3357, "s": 3350, "text": "Input:" }, { "code": null, "e": 3365, "s": 3357, "text": "Output:" }, { "code": null, "e": 3374, "s": 3365, "text": "gabaa406" }, { "code": null, "e": 3391, "s": 3374, "text": "Image-Processing" }, { "code": null, "e": 3405, "s": 3391, "text": "Python-OpenCV" }, { "code": null, "e": 3429, "s": 3405, "text": "Technical Scripter 2020" }, { "code": null, "e": 3436, "s": 3429, "text": "Python" }, { "code": null, "e": 3455, "s": 3436, "text": "Technical Scripter" } ]
Python | Subtract two list elements if element in first list is greater
01 Jun, 2021 Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5, 5, 20, 23, 52, 5, 4, 9] Method 1: The naive approach is to traverse both list simultaneously and if the element in first list in greater than element in second list, then subtract it, else if the element in first list in smaller than element in second list, then return element of first list only. Python3 # Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. # Input list initialisationInput1 = [10, 20, 30, 40, 50, 60]Input2 = [60, 50, 40, 30, 20, 10] # Output list initialisationOutput = [] for i in range(len(Input1)): if Input1[i] > Input2[i]: Output.append(Input1[i] - Input2[i]) else: Output.append(Input1[i]) print("Original list are :")print(Input1)print(Input2) print("\nOutput list is")print(Output) Output: Original list are : [10, 20, 30, 40, 50, 60] [60, 50, 40, 30, 20, 10] Output list is [10, 20, 30, 10, 30, 50] Method 2: Using zip() we subtract if element in first list is greater than element in second list, else we output element of first list. Python3 # Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. # Input list initialisationInput1 = [10, 20, 30, 40, 50, 60]Input2 = [60, 50, 40, 30, 20, 10] # using zip()Output =[e1-e2 if e1>e2 else e1 for (e1, e2) in zip(Input1, Input2)] # Printing outputprint("Original list are :")print(Input1)print(Input2) print("\nOutput list is")print(Output) Output: Original list are : [10, 20, 30, 40, 50, 60] [60, 50, 40, 30, 20, 10] Output list is [10, 20, 30, 10, 30, 50] Method 3: Using list comprehension. Python3 # Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. # Input list initialisationInput1 = [10, 20, 30, 40, 50, 60]Input2 = [60, 50, 40, 30, 20, 10] # Output list initialisationOutput = [Input1[i]-Input2[i] if Input1[i] > Input2[i] \ else Input1[i] for i in range(len(Input1))] # Printing outputprint("Original list are :")print(Input1)print(Input2) print("\nOutput list is")print(Output) Output: Original list are : [10, 20, 30, 40, 50, 60] [60, 50, 40, 30, 20, 10] Output list is [10, 20, 30, 10, 30, 50] Method 4: Using numpy() to complete the above task. Python3 # Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. import numpy as np # Input list initialisationInput1 = np.array([10, 20, 30, 40, 50, 60])Input2 = np.array([60, 50, 40, 30, 20, 10]) # using numpyOutput = np.where(Input1 >= Input2, Input1 - Input2, Input1) # Printing outputprint("Original list are :")print(Input1)print(Input2) print("\nOutput list is")print(Output) Output: Original list are : [10 20 30 40 50 60] [60 50 40 30 20 10] Output list is [10 20 30 10 30 50] sweetyty Python list-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jun, 2021" }, { "code": null, "e": 207, "s": 54, "text": "Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: " }, { "code": null, "e": 431, "s": 207, "text": "Input:\nl1 = [10, 20, 30, 40, 50, 60]\nl2 = [60, 50, 40, 30, 20, 10]\nOutput:\n[10, 20, 30, 10, 30, 50]\n\nInput:\nl1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]\nl2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]\nOutput:\n[6, 5, 5, 20, 23, 52, 5, 4, 9]" }, { "code": null, "e": 706, "s": 431, "text": "Method 1: The naive approach is to traverse both list simultaneously and if the element in first list in greater than element in second list, then subtract it, else if the element in first list in smaller than element in second list, then return element of first list only. " }, { "code": null, "e": 714, "s": 706, "text": "Python3" }, { "code": "# Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. # Input list initialisationInput1 = [10, 20, 30, 40, 50, 60]Input2 = [60, 50, 40, 30, 20, 10] # Output list initialisationOutput = [] for i in range(len(Input1)): if Input1[i] > Input2[i]: Output.append(Input1[i] - Input2[i]) else: Output.append(Input1[i]) print(\"Original list are :\")print(Input1)print(Input2) print(\"\\nOutput list is\")print(Output)", "e": 1224, "s": 714, "text": null }, { "code": null, "e": 1233, "s": 1224, "text": "Output: " }, { "code": null, "e": 1344, "s": 1233, "text": "Original list are :\n[10, 20, 30, 40, 50, 60]\n[60, 50, 40, 30, 20, 10]\n\nOutput list is\n[10, 20, 30, 10, 30, 50]" }, { "code": null, "e": 1482, "s": 1344, "text": "Method 2: Using zip() we subtract if element in first list is greater than element in second list, else we output element of first list. " }, { "code": null, "e": 1490, "s": 1482, "text": "Python3" }, { "code": "# Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. # Input list initialisationInput1 = [10, 20, 30, 40, 50, 60]Input2 = [60, 50, 40, 30, 20, 10] # using zip()Output =[e1-e2 if e1>e2 else e1 for (e1, e2) in zip(Input1, Input2)] # Printing outputprint(\"Original list are :\")print(Input1)print(Input2) print(\"\\nOutput list is\")print(Output)", "e": 1908, "s": 1490, "text": null }, { "code": null, "e": 1917, "s": 1908, "text": "Output: " }, { "code": null, "e": 2028, "s": 1917, "text": "Original list are :\n[10, 20, 30, 40, 50, 60]\n[60, 50, 40, 30, 20, 10]\n\nOutput list is\n[10, 20, 30, 10, 30, 50]" }, { "code": null, "e": 2065, "s": 2028, "text": "Method 3: Using list comprehension. " }, { "code": null, "e": 2073, "s": 2065, "text": "Python3" }, { "code": "# Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. # Input list initialisationInput1 = [10, 20, 30, 40, 50, 60]Input2 = [60, 50, 40, 30, 20, 10] # Output list initialisationOutput = [Input1[i]-Input2[i] if Input1[i] > Input2[i] \\ else Input1[i] for i in range(len(Input1))] # Printing outputprint(\"Original list are :\")print(Input1)print(Input2) print(\"\\nOutput list is\")print(Output)", "e": 2547, "s": 2073, "text": null }, { "code": null, "e": 2557, "s": 2547, "text": "Output: " }, { "code": null, "e": 2668, "s": 2557, "text": "Original list are :\n[10, 20, 30, 40, 50, 60]\n[60, 50, 40, 30, 20, 10]\n\nOutput list is\n[10, 20, 30, 10, 30, 50]" }, { "code": null, "e": 2721, "s": 2668, "text": "Method 4: Using numpy() to complete the above task. " }, { "code": null, "e": 2729, "s": 2721, "text": "Python3" }, { "code": "# Python code to subtract if element in first# list is greater than element in second list,# else we output element of first list. import numpy as np # Input list initialisationInput1 = np.array([10, 20, 30, 40, 50, 60])Input2 = np.array([60, 50, 40, 30, 20, 10]) # using numpyOutput = np.where(Input1 >= Input2, Input1 - Input2, Input1) # Printing outputprint(\"Original list are :\")print(Input1)print(Input2) print(\"\\nOutput list is\")print(Output)", "e": 3182, "s": 2729, "text": null }, { "code": null, "e": 3191, "s": 3182, "text": "Output: " }, { "code": null, "e": 3287, "s": 3191, "text": "Original list are :\n[10 20 30 40 50 60]\n[60 50 40 30 20 10]\n\nOutput list is\n[10 20 30 10 30 50]" }, { "code": null, "e": 3298, "s": 3289, "text": "sweetyty" }, { "code": null, "e": 3319, "s": 3298, "text": "Python list-programs" }, { "code": null, "e": 3326, "s": 3319, "text": "Python" }, { "code": null, "e": 3424, "s": 3326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3456, "s": 3424, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3483, "s": 3456, "text": "Python Classes and Objects" }, { "code": null, "e": 3514, "s": 3483, "text": "Python | os.path.join() method" }, { "code": null, "e": 3537, "s": 3514, "text": "Introduction To PYTHON" }, { "code": null, "e": 3558, "s": 3537, "text": "Python OOPs Concepts" }, { "code": null, "e": 3614, "s": 3558, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3656, "s": 3614, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3698, "s": 3656, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3737, "s": 3698, "text": "Python | Get unique values from a list" } ]
How to pass a json object as a parameter to a python function?
We have this code below which will the given json object as a parameter to a python function. import json json_string = '{"name":"Rupert", "age": 25, "desig":"developer"}' print type (json_string) def func(strng): a =json.loads(strng) print type(a) for k,v in a.iteritems(): print k,v print dict(a) func(json_string) <type 'str'> <type 'dict'> desig developer age 25 name Rupert {u'desig': u'developer', u'age': 25, u'name': u'Rupert'}
[ { "code": null, "e": 1281, "s": 1187, "text": "We have this code below which will the given json object as a parameter to a python function." }, { "code": null, "e": 1537, "s": 1281, "text": "import json\njson_string = '{\"name\":\"Rupert\", \"age\": 25, \"desig\":\"developer\"}'\nprint type (json_string)\ndef func(strng):\n a =json.loads(strng)\n print type(a)\n for k,v in a.iteritems():\n print k,v\n print dict(a) \nfunc(json_string)" }, { "code": null, "e": 1656, "s": 1537, "text": "<type 'str'>\n<type 'dict'>\ndesig developer\nage 25\nname Rupert\n{u'desig': u'developer', u'age': 25, u'name': u'Rupert'}" } ]
TIKA - Content Extraction
Tika uses various parser libraries to extract content from given parsers. It chooses the right parser for extracting the given document type. For parsing documents, the parseToString() method of Tika facade class is generally used. Shown below are the steps involved in the parsing process and these are abstracted by the Tika ParsertoString() method. Abstracting the parsing process − Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type. Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type. Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries. Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries. Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats. Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats. Given below is the program for extracting text from a file using Tika facade class − import java.io.File; import java.io.IOException; import org.apache.tika.Tika; import org.apache.tika.exception.TikaException; import org.xml.sax.SAXException; public class TikaExtraction { public static void main(final String[] args) throws IOException, TikaException { //Assume sample.txt is in your current directory File file = new File("sample.txt"); //Instantiating Tika facade class Tika tika = new Tika(); String filecontent = tika.parseToString(file); System.out.println("Extracted Content: " + filecontent); } } Save the above code as TikaExtraction.java and run it from the command prompt − javac TikaExtraction.java java TikaExtraction Given below is the content of sample.txt. Hi students welcome to tutorialspoint It gives you the following output − Extracted Content: Hi students welcome to tutorialspoint The parser package of Tika provides several interfaces and classes using which we can parse a text document. Given below is the block diagram of the org.apache.tika.parser package. There are several parser classes available, e.g., pdf parser, Mp3Passer, OfficeParser, etc., to parse respective documents individually. All these classes implement the parser interface. The given diagram shows Tika’s general-purpose parser classes: CompositeParser and AutoDetectParser. Since the CompositeParser class follows composite design pattern, you can use a group of parser instances as a single parser. The CompositeParser class also allows access to all the classes that implement the parser interface. This is a subclass of CompositeParser and it provides automatic type detection. Using this functionality, the AutoDetectParser automatically sends the incoming documents to the appropriate parser classes using the composite methodology. Along with parseToString(), you can also use the parse() method of the parser Interface. The prototype of this method is shown below. parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) The following table lists the four objects it accepts as parameters. InputStream stream Any Inputstream object that contains the content of the file ContentHandler handler Tika passes the document as XHTML content to this handler, thereafter the document is processed using SAX API. It provides efficient postprocessing of the contents in a document. Metadata metadata The metadata object is used both as a source and a target of document metadata. ParseContext context This object is used in cases where the client application wants to customize the parsing process. Given below is an example that shows how the parse() method is used. Step 1 − To use the parse() method of the parser interface, instantiate any of the classes providing the implementation for this interface. There are individual parser classes such as PDFParser, OfficeParser, XMLParser, etc. You can use any of these individual document parsers. Alternatively, you can use either CompositeParser or AutoDetectParser that uses all the parser classes internally and extracts the contents of a document using a suitable parser. Parser parser = new AutoDetectParser(); (or) Parser parser = new CompositeParser(); (or) object of any individual parsers given in Tika Library Step 2 − Create a handler class object. Given below are the three content handlers − BodyContentHandler This class picks the body part of the XHTML output and writes that content to the output writer or output stream. Then it redirects the XHTML content to another content handler instance. LinkContentHandler This class detects and picks all the H-Ref tags of the XHTML document and forwards those for the use of tools like web crawlers. TeeContentHandler This class helps in using multiple tools simultaneously. Since our target is to extract the text contents from a document, instantiate BodyContentHandler as shown below − BodyContentHandler handler = new BodyContentHandler( ); Step 3 − Create the Metadata object as shown below − Metadata metadata = new Metadata(); Step 4 − Create any of the input stream objects, and pass your file that should be extracted to it. Instantiate a file object by passing the file path as parameter and pass this object to the FileInputStream class constructor. Note − The path passed to the file object should not contain spaces. The problem with these input stream classes is that they don’t support random access reads, which is required to process some file formats efficiently. To resolve this problem, Tika provides TikaInputStream. File file = new File(filepath) FileInputStream inputstream = new FileInputStream(file); (or) InputStream stream = TikaInputStream.get(new File(filename)); Step 5 − Create a parse context object as shown below − ParseContext context =new ParseContext(); Step 6 − Instantiate the parser object, invoke the parse method, and pass all the objects required, as shown in the prototype below − parser.parse(inputstream, handler, metadata, context); Given below is the program for content extraction using the parser interface − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class ParserExtraction { public static void main(final String[] args) throws IOException,SAXException, TikaException { //Assume sample.txt is in your current directory File file = new File("sample.txt"); //parse method parameters Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(file); ParseContext context = new ParseContext(); //parsing the file parser.parse(inputstream, handler, metadata, context); System.out.println("File content : " + Handler.toString()); } } Save the above code as ParserExtraction.java and run it from the command prompt − javac ParserExtraction.java java ParserExtraction Given below is the content of sample.txt Hi students welcome to tutorialspoint If you execute the above program, it will give you the following output − File content : Hi students welcome to tutorialspoint
[ { "code": null, "e": 2386, "s": 2244, "text": "Tika uses various parser libraries to extract content from given parsers. It chooses the right parser for extracting the given document type." }, { "code": null, "e": 2596, "s": 2386, "text": "For parsing documents, the parseToString() method of Tika facade class is generally used. Shown below are the steps involved in the parsing process and these are abstracted by the Tika ParsertoString() method." }, { "code": null, "e": 2630, "s": 2596, "text": "Abstracting the parsing process −" }, { "code": null, "e": 2766, "s": 2630, "text": "Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type." }, { "code": null, "e": 2902, "s": 2766, "text": "Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type." }, { "code": null, "e": 3068, "s": 2902, "text": "Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries." }, { "code": null, "e": 3234, "s": 3068, "text": "Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries." }, { "code": null, "e": 3381, "s": 3234, "text": "Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats." }, { "code": null, "e": 3528, "s": 3381, "text": "Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats." }, { "code": null, "e": 3613, "s": 3528, "text": "Given below is the program for extracting text from a file using Tika facade class −" }, { "code": null, "e": 4202, "s": 3613, "text": "import java.io.File;\nimport java.io.IOException;\n\nimport org.apache.tika.Tika;\nimport org.apache.tika.exception.TikaException;\n\nimport org.xml.sax.SAXException;\n\npublic class TikaExtraction {\n\t\n public static void main(final String[] args) throws IOException, TikaException {\n\n //Assume sample.txt is in your current directory\t\t \n File file = new File(\"sample.txt\");\n \n //Instantiating Tika facade class\n Tika tika = new Tika();\n String filecontent = tika.parseToString(file);\n System.out.println(\"Extracted Content: \" + filecontent);\n }\t\t \n}" }, { "code": null, "e": 4282, "s": 4202, "text": "Save the above code as TikaExtraction.java and run it from the command prompt −" }, { "code": null, "e": 4330, "s": 4282, "text": "javac TikaExtraction.java \njava TikaExtraction\n" }, { "code": null, "e": 4372, "s": 4330, "text": "Given below is the content of sample.txt." }, { "code": null, "e": 4411, "s": 4372, "text": "Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 4447, "s": 4411, "text": "It gives you the following output −" }, { "code": null, "e": 4505, "s": 4447, "text": "Extracted Content: Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 4686, "s": 4505, "text": "The parser package of Tika provides several interfaces and classes using which we can parse a text document. Given below is the block diagram of the org.apache.tika.parser package." }, { "code": null, "e": 4873, "s": 4686, "text": "There are several parser classes available, e.g., pdf parser, Mp3Passer, OfficeParser, etc., to parse respective documents individually. All these classes implement the parser interface." }, { "code": null, "e": 5201, "s": 4873, "text": "The given diagram shows Tika’s general-purpose parser classes: CompositeParser and AutoDetectParser. Since the CompositeParser class follows composite design pattern, you can use a group of parser instances as a single parser. The CompositeParser class also allows access to all the classes that implement the parser interface." }, { "code": null, "e": 5438, "s": 5201, "text": "This is a subclass of CompositeParser and it provides automatic type detection. Using this functionality, the AutoDetectParser automatically sends the incoming documents to the appropriate parser classes using the composite methodology." }, { "code": null, "e": 5572, "s": 5438, "text": "Along with parseToString(), you can also use the parse() method of the parser Interface. The prototype of this method is shown below." }, { "code": null, "e": 5663, "s": 5572, "text": "parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)" }, { "code": null, "e": 5732, "s": 5663, "text": "The following table lists the four objects it accepts as parameters." }, { "code": null, "e": 5751, "s": 5732, "text": "InputStream stream" }, { "code": null, "e": 5812, "s": 5751, "text": "Any Inputstream object that contains the content of the file" }, { "code": null, "e": 5835, "s": 5812, "text": "ContentHandler handler" }, { "code": null, "e": 6014, "s": 5835, "text": "Tika passes the document as XHTML content to this handler, thereafter the document is processed using SAX API. It provides efficient postprocessing of the contents in a document." }, { "code": null, "e": 6032, "s": 6014, "text": "Metadata metadata" }, { "code": null, "e": 6112, "s": 6032, "text": "The metadata object is used both as a source and a target of document metadata." }, { "code": null, "e": 6133, "s": 6112, "text": "ParseContext context" }, { "code": null, "e": 6231, "s": 6133, "text": "This object is used in cases where the client application wants to customize the parsing process." }, { "code": null, "e": 6300, "s": 6231, "text": "Given below is an example that shows how the parse() method is used." }, { "code": null, "e": 6309, "s": 6300, "text": "Step 1 −" }, { "code": null, "e": 6440, "s": 6309, "text": "To use the parse() method of the parser interface, instantiate any of the classes providing the implementation for this interface." }, { "code": null, "e": 6758, "s": 6440, "text": "There are individual parser classes such as PDFParser, OfficeParser, XMLParser, etc. You can use any of these individual document parsers. Alternatively, you can use either CompositeParser or AutoDetectParser that uses all the parser classes internally and extracts the contents of a document using a suitable parser." }, { "code": null, "e": 6919, "s": 6758, "text": "Parser parser = new AutoDetectParser();\n (or)\nParser parser = new CompositeParser(); \n (or) \nobject of any individual parsers given in Tika Library " }, { "code": null, "e": 6928, "s": 6919, "text": "Step 2 −" }, { "code": null, "e": 7004, "s": 6928, "text": "Create a handler class object. Given below are the three content handlers −" }, { "code": null, "e": 7023, "s": 7004, "text": "BodyContentHandler" }, { "code": null, "e": 7210, "s": 7023, "text": "This class picks the body part of the XHTML output and writes that content to the output writer or output stream. Then it redirects the XHTML content to another content handler instance." }, { "code": null, "e": 7229, "s": 7210, "text": "LinkContentHandler" }, { "code": null, "e": 7358, "s": 7229, "text": "This class detects and picks all the H-Ref tags of the XHTML document and forwards those for the use of tools like web crawlers." }, { "code": null, "e": 7376, "s": 7358, "text": "TeeContentHandler" }, { "code": null, "e": 7433, "s": 7376, "text": "This class helps in using multiple tools simultaneously." }, { "code": null, "e": 7547, "s": 7433, "text": "Since our target is to extract the text contents from a document, instantiate BodyContentHandler as shown below −" }, { "code": null, "e": 7603, "s": 7547, "text": "BodyContentHandler handler = new BodyContentHandler( );" }, { "code": null, "e": 7612, "s": 7603, "text": "Step 3 −" }, { "code": null, "e": 7656, "s": 7612, "text": "Create the Metadata object as shown below −" }, { "code": null, "e": 7692, "s": 7656, "text": "Metadata metadata = new Metadata();" }, { "code": null, "e": 7701, "s": 7692, "text": "Step 4 −" }, { "code": null, "e": 7792, "s": 7701, "text": "Create any of the input stream objects, and pass your file that should be extracted to it." }, { "code": null, "e": 7919, "s": 7792, "text": "Instantiate a file object by passing the file path as parameter and pass this object to the FileInputStream class constructor." }, { "code": null, "e": 7988, "s": 7919, "text": "Note − The path passed to the file object should not contain spaces." }, { "code": null, "e": 8196, "s": 7988, "text": "The problem with these input stream classes is that they don’t support random access reads, which is required to process some file formats efficiently. To resolve this problem, Tika provides TikaInputStream." }, { "code": null, "e": 8355, "s": 8196, "text": "File file = new File(filepath)\nFileInputStream inputstream = new FileInputStream(file);\n (or)\nInputStream stream = TikaInputStream.get(new File(filename));" }, { "code": null, "e": 8364, "s": 8355, "text": "Step 5 −" }, { "code": null, "e": 8411, "s": 8364, "text": "Create a parse context object as shown below −" }, { "code": null, "e": 8453, "s": 8411, "text": "ParseContext context =new ParseContext();" }, { "code": null, "e": 8462, "s": 8453, "text": "Step 6 −" }, { "code": null, "e": 8587, "s": 8462, "text": "Instantiate the parser object, invoke the parse method, and pass all the objects required, as shown in the prototype below −" }, { "code": null, "e": 8642, "s": 8587, "text": "parser.parse(inputstream, handler, metadata, context);" }, { "code": null, "e": 8721, "s": 8642, "text": "Given below is the program for content extraction using the parser interface −" }, { "code": null, "e": 9800, "s": 8721, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\n\nimport org.apache.tika.exception.TikaException;\nimport org.apache.tika.metadata.Metadata;\nimport org.apache.tika.parser.AutoDetectParser;\nimport org.apache.tika.parser.ParseContext;\nimport org.apache.tika.parser.Parser;\nimport org.apache.tika.sax.BodyContentHandler;\n\nimport org.xml.sax.SAXException;\n\npublic class ParserExtraction {\n\t\n public static void main(final String[] args) throws IOException,SAXException, TikaException {\n\n //Assume sample.txt is in your current directory\n File file = new File(\"sample.txt\");\n \n //parse method parameters\n Parser parser = new AutoDetectParser();\n BodyContentHandler handler = new BodyContentHandler();\n Metadata metadata = new Metadata();\n FileInputStream inputstream = new FileInputStream(file);\n ParseContext context = new ParseContext();\n \n //parsing the file\n parser.parse(inputstream, handler, metadata, context);\n System.out.println(\"File content : \" + Handler.toString());\n }\n}" }, { "code": null, "e": 9882, "s": 9800, "text": "Save the above code as ParserExtraction.java and run it from the command prompt −" }, { "code": null, "e": 9936, "s": 9882, "text": "javac ParserExtraction.java \njava ParserExtraction\n" }, { "code": null, "e": 9977, "s": 9936, "text": "Given below is the content of sample.txt" }, { "code": null, "e": 10016, "s": 9977, "text": "Hi students welcome to tutorialspoint\n" }, { "code": null, "e": 10090, "s": 10016, "text": "If you execute the above program, it will give you the following output −" } ]
Parsing Time in Golang
08 Jun, 2020 Parsing time is to convert our time to Golang time object so that we can extract information such as date, month, etc from it easily. We can parse any time by using time.Parse function which takes our time string and format in which our string is written as input and if there is no error in our format, it will return a Golang time object. Examples: Input : "2018-04-24" Output : 2018-04-24 00:00:00 +0000 UTC Input : "04/08/2017" Output : 2017-04-08 00:00:00 +0000 UTC Code: // Golang program to show the parsing of timepackage main import ( "fmt" "time") func main() { // The date we're trying to // parse, work with and format myDateString := "2018-01-20 04:35" fmt.Println("My Starting Date:\t", myDateString) // Parse the date string into Go's time object // The 1st param specifies the format, // 2nd is our date string myDate, err := time.Parse("2006-01-02 15:04", myDateString) if err != nil { panic(err) } // Format uses the same formatting style // as parse, or we can use a pre-made constant fmt.Println("My Date Reformatted:\t", myDate.Format(time.RFC822)) // In YY-MM-DD fmt.Println("Just The Date:\t\t", myDate.Format("2006-01-02"))} Output: My Starting Date: 2018-01-20 04:35 My Date Reformatted: 20 Jan 18 04:35 UTC Just The Date: 2018-01-20 GoLang-time Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples fmt.Sprintf() Function in Golang With Examples Arrays in Go Golang Maps How to Split a String in Golang? Interfaces in Golang Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to Trim a String in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 369, "s": 28, "text": "Parsing time is to convert our time to Golang time object so that we can extract information such as date, month, etc from it easily. We can parse any time by using time.Parse function which takes our time string and format in which our string is written as input and if there is no error in our format, it will return a Golang time object." }, { "code": null, "e": 379, "s": 369, "text": "Examples:" }, { "code": null, "e": 501, "s": 379, "text": "Input : \"2018-04-24\"\nOutput : 2018-04-24 00:00:00 +0000 UTC\n\nInput : \"04/08/2017\"\nOutput : 2017-04-08 00:00:00 +0000 UTC\n" }, { "code": null, "e": 507, "s": 501, "text": "Code:" }, { "code": "// Golang program to show the parsing of timepackage main import ( \"fmt\" \"time\") func main() { // The date we're trying to // parse, work with and format myDateString := \"2018-01-20 04:35\" fmt.Println(\"My Starting Date:\\t\", myDateString) // Parse the date string into Go's time object // The 1st param specifies the format, // 2nd is our date string myDate, err := time.Parse(\"2006-01-02 15:04\", myDateString) if err != nil { panic(err) } // Format uses the same formatting style // as parse, or we can use a pre-made constant fmt.Println(\"My Date Reformatted:\\t\", myDate.Format(time.RFC822)) // In YY-MM-DD fmt.Println(\"Just The Date:\\t\\t\", myDate.Format(\"2006-01-02\"))}", "e": 1248, "s": 507, "text": null }, { "code": null, "e": 1256, "s": 1248, "text": "Output:" }, { "code": null, "e": 1375, "s": 1256, "text": "My Starting Date: 2018-01-20 04:35\nMy Date Reformatted: 20 Jan 18 04:35 UTC\nJust The Date: 2018-01-20\n" }, { "code": null, "e": 1387, "s": 1375, "text": "GoLang-time" }, { "code": null, "e": 1394, "s": 1387, "text": "Picked" }, { "code": null, "e": 1406, "s": 1394, "text": "Go Language" }, { "code": null, "e": 1504, "s": 1406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1555, "s": 1504, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 1602, "s": 1555, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 1615, "s": 1602, "text": "Arrays in Go" }, { "code": null, "e": 1627, "s": 1615, "text": "Golang Maps" }, { "code": null, "e": 1660, "s": 1627, "text": "How to Split a String in Golang?" }, { "code": null, "e": 1681, "s": 1660, "text": "Interfaces in Golang" }, { "code": null, "e": 1698, "s": 1681, "text": "Slices in Golang" }, { "code": null, "e": 1752, "s": 1698, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 1781, "s": 1752, "text": "How to Parse JSON in Golang?" } ]
Creating Word Embeddings: Coding the Word2Vec Algorithm in Python using Deep Learning | by Eligijus Bujokas | Towards Data Science
When I was writing another article that showcased how to use word embeddings in a text classification objective I realized that I always used pre-trained word embeddings downloaded from an external source (for example https://nlp.stanford.edu/projects/glove/). I started thinking about how to create word embeddings from scratch and thus this is how this article was born. My main goal is for people to read this article with my code snippets and to get an in-depth understanding of the logic behind the creation of vector representations of words. The whole code can be found here: https://github.com/Eligijus112/word-embedding-creation The short version of the creation of the word embeddings can be summarized in the following pipeline: Read the text -> Preprocess text -> Create (x, y) data points -> Create one hot encoded (X, Y) matrices -> train a neural network -> extract the weights from the input layer In this article, I will briefly explain every step of the way. From wiki: Word embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. The term word2vec literally translates to word to vector. For example, “dad” = [0.1548, 0.4848, ..., 1.864] “mom” = [0.8785, 0.8974, ..., 2.794] The most important feature of word embeddings is that similar words in a semantic sense have a smaller distance (either Euclidean, cosine or other) between them than words that have no semantic relationship. For example, words like “mom” and “dad” should be closer together than the words “mom” and “ketchup” or “dad” and “butter”. Word embeddings are created using a neural network with one input layer, one hidden layer and one output layer. To create word embeddings the first thing that is needed is text. Let us create a simple example stating some well-known facts about a fictional royal family containing 12 sentences: The future king is the princeDaughter is the princessSon is the princeOnly a man can be a kingOnly a woman can be a queenThe princess will be a queenQueen and king rule the realmThe prince is a strong manThe princess is a beautiful womanThe royal family is the king and queen and their childrenPrince is only a boy nowA boy will be a man The computer does not understand that the words king, prince and man are closer together in a semantic sense than the words queen, princess, and daughter. All it sees are encoded characters to binary. So how do we make the computer understand the relationship between certain words? By creating X and Y matrices and using a neural network. When creating the training matrices for word embeddings one of the hyperparameters is the window size of the context (w). The minimum value for this is 1 because without context the algorithm cannot work. Lets us take the first sentence and lets us assume that w = 2. The future king is the prince The bolded word the is called the focus word and 2 words to the left and 2 words to the right (because w = 2) are the so-called context words. So we can start building our data points: (The, future), (The, king) Now if we scan the whole sentence we would get: (The, future), (The, king), (future, the), (future, king), (future, is)(king, the), (king, future), (king, is), (king, the)(is, future), (is, king), (is, the), (is, prince),(the, king), (the, is), (the, prince)(prince, is), (prince, the) From 6 words we are able to create 18 data points. In practice, we do some preprocessing of the text and remove stop words like is, the, a, etc. By scanning our whole text document and appending the data we create the initial input which we can then transform into a matrix form. The full pipeline to create the (X, Y) word pairs given a list of strings texts: The first entries of the created data points: ['future', 'king'],['future', 'prince'],['king', 'prince'],['king', 'future'],['prince', 'king'],['prince', 'future'],['daughter', 'princess'],['princess', 'daughter'],['son', 'prince']... After the initial creation of the data points, we need to assign a unique integer (often called index) to each unique word of our vocabulary. This will be used further on when creating one-hot encoded vectors. After using the above function on the text we get the dictionary: unique_word_dict = { 'beautiful': 0, 'boy': 1, 'can': 2, 'children': 3, 'daughter': 4, 'family': 5, 'future': 6, 'king': 7, 'man': 8, 'now': 9, 'only': 10, 'prince': 11, 'princess': 12, 'queen': 13, 'realm': 14, 'royal': 15, 'rule': 16, 'son': 17, 'strong': 18, 'their': 19, 'woman': 20} What we created up to this point is still not neural network friendly because what we have as data is the pairs of (focus word, context word). In order for the computer to start doing computations, we need a clever way to transform these data points into data points made up of numbers. One such clever way is the one-hot encoding technique. One-hot encoding transforms a word into a vector that is made up of 0 with one coordinate, representing the string, equal to 1. The vector size is equal to the number of unique words in a document. For example, lets us define a simple list of strings: a = ['blue', 'sky', 'blue', 'car'] There are 3 unique words: blue, sky and car. One hot representation for each word: 'blue' = [1, 0, 0]'car' = [0, 1, 0]'sky' = [0, 0, 1] Thus the list can be converted into a matrix: A = [1, 0, 00, 0, 11, 0, 00, 1, 0] We will be creating two matrices, X and Y, with the exact same technique. The X matrix will be created using the focus words and the Y matrix will be created using the context words. Recall the first three data points which we created given the texts about royalties: ['future', 'king'],['future', 'prince'],['king', 'prince'] The one-hot encoded X matrix (words future, future, king) in python would be: [array([0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])] The one-hot encoded Y matrix (words king, prince, prince) in python would be: [array([0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.])] The final sizes of these matrices will be n x m, where n - number of created data points (pairs of focus words and context words) m - number of unique words We now have X and Y matrices built from the focus word and context word pairs. The next step is to choose the embedding dimension. I will choose the dimension to be equal to 2 in order to later plot the words and see whether similar words form clusters. The hidden layer dimension is the size of our word embedding. The output layers activation function is softmax. The activation function of the hidden layer is linear. The input dimension is equal to the total number of unique words (remember, our X matrix is of the dimension n x 21). Each input node will have two weights connecting it to the hidden layer. These weights are the word embeddings! After the training of the network, we extract these weights and remove all the rest. We do not necessarily care about the output. For the training of the network, we will use keras and tensorflow: After the training of the network, we can obtain the weights and plot the results: import matplotlib.pyplot as pltplt.figure(figsize=(10, 10))for word in list(unique_word_dict.keys()): coord = embedding_dict.get(word) plt.scatter(coord[0], coord[1]) plt.annotate(word, (coord[0], coord[1])) As we can see, there are the words ‘man’, ‘future’, ‘prince’, ‘boy’ and ‘daughter’, ‘woman’, ‘princess’ in separate corners of the plot and form clusters. All this was achieved from just 21 unique words and 12 sentences. Often in practice, pre-trained word embeddings are used with typical word embedding dimensions being either 100, 200 or 300. I personally use the embeddings stored here: \https://nlp.stanford.edu/projects/glove/.
[ { "code": null, "e": 720, "s": 171, "text": "When I was writing another article that showcased how to use word embeddings in a text classification objective I realized that I always used pre-trained word embeddings downloaded from an external source (for example https://nlp.stanford.edu/projects/glove/). I started thinking about how to create word embeddings from scratch and thus this is how this article was born. My main goal is for people to read this article with my code snippets and to get an in-depth understanding of the logic behind the creation of vector representations of words." }, { "code": null, "e": 754, "s": 720, "text": "The whole code can be found here:" }, { "code": null, "e": 809, "s": 754, "text": "https://github.com/Eligijus112/word-embedding-creation" }, { "code": null, "e": 911, "s": 809, "text": "The short version of the creation of the word embeddings can be summarized in the following pipeline:" }, { "code": null, "e": 1085, "s": 911, "text": "Read the text -> Preprocess text -> Create (x, y) data points -> Create one hot encoded (X, Y) matrices -> train a neural network -> extract the weights from the input layer" }, { "code": null, "e": 1148, "s": 1085, "text": "In this article, I will briefly explain every step of the way." }, { "code": null, "e": 1450, "s": 1148, "text": "From wiki: Word embedding is the collective name for a set of language modeling and feature learning techniques in natural language processing (NLP) where words or phrases from the vocabulary are mapped to vectors of real numbers. The term word2vec literally translates to word to vector. For example," }, { "code": null, "e": 1487, "s": 1450, "text": "“dad” = [0.1548, 0.4848, ..., 1.864]" }, { "code": null, "e": 1524, "s": 1487, "text": "“mom” = [0.8785, 0.8974, ..., 2.794]" }, { "code": null, "e": 1856, "s": 1524, "text": "The most important feature of word embeddings is that similar words in a semantic sense have a smaller distance (either Euclidean, cosine or other) between them than words that have no semantic relationship. For example, words like “mom” and “dad” should be closer together than the words “mom” and “ketchup” or “dad” and “butter”." }, { "code": null, "e": 1968, "s": 1856, "text": "Word embeddings are created using a neural network with one input layer, one hidden layer and one output layer." }, { "code": null, "e": 2151, "s": 1968, "text": "To create word embeddings the first thing that is needed is text. Let us create a simple example stating some well-known facts about a fictional royal family containing 12 sentences:" }, { "code": null, "e": 2489, "s": 2151, "text": "The future king is the princeDaughter is the princessSon is the princeOnly a man can be a kingOnly a woman can be a queenThe princess will be a queenQueen and king rule the realmThe prince is a strong manThe princess is a beautiful womanThe royal family is the king and queen and their childrenPrince is only a boy nowA boy will be a man" }, { "code": null, "e": 2829, "s": 2489, "text": "The computer does not understand that the words king, prince and man are closer together in a semantic sense than the words queen, princess, and daughter. All it sees are encoded characters to binary. So how do we make the computer understand the relationship between certain words? By creating X and Y matrices and using a neural network." }, { "code": null, "e": 3097, "s": 2829, "text": "When creating the training matrices for word embeddings one of the hyperparameters is the window size of the context (w). The minimum value for this is 1 because without context the algorithm cannot work. Lets us take the first sentence and lets us assume that w = 2." }, { "code": null, "e": 3127, "s": 3097, "text": "The future king is the prince" }, { "code": null, "e": 3312, "s": 3127, "text": "The bolded word the is called the focus word and 2 words to the left and 2 words to the right (because w = 2) are the so-called context words. So we can start building our data points:" }, { "code": null, "e": 3339, "s": 3312, "text": "(The, future), (The, king)" }, { "code": null, "e": 3387, "s": 3339, "text": "Now if we scan the whole sentence we would get:" }, { "code": null, "e": 3625, "s": 3387, "text": "(The, future), (The, king), (future, the), (future, king), (future, is)(king, the), (king, future), (king, is), (king, the)(is, future), (is, king), (is, the), (is, prince),(the, king), (the, is), (the, prince)(prince, is), (prince, the)" }, { "code": null, "e": 3905, "s": 3625, "text": "From 6 words we are able to create 18 data points. In practice, we do some preprocessing of the text and remove stop words like is, the, a, etc. By scanning our whole text document and appending the data we create the initial input which we can then transform into a matrix form." }, { "code": null, "e": 3986, "s": 3905, "text": "The full pipeline to create the (X, Y) word pairs given a list of strings texts:" }, { "code": null, "e": 4032, "s": 3986, "text": "The first entries of the created data points:" }, { "code": null, "e": 4221, "s": 4032, "text": "['future', 'king'],['future', 'prince'],['king', 'prince'],['king', 'future'],['prince', 'king'],['prince', 'future'],['daughter', 'princess'],['princess', 'daughter'],['son', 'prince']..." }, { "code": null, "e": 4431, "s": 4221, "text": "After the initial creation of the data points, we need to assign a unique integer (often called index) to each unique word of our vocabulary. This will be used further on when creating one-hot encoded vectors." }, { "code": null, "e": 4497, "s": 4431, "text": "After using the above function on the text we get the dictionary:" }, { "code": null, "e": 4785, "s": 4497, "text": "unique_word_dict = { 'beautiful': 0, 'boy': 1, 'can': 2, 'children': 3, 'daughter': 4, 'family': 5, 'future': 6, 'king': 7, 'man': 8, 'now': 9, 'only': 10, 'prince': 11, 'princess': 12, 'queen': 13, 'realm': 14, 'royal': 15, 'rule': 16, 'son': 17, 'strong': 18, 'their': 19, 'woman': 20}" }, { "code": null, "e": 5127, "s": 4785, "text": "What we created up to this point is still not neural network friendly because what we have as data is the pairs of (focus word, context word). In order for the computer to start doing computations, we need a clever way to transform these data points into data points made up of numbers. One such clever way is the one-hot encoding technique." }, { "code": null, "e": 5379, "s": 5127, "text": "One-hot encoding transforms a word into a vector that is made up of 0 with one coordinate, representing the string, equal to 1. The vector size is equal to the number of unique words in a document. For example, lets us define a simple list of strings:" }, { "code": null, "e": 5414, "s": 5379, "text": "a = ['blue', 'sky', 'blue', 'car']" }, { "code": null, "e": 5497, "s": 5414, "text": "There are 3 unique words: blue, sky and car. One hot representation for each word:" }, { "code": null, "e": 5550, "s": 5497, "text": "'blue' = [1, 0, 0]'car' = [0, 1, 0]'sky' = [0, 0, 1]" }, { "code": null, "e": 5596, "s": 5550, "text": "Thus the list can be converted into a matrix:" }, { "code": null, "e": 5631, "s": 5596, "text": "A = [1, 0, 00, 0, 11, 0, 00, 1, 0]" }, { "code": null, "e": 5814, "s": 5631, "text": "We will be creating two matrices, X and Y, with the exact same technique. The X matrix will be created using the focus words and the Y matrix will be created using the context words." }, { "code": null, "e": 5899, "s": 5814, "text": "Recall the first three data points which we created given the texts about royalties:" }, { "code": null, "e": 5958, "s": 5899, "text": "['future', 'king'],['future', 'prince'],['king', 'prince']" }, { "code": null, "e": 6036, "s": 5958, "text": "The one-hot encoded X matrix (words future, future, king) in python would be:" }, { "code": null, "e": 6337, "s": 6036, "text": "[array([0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])]" }, { "code": null, "e": 6415, "s": 6337, "text": "The one-hot encoded Y matrix (words king, prince, prince) in python would be:" }, { "code": null, "e": 6716, "s": 6415, "text": "[array([0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.])]" }, { "code": null, "e": 6771, "s": 6716, "text": "The final sizes of these matrices will be n x m, where" }, { "code": null, "e": 6846, "s": 6771, "text": "n - number of created data points (pairs of focus words and context words)" }, { "code": null, "e": 6873, "s": 6846, "text": "m - number of unique words" }, { "code": null, "e": 7127, "s": 6873, "text": "We now have X and Y matrices built from the focus word and context word pairs. The next step is to choose the embedding dimension. I will choose the dimension to be equal to 2 in order to later plot the words and see whether similar words form clusters." }, { "code": null, "e": 7654, "s": 7127, "text": "The hidden layer dimension is the size of our word embedding. The output layers activation function is softmax. The activation function of the hidden layer is linear. The input dimension is equal to the total number of unique words (remember, our X matrix is of the dimension n x 21). Each input node will have two weights connecting it to the hidden layer. These weights are the word embeddings! After the training of the network, we extract these weights and remove all the rest. We do not necessarily care about the output." }, { "code": null, "e": 7721, "s": 7654, "text": "For the training of the network, we will use keras and tensorflow:" }, { "code": null, "e": 7804, "s": 7721, "text": "After the training of the network, we can obtain the weights and plot the results:" }, { "code": null, "e": 8015, "s": 7804, "text": "import matplotlib.pyplot as pltplt.figure(figsize=(10, 10))for word in list(unique_word_dict.keys()): coord = embedding_dict.get(word) plt.scatter(coord[0], coord[1]) plt.annotate(word, (coord[0], coord[1]))" }, { "code": null, "e": 8236, "s": 8015, "text": "As we can see, there are the words ‘man’, ‘future’, ‘prince’, ‘boy’ and ‘daughter’, ‘woman’, ‘princess’ in separate corners of the plot and form clusters. All this was achieved from just 21 unique words and 12 sentences." } ]
How to create Android Notification with BroadcastReceiver?
This example demonstrate about How to create Android Notification with BroadcastReceiver. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding = "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width = "match_parent" android :layout_height = "match_parent" android :padding = "16dp" tools :context = ".MainActivity" /> Step 3 − Add the following code to res/menu/main_menu.xml. <? xml version = "1.0" encoding = "utf-8" ?> <menu xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: app = "http://schemas.android.com/apk/res-auto" > <item android :id = "@+id/action_5" app :showAsAction = "never" android :title = "5 seconds" /> <item android :id = "@+id/action_10" app :showAsAction = "never" android :title = "10 seconds" /> <item android :id = "@+id/action_30" app :showAsAction = "never" android :title = "30 seconds" /> </menu> Step 4 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.AlarmManager ; import android.app.Notification ; import android.app.NotificationManager ; import android.app.PendingIntent ; import android.content.Context ; import android.content.Intent ; import android.os.Bundle ; import android.os.SystemClock ; import android.support.v4.app.NotificationCompat ; import android.support.v7.app.AppCompatActivity ; import android.view.Menu ; import android.view.MenuItem ; public class MainActivity extends AppCompatActivity { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } @Override public boolean onCreateOptionsMenu (Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu. menu_main , menu) ; return true; } @Override public boolean onOptionsItemSelected (MenuItem item) { switch (item.getItemId()) { case R.id. action_5 : scheduleNotification(getNotification( "5 second delay" ) , 5000 ) ; return true; case R.id. action_10 : scheduleNotification(getNotification( "10 second delay" ) , 10000 ) ; return true; case R.id. action_30 : scheduleNotification(getNotification( "30 second delay" ) , 30000 ) ; return true; default : return super .onOptionsItemSelected(item) ; } } private void scheduleNotification (Notification notification , int delay) { Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ; notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ; notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ; PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ; long futureInMillis = SystemClock. elapsedRealtime () + delay ; AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ; assert alarmManager != null; alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , futureInMillis , pendingIntent) ; } private Notification getNotification (String content) { NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ; builder.setContentTitle( "Scheduled Notification" ) ; builder.setContentText(content) ; builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; builder.setAutoCancel( true ) ; builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; return builder.build() ; } } Step 5 − Add the following code to src/MyNotificationPublisher. package app.tutorialspoint.com.notifyme ; import android.app.Notification ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.content.BroadcastReceiver ; import android.content.Context ; import android.content.Intent ; import static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ; public class MyNotificationPublisher extends BroadcastReceiver { public static String NOTIFICATION_ID = "notification-id" ; public static String NOTIFICATION = "notification" ; public void onReceive (Context context , Intent intent) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ; Notification notification = intent.getParcelableExtra( NOTIFICATION ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; assert notificationManager != null; notificationManager.createNotificationChannel(notificationChannel) ; } int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ; assert notificationManager != null; notificationManager.notify(id , notification) ; } } Step 6 − 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.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <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> <receiver android :name = ".MyNotificationPublisher" /> </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": 1152, "s": 1062, "text": "This example demonstrate about How to create Android Notification with BroadcastReceiver." }, { "code": null, "e": 1281, "s": 1152, "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": 1346, "s": 1281, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1675, "s": 1346, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" />" }, { "code": null, "e": 1734, "s": 1675, "text": "Step 3 − Add the following code to res/menu/main_menu.xml." }, { "code": null, "e": 2270, "s": 1734, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<menu xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: app = \"http://schemas.android.com/apk/res-auto\" >\n <item\n android :id = \"@+id/action_5\"\n app :showAsAction = \"never\"\n android :title = \"5 seconds\" />\n <item\n android :id = \"@+id/action_10\"\n app :showAsAction = \"never\"\n android :title = \"10 seconds\" />\n <item\n android :id = \"@+id/action_30\"\n app :showAsAction = \"never\"\n android :title = \"30 seconds\" />\n</menu>" }, { "code": null, "e": 2323, "s": 2270, "text": "Step 4 − Add the following code to src/MainActivity." }, { "code": null, "e": 5241, "s": 2323, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.AlarmManager ;\nimport android.app.Notification ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.os.SystemClock ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.Menu ;\nimport android.view.MenuItem ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n @Override\n public boolean onCreateOptionsMenu (Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu. menu_main , menu) ;\n return true;\n }\n @Override\n public boolean onOptionsItemSelected (MenuItem item) {\n switch (item.getItemId()) {\n case R.id. action_5 :\n scheduleNotification(getNotification( \"5 second delay\" ) , 5000 ) ;\n return true;\n case R.id. action_10 :\n scheduleNotification(getNotification( \"10 second delay\" ) , 10000 ) ;\n return true;\n case R.id. action_30 :\n scheduleNotification(getNotification( \"30 second delay\" ) , 30000 ) ;\n return true;\n default :\n return super .onOptionsItemSelected(item) ;\n }\n }\n private void scheduleNotification (Notification notification , int delay) {\n Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ;\n PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ;\n long futureInMillis = SystemClock. elapsedRealtime () + delay ;\n AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ;\n assert alarmManager != null;\n alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , futureInMillis , pendingIntent) ;\n }\n private Notification getNotification (String content) {\n NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ;\n builder.setContentTitle( \"Scheduled Notification\" ) ;\n builder.setContentText(content) ;\n builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n builder.setAutoCancel( true ) ;\n builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n return builder.build() ;\n }\n}" }, { "code": null, "e": 5305, "s": 5241, "text": "Step 5 − Add the following code to src/MyNotificationPublisher." }, { "code": null, "e": 6699, "s": 5305, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.Notification ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.BroadcastReceiver ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ;\npublic class MyNotificationPublisher extends BroadcastReceiver {\n public static String NOTIFICATION_ID = \"notification-id\" ;\n public static String NOTIFICATION = \"notification\" ;\n public void onReceive (Context context , Intent intent) {\n NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ;\n Notification notification = intent.getParcelableExtra( NOTIFICATION ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n assert notificationManager != null;\n notificationManager.createNotificationChannel(notificationChannel) ;\n } \n int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ;\n assert notificationManager != null;\n notificationManager.notify(id , notification) ;\n }\n}" }, { "code": null, "e": 6754, "s": 6699, "text": "Step 6 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 7615, "s": 6754, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\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 <receiver android :name = \".MyNotificationPublisher\" />\n </application>\n</manifest>" }, { "code": null, "e": 7962, "s": 7615, "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": 8004, "s": 7962, "text": "Click here to download the project code" } ]
Plotting graph using seaborn in python.
Plotly's Python graphing library makes interactive, publication-quality graphs online. this graph is mainly used when we want to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, polar charts, and bubble charts. Seaborn is a library for making statistical graphics in Python. It is built on top of matplotlib and it is integrated with pandas data structures. 1. We import seaborn, which is the only library necessary for this simple example. import seaborn as sns 2. We apply the default default seaborn theme, scaling, and color palette. sns.set() 3. We load one of the example datasets. tips = sns.load_dataset("tips") 4. We draw a faceted scatter plot with multiple semantic variables. # This Python program will illustrate scatter plot with Seaborn # importing modules import matplotlib.pyplot as plt import seaborn as sns # values for x-axis x=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] # valueds for y-axis y=[10.5, 12.5, 11.4, 11.2, 9.2, 14.5, 10.1] # plotting with seaborn my_plot = sns.stripplot(x, y); # assigning x-axis and y-axis labels my_plot.set(xlabel ='Day Names', ylabel ='Turn Over (In Million Dollars)') # assigning plot title plt.title('Scatter Plot'); # function to show plot plt.show()
[ { "code": null, "e": 1351, "s": 1062, "text": "Plotly's Python graphing library makes interactive, publication-quality graphs online. this graph is mainly used when we want to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, polar charts, and bubble charts." }, { "code": null, "e": 1498, "s": 1351, "text": "Seaborn is a library for making statistical graphics in Python. It is built on top of matplotlib and it is integrated with pandas data structures." }, { "code": null, "e": 1581, "s": 1498, "text": "1. We import seaborn, which is the only library necessary for this simple example." }, { "code": null, "e": 1604, "s": 1581, "text": "import seaborn as sns\n" }, { "code": null, "e": 1679, "s": 1604, "text": "2. We apply the default default seaborn theme, scaling, and color palette." }, { "code": null, "e": 1690, "s": 1679, "text": "sns.set()\n" }, { "code": null, "e": 1730, "s": 1690, "text": "3. We load one of the example datasets." }, { "code": null, "e": 1763, "s": 1730, "text": "tips = sns.load_dataset(\"tips\")\n" }, { "code": null, "e": 1831, "s": 1763, "text": "4. We draw a faceted scatter plot with multiple semantic variables." }, { "code": null, "e": 2394, "s": 1831, "text": "# This Python program will illustrate scatter plot with Seaborn\n# importing modules\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# values for x-axis \nx=['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] \n# valueds for y-axis \ny=[10.5, 12.5, 11.4, 11.2, 9.2, 14.5, 10.1] \n# plotting with seaborn\nmy_plot = sns.stripplot(x, y);\n# assigning x-axis and y-axis labels\nmy_plot.set(xlabel ='Day Names', ylabel ='Turn Over (In Million Dollars)') \n# assigning plot title\nplt.title('Scatter Plot'); \n# function to show plot \nplt.show()" } ]
5 tips to boost your Power BI development | by Nikola Ilic | Towards Data Science
One of the things that I like most about Power BI is rapid report development. In just a few clicks, results can be visible and ready for analysis. Of course, complexity comes later, but that first visual impression can be easily achieved within a few minutes. I’m sure that most of you have your own tips and tricks for boosting Power BI development. However, I would like to share my 5 tips, which I often use during the report development. Creating measures is a must for every Power BI report. And it’s not an issue when your report has just a few measures. But, things become more complicated when you need to operate with tens or even hundreds of measures. To prevent that, I always use the following techniques to better organize my measures. By default, the measure will reside in the table where you created it. I’m using sample Contoso database and I’ve created a simple measure for calculating Sales Total in FactOnlineSales table: Sales Total = SUMX(FactOnlineSales, FactOnlineSales[SalesQuantity]*FactOnlineSales[UnitPrice]) As you see, measure resides in the FactOnlineSales table, where it was originally created. In order to change this, I need to create a brand new table which will hold my measures. Under the Home tab, select Enter Data and create a plain empty table called Sales Measures. Click Load and you will see a new table in your model. After that, click on your measure Sales Total, and under Home table, select Sales Measures. Then, just simply delete Column 1 and you are good to go. This way, you can separate and group your measures. Trust me, it will make your life much easier. Up until the latest Power BI Desktop update, there was one thing that annoyed me pretty much. When you open Options and Settings under the File tab, then under Options and Data Load, there was a section for Time Intelligence. By default, checkbox was checked. What does that mean? Power BI automatically created hidden date tables for EVERY SINGLE field of data type date in your model! This is not bad “per se”, because Power BI prevents you from suffering in case you don’t have proper Date dimension. However, as the proper Date dimension is one of the key things you need when building reports, please disable this feature, because it increases your data model size. I’m glad to see that the Power BI team finally disabled this by default. It might look straightforward and stupid to many of you, but I was regularly struggling to properly format DAX code while writing my measures. I’m using a fantastic tool called DAX Studio for my Power BI development and there is a nice little thing called DAX Formatter inside. However, when you write your measures directly in Power BI Desktop, if you hit Enter, instead of moving to a new row, you confirm your measure for evaluation. The solution is to hit Shift+Enter and your cursor will be moved to a new row, making your DAX code formatted as it should be:) When I import data into Power BI Desktop, before I proceed further with data modeling and visualizations, I like to take a quick look at my data. I want to check the data quality, distribution and maybe identify some outliers in the early stage of development. Therefore, I am regularly turning on column profiling under the View tab in Power Query editor. This way, I get a feeling about my data, so I can make proper decisions before going deeper. In most cases, dimensions in your data model contain all necessary attributes for understanding figures from the fact table. However, in some scenarios, you may want to extend dimension attributes to enable your end-users with more flexibility in analysis. Imagine the following situation: in the dimProduct table, we have a whole bunch of different attributes, such as Category, SubCategory, Color, etc. But, let’s say that I want to classify my products based on their sales data. So, products with sales greater than X value will be “High”, moderate sales will mark the product as “Medium” and products with sales amount less than Y value will belong to the “Low” group. Since I’ve already created my Sales Total measure in one of the previous examples, I will use this value to determine which group should product belong. Now, I will use the Calculated column to store values of Sales Total per product. It’s just as simple as: Sales Amt Product = [Sales Total] Based on this value, I will determine if the product belongs to a High, Medium, or Low group. To achieve that, the SWITCH function comes in handy: Product Sales Grouping = SWITCH(TRUE() ,DimProduct[Sales Amt Product] > 100000,"High" ,DimProduct[Sales Amt Product] > 20000,"Medium" ,DimProduct[Sales Amt Product] <=20000,"Low") Basically, what happens here is that every single row has been evaluated and, depending on the value, classified accordingly. This way, we created a brand new attribute for our products, based on their sales value. Now, we can simply use this attribute for filtering, as any other regular attribute: We can also use our new attribute as a slicer: Maybe some of these tips look trivial and not so advanced, but I found them quite useful in day-to-day work with Power BI. What are your favorite tips? Feel free to share them in the comments and check more tricks on how to make music from your data. Become a member and read every story on Medium! Subscribe here to get more insightful data articles!
[ { "code": null, "e": 433, "s": 172, "text": "One of the things that I like most about Power BI is rapid report development. In just a few clicks, results can be visible and ready for analysis. Of course, complexity comes later, but that first visual impression can be easily achieved within a few minutes." }, { "code": null, "e": 615, "s": 433, "text": "I’m sure that most of you have your own tips and tricks for boosting Power BI development. However, I would like to share my 5 tips, which I often use during the report development." }, { "code": null, "e": 835, "s": 615, "text": "Creating measures is a must for every Power BI report. And it’s not an issue when your report has just a few measures. But, things become more complicated when you need to operate with tens or even hundreds of measures." }, { "code": null, "e": 993, "s": 835, "text": "To prevent that, I always use the following techniques to better organize my measures. By default, the measure will reside in the table where you created it." }, { "code": null, "e": 1115, "s": 993, "text": "I’m using sample Contoso database and I’ve created a simple measure for calculating Sales Total in FactOnlineSales table:" }, { "code": null, "e": 1220, "s": 1115, "text": "Sales Total = SUMX(FactOnlineSales, FactOnlineSales[SalesQuantity]*FactOnlineSales[UnitPrice])" }, { "code": null, "e": 1400, "s": 1220, "text": "As you see, measure resides in the FactOnlineSales table, where it was originally created. In order to change this, I need to create a brand new table which will hold my measures." }, { "code": null, "e": 1492, "s": 1400, "text": "Under the Home tab, select Enter Data and create a plain empty table called Sales Measures." }, { "code": null, "e": 1639, "s": 1492, "text": "Click Load and you will see a new table in your model. After that, click on your measure Sales Total, and under Home table, select Sales Measures." }, { "code": null, "e": 1795, "s": 1639, "text": "Then, just simply delete Column 1 and you are good to go. This way, you can separate and group your measures. Trust me, it will make your life much easier." }, { "code": null, "e": 2055, "s": 1795, "text": "Up until the latest Power BI Desktop update, there was one thing that annoyed me pretty much. When you open Options and Settings under the File tab, then under Options and Data Load, there was a section for Time Intelligence. By default, checkbox was checked." }, { "code": null, "e": 2076, "s": 2055, "text": "What does that mean?" }, { "code": null, "e": 2182, "s": 2076, "text": "Power BI automatically created hidden date tables for EVERY SINGLE field of data type date in your model!" }, { "code": null, "e": 2466, "s": 2182, "text": "This is not bad “per se”, because Power BI prevents you from suffering in case you don’t have proper Date dimension. However, as the proper Date dimension is one of the key things you need when building reports, please disable this feature, because it increases your data model size." }, { "code": null, "e": 2539, "s": 2466, "text": "I’m glad to see that the Power BI team finally disabled this by default." }, { "code": null, "e": 2817, "s": 2539, "text": "It might look straightforward and stupid to many of you, but I was regularly struggling to properly format DAX code while writing my measures. I’m using a fantastic tool called DAX Studio for my Power BI development and there is a nice little thing called DAX Formatter inside." }, { "code": null, "e": 2976, "s": 2817, "text": "However, when you write your measures directly in Power BI Desktop, if you hit Enter, instead of moving to a new row, you confirm your measure for evaluation." }, { "code": null, "e": 3104, "s": 2976, "text": "The solution is to hit Shift+Enter and your cursor will be moved to a new row, making your DAX code formatted as it should be:)" }, { "code": null, "e": 3365, "s": 3104, "text": "When I import data into Power BI Desktop, before I proceed further with data modeling and visualizations, I like to take a quick look at my data. I want to check the data quality, distribution and maybe identify some outliers in the early stage of development." }, { "code": null, "e": 3461, "s": 3365, "text": "Therefore, I am regularly turning on column profiling under the View tab in Power Query editor." }, { "code": null, "e": 3554, "s": 3461, "text": "This way, I get a feeling about my data, so I can make proper decisions before going deeper." }, { "code": null, "e": 3811, "s": 3554, "text": "In most cases, dimensions in your data model contain all necessary attributes for understanding figures from the fact table. However, in some scenarios, you may want to extend dimension attributes to enable your end-users with more flexibility in analysis." }, { "code": null, "e": 3959, "s": 3811, "text": "Imagine the following situation: in the dimProduct table, we have a whole bunch of different attributes, such as Category, SubCategory, Color, etc." }, { "code": null, "e": 4228, "s": 3959, "text": "But, let’s say that I want to classify my products based on their sales data. So, products with sales greater than X value will be “High”, moderate sales will mark the product as “Medium” and products with sales amount less than Y value will belong to the “Low” group." }, { "code": null, "e": 4381, "s": 4228, "text": "Since I’ve already created my Sales Total measure in one of the previous examples, I will use this value to determine which group should product belong." }, { "code": null, "e": 4487, "s": 4381, "text": "Now, I will use the Calculated column to store values of Sales Total per product. It’s just as simple as:" }, { "code": null, "e": 4521, "s": 4487, "text": "Sales Amt Product = [Sales Total]" }, { "code": null, "e": 4668, "s": 4521, "text": "Based on this value, I will determine if the product belongs to a High, Medium, or Low group. To achieve that, the SWITCH function comes in handy:" }, { "code": null, "e": 4896, "s": 4668, "text": "Product Sales Grouping = SWITCH(TRUE() ,DimProduct[Sales Amt Product] > 100000,\"High\" ,DimProduct[Sales Amt Product] > 20000,\"Medium\" ,DimProduct[Sales Amt Product] <=20000,\"Low\")" }, { "code": null, "e": 5196, "s": 4896, "text": "Basically, what happens here is that every single row has been evaluated and, depending on the value, classified accordingly. This way, we created a brand new attribute for our products, based on their sales value. Now, we can simply use this attribute for filtering, as any other regular attribute:" }, { "code": null, "e": 5243, "s": 5196, "text": "We can also use our new attribute as a slicer:" }, { "code": null, "e": 5366, "s": 5243, "text": "Maybe some of these tips look trivial and not so advanced, but I found them quite useful in day-to-day work with Power BI." }, { "code": null, "e": 5494, "s": 5366, "text": "What are your favorite tips? Feel free to share them in the comments and check more tricks on how to make music from your data." }, { "code": null, "e": 5542, "s": 5494, "text": "Become a member and read every story on Medium!" } ]
Lodash _.lowerCase() Method - GeeksforGeeks
07 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.lowerCase() method is used to convert the given string, as space separated words, to lower case. Syntax: _.lowerCase([string='']) Parameters: This method accepts single parameter as mentioned above and described below: string: This parameter holds the string that need to convert into lower case. Return Value: This method returns the lower cased string. Example 1: Javascript const _ = require('lodash'); var str1 = _.lowerCase("GEEKS FOR GEEKS");console.log(str1); var str2 = _.lowerCase("GFG--Geeks");console.log(str2); Output: "geeks for geeks" "gfg geeks" Example 2: Javascript const _ = require('lodash'); var str1 = _.lowerCase("GEEKS__FOR__GEEKS");console.log(str1); var str2 = _.kebabCase("G4G--geeks--GEEKS");console.log(str2); var str3 = _.kebabCase("GEEKS-----FOR_____Geeks");console.log(str3); Output: "geeks for geeks" "g-4-g-geeks-geeks" "geeks-for-geeks" JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript Hide or show elements in HTML using display property Set the value of an input field in JavaScript How to calculate the number of days between two dates in javascript? Express.js express.Router() Function Installation of Node.js on Linux How to set input type date in dd-mm-yyyy format using HTML ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 37045, "s": 37017, "text": "\n07 Sep, 2020" }, { "code": null, "e": 37185, "s": 37045, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc." }, { "code": null, "e": 37288, "s": 37185, "text": "The _.lowerCase() method is used to convert the given string, as space separated words, to lower case." }, { "code": null, "e": 37296, "s": 37288, "text": "Syntax:" }, { "code": null, "e": 37322, "s": 37296, "text": "_.lowerCase([string=''])\n" }, { "code": null, "e": 37411, "s": 37322, "text": "Parameters: This method accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 37489, "s": 37411, "text": "string: This parameter holds the string that need to convert into lower case." }, { "code": null, "e": 37547, "s": 37489, "text": "Return Value: This method returns the lower cased string." }, { "code": null, "e": 37558, "s": 37547, "text": "Example 1:" }, { "code": null, "e": 37569, "s": 37558, "text": "Javascript" }, { "code": "const _ = require('lodash'); var str1 = _.lowerCase(\"GEEKS FOR GEEKS\");console.log(str1); var str2 = _.lowerCase(\"GFG--Geeks\");console.log(str2);", "e": 37718, "s": 37569, "text": null }, { "code": null, "e": 37726, "s": 37718, "text": "Output:" }, { "code": null, "e": 37757, "s": 37726, "text": "\"geeks for geeks\"\n\"gfg geeks\"\n" }, { "code": null, "e": 37768, "s": 37757, "text": "Example 2:" }, { "code": null, "e": 37779, "s": 37768, "text": "Javascript" }, { "code": "const _ = require('lodash'); var str1 = _.lowerCase(\"GEEKS__FOR__GEEKS\");console.log(str1); var str2 = _.kebabCase(\"G4G--geeks--GEEKS\");console.log(str2); var str3 = _.kebabCase(\"GEEKS-----FOR_____Geeks\");console.log(str3);", "e": 38007, "s": 37779, "text": null }, { "code": null, "e": 38015, "s": 38007, "text": "Output:" }, { "code": null, "e": 38072, "s": 38015, "text": "\"geeks for geeks\"\n\"g-4-g-geeks-geeks\"\n\"geeks-for-geeks\"\n" }, { "code": null, "e": 38090, "s": 38072, "text": "JavaScript-Lodash" }, { "code": null, "e": 38101, "s": 38090, "text": "JavaScript" }, { "code": null, "e": 38118, "s": 38101, "text": "Web Technologies" }, { "code": null, "e": 38216, "s": 38118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38225, "s": 38216, "text": "Comments" }, { "code": null, "e": 38238, "s": 38225, "text": "Old Comments" }, { "code": null, "e": 38310, "s": 38238, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 38355, "s": 38310, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 38408, "s": 38355, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 38454, "s": 38408, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 38523, "s": 38454, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 38560, "s": 38523, "text": "Express.js express.Router() Function" }, { "code": null, "e": 38593, "s": 38560, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 38654, "s": 38593, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 38726, "s": 38654, "text": "Differences between Functional Components and Class Components in React" } ]
How to access a NumPy array by column - GeeksforGeeks
29 May, 2021 Accessing a NumPy based array by a specific Column index can be achieved by the indexing. Let’s discuss this in detail. NumPy follows standard 0 based indexing. Row and column in NumPy are similar to Python List Examples: Given array : 1 13 6 9 4 7 19 16 2 Input: print(NumPy_array_name[ :,2]) # printing 2nd column Output: [6 7 2] Input: x = NumPy_array_name[ :,1] print(x) # storing 1st column into variable x Output: [13 4 16] Method #1: Selection using slices Syntax : For column : numpy_Array_name[ : ,column] For row : numpy_Array_name[ row, : ] Python3 # Python code to select row and column# in NumPy import numpy as np array = [[1, 13, 6], [9, 4, 7], [19, 16, 2]] # defining arrayarr = np.array(array) print('printing array as it is')print(arr) print('printing 0th row')print(arr[0, :]) print('printing 2nd column')print(arr[:, 2]) # multiple columns or rows can be selected as wellprint('selecting 0th and 1st row simultaneously')print(arr[:,[0,1]]) Output : printing array as it is [[ 1 13 6] [ 9 4 7] [19 16 2]] printing 0th row [ 1 13 6] printing 2nd column [6 7 2] selecting 0th and 1st row simultaneously [[ 1 13] [ 9 4] [19 16]] Method #2: Using Ellipsis Syntax : For column : numpy_Array_name[...,column] For row : numpy_Array_name[row,...] where ‘...‘ represents no of elements in the given row or column Note: This is not a very practical method but one must know as much as they can. Python3 # program to select row and column# in numpy using ellipsis import numpy as np # defining arrayarray = [[1, 13, 6], [9, 4, 7], [19, 16, 2]] # converting to numpy arrayarr = np.array(array) print('printing array as it is')print(arr) print('selecting 0th column')print(arr[..., 0]) print('selecting 1st row')print(arr[1, ...]) Output : printing array as it is [[ 1 13 6] [ 9 4 7] [19 16 2]] selecting 0th column [ 1 9 19] selecting 1st row [9 4 7] ireshaupulie Python numpy-Indexing Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 24814, "s": 24786, "text": "\n29 May, 2021" }, { "code": null, "e": 24934, "s": 24814, "text": "Accessing a NumPy based array by a specific Column index can be achieved by the indexing. Let’s discuss this in detail." }, { "code": null, "e": 24975, "s": 24934, "text": "NumPy follows standard 0 based indexing." }, { "code": null, "e": 25026, "s": 24975, "text": "Row and column in NumPy are similar to Python List" }, { "code": null, "e": 25036, "s": 25026, "text": "Examples:" }, { "code": null, "e": 25286, "s": 25036, "text": "Given array : 1 13 6\n 9 4 7\n 19 16 2\n\nInput: print(NumPy_array_name[ :,2])\n\n# printing 2nd column\nOutput: [6 7 2]\n\nInput: x = NumPy_array_name[ :,1]\n print(x)\n\n# storing 1st column into variable x\nOutput: [13 4 16]" }, { "code": null, "e": 25320, "s": 25286, "text": "Method #1: Selection using slices" }, { "code": null, "e": 25329, "s": 25320, "text": "Syntax :" }, { "code": null, "e": 25373, "s": 25329, "text": "For column : numpy_Array_name[ : ,column] " }, { "code": null, "e": 25411, "s": 25373, "text": "For row : numpy_Array_name[ row, : ]" }, { "code": null, "e": 25419, "s": 25411, "text": "Python3" }, { "code": "# Python code to select row and column# in NumPy import numpy as np array = [[1, 13, 6], [9, 4, 7], [19, 16, 2]] # defining arrayarr = np.array(array) print('printing array as it is')print(arr) print('printing 0th row')print(arr[0, :]) print('printing 2nd column')print(arr[:, 2]) # multiple columns or rows can be selected as wellprint('selecting 0th and 1st row simultaneously')print(arr[:,[0,1]])", "e": 25819, "s": 25419, "text": null }, { "code": null, "e": 25829, "s": 25819, "text": " Output :" }, { "code": null, "e": 26015, "s": 25829, "text": "printing array as it is\n[[ 1 13 6]\n [ 9 4 7]\n [19 16 2]]\nprinting 0th row\n[ 1 13 6]\nprinting 2nd column\n[6 7 2]\nselecting 0th and 1st row simultaneously\n[[ 1 13]\n [ 9 4]\n [19 16]]" }, { "code": null, "e": 26043, "s": 26017, "text": "Method #2: Using Ellipsis" }, { "code": null, "e": 26052, "s": 26043, "text": "Syntax :" }, { "code": null, "e": 26094, "s": 26052, "text": "For column : numpy_Array_name[...,column]" }, { "code": null, "e": 26130, "s": 26094, "text": "For row : numpy_Array_name[row,...]" }, { "code": null, "e": 26196, "s": 26130, "text": "where ‘...‘ represents no of elements in the given row or column " }, { "code": null, "e": 26277, "s": 26196, "text": "Note: This is not a very practical method but one must know as much as they can." }, { "code": null, "e": 26285, "s": 26277, "text": "Python3" }, { "code": "# program to select row and column# in numpy using ellipsis import numpy as np # defining arrayarray = [[1, 13, 6], [9, 4, 7], [19, 16, 2]] # converting to numpy arrayarr = np.array(array) print('printing array as it is')print(arr) print('selecting 0th column')print(arr[..., 0]) print('selecting 1st row')print(arr[1, ...])", "e": 26610, "s": 26285, "text": null }, { "code": null, "e": 26619, "s": 26610, "text": "Output :" }, { "code": null, "e": 26738, "s": 26619, "text": "printing array as it is\n[[ 1 13 6]\n [ 9 4 7]\n [19 16 2]]\nselecting 0th column\n[ 1 9 19]\nselecting 1st row\n[9 4 7]" }, { "code": null, "e": 26751, "s": 26738, "text": "ireshaupulie" }, { "code": null, "e": 26773, "s": 26751, "text": "Python numpy-Indexing" }, { "code": null, "e": 26786, "s": 26773, "text": "Python-numpy" }, { "code": null, "e": 26793, "s": 26786, "text": "Python" }, { "code": null, "e": 26891, "s": 26793, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26909, "s": 26891, "text": "Python Dictionary" }, { "code": null, "e": 26941, "s": 26909, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26963, "s": 26941, "text": "Enumerate() in Python" }, { "code": null, "e": 27005, "s": 26963, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27031, "s": 27005, "text": "Python String | replace()" }, { "code": null, "e": 27075, "s": 27031, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27112, "s": 27075, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27141, "s": 27112, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27183, "s": 27141, "text": "Check if element exists in list in Python" } ]
How to pass multiple data from one activity to another in Android?
This example demonstrate about How to pass multiple data from one activity to another in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".MainActivity"> <EditText android:id = "@+id/etName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Name" android:inputType = "text" /> <EditText android:id = "@+id/etAge" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Age" android:inputType = "number" /> <Button android:id = "@+id/button" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Next" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package com.example.myapplication; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText etName, etAge; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etName = findViewById(R.id.etName); etAge = findViewById(R.id.etAge); Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String name = etName.getText().toString().trim(); String age = etAge.getText().toString().trim(); Bundle bundle = new Bundle(); bundle.putString("name", name); bundle.putString("age", age); Intent intent = new Intent(MainActivity.this, SecondActivity.class); intent.putExtras(bundle); startActivity(intent); } }); } } Step 4 − Add the following code to res/layout/activity_second.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:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".SecondActivity"> <TextView android:id = "@+id/tvName" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> <TextView android:id = "@+id/tvAge" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout> Step 5 − Add the following code to src/SecondActivity.java package com.example.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Bundle bundle = getIntent().getExtras(); if (bundle ! = null) { String name = bundle.getString("name"); String age = bundle.getString("age"); TextView tvName = findViewById(R.id.tvName); TextView tvAge = findViewById(R.id.tvAge); tvName.setText(name); tvAge.setText(age); } } } Step 6 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <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> <activity android:name = ".SecondActivity"></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": 1159, "s": 1062, "text": "This example demonstrate about How to pass multiple data from one activity to another in Android" }, { "code": null, "e": 1288, "s": 1159, "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": 1353, "s": 1288, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2450, "s": 1353, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/etName\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:hint = \"Name\"\n android:inputType = \"text\" />\n <EditText\n android:id = \"@+id/etAge\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:hint = \"Age\"\n android:inputType = \"number\" />\n <Button\n android:id = \"@+id/button\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Next\" />\n</LinearLayout>" }, { "code": null, "e": 2507, "s": 2450, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3657, "s": 2507, "text": "package com.example.myapplication;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\n\npublic class MainActivity extends AppCompatActivity {\n EditText etName, etAge;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n etName = findViewById(R.id.etName);\n etAge = findViewById(R.id.etAge);\n Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String name = etName.getText().toString().trim();\n String age = etAge.getText().toString().trim();\n Bundle bundle = new Bundle();\n bundle.putString(\"name\", name);\n bundle.putString(\"age\", age);\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n intent.putExtras(bundle);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 3724, "s": 3657, "text": "Step 4 − Add the following code to res/layout/activity_second.xml." }, { "code": null, "e": 4376, "s": 3724, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".SecondActivity\">\n <TextView\n android:id = \"@+id/tvName\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n <TextView\n android:id = \"@+id/tvAge\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 4435, "s": 4376, "text": "Step 5 − Add the following code to src/SecondActivity.java" }, { "code": null, "e": 5146, "s": 4435, "text": "package com.example.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\npublic class SecondActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n Bundle bundle = getIntent().getExtras();\n if (bundle ! = null) {\n String name = bundle.getString(\"name\");\n String age = bundle.getString(\"age\");\n TextView tvName = findViewById(R.id.tvName);\n TextView tvAge = findViewById(R.id.tvAge);\n tvName.setText(name);\n tvAge.setText(age);\n }\n }\n}" }, { "code": null, "e": 5201, "s": 5146, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5972, "s": 5201, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\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 <activity android:name = \".SecondActivity\"></activity>\n </application>\n</manifest>" }, { "code": null, "e": 6321, "s": 5972, "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": 6361, "s": 6321, "text": "Click here to download the project code" } ]
GWT - Button Widget
The Button widget represents a standard push button. Following is the declaration for com.google.gwt.user.client.ui.Button class − public class Button extends ButtonBase Following default CSS Style rule will be applied to all the Button widget. You can override it as per your requirements. .gwt-Button { } Button() Creates a button with no caption. protected Button(Element element) This constructor may be used by subclasses to explicitly use an existing element. Button(java.lang.String html) Creates a button with the given HTML caption. Button(java.lang.String html, ClickListener listener) Creates a button with the given HTML caption and click listener. click() Programmatic equivalent of the user clicking the button. static Button wrap(Element element) Creates a Button widget that wraps an existing <a> element. This class inherits methods from the following classes − com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.FocusWidget com.google.gwt.user.client.ui.FocusWidget com.google.gwt.user.client.ui.ButtonBase com.google.gwt.user.client.ui.ButtonBase java.lang.Object java.lang.Object This example will take you through simple steps to show usage of a Button Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter − Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } .gwt-Button { color:red; } .gwt-Green-Button { color:green; } .gwt-Blue-Button { color:blue; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>Button Widget Demonstration</h1> <div id = "gwtContainer"></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Button widget. package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { public void onModuleLoad() { //create buttons Button redButton = new Button("Red"); Button greenButton = new Button("Green"); Button blueButton = new Button("Blue"); // use UIObject methods to set button properties. redButton.setWidth("100px"); greenButton.setWidth("100px"); blueButton.setWidth("100px"); greenButton.addStyleName("gwt-Green-Button"); blueButton.addStyleName("gwt-Blue-Button"); //add a clickListener to the button redButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.alert("Red Button clicked!"); } }); //add a clickListener to the button greenButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.alert("Green Button clicked!"); } }); //add a clickListener to the button blueButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.alert("Blue Button clicked!"); } }); // Add button to the root panel. VerticalPanel panel = new VerticalPanel(); panel.setSpacing(10); panel.add(redButton); panel.add(greenButton); panel.add(blueButton); RootPanel.get("gwtContainer").add(panel); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result − When you click Click Me button, it will show an alert message Hello World! Print Add Notes Bookmark this page
[ { "code": null, "e": 2076, "s": 2023, "text": "The Button widget represents a standard push button." }, { "code": null, "e": 2154, "s": 2076, "text": "Following is the declaration for com.google.gwt.user.client.ui.Button class −" }, { "code": null, "e": 2196, "s": 2154, "text": "public class Button\n extends ButtonBase" }, { "code": null, "e": 2317, "s": 2196, "text": "Following default CSS Style rule will be applied to all the Button widget. You can override it as per your requirements." }, { "code": null, "e": 2333, "s": 2317, "text": ".gwt-Button { }" }, { "code": null, "e": 2342, "s": 2333, "text": "Button()" }, { "code": null, "e": 2376, "s": 2342, "text": "Creates a button with no caption." }, { "code": null, "e": 2410, "s": 2376, "text": "protected Button(Element element)" }, { "code": null, "e": 2492, "s": 2410, "text": "This constructor may be used by subclasses to explicitly use an existing element." }, { "code": null, "e": 2522, "s": 2492, "text": "Button(java.lang.String html)" }, { "code": null, "e": 2568, "s": 2522, "text": "Creates a button with the given HTML caption." }, { "code": null, "e": 2622, "s": 2568, "text": "Button(java.lang.String html, ClickListener listener)" }, { "code": null, "e": 2688, "s": 2622, "text": " Creates a button with the given HTML caption and click listener." }, { "code": null, "e": 2696, "s": 2688, "text": "click()" }, { "code": null, "e": 2753, "s": 2696, "text": "Programmatic equivalent of the user clicking the button." }, { "code": null, "e": 2789, "s": 2753, "text": "static Button wrap(Element element)" }, { "code": null, "e": 2849, "s": 2789, "text": "Creates a Button widget that wraps an existing <a> element." }, { "code": null, "e": 2906, "s": 2849, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 2945, "s": 2906, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 2984, "s": 2945, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 3021, "s": 2984, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 3058, "s": 3021, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 3100, "s": 3058, "text": "com.google.gwt.user.client.ui.FocusWidget" }, { "code": null, "e": 3142, "s": 3100, "text": "com.google.gwt.user.client.ui.FocusWidget" }, { "code": null, "e": 3183, "s": 3142, "text": "com.google.gwt.user.client.ui.ButtonBase" }, { "code": null, "e": 3224, "s": 3183, "text": "com.google.gwt.user.client.ui.ButtonBase" }, { "code": null, "e": 3241, "s": 3224, "text": "java.lang.Object" }, { "code": null, "e": 3258, "s": 3241, "text": "java.lang.Object" }, { "code": null, "e": 3453, "s": 3258, "text": "This example will take you through simple steps to show usage of a Button Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −" }, { "code": null, "e": 3555, "s": 3453, "text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml." }, { "code": null, "e": 4164, "s": 3555, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 4242, "s": 4164, "text": "Following is the content of the modified Style Sheet file war/HelloWorld.css." }, { "code": null, "e": 4547, "s": 4242, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}\n\n.gwt-Button { \n color:red; \n}\n\n.gwt-Green-Button { \n color:green; \n}\n\n.gwt-Blue-Button { \n color:blue; \n}" }, { "code": null, "e": 4624, "s": 4547, "text": "Following is the content of the modified HTML host file war/HelloWorld.html." }, { "code": null, "e": 4949, "s": 4624, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>Button Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>" }, { "code": null, "e": 5076, "s": 4949, "text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of Button widget." }, { "code": null, "e": 6949, "s": 5076, "text": "package com.tutorialspoint.client;\n\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.event.dom.client.ClickEvent;\nimport com.google.gwt.event.dom.client.ClickHandler;\nimport com.google.gwt.user.client.Window;\nimport com.google.gwt.user.client.ui.Button;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.VerticalPanel;\n\npublic class HelloWorld implements EntryPoint {\n public void onModuleLoad() {\n\t \n //create buttons\n Button redButton = new Button(\"Red\");\n Button greenButton = new Button(\"Green\");\n Button blueButton = new Button(\"Blue\");\n \n // use UIObject methods to set button properties.\n redButton.setWidth(\"100px\");\n greenButton.setWidth(\"100px\");\n blueButton.setWidth(\"100px\");\n greenButton.addStyleName(\"gwt-Green-Button\");\n blueButton.addStyleName(\"gwt-Blue-Button\");\n \n //add a clickListener to the button\n redButton.addClickHandler(new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n Window.alert(\"Red Button clicked!\");\n }\n });\n\n //add a clickListener to the button\n greenButton.addClickHandler(new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n Window.alert(\"Green Button clicked!\");\n }\n });\n\n //add a clickListener to the button\n blueButton.addClickHandler(new ClickHandler() {\n @Override\n public void onClick(ClickEvent event) {\n Window.alert(\"Blue Button clicked!\");\n }\n });\n\n // Add button to the root panel.\n VerticalPanel panel = new VerticalPanel();\n panel.setSpacing(10);\n panel.add(redButton);\n panel.add(greenButton);\n panel.add(blueButton);\n \n RootPanel.get(\"gwtContainer\").add(panel);\n }\t\n}" }, { "code": null, "e": 7183, "s": 6949, "text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −" }, { "code": null, "e": 7258, "s": 7183, "text": "When you click Click Me button, it will show an alert message Hello World!" }, { "code": null, "e": 7265, "s": 7258, "text": " Print" }, { "code": null, "e": 7276, "s": 7265, "text": " Add Notes" } ]
Pyspark – demand forecasting data science project | by Alexandre Wrg | Towards Data Science
In this article, we will build a step-by-step demand forecasting project with Pyspark. Here, the list of tasks: Import dataFilter dataFeatures engineering (features creation)Imputing dataFeatures engineering (features transformation)Applying a gradient boosted tree regressorOptimise the model with Kfold and GridSearch MethodOneshot Import data Filter data Features engineering (features creation) Imputing data Features engineering (features transformation) Applying a gradient boosted tree regressor Optimise the model with Kfold and GridSearch Method Oneshot First we will import our data with a predefined schema. I work on a virtual machine on google cloud platform data comes from a bucket on cloud storage. Let’s import it. from pyspark.sql.types import *schema = StructType([StructField("DATE", DateType()),StructField("STORE", IntegerType()),StructField("NUMBERS_OF_TICKETS", IntegerType()),StructField("QTY", IntegerType()),StructField("CA", DoubleType()),StructField("FORMAT", StringType())])df = spark.read.csv("gs://my_bucket/my_table_in_csv_format", header = 'true', schema=schema) Then we will apply some filters, we will only work on hypermarkets and make sure that there are no negative quantities or missing date in the data for example. df = df.filter( (F.col("QTY") > 0) &(F.col("DATE").notNull())& (F.col("DATE").between("2015-01-01", "2019-01-01")) & (~F.col("FORMAT").isin(["PRO", "SUP"])) ) Then, we will define some variables that will be useful for modeling, such as date derivatives. df = (df .withColumn('yearday', F.dayofyear(F.col("DATE"))) .withColumn('Month', F.Month(F.col('DATE'))) .withColumn('dayofweek', F.dayofweek(F.col('DATE'))) .withColumn('YEAR', F.year(F.col('DATE'))) .withColumn('QUARTER', F.q(F.col('DATE'))) .withColumn('Month', F.Month(F.col('DATE'))) .withColumn('WeekOfYear', F.weekofyear(F.col('DATE'))) .withColumn('Week', F.date_trunc('week',F.col('DATE'))) .withColumn('MonthQuarter', F.when((df[DATE] <= 8), 0) .otherwise(F.when((df['DATE'] <= 16), 1) .otherwise(F.when((df['DATE'] <= 24), 2) .otherwise(3))))) Now we will calculate the reference quantity for each store i.e. the quantity that was sold for the same day 1 year ago. Nevertheless, it may happen that there has been no sale for this day so we will average a 7-day period around this reference date. this function will be more complex and requires numpy. It’s indeed possible to articulate numpy and spark, let’s see how. First, a user-defined function must be defined to extract the time series from each store in a vectorized and sparse way. We will define one that will create a sparse vector indexed with the days of the year and in values the associated quantities All right, let’s take a break, he has a few things to explain here. Input : we ask a list of days index and qty values associated Output : we return a sparse vector indexed by day that allow us to find qty related to his day index The whole thing is passed through an UDF and expected to be a VectorUDT to be concise this is a type of vector that can be manipulated by UDF. Then, to respond to the inputs requested by the function we will create an aggregated dataframe per year, store and apply a collect_list to the days and quantities. As you can see below, we recover all the day-quantity values of the store for its year. These two lists enter our UDF to create the desired vector, now we can work in numpy on this vector! Now we can define a function that will work on this vector and put it in a UDF again. and apply it : df= (df .join(self_join , ([self_join.p_id_store == df.STORE, self_join.year_join == df.year]), how = "left" ) .withColumn("qty_reference", getReference(F.col("yearday"), F.col("qties_vectorized"))) ) Let’s detail this function, first it tries to find the exact reference day, we have attached our dataframe on itself with its previous year so we want the current days to be equal to the index days in the vector and get the value. In case it is not possible to retrieve this value then we will define a window around this key date and average the values of this window. And finally the result : But instead of leaving them hard coded like that, we’re going to wrap everything in a Spark Pipeline. To do this we will create a class template that inherits from the Spark Transformer object like the one below and we will repeat this template for each variable. I’m not going to write the whole feature’s pipeline in this article but you can find it in the code on github. We will see at the end of this article how to put together this feature’s pipeline and insert it into the process. for more details on the features of this class template see my article... : https://towardsdatascience.com/pyspark-wrap-your-feature-engineering-in-a-pipeline-ee63bdb913 Let’s check if there’s some missing values. df.select([F.count(F.when(F.isnan(c) | F.col(c).isNull(), c)).alias(c) for c in df.columns]).show() There may not be any more but there could be some after the insertion of our new variables so we will define an Imputer that will come after the variable creation pipeline. from pyspark.ml.feature import Imputerimputer = Imputer( inputCols=df.columns, outputCols=["{}_imputed".format(c) for c in df.columns])#imputer.fit(df).transform(df) From this table extract below I will show you how we will proceed for the rest of the data transformations before insertion into the forecast algorithm. We will do the whole process in one go at the very end only. # needed importfrom pyspark.ml import Pipelinefrom pyspark.ml.feature import PCAfrom pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler Spark String Indexerencodes a string column of labels to a column of label indices. The indices are in [0, numLabels) the mapping is done by the highest frequency first. indexers = [ StringIndexer(inputCol=c, outputCol="{0}_indexedd".format(c), handleInvalid = 'error') for c in categorical_col]pip = Pipeline(stages = indexers)fitted_df =pip.fit(df)df = fitted_df.transform(df) Spark’s OneHotEncoder One-hot encoding maps a categorical feature, represented as a label index, to a binary vector with at most a single one-value indicating the presence of a specific feature value from among the set of all feature values. For string type input data, it is common to encode categorical features using StringIndexer first. indexers = [ StringIndexer(inputCol=c, outputCol="{0}_indexedd".format(c), handleInvalid = 'error') for c in categorical_col]encoders = [OneHotEncoder(dropLast=True,inputCol=indexer.getOutputCol(), outputCol="{0}_encodedd".format(indexer.getOutputCol())) for indexer in indexers]pip = Pipeline(stages = indexers + encoders)fitted_df =pip.fit(df)df = fitted_df.transform(df) Before executing our pipeline, let’s check if there are any missing values that can be annoying in our process. Before running our dimensional reduction algorithm we must pass all our variables in a vector assembler that will return a sparse representation of all our data. Then the PCA algorithm will take this vector to “reduce” it and return another sparse representation in a dataframe column. We saw how to index, one-hot encode our data, apply an PCA and put everything in a vector ready to be modeled. There are obviously other possibilities to Standardize, normalize...etc. nevertheless the global principle remains the same. Now our feature Inpure have the good shape to be modeled througout a Pyspark Algorithm. Split dataset X_train = final_dataset.filter(F.col('DATE').between("2015-01-02", "2018-06-01"))X_test = final_dataset.filter(F.col('DATE') > "2018-06-01")X_train = X_train.withColumn(target, F.log1p(F.col(target)))X_test = X_test.withColumn(target, F.log1p(F.col(target))) We will train a gradient boosted trees model to do a regression on total qty sold by day by store. target = 'QTY'gbt = GBTRegressor(featuresCol = 'Features', labelCol=target)fitted = gbt.fit(X_train)yhat = (fitted.transform(X_test) .withColumn("prediction", F.expm1(F.col("prediction"))) .withColumn(target, F.expm1(F.col(target))) ).select(F.col("prediction"), F.col("STORE").alias('SID_STORE'), F.col("DATE").alias("ID_DAY")).show() We will define a python object that we use as a basis to evaluate our model on different metrics. eval_ = RegressionEvaluator(labelCol= target, predictionCol= "prediction", metricName="rmse")rmse = eval_.evaluate(yhat)print('rmse is %.2f', %rmse)mae = eval_.evaluate(yhat, {eval_.metricName: "mae"})print('mae is %.2f', %mae)r2 = eval_.evaluate(yhat, {eval_.metricName: "r2"})print('R2 is %.2f', %r2) R2 is 0.84 rmse is 20081.54 mae is 13289.10 Model seems not bad we will try to improve it. We will try to optimize our GBDT with different parameters and make a kfold to ensure its robustness. from pyspark.ml.tuning import CrossValidator, ParamGridBuilderparamGrid = (ParamGridBuilder() .addGrid(gbt.maxDepth, [5, 8, 10, 12]) .addGrid(gbt.maxBins, [32, 64]) .build())cv = CrossValidator(estimator=gbt, estimatorParamMaps=paramGrid, evaluator=eval_, numFolds=3) cvModel = cv.fit(X_train)yhat = (cvModel.transform(X_test) .withColumn("prediction", F.expm1(F.col("prediction"))) .withColumn(target, F.expm1(F.col(target))) ) I only got 0.3 more points but that’s enough! :) bonus : features importances :) fi = fitted.featureImportances.toArray()import pandas as pdfeatures = [encoder.getOutputCol() for encoder in encoders] + \ [x +'_imputed' for x in numeric_col] + ['day', 'month', 'weekday', 'weekend', 'monthend', 'monthbegin', 'monthquarter', 'yearquarter']feat_imp = (pd.DataFrame(dict(zip(features, fi)), range(1)) .T.rename(columns={0:'Score'}) .sort_values("Score", ascending =False) ) N.B : In the features_utils package there are all the classes associated with the features pipeline. This article concludes my very brief guide on the various bricks of Pyspark for a data science project. I hope they will help even one person in his work. Pyspark is a very powerful tool on large volumes. He does not have the merit of having at his disposal a battery of algorithms like sklearn but he has the main ones and many resources. Feel free to let me know about anything you would like me to do with Pyspark and thank you ! You can find the code here : https://github.com/AlexWarembourg/Medium
[ { "code": null, "e": 284, "s": 172, "text": "In this article, we will build a step-by-step demand forecasting project with Pyspark. Here, the list of tasks:" }, { "code": null, "e": 506, "s": 284, "text": "Import dataFilter dataFeatures engineering (features creation)Imputing dataFeatures engineering (features transformation)Applying a gradient boosted tree regressorOptimise the model with Kfold and GridSearch MethodOneshot" }, { "code": null, "e": 518, "s": 506, "text": "Import data" }, { "code": null, "e": 530, "s": 518, "text": "Filter data" }, { "code": null, "e": 571, "s": 530, "text": "Features engineering (features creation)" }, { "code": null, "e": 585, "s": 571, "text": "Imputing data" }, { "code": null, "e": 632, "s": 585, "text": "Features engineering (features transformation)" }, { "code": null, "e": 675, "s": 632, "text": "Applying a gradient boosted tree regressor" }, { "code": null, "e": 727, "s": 675, "text": "Optimise the model with Kfold and GridSearch Method" }, { "code": null, "e": 735, "s": 727, "text": "Oneshot" }, { "code": null, "e": 904, "s": 735, "text": "First we will import our data with a predefined schema. I work on a virtual machine on google cloud platform data comes from a bucket on cloud storage. Let’s import it." }, { "code": null, "e": 1269, "s": 904, "text": "from pyspark.sql.types import *schema = StructType([StructField(\"DATE\", DateType()),StructField(\"STORE\", IntegerType()),StructField(\"NUMBERS_OF_TICKETS\", IntegerType()),StructField(\"QTY\", IntegerType()),StructField(\"CA\", DoubleType()),StructField(\"FORMAT\", StringType())])df = spark.read.csv(\"gs://my_bucket/my_table_in_csv_format\", header = 'true', schema=schema)" }, { "code": null, "e": 1429, "s": 1269, "text": "Then we will apply some filters, we will only work on hypermarkets and make sure that there are no negative quantities or missing date in the data for example." }, { "code": null, "e": 1588, "s": 1429, "text": "df = df.filter( (F.col(\"QTY\") > 0) &(F.col(\"DATE\").notNull())& (F.col(\"DATE\").between(\"2015-01-01\", \"2019-01-01\")) & (~F.col(\"FORMAT\").isin([\"PRO\", \"SUP\"])) )" }, { "code": null, "e": 1684, "s": 1588, "text": "Then, we will define some variables that will be useful for modeling, such as date derivatives." }, { "code": null, "e": 2334, "s": 1684, "text": "df = (df .withColumn('yearday', F.dayofyear(F.col(\"DATE\"))) .withColumn('Month', F.Month(F.col('DATE'))) .withColumn('dayofweek', F.dayofweek(F.col('DATE'))) .withColumn('YEAR', F.year(F.col('DATE'))) .withColumn('QUARTER', F.q(F.col('DATE'))) .withColumn('Month', F.Month(F.col('DATE'))) .withColumn('WeekOfYear', F.weekofyear(F.col('DATE'))) .withColumn('Week', F.date_trunc('week',F.col('DATE'))) .withColumn('MonthQuarter', F.when((df[DATE] <= 8), 0) .otherwise(F.when((df['DATE'] <= 16), 1) .otherwise(F.when((df['DATE'] <= 24), 2) .otherwise(3)))))" }, { "code": null, "e": 2708, "s": 2334, "text": "Now we will calculate the reference quantity for each store i.e. the quantity that was sold for the same day 1 year ago. Nevertheless, it may happen that there has been no sale for this day so we will average a 7-day period around this reference date. this function will be more complex and requires numpy. It’s indeed possible to articulate numpy and spark, let’s see how." }, { "code": null, "e": 2956, "s": 2708, "text": "First, a user-defined function must be defined to extract the time series from each store in a vectorized and sparse way. We will define one that will create a sparse vector indexed with the days of the year and in values the associated quantities" }, { "code": null, "e": 3024, "s": 2956, "text": "All right, let’s take a break, he has a few things to explain here." }, { "code": null, "e": 3086, "s": 3024, "text": "Input : we ask a list of days index and qty values associated" }, { "code": null, "e": 3187, "s": 3086, "text": "Output : we return a sparse vector indexed by day that allow us to find qty related to his day index" }, { "code": null, "e": 3330, "s": 3187, "text": "The whole thing is passed through an UDF and expected to be a VectorUDT to be concise this is a type of vector that can be manipulated by UDF." }, { "code": null, "e": 3684, "s": 3330, "text": "Then, to respond to the inputs requested by the function we will create an aggregated dataframe per year, store and apply a collect_list to the days and quantities. As you can see below, we recover all the day-quantity values of the store for its year. These two lists enter our UDF to create the desired vector, now we can work in numpy on this vector!" }, { "code": null, "e": 3770, "s": 3684, "text": "Now we can define a function that will work on this vector and put it in a UDF again." }, { "code": null, "e": 3785, "s": 3770, "text": "and apply it :" }, { "code": null, "e": 4025, "s": 3785, "text": "df= (df .join(self_join , ([self_join.p_id_store == df.STORE, self_join.year_join == df.year]), how = \"left\" ) .withColumn(\"qty_reference\", getReference(F.col(\"yearday\"), F.col(\"qties_vectorized\"))) )" }, { "code": null, "e": 4395, "s": 4025, "text": "Let’s detail this function, first it tries to find the exact reference day, we have attached our dataframe on itself with its previous year so we want the current days to be equal to the index days in the vector and get the value. In case it is not possible to retrieve this value then we will define a window around this key date and average the values of this window." }, { "code": null, "e": 4420, "s": 4395, "text": "And finally the result :" }, { "code": null, "e": 4910, "s": 4420, "text": "But instead of leaving them hard coded like that, we’re going to wrap everything in a Spark Pipeline. To do this we will create a class template that inherits from the Spark Transformer object like the one below and we will repeat this template for each variable. I’m not going to write the whole feature’s pipeline in this article but you can find it in the code on github. We will see at the end of this article how to put together this feature’s pipeline and insert it into the process." }, { "code": null, "e": 5080, "s": 4910, "text": "for more details on the features of this class template see my article... : https://towardsdatascience.com/pyspark-wrap-your-feature-engineering-in-a-pipeline-ee63bdb913" }, { "code": null, "e": 5124, "s": 5080, "text": "Let’s check if there’s some missing values." }, { "code": null, "e": 5224, "s": 5124, "text": "df.select([F.count(F.when(F.isnan(c) | F.col(c).isNull(), c)).alias(c) for c in df.columns]).show()" }, { "code": null, "e": 5397, "s": 5224, "text": "There may not be any more but there could be some after the insertion of our new variables so we will define an Imputer that will come after the variable creation pipeline." }, { "code": null, "e": 5570, "s": 5397, "text": "from pyspark.ml.feature import Imputerimputer = Imputer( inputCols=df.columns, outputCols=[\"{}_imputed\".format(c) for c in df.columns])#imputer.fit(df).transform(df)" }, { "code": null, "e": 5723, "s": 5570, "text": "From this table extract below I will show you how we will proceed for the rest of the data transformations before insertion into the forecast algorithm." }, { "code": null, "e": 5784, "s": 5723, "text": "We will do the whole process in one go at the very end only." }, { "code": null, "e": 5941, "s": 5784, "text": "# needed importfrom pyspark.ml import Pipelinefrom pyspark.ml.feature import PCAfrom pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssembler" }, { "code": null, "e": 6111, "s": 5941, "text": "Spark String Indexerencodes a string column of labels to a column of label indices. The indices are in [0, numLabels) the mapping is done by the highest frequency first." }, { "code": null, "e": 6320, "s": 6111, "text": "indexers = [ StringIndexer(inputCol=c, outputCol=\"{0}_indexedd\".format(c), handleInvalid = 'error') for c in categorical_col]pip = Pipeline(stages = indexers)fitted_df =pip.fit(df)df = fitted_df.transform(df)" }, { "code": null, "e": 6661, "s": 6320, "text": "Spark’s OneHotEncoder One-hot encoding maps a categorical feature, represented as a label index, to a binary vector with at most a single one-value indicating the presence of a specific feature value from among the set of all feature values. For string type input data, it is common to encode categorical features using StringIndexer first." }, { "code": null, "e": 7039, "s": 6661, "text": "indexers = [ StringIndexer(inputCol=c, outputCol=\"{0}_indexedd\".format(c), handleInvalid = 'error') for c in categorical_col]encoders = [OneHotEncoder(dropLast=True,inputCol=indexer.getOutputCol(), outputCol=\"{0}_encodedd\".format(indexer.getOutputCol())) for indexer in indexers]pip = Pipeline(stages = indexers + encoders)fitted_df =pip.fit(df)df = fitted_df.transform(df)" }, { "code": null, "e": 7437, "s": 7039, "text": "Before executing our pipeline, let’s check if there are any missing values that can be annoying in our process. Before running our dimensional reduction algorithm we must pass all our variables in a vector assembler that will return a sparse representation of all our data. Then the PCA algorithm will take this vector to “reduce” it and return another sparse representation in a dataframe column." }, { "code": null, "e": 7761, "s": 7437, "text": "We saw how to index, one-hot encode our data, apply an PCA and put everything in a vector ready to be modeled. There are obviously other possibilities to Standardize, normalize...etc. nevertheless the global principle remains the same. Now our feature Inpure have the good shape to be modeled througout a Pyspark Algorithm." }, { "code": null, "e": 7775, "s": 7761, "text": "Split dataset" }, { "code": null, "e": 8034, "s": 7775, "text": "X_train = final_dataset.filter(F.col('DATE').between(\"2015-01-02\", \"2018-06-01\"))X_test = final_dataset.filter(F.col('DATE') > \"2018-06-01\")X_train = X_train.withColumn(target, F.log1p(F.col(target)))X_test = X_test.withColumn(target, F.log1p(F.col(target)))" }, { "code": null, "e": 8133, "s": 8034, "text": "We will train a gradient boosted trees model to do a regression on total qty sold by day by store." }, { "code": null, "e": 8478, "s": 8133, "text": "target = 'QTY'gbt = GBTRegressor(featuresCol = 'Features', labelCol=target)fitted = gbt.fit(X_train)yhat = (fitted.transform(X_test) .withColumn(\"prediction\", F.expm1(F.col(\"prediction\"))) .withColumn(target, F.expm1(F.col(target))) ).select(F.col(\"prediction\"), F.col(\"STORE\").alias('SID_STORE'), F.col(\"DATE\").alias(\"ID_DAY\")).show()" }, { "code": null, "e": 8576, "s": 8478, "text": "We will define a python object that we use as a basis to evaluate our model on different metrics." }, { "code": null, "e": 8879, "s": 8576, "text": "eval_ = RegressionEvaluator(labelCol= target, predictionCol= \"prediction\", metricName=\"rmse\")rmse = eval_.evaluate(yhat)print('rmse is %.2f', %rmse)mae = eval_.evaluate(yhat, {eval_.metricName: \"mae\"})print('mae is %.2f', %mae)r2 = eval_.evaluate(yhat, {eval_.metricName: \"r2\"})print('R2 is %.2f', %r2)" }, { "code": null, "e": 8890, "s": 8879, "text": "R2 is 0.84" }, { "code": null, "e": 8907, "s": 8890, "text": "rmse is 20081.54" }, { "code": null, "e": 8923, "s": 8907, "text": "mae is 13289.10" }, { "code": null, "e": 8970, "s": 8923, "text": "Model seems not bad we will try to improve it." }, { "code": null, "e": 9072, "s": 8970, "text": "We will try to optimize our GBDT with different parameters and make a kfold to ensure its robustness." }, { "code": null, "e": 9622, "s": 9072, "text": "from pyspark.ml.tuning import CrossValidator, ParamGridBuilderparamGrid = (ParamGridBuilder() .addGrid(gbt.maxDepth, [5, 8, 10, 12]) .addGrid(gbt.maxBins, [32, 64]) .build())cv = CrossValidator(estimator=gbt, estimatorParamMaps=paramGrid, evaluator=eval_, numFolds=3) cvModel = cv.fit(X_train)yhat = (cvModel.transform(X_test) .withColumn(\"prediction\", F.expm1(F.col(\"prediction\"))) .withColumn(target, F.expm1(F.col(target))) )" }, { "code": null, "e": 9671, "s": 9622, "text": "I only got 0.3 more points but that’s enough! :)" }, { "code": null, "e": 9703, "s": 9671, "text": "bonus : features importances :)" }, { "code": null, "e": 10096, "s": 9703, "text": "fi = fitted.featureImportances.toArray()import pandas as pdfeatures = [encoder.getOutputCol() for encoder in encoders] + \\ [x +'_imputed' for x in numeric_col] + ['day', 'month', 'weekday', 'weekend', 'monthend', 'monthbegin', 'monthquarter', 'yearquarter']feat_imp = (pd.DataFrame(dict(zip(features, fi)), range(1)) .T.rename(columns={0:'Score'}) .sort_values(\"Score\", ascending =False) )" }, { "code": null, "e": 10197, "s": 10096, "text": "N.B : In the features_utils package there are all the classes associated with the features pipeline." }, { "code": null, "e": 10537, "s": 10197, "text": "This article concludes my very brief guide on the various bricks of Pyspark for a data science project. I hope they will help even one person in his work. Pyspark is a very powerful tool on large volumes. He does not have the merit of having at his disposal a battery of algorithms like sklearn but he has the main ones and many resources." }, { "code": null, "e": 10630, "s": 10537, "text": "Feel free to let me know about anything you would like me to do with Pyspark and thank you !" } ]
Isolation Forest from Scratch. Implementation of Isolation forest from... | by Carlos Mougan | Towards Data Science
Lately, I have been reading about Isolation Forest and its performance in outlier/anomaly detection. After carefully reading about the algorithm (and not finding any vanilla tutorial of my taste). I decided to code it from scratch in the simplest possible way in order to grasp the algorithm better. The goal of this post is that after reading it you can understand Isolation Forest in-depth, its strength, weakness, parameters and you are able to use it whenever you consider with knowledge of the algorithm. For this blog/implementation, I have used this paper about Isolation forest for the pseudo-code, this Extended Isolation Forest paper for the visualizations (that corresponds with this other blog post) and using this youtube tutorial example of Random Forest implementation from Sebastian Mantey Before getting to the code I believe that there is the need for a bit of theory. Isolation Forest is used for outlier/anomaly detection Isolation Forest is an Unsupervised Learning technique (does not need label) Uses Binary Decision Trees bagging (resembles Random Forest, in supervised learning) This method isolates anomalies from normal instances, for doing this the following assumptions for anomalies are made: They are a minority consisting of fewer instances They have attribute-values that are different from normal instances In other words, anomalies are “few and different.” Because of these first two assumptions, anomalies are susceptible to be isolated and this makes them fall closer to the root of the tree. Isolation Forest builds an ensemble of Binary Trees for a given dataset. Anomalies, due to their nature, they have the shortest path in the trees than normal instances. Isolation Forest converges quickly with a very small number of trees and subsampling enables us to achieve good results while being computationally efficient. The overall code strategy will be the following. First coding a tree, then doing a forest of trees (ensembling) and finally measuring how far a certain instance goes in each tree and determining whether it is or not an outlier. Let’s start with the tree The input will be a sample of the data, the current tree height, and the maximum depth. For the output, we will have a built tree. To make it easier to follow I am working with pandas data frames, even if it is not optimal in terms of performance, makes it easier to follow for regular users. Selecting a feature(column) of the data def select_feature(data): return random.choice(data.columns) Select a random value within the range def select_value(data,feat): mini = data[feat].min() maxi = data[feat].max() return (maxi-mini)*np.random.random()+mini Split data def split_data(data, split_column, split_value): data_below = data[data[split_column] <= split_value] data_above = data[data[split_column] > split_value] return data_below, data_above All together: The Isolation Tree. The idea is the following: selecting a feature, a value of the feature, and splitting the data. If there is only one data point in the branch or the tree has reached the maximum depth: stop. def isolation_tree(data,counter=0, max_depth=50,random_subspace=False): # End Loop if max depth or isolated if (counter == max_depth) or data.shape[0]<=1: classification = classify_data(data) return classification else: # Counter counter +=1 # Select feature split_column = select_feature(data) # Select value split_value = select_value(data,split_column) # Split data data_below, data_above = split_data(data,split_column,split_value) # instantiate sub-tree question = "{} <= {}".format(split_column, split_value) sub_tree = {question: []} # Recursive part below_answer = isolation_tree(data_below, counter,max_depth=max_depth) above_answer = isolation_tree(data_above, counter,max_depth=max_depth) if below_answer == above_answer: sub_tree = below_answer else: sub_tree[question].append(below_answer) sub_tree[question].append(above_answer) return sub_tree Once we have our tree, we have to make a forest of them. The pseudo-code is the following: Given an input data, a number of trees and a sampling size (how many data is fed to each tree), we fit as many trees as desired and return a forest. The actual code: def isolation_forest(df,n_trees=5, max_depth=5, subspace=256): forest = []for i in range(n_trees): # Sample the subspace if subspace<=1: df = df.sample(frac=subspace) else: df = df.sample(subspace) # Fit tree tree = isolation_tree(df,max_depth=max_depth) # Save tree to forest forest.append(tree) return forest After having built an Isolation Forest, we have to evaluate instances, for that we define Path Length Given an instance and an Isolation Tree, we compute how many nodes does each instance goes through before being isolated or reaching maximum depth. The pseudo code is extracted from Isolation forest paper. def pathLength(example,iTree,path=0,trace=False): # Initialize question and counter path=path+1 question = list(iTree.keys())[0] feature_name, comparison_operator, value = question.split() # ask question if example[feature_name].values <= float(value): answer = iTree[question][0] else: answer = iTree[question][1] # base case if not isinstance(answer, dict): return path # recursive part else: residual_tree = answer return pathLength(example, residual_tree,path=path)return path This is just counting how many nodes an instance goes through given how data has been stored before. Let’s play a little bit around to see mean = [0, 0]cov = [[1, 0], [0, 1]] # diagonal covarianceNobjs = 2000x, y = np.random.multivariate_normal(mean, cov, Nobjs).T#Add manual outlierx[0]=3.3y[0]=3.3X=np.array([x,y]).TX = pd.DataFrame(X,columns=['feat1','feat2'])plt.figure(figsize=(7,7))plt.plot(x,y,'bo'); We will train and evaluate with our data. iForest = isolation_forest(X,n_trees=20, max_depth=100, subspace=256)# Evaluate one instancedef evaluate_instance(instance,forest): paths = [] for tree in forest: paths.append(pathLength(instance,tree)) return paths We select one normal instance of the data (selected at random) and an outlier (remember that we hardcoded an outlier at the beginning as the first row). we see how far in the tree does it fall and plot the results. outlier = evaluate_instance(X.head(1),iForest)normal = evaluate_instance(X.sample(1),iForest) In blue a random normal sample, in red an outlier. np.mean(outlier)# 4.85np.mean(normal)# 12.55 We can see that there is a visual and statistical difference between the normal sample and the outlier in how deep instance falls in each tree. From the paper of Extended Isolation Forest, there is another visualization in a radial form that provides a clear intuition of the outlier A more formal way to evaluate the forest is using the anomaly score (s) of an instance (x): Where H(i) is the harmonic number and it can be estimated by ln(i) + 0.5772156649 (Euler’s constant). As c(n) is the average of h(x) given n, we use it to normalize h(x). def c_factor(n) : """ Average path length of unsuccesful search in a binary search tree given n points Parameters ---------- n : int Number of data points for the BST. Returns ------- float Average path length of unsuccesful search in a BST """ return 2.0*(np.log(n-1)+0.5772156649) - (2.0*(n-1.)/(n*1.0))def anomaly_score(data_point,forest,n): ''' Anomaly Score Returns ------- 0.5 -- sample does not have any distinct anomaly 0 -- Normal Instance 1 -- An anomaly ''' # Mean depth for an instance E = np.mean(evaluate_instance(data_point,forest)) c = c_factor(n) return 2**-(E/c) Using this method we can get a mathematical definition of what is an outlier, but I believe that stopping here already allows you to have an intuition of how does the algorithm work, what are the parameters, and for which cases it might be successful. Feel free to drop any comments or to DM message me with suggestions or anything else. This blog has been done following [1] Isolation forest paper for the pseudo-code from Fei Tony Liu, Kai Ming Ting and Zhi-Hua Zhou [2] Extended isolation forest for the visualizations (that corresponds with this other blog post) [3] Youtube Random Forest implementation from Sebastian Mantey The full code, notebook, and images can be seen in this repository
[ { "code": null, "e": 472, "s": 172, "text": "Lately, I have been reading about Isolation Forest and its performance in outlier/anomaly detection. After carefully reading about the algorithm (and not finding any vanilla tutorial of my taste). I decided to code it from scratch in the simplest possible way in order to grasp the algorithm better." }, { "code": null, "e": 682, "s": 472, "text": "The goal of this post is that after reading it you can understand Isolation Forest in-depth, its strength, weakness, parameters and you are able to use it whenever you consider with knowledge of the algorithm." }, { "code": null, "e": 978, "s": 682, "text": "For this blog/implementation, I have used this paper about Isolation forest for the pseudo-code, this Extended Isolation Forest paper for the visualizations (that corresponds with this other blog post) and using this youtube tutorial example of Random Forest implementation from Sebastian Mantey" }, { "code": null, "e": 1059, "s": 978, "text": "Before getting to the code I believe that there is the need for a bit of theory." }, { "code": null, "e": 1114, "s": 1059, "text": "Isolation Forest is used for outlier/anomaly detection" }, { "code": null, "e": 1191, "s": 1114, "text": "Isolation Forest is an Unsupervised Learning technique (does not need label)" }, { "code": null, "e": 1276, "s": 1191, "text": "Uses Binary Decision Trees bagging (resembles Random Forest, in supervised learning)" }, { "code": null, "e": 1395, "s": 1276, "text": "This method isolates anomalies from normal instances, for doing this the following assumptions for anomalies are made:" }, { "code": null, "e": 1445, "s": 1395, "text": "They are a minority consisting of fewer instances" }, { "code": null, "e": 1513, "s": 1445, "text": "They have attribute-values that are different from normal instances" }, { "code": null, "e": 1564, "s": 1513, "text": "In other words, anomalies are “few and different.”" }, { "code": null, "e": 1702, "s": 1564, "text": "Because of these first two assumptions, anomalies are susceptible to be isolated and this makes them fall closer to the root of the tree." }, { "code": null, "e": 1871, "s": 1702, "text": "Isolation Forest builds an ensemble of Binary Trees for a given dataset. Anomalies, due to their nature, they have the shortest path in the trees than normal instances." }, { "code": null, "e": 2030, "s": 1871, "text": "Isolation Forest converges quickly with a very small number of trees and subsampling enables us to achieve good results while being computationally efficient." }, { "code": null, "e": 2258, "s": 2030, "text": "The overall code strategy will be the following. First coding a tree, then doing a forest of trees (ensembling) and finally measuring how far a certain instance goes in each tree and determining whether it is or not an outlier." }, { "code": null, "e": 2284, "s": 2258, "text": "Let’s start with the tree" }, { "code": null, "e": 2372, "s": 2284, "text": "The input will be a sample of the data, the current tree height, and the maximum depth." }, { "code": null, "e": 2415, "s": 2372, "text": "For the output, we will have a built tree." }, { "code": null, "e": 2577, "s": 2415, "text": "To make it easier to follow I am working with pandas data frames, even if it is not optimal in terms of performance, makes it easier to follow for regular users." }, { "code": null, "e": 2617, "s": 2577, "text": "Selecting a feature(column) of the data" }, { "code": null, "e": 2682, "s": 2617, "text": "def select_feature(data): return random.choice(data.columns)" }, { "code": null, "e": 2721, "s": 2682, "text": "Select a random value within the range" }, { "code": null, "e": 2850, "s": 2721, "text": "def select_value(data,feat): mini = data[feat].min() maxi = data[feat].max() return (maxi-mini)*np.random.random()+mini" }, { "code": null, "e": 2861, "s": 2850, "text": "Split data" }, { "code": null, "e": 3059, "s": 2861, "text": "def split_data(data, split_column, split_value): data_below = data[data[split_column] <= split_value] data_above = data[data[split_column] > split_value] return data_below, data_above" }, { "code": null, "e": 3093, "s": 3059, "text": "All together: The Isolation Tree." }, { "code": null, "e": 3284, "s": 3093, "text": "The idea is the following: selecting a feature, a value of the feature, and splitting the data. If there is only one data point in the branch or the tree has reached the maximum depth: stop." }, { "code": null, "e": 4380, "s": 3284, "text": "def isolation_tree(data,counter=0, max_depth=50,random_subspace=False): # End Loop if max depth or isolated if (counter == max_depth) or data.shape[0]<=1: classification = classify_data(data) return classification else: # Counter counter +=1 # Select feature split_column = select_feature(data) # Select value split_value = select_value(data,split_column) # Split data data_below, data_above = split_data(data,split_column,split_value) # instantiate sub-tree question = \"{} <= {}\".format(split_column, split_value) sub_tree = {question: []} # Recursive part below_answer = isolation_tree(data_below, counter,max_depth=max_depth) above_answer = isolation_tree(data_above, counter,max_depth=max_depth) if below_answer == above_answer: sub_tree = below_answer else: sub_tree[question].append(below_answer) sub_tree[question].append(above_answer) return sub_tree" }, { "code": null, "e": 4471, "s": 4380, "text": "Once we have our tree, we have to make a forest of them. The pseudo-code is the following:" }, { "code": null, "e": 4620, "s": 4471, "text": "Given an input data, a number of trees and a sampling size (how many data is fed to each tree), we fit as many trees as desired and return a forest." }, { "code": null, "e": 4637, "s": 4620, "text": "The actual code:" }, { "code": null, "e": 5037, "s": 4637, "text": "def isolation_forest(df,n_trees=5, max_depth=5, subspace=256): forest = []for i in range(n_trees): # Sample the subspace if subspace<=1: df = df.sample(frac=subspace) else: df = df.sample(subspace) # Fit tree tree = isolation_tree(df,max_depth=max_depth) # Save tree to forest forest.append(tree) return forest" }, { "code": null, "e": 5139, "s": 5037, "text": "After having built an Isolation Forest, we have to evaluate instances, for that we define Path Length" }, { "code": null, "e": 5287, "s": 5139, "text": "Given an instance and an Isolation Tree, we compute how many nodes does each instance goes through before being isolated or reaching maximum depth." }, { "code": null, "e": 5345, "s": 5287, "text": "The pseudo code is extracted from Isolation forest paper." }, { "code": null, "e": 5916, "s": 5345, "text": "def pathLength(example,iTree,path=0,trace=False): # Initialize question and counter path=path+1 question = list(iTree.keys())[0] feature_name, comparison_operator, value = question.split() # ask question if example[feature_name].values <= float(value): answer = iTree[question][0] else: answer = iTree[question][1] # base case if not isinstance(answer, dict): return path # recursive part else: residual_tree = answer return pathLength(example, residual_tree,path=path)return path" }, { "code": null, "e": 6017, "s": 5916, "text": "This is just counting how many nodes an instance goes through given how data has been stored before." }, { "code": null, "e": 6055, "s": 6017, "text": "Let’s play a little bit around to see" }, { "code": null, "e": 6325, "s": 6055, "text": "mean = [0, 0]cov = [[1, 0], [0, 1]] # diagonal covarianceNobjs = 2000x, y = np.random.multivariate_normal(mean, cov, Nobjs).T#Add manual outlierx[0]=3.3y[0]=3.3X=np.array([x,y]).TX = pd.DataFrame(X,columns=['feat1','feat2'])plt.figure(figsize=(7,7))plt.plot(x,y,'bo');" }, { "code": null, "e": 6367, "s": 6325, "text": "We will train and evaluate with our data." }, { "code": null, "e": 6599, "s": 6367, "text": "iForest = isolation_forest(X,n_trees=20, max_depth=100, subspace=256)# Evaluate one instancedef evaluate_instance(instance,forest): paths = [] for tree in forest: paths.append(pathLength(instance,tree)) return paths" }, { "code": null, "e": 6814, "s": 6599, "text": "We select one normal instance of the data (selected at random) and an outlier (remember that we hardcoded an outlier at the beginning as the first row). we see how far in the tree does it fall and plot the results." }, { "code": null, "e": 6909, "s": 6814, "text": "outlier = evaluate_instance(X.head(1),iForest)normal = evaluate_instance(X.sample(1),iForest)" }, { "code": null, "e": 6960, "s": 6909, "text": "In blue a random normal sample, in red an outlier." }, { "code": null, "e": 7005, "s": 6960, "text": "np.mean(outlier)# 4.85np.mean(normal)# 12.55" }, { "code": null, "e": 7149, "s": 7005, "text": "We can see that there is a visual and statistical difference between the normal sample and the outlier in how deep instance falls in each tree." }, { "code": null, "e": 7289, "s": 7149, "text": "From the paper of Extended Isolation Forest, there is another visualization in a radial form that provides a clear intuition of the outlier" }, { "code": null, "e": 7381, "s": 7289, "text": "A more formal way to evaluate the forest is using the anomaly score (s) of an instance (x):" }, { "code": null, "e": 7552, "s": 7381, "text": "Where H(i) is the harmonic number and it can be estimated by ln(i) + 0.5772156649 (Euler’s constant). As c(n) is the average of h(x) given n, we use it to normalize h(x)." }, { "code": null, "e": 8241, "s": 7552, "text": "def c_factor(n) : \"\"\" Average path length of unsuccesful search in a binary search tree given n points Parameters ---------- n : int Number of data points for the BST. Returns ------- float Average path length of unsuccesful search in a BST \"\"\" return 2.0*(np.log(n-1)+0.5772156649) - (2.0*(n-1.)/(n*1.0))def anomaly_score(data_point,forest,n): ''' Anomaly Score Returns ------- 0.5 -- sample does not have any distinct anomaly 0 -- Normal Instance 1 -- An anomaly ''' # Mean depth for an instance E = np.mean(evaluate_instance(data_point,forest)) c = c_factor(n) return 2**-(E/c)" }, { "code": null, "e": 8493, "s": 8241, "text": "Using this method we can get a mathematical definition of what is an outlier, but I believe that stopping here already allows you to have an intuition of how does the algorithm work, what are the parameters, and for which cases it might be successful." }, { "code": null, "e": 8579, "s": 8493, "text": "Feel free to drop any comments or to DM message me with suggestions or anything else." }, { "code": null, "e": 8613, "s": 8579, "text": "This blog has been done following" }, { "code": null, "e": 8710, "s": 8613, "text": "[1] Isolation forest paper for the pseudo-code from Fei Tony Liu, Kai Ming Ting and Zhi-Hua Zhou" }, { "code": null, "e": 8808, "s": 8710, "text": "[2] Extended isolation forest for the visualizations (that corresponds with this other blog post)" }, { "code": null, "e": 8871, "s": 8808, "text": "[3] Youtube Random Forest implementation from Sebastian Mantey" } ]
C - Constants and Literals
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well. Constants are treated just like regular variables except that their values cannot be modified after their definition. An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here are some examples of integer literals − 212 /* Legal */ 215u /* Legal */ 0xFeeL /* Legal */ 078 /* Illegal: 8 is not an octal digit */ 032UU /* Illegal: cannot repeat a suffix */ Following are other examples of various types of integer literals − 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */ A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. While representing decimal form, you must include the decimal point, the exponent, or both; and while representing exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here are some examples of floating-point literals − 3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */ Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). There are certain characters in C that represent special meaning when preceded by a backslash for example, newline (\n) or tab (\t). Here, you have a list of such escape sequence codes − Escape sequence Meaning \\ \ character \' ' character \" " character \? ? character \a Alert or bell \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \ooo Octal number of one to three digits \xhh . . . Hexadecimal number of one or more digits Following is the example to show a few escape sequence characters − #include <stdio.h> int main() { printf("Hello\tWorld\n\n"); return 0; } When the above code is compiled and executed, it produces the following result − Hello World String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using white spaces. Here are some examples of string literals. All the three forms are identical strings. "hello, dear" "hello, \ dear" "hello, " "d" "ear" There are two simple ways in C to define constants − Using #define preprocessor. Using #define preprocessor. Using const keyword. Using const keyword. Given below is the form to use #define preprocessor to define a constant − #define identifier value The following example explains it in detail − #include <stdio.h> #define LENGTH 10 #define WIDTH 5 #define NEWLINE '\n' int main() { int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0; } When the above code is compiled and executed, it produces the following result − value of area : 50 You can use const prefix to declare constants with a specific type as follows − const type variable = value; The following example explains it in detail − #include <stdio.h> int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; printf("value of area : %d", area); printf("%c", NEWLINE); return 0; } When the above code is compiled and executed, it produces the following result − value of area : 50 Note that it is a good programming practice to define constants in CAPITALS. Print Add Notes Bookmark this page
[ { "code": null, "e": 2214, "s": 2084, "text": "Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals." }, { "code": null, "e": 2393, "s": 2214, "text": "Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well." }, { "code": null, "e": 2511, "s": 2393, "text": "Constants are treated just like regular variables except that their values cannot be modified after their definition." }, { "code": null, "e": 2682, "s": 2511, "text": "An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal." }, { "code": null, "e": 2861, "s": 2682, "text": "An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order." }, { "code": null, "e": 2906, "s": 2861, "text": "Here are some examples of integer literals −" }, { "code": null, "e": 3080, "s": 2906, "text": "212 /* Legal */\n215u /* Legal */\n0xFeeL /* Legal */\n078 /* Illegal: 8 is not an octal digit */\n032UU /* Illegal: cannot repeat a suffix */\n" }, { "code": null, "e": 3148, "s": 3080, "text": "Following are other examples of various types of integer literals −" }, { "code": null, "e": 3330, "s": 3148, "text": "85 /* decimal */\n0213 /* octal */\n0x4b /* hexadecimal */\n30 /* int */\n30u /* unsigned int */\n30l /* long */\n30ul /* unsigned long */\n" }, { "code": null, "e": 3520, "s": 3330, "text": "A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form." }, { "code": null, "e": 3763, "s": 3520, "text": "While representing decimal form, you must include the decimal point, the exponent, or both; and while representing exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E." }, { "code": null, "e": 3815, "s": 3763, "text": "Here are some examples of floating-point literals −" }, { "code": null, "e": 4026, "s": 3815, "text": "3.14159 /* Legal */\n314159E-5L /* Legal */\n510E /* Illegal: incomplete exponent */\n210f /* Illegal: no decimal or exponent */\n.e55 /* Illegal: missing integer or fraction */\n" }, { "code": null, "e": 4135, "s": 4026, "text": "Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type." }, { "code": null, "e": 4269, "s": 4135, "text": "A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\\t'), or a universal character (e.g., '\\u02C0')." }, { "code": null, "e": 4402, "s": 4269, "text": "There are certain characters in C that represent special meaning when preceded by a backslash for example, newline (\\n) or tab (\\t)." }, { "code": null, "e": 4776, "s": 4402, "text": "\n\nHere, you have a list of such escape sequence codes −\n\n\n\nEscape sequence\nMeaning\n\n\n\\\\\n\\ character\n\n\n\\'\n ' character\n\n\n\\\"\n\" character\n\n\n\\?\n? character\n\n\n\\a\nAlert or bell\n\n\n\\b\nBackspace\n\n\n\\f\nForm feed\n\n\n\\n\nNewline\n\n\n\\r\nCarriage return\n\n\n\\t\nHorizontal tab\n\n\n\\v\nVertical tab\n\n\n\\ooo\nOctal number of one to three digits\n\n\n\\xhh . . .\nHexadecimal number of one or more digits\n\n\n\n" }, { "code": null, "e": 4844, "s": 4776, "text": "Following is the example to show a few escape sequence characters −" }, { "code": null, "e": 4924, "s": 4844, "text": "#include <stdio.h>\n\nint main() {\n printf(\"Hello\\tWorld\\n\\n\");\n\n return 0;\n}" }, { "code": null, "e": 5005, "s": 4924, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5018, "s": 5005, "text": "Hello World\n" }, { "code": null, "e": 5212, "s": 5018, "text": "String literals or constants are enclosed in double quotes \"\". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters." }, { "code": null, "e": 5320, "s": 5212, "text": "You can break a long line into multiple lines using string literals and separating them using white spaces." }, { "code": null, "e": 5406, "s": 5320, "text": "Here are some examples of string literals. All the three forms are identical strings." }, { "code": null, "e": 5460, "s": 5406, "text": "\"hello, dear\"\n\n\"hello, \\\n\ndear\"\n\n\"hello, \" \"d\" \"ear\"\n" }, { "code": null, "e": 5513, "s": 5460, "text": "There are two simple ways in C to define constants −" }, { "code": null, "e": 5541, "s": 5513, "text": "Using #define preprocessor." }, { "code": null, "e": 5569, "s": 5541, "text": "Using #define preprocessor." }, { "code": null, "e": 5590, "s": 5569, "text": "Using const keyword." }, { "code": null, "e": 5611, "s": 5590, "text": "Using const keyword." }, { "code": null, "e": 5686, "s": 5611, "text": "Given below is the form to use #define preprocessor to define a constant −" }, { "code": null, "e": 5712, "s": 5686, "text": "#define identifier value\n" }, { "code": null, "e": 5758, "s": 5712, "text": "The following example explains it in detail −" }, { "code": null, "e": 5976, "s": 5758, "text": "#include <stdio.h>\n\n#define LENGTH 10 \n#define WIDTH 5\n#define NEWLINE '\\n'\n\nint main() {\n int area; \n \n area = LENGTH * WIDTH;\n printf(\"value of area : %d\", area);\n printf(\"%c\", NEWLINE);\n\n return 0;\n}" }, { "code": null, "e": 6057, "s": 5976, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6077, "s": 6057, "text": "value of area : 50\n" }, { "code": null, "e": 6157, "s": 6077, "text": "You can use const prefix to declare constants with a specific type as follows −" }, { "code": null, "e": 6187, "s": 6157, "text": "const type variable = value;\n" }, { "code": null, "e": 6233, "s": 6187, "text": "The following example explains it in detail −" }, { "code": null, "e": 6474, "s": 6233, "text": "#include <stdio.h>\n\nint main() {\n const int LENGTH = 10;\n const int WIDTH = 5;\n const char NEWLINE = '\\n';\n int area; \n \n area = LENGTH * WIDTH;\n printf(\"value of area : %d\", area);\n printf(\"%c\", NEWLINE);\n\n return 0;\n}" }, { "code": null, "e": 6555, "s": 6474, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6575, "s": 6555, "text": "value of area : 50\n" }, { "code": null, "e": 6652, "s": 6575, "text": "Note that it is a good programming practice to define constants in CAPITALS." }, { "code": null, "e": 6659, "s": 6652, "text": " Print" }, { "code": null, "e": 6670, "s": 6659, "text": " Add Notes" } ]
C# StartsWith() Method
The StartsWith() method in C# is used to determine whether the beginning of this string instance matches the specified string. public bool StartsWith (string val); Above, val is the string to compare. Live Demo using System; public class Demo { public static void Main() { string str = "JohnAndJacob"; Console.WriteLine("String = "+str); Console.WriteLine("Does String begins with J? = "+str.StartsWith("J")); char[] destArr = new char[20]; str.CopyTo(1, destArr, 0, 4); Console.Write(destArr); } } This will produce the following output - String = JohnAndJacob Does String begins with J? = True ohnA Let us now see another example - Live Demo using System; public class Demo { public static void Main(String[] args) { string str1 = "Akon"; string str2 = "Eminem"; Console.WriteLine("String 1 = "+str1); Console.WriteLine("HashCode of String 1 = "+str1.GetHashCode()); Console.WriteLine("Does String1 begins with E? = "+str1.StartsWith("E")); Console.WriteLine("\nString 2 = "+str2); Console.WriteLine("HashCode of String 2 = "+str2.GetHashCode()); Console.WriteLine("Does String2 begins with E? = "+str2.StartsWith("E")); Console.WriteLine("\nString 1 is equal to String 2? = {0}", str1.Equals(str2)); } } This will produce the following output - String 1 = Akon HashCode of String 1 = 416613838 Does String1 begins with E? = False String 2 = Eminem HashCode of String 2 = 40371907 Does String2 begins with E? = True String 1 is equal to String 2? = False
[ { "code": null, "e": 1189, "s": 1062, "text": "The StartsWith() method in C# is used to determine whether the beginning of this string instance matches the specified string." }, { "code": null, "e": 1226, "s": 1189, "text": "public bool StartsWith (string val);" }, { "code": null, "e": 1263, "s": 1226, "text": "Above, val is the string to compare." }, { "code": null, "e": 1274, "s": 1263, "text": " Live Demo" }, { "code": null, "e": 1604, "s": 1274, "text": "using System;\npublic class Demo {\n public static void Main() {\n string str = \"JohnAndJacob\";\n Console.WriteLine(\"String = \"+str);\n Console.WriteLine(\"Does String begins with J? = \"+str.StartsWith(\"J\"));\n char[] destArr = new char[20];\n str.CopyTo(1, destArr, 0, 4);\n Console.Write(destArr);\n }\n}" }, { "code": null, "e": 1645, "s": 1604, "text": "This will produce the following output -" }, { "code": null, "e": 1706, "s": 1645, "text": "String = JohnAndJacob\nDoes String begins with J? = True\nohnA" }, { "code": null, "e": 1739, "s": 1706, "text": "Let us now see another example -" }, { "code": null, "e": 1750, "s": 1739, "text": " Live Demo" }, { "code": null, "e": 2373, "s": 1750, "text": "using System;\npublic class Demo {\n public static void Main(String[] args) {\n string str1 = \"Akon\";\n string str2 = \"Eminem\";\n Console.WriteLine(\"String 1 = \"+str1);\n Console.WriteLine(\"HashCode of String 1 = \"+str1.GetHashCode());\n Console.WriteLine(\"Does String1 begins with E? = \"+str1.StartsWith(\"E\"));\n Console.WriteLine(\"\\nString 2 = \"+str2);\n Console.WriteLine(\"HashCode of String 2 = \"+str2.GetHashCode());\n Console.WriteLine(\"Does String2 begins with E? = \"+str2.StartsWith(\"E\"));\n Console.WriteLine(\"\\nString 1 is equal to String 2? = {0}\", str1.Equals(str2));\n }\n}" }, { "code": null, "e": 2414, "s": 2373, "text": "This will produce the following output -" }, { "code": null, "e": 2623, "s": 2414, "text": "String 1 = Akon\nHashCode of String 1 = 416613838\nDoes String1 begins with E? = False\nString 2 = Eminem\nHashCode of String 2 = 40371907\nDoes String2 begins with E? = True\nString 1 is equal to String 2? = False" } ]
How to copy a collection from one database to another in MongoDB?
In MongoDB, the command does not exist to copy a collection from one database to another. To achieve it, use the below concept − db.yourCollectionName.find().forEach(function(yourVariableName){ db.getSiblingDB('yourDestinationDatabase')['yourCollectionName'].insert(yourVariableName); }); Let us create a collection in the test database and copy this collection to another database with the name „sample‟. To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows − <test> > use test switched to db test > db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":101,"UserName":"Larr y"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77ad622386c62d05142a67") } > db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":102,"UserName":"Maxwell"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77ad6e2386c62d05142a68") } > db.copyThisCollectionToSampleDatabaseDemo.insertOne({"User_Id":103,"UserName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5c77ad7c2386c62d05142a69") } Display all documents from a collection with the help of find() method. The query is as follows − > db.copyThisCollectionToSampleDatabaseDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c77ad622386c62d05142a67"), "User_Id" : 101, "UserName" : "Larry" } { "_id" : ObjectId("5c77ad6e2386c62d05142a68"), "User_Id" : 102, "UserName" : "Maxwell" } { "_id" : ObjectId("5c77ad7c2386c62d05142a69"), "User_Id" : 103, "UserName" : "Robert" } Let us check the sample database has a collection with the name “copyThisCollectionToSampleDatabaseDemo” or not. The query is as follows − <sample> > use sample; switched to db sample > show collections; The following is the output − deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation So, there is no collection with name “copyThisCollectionToSampleDatabaseDemo”. Now we will copy the above collection from a test database to sample database. The query is as follows − > use test; switched to db test > db.copyThisCollectionToSampleDatabaseDemo.find().forEach(function(send){ db.getSiblingDB('sample')['copyThisCollectionToSampleDatabaseDemo'].insert(send); }); Now let us check once again the collection is copied or not successfully in the sample database. The query is as follows − > use sample; switched to db sample > show collections; The following is the output − copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation Look at the sample output, the collection “copyThisCollectionToSampleDatabaseDemo” is present in the sample database while it is present in the test database also.
[ { "code": null, "e": 1191, "s": 1062, "text": "In MongoDB, the command does not exist to copy a collection from one database to another. To achieve it, use the below concept −" }, { "code": null, "e": 1354, "s": 1191, "text": "db.yourCollectionName.find().forEach(function(yourVariableName){\n db.getSiblingDB('yourDestinationDatabase')['yourCollectionName'].insert(yourVariableName);\n});" }, { "code": null, "e": 1471, "s": 1354, "text": "Let us create a collection in the test database and copy this collection to another database with the name „sample‟." }, { "code": null, "e": 1614, "s": 1471, "text": "To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −" }, { "code": null, "e": 1621, "s": 1614, "text": "<test>" }, { "code": null, "e": 2184, "s": 1621, "text": "> use test\nswitched to db test\n> db.copyThisCollectionToSampleDatabaseDemo.insertOne({\"User_Id\":101,\"UserName\":\"Larr\ny\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77ad622386c62d05142a67\")\n}\n> db.copyThisCollectionToSampleDatabaseDemo.insertOne({\"User_Id\":102,\"UserName\":\"Maxwell\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77ad6e2386c62d05142a68\")\n}\n> db.copyThisCollectionToSampleDatabaseDemo.insertOne({\"User_Id\":103,\"UserName\":\"Robert\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77ad7c2386c62d05142a69\")\n}" }, { "code": null, "e": 2282, "s": 2184, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 2343, "s": 2282, "text": "> db.copyThisCollectionToSampleDatabaseDemo.find().pretty();" }, { "code": null, "e": 2373, "s": 2343, "text": "The following is the output −" }, { "code": null, "e": 2667, "s": 2373, "text": "{\n \"_id\" : ObjectId(\"5c77ad622386c62d05142a67\"),\n \"User_Id\" : 101,\n \"UserName\" : \"Larry\"\n}\n{\n \"_id\" : ObjectId(\"5c77ad6e2386c62d05142a68\"),\n \"User_Id\" : 102,\n \"UserName\" : \"Maxwell\"\n}\n{\n \"_id\" : ObjectId(\"5c77ad7c2386c62d05142a69\"),\n \"User_Id\" : 103,\n \"UserName\" : \"Robert\"\n}" }, { "code": null, "e": 2780, "s": 2667, "text": "Let us check the sample database has a collection with the name “copyThisCollectionToSampleDatabaseDemo” or not." }, { "code": null, "e": 2806, "s": 2780, "text": "The query is as follows −" }, { "code": null, "e": 2815, "s": 2806, "text": "<sample>" }, { "code": null, "e": 2871, "s": 2815, "text": "> use sample;\nswitched to db sample\n> show collections;" }, { "code": null, "e": 2901, "s": 2871, "text": "The following is the output −" }, { "code": null, "e": 3037, "s": 2901, "text": "deleteDocuments\ndeleteDocumentsDemo\ndeleteInformation\nemployee\ninternalArraySizeDemo\nsourceCollection\nupdateInformation\nuserInformation" }, { "code": null, "e": 3116, "s": 3037, "text": "So, there is no collection with name “copyThisCollectionToSampleDatabaseDemo”." }, { "code": null, "e": 3221, "s": 3116, "text": "Now we will copy the above collection from a test database to sample database. The query is as follows −" }, { "code": null, "e": 3414, "s": 3221, "text": "> use test;\nswitched to db test\n> db.copyThisCollectionToSampleDatabaseDemo.find().forEach(function(send){\ndb.getSiblingDB('sample')['copyThisCollectionToSampleDatabaseDemo'].insert(send); });" }, { "code": null, "e": 3511, "s": 3414, "text": "Now let us check once again the collection is copied or not successfully in the sample database." }, { "code": null, "e": 3537, "s": 3511, "text": "The query is as follows −" }, { "code": null, "e": 3593, "s": 3537, "text": "> use sample;\nswitched to db sample\n> show collections;" }, { "code": null, "e": 3623, "s": 3593, "text": "The following is the output −" }, { "code": null, "e": 3798, "s": 3623, "text": "copyThisCollectionToSampleDatabaseDemo\ndeleteDocuments\ndeleteDocumentsDemo\ndeleteInformation\nemployee\ninternalArraySizeDemo\nsourceCollection\nupdateInformation\nuserInformation" }, { "code": null, "e": 3962, "s": 3798, "text": "Look at the sample output, the collection “copyThisCollectionToSampleDatabaseDemo” is present in the sample database while it is present in the test database also." } ]
Creating an index on a nested MongoDB field?
You can use dot(.) notation for this. Let us first create a collection with documents − > db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"John","UserLastName":"Smith"}}}); { "acknowledged" : true, "insertedId" : ObjectId("5ce929c778f00858fb12e916") } > > db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"Chris","UserLastName":"Brown"}}}); { "acknowledged" : true, "insertedId" : ObjectId("5ce929d678f00858fb12e917") } > db.createIndexOnNestedFieldDemo.insertOne( {"UserDetails":{"UserPersonalDetails":{"UserFirstName":"David","UserLastName":"Miller"}}}); { "acknowledged" : true, "insertedId" : ObjectId("5ce929e378f00858fb12e918") } Following is the query to display all documents from a collection with the help of find() method − > db.createIndexOnNestedFieldDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5ce929c778f00858fb12e916"), "UserDetails" : { "UserPersonalDetails" : { "UserFirstName" : "John", "UserLastName" : "Smith" } } } { "_id" : ObjectId("5ce929d678f00858fb12e917"), "UserDetails" : { "UserPersonalDetails" : { "UserFirstName" : "Chris", "UserLastName" : "Brown" } } } { "_id" : ObjectId("5ce929e378f00858fb12e918"), "UserDetails" : { "UserPersonalDetails" : { "UserFirstName" : "David", "UserLastName" : "Miller" } } } Following is the query to create an index on a nested field − >db.createIndexOnNestedFieldDemo.createIndex({"UserDetails.UserPersonalDetails.UserLastName":1}); This will produce the following output − { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
[ { "code": null, "e": 1150, "s": 1062, "text": "You can use dot(.) notation for this. Let us first create a collection with documents −" }, { "code": null, "e": 1830, "s": 1150, "text": "> db.createIndexOnNestedFieldDemo.insertOne(\n {\"UserDetails\":{\"UserPersonalDetails\":{\"UserFirstName\":\"John\",\"UserLastName\":\"Smith\"}}});\n {\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce929c778f00858fb12e916\")\n }\n>\n> db.createIndexOnNestedFieldDemo.insertOne( {\"UserDetails\":{\"UserPersonalDetails\":{\"UserFirstName\":\"Chris\",\"UserLastName\":\"Brown\"}}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce929d678f00858fb12e917\")\n}\n> db.createIndexOnNestedFieldDemo.insertOne( {\"UserDetails\":{\"UserPersonalDetails\":{\"UserFirstName\":\"David\",\"UserLastName\":\"Miller\"}}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ce929e378f00858fb12e918\")\n}" }, { "code": null, "e": 1929, "s": 1830, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1980, "s": 1929, "text": "> db.createIndexOnNestedFieldDemo.find().pretty();" }, { "code": null, "e": 2021, "s": 1980, "text": "This will produce the following output −" }, { "code": null, "e": 2588, "s": 2021, "text": "{\n \"_id\" : ObjectId(\"5ce929c778f00858fb12e916\"),\n \"UserDetails\" : {\n \"UserPersonalDetails\" : {\n \"UserFirstName\" : \"John\",\n \"UserLastName\" : \"Smith\"\n }\n }\n}\n{\n \"_id\" : ObjectId(\"5ce929d678f00858fb12e917\"),\n \"UserDetails\" : {\n \"UserPersonalDetails\" : {\n \"UserFirstName\" : \"Chris\",\n \"UserLastName\" : \"Brown\"\n }\n }\n}\n{\n \"_id\" : ObjectId(\"5ce929e378f00858fb12e918\"),\n \"UserDetails\" : {\n \"UserPersonalDetails\" : {\n \"UserFirstName\" : \"David\",\n \"UserLastName\" : \"Miller\"\n }\n }\n}" }, { "code": null, "e": 2650, "s": 2588, "text": "Following is the query to create an index on a nested field −" }, { "code": null, "e": 2748, "s": 2650, "text": ">db.createIndexOnNestedFieldDemo.createIndex({\"UserDetails.UserPersonalDetails.UserLastName\":1});" }, { "code": null, "e": 2789, "s": 2748, "text": "This will produce the following output −" }, { "code": null, "e": 2903, "s": 2789, "text": "{\n \"createdCollectionAutomatically\" : false,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}" } ]
What are the DDL commands in DBMS?
Data definition language (DDL) is a language that allows the user to define the data and their relationship to other types of data. Data Definition language statements work with the structure of the database table. Various data types used in defining columns in a database table Various data types used in defining columns in a database table Integrity and value constraints Integrity and value constraints Viewing, modifying and removing a table structure Viewing, modifying and removing a table structure The Data Definition Languages (DDL) Commands are as follows − Create − It is used to create a new table or a new database. Create − It is used to create a new table or a new database. Alter − It is used to alter or change the structure of the database table. Alter − It is used to alter or change the structure of the database table. Drop − It is used to delete a table, index, or views from the database. Drop − It is used to delete a table, index, or views from the database. Truncate − It is used to delete the records or data from the table, but its structure remains as it is. Truncate − It is used to delete the records or data from the table, but its structure remains as it is. Rename − It is used to rename an object from the database. Rename − It is used to rename an object from the database. When you create a table, you have to specify the following − Table name. Table name. Name of each column. Name of each column. Data type of each column. Data type of each column. Size of each column. Size of each column. When a table is created, each column in the table is assigned a data type. Some of the important data types are as follows − Varchar2 Varchar2 Char Char Number Number Let’s see each DDL command with an example. Create It is used to create a new table or a new database. An example of the create command is as follows − create table student(stdname varchar(20) , branch varchar(20),college varchar(20), age number, telephone number, address varchar(20)); A student table is created with the fields given below − Alter It is used to alter or change the structure of the database table An example of the alter command is as follows − ALTER TABLE student ADD birthdate DATETIME Drop It is used to delete a table, index, or views from the database. An example of the drop command is as follows − DROP TABLE student
[ { "code": null, "e": 1194, "s": 1062, "text": "Data definition language (DDL) is a language that allows the user to define the data and their relationship to other types of data." }, { "code": null, "e": 1277, "s": 1194, "text": "Data Definition language statements work with the structure of the database table." }, { "code": null, "e": 1341, "s": 1277, "text": "Various data types used in defining columns in a database table" }, { "code": null, "e": 1405, "s": 1341, "text": "Various data types used in defining columns in a database table" }, { "code": null, "e": 1437, "s": 1405, "text": "Integrity and value constraints" }, { "code": null, "e": 1469, "s": 1437, "text": "Integrity and value constraints" }, { "code": null, "e": 1519, "s": 1469, "text": "Viewing, modifying and removing a table structure" }, { "code": null, "e": 1569, "s": 1519, "text": "Viewing, modifying and removing a table structure" }, { "code": null, "e": 1631, "s": 1569, "text": "The Data Definition Languages (DDL) Commands are as follows −" }, { "code": null, "e": 1692, "s": 1631, "text": "Create − It is used to create a new table or a new database." }, { "code": null, "e": 1753, "s": 1692, "text": "Create − It is used to create a new table or a new database." }, { "code": null, "e": 1828, "s": 1753, "text": "Alter − It is used to alter or change the structure of the database table." }, { "code": null, "e": 1903, "s": 1828, "text": "Alter − It is used to alter or change the structure of the database table." }, { "code": null, "e": 1975, "s": 1903, "text": "Drop − It is used to delete a table, index, or views from the database." }, { "code": null, "e": 2047, "s": 1975, "text": "Drop − It is used to delete a table, index, or views from the database." }, { "code": null, "e": 2151, "s": 2047, "text": "Truncate − It is used to delete the records or data from the table, but its structure remains as it is." }, { "code": null, "e": 2255, "s": 2151, "text": "Truncate − It is used to delete the records or data from the table, but its structure remains as it is." }, { "code": null, "e": 2314, "s": 2255, "text": "Rename − It is used to rename an object from the database." }, { "code": null, "e": 2373, "s": 2314, "text": "Rename − It is used to rename an object from the database." }, { "code": null, "e": 2434, "s": 2373, "text": "When you create a table, you have to specify the following −" }, { "code": null, "e": 2446, "s": 2434, "text": "Table name." }, { "code": null, "e": 2458, "s": 2446, "text": "Table name." }, { "code": null, "e": 2479, "s": 2458, "text": "Name of each column." }, { "code": null, "e": 2500, "s": 2479, "text": "Name of each column." }, { "code": null, "e": 2526, "s": 2500, "text": "Data type of each column." }, { "code": null, "e": 2552, "s": 2526, "text": "Data type of each column." }, { "code": null, "e": 2573, "s": 2552, "text": "Size of each column." }, { "code": null, "e": 2594, "s": 2573, "text": "Size of each column." }, { "code": null, "e": 2669, "s": 2594, "text": "When a table is created, each column in the table is assigned a data type." }, { "code": null, "e": 2719, "s": 2669, "text": "Some of the important data types are as follows −" }, { "code": null, "e": 2728, "s": 2719, "text": "Varchar2" }, { "code": null, "e": 2737, "s": 2728, "text": "Varchar2" }, { "code": null, "e": 2742, "s": 2737, "text": "Char" }, { "code": null, "e": 2747, "s": 2742, "text": "Char" }, { "code": null, "e": 2754, "s": 2747, "text": "Number" }, { "code": null, "e": 2761, "s": 2754, "text": "Number" }, { "code": null, "e": 2805, "s": 2761, "text": "Let’s see each DDL command with an example." }, { "code": null, "e": 2812, "s": 2805, "text": "Create" }, { "code": null, "e": 2864, "s": 2812, "text": "It is used to create a new table or a new database." }, { "code": null, "e": 2913, "s": 2864, "text": "An example of the create command is as follows −" }, { "code": null, "e": 3048, "s": 2913, "text": "create table student(stdname varchar(20) , branch varchar(20),college varchar(20), age number, telephone number, address varchar(20));" }, { "code": null, "e": 3105, "s": 3048, "text": "A student table is created with the fields given below −" }, { "code": null, "e": 3111, "s": 3105, "text": "Alter" }, { "code": null, "e": 3177, "s": 3111, "text": "It is used to alter or change the structure of the database table" }, { "code": null, "e": 3225, "s": 3177, "text": "An example of the alter command is as follows −" }, { "code": null, "e": 3268, "s": 3225, "text": "ALTER TABLE student ADD birthdate DATETIME" }, { "code": null, "e": 3273, "s": 3268, "text": "Drop" }, { "code": null, "e": 3338, "s": 3273, "text": "It is used to delete a table, index, or views from the database." }, { "code": null, "e": 3385, "s": 3338, "text": "An example of the drop command is as follows −" }, { "code": null, "e": 3405, "s": 3385, "text": " DROP TABLE student" } ]
NHibernate - Load/Get
In this chapter, we will be covering how the Load and Get features are working and how we can use them. These are two very similar APIs provided by ISession for loading an object by primary key. Get − it will return the object or a null. Get − it will return the object or a null. Load − it will return the object or it will throw an ObjectNotFoundException. Load − it will return the object or it will throw an ObjectNotFoundException. Now, why do we have these two different APIs? It's because Load can optimize database round trips much more efficiently. It's because Load can optimize database round trips much more efficiently. Load actually returns a proxy object and doesn't need to access the database right when you issue that Load call. Load actually returns a proxy object and doesn't need to access the database right when you issue that Load call. When you access that proxy, the object doesn't happen to be in the database, it can throw an ObjectNotFoundException at that point. When you access that proxy, the object doesn't happen to be in the database, it can throw an ObjectNotFoundException at that point. Conversely, with Get because of limitations of the CLR or Common Language Runtime and NHibernate must go to the database immediately, check if the objects are there and return null, if it's not present. Conversely, with Get because of limitations of the CLR or Common Language Runtime and NHibernate must go to the database immediately, check if the objects are there and return null, if it's not present. It doesn't have the object option of delaying that fetch, that roundtrip to the database to a later time because it cannot return a proxy object and that swapped that proxy object out for a null, when the user actually accesses it. It doesn't have the object option of delaying that fetch, that roundtrip to the database to a later time because it cannot return a proxy object and that swapped that proxy object out for a null, when the user actually accesses it. Let’s have a look into a simple example in which you will see how these are actually used and the difference between Get and Load. We will continue with same domain classes Customers and Orders and similarly the same mapping files from the last chapter. In this example, we will first use the Get as shown in the following program. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var id1 = Guid.Parse("4e97c816-6bce-11e1-b095-6cf049ee52be"); var id2 = Guid.Parse("AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"); var customer1 = session.Get<Customer>(id1); Console.WriteLine("Customer1 data"); Console.WriteLine(customer1); var customer2 = session.Get<Customer>(id2); Console.WriteLine("Customer2 data"); Console.WriteLine(customer2); tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = "default"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } As you can see that we have two Guid ID’s, the first one is a good ID, it's the ID of a customer that we know is in the database. While the second ID is not present in the database. Both these ID’s are passed as a parameter to Get() method and then the result is printed on the console. When the above code is compiled and executed you will see the following output. Customer1 data Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Customer2 data Press <ENTER> to exit... As you can see that Customer1 data is printed but the Customer2 data is empty, that is because the Customer2 record is not available in the database. When you run your application again, we can insert a break point before the commit statement and then let’s look at both customers in the Watch window. As you can see that Customer1 data is available, while Customer2 is null and the type is NHibernateDemo.Customer for both. Now let’s use the Load method instead of Get in the same example as shown in the following code. using System; using System.Data; using System.Linq; using System.Reflection; using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Linq; namespace NHibernateDemo { internal class Program { private static void Main() { var cfg = ConfigureNHibernate(); var sessionFactory = cfg.BuildSessionFactory(); using(var session = sessionFactory.OpenSession()) using(var tx = session.BeginTransaction()) { var id1 = Guid.Parse("4e97c816-6bce-11e1-b095-6cf049ee52be"); var id2 = Guid.Parse("AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE"); var customer1 = session.Load<Customer>(id1); Console.WriteLine("Customer1 data"); Console.WriteLine(customer1); var customer2 = session.Load<Customer>(id2); Console.WriteLine("Customer2 data"); Console.WriteLine(customer2); tx.Commit(); } Console.WriteLine("Press <ENTER> to exit..."); Console.ReadLine(); } private static Configuration ConfigureNHibernate() { NHibernateProfiler.Initialize(); var cfg = new Configuration(); cfg.DataBaseIntegration(x => { x.ConnectionStringName = "default"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.IsolationLevel = IsolationLevel.RepeatableRead; x.Timeout = 10; x.BatchSize = 10; }); cfg.SessionFactory().GenerateStatistics(); cfg.AddAssembly(Assembly.GetExecutingAssembly()); return cfg; } } } Now let’s run this example and you will see that the following exception is thrown as seen in the screenshot. Now if you look at the Watch window, you will see the type is customer proxy for both objects. And you also see the same data for Customer1 on the console window. Customer1 data Laverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be) Points: 74 HasGoldStatus: True MemberSince: 4/4/2009 12:00:00 AM (Utc) CreditRating: Neutral AverageRating: 0 Orders: Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be Customer2 data Print Add Notes Bookmark this page
[ { "code": null, "e": 2528, "s": 2333, "text": "In this chapter, we will be covering how the Load and Get features are working and how we can use them. These are two very similar APIs provided by ISession for loading an object by primary key." }, { "code": null, "e": 2571, "s": 2528, "text": "Get − it will return the object or a null." }, { "code": null, "e": 2614, "s": 2571, "text": "Get − it will return the object or a null." }, { "code": null, "e": 2692, "s": 2614, "text": "Load − it will return the object or it will throw an ObjectNotFoundException." }, { "code": null, "e": 2770, "s": 2692, "text": "Load − it will return the object or it will throw an ObjectNotFoundException." }, { "code": null, "e": 2816, "s": 2770, "text": "Now, why do we have these two different APIs?" }, { "code": null, "e": 2891, "s": 2816, "text": "It's because Load can optimize database round trips much more efficiently." }, { "code": null, "e": 2966, "s": 2891, "text": "It's because Load can optimize database round trips much more efficiently." }, { "code": null, "e": 3080, "s": 2966, "text": "Load actually returns a proxy object and doesn't need to access the database right when you issue that Load call." }, { "code": null, "e": 3194, "s": 3080, "text": "Load actually returns a proxy object and doesn't need to access the database right when you issue that Load call." }, { "code": null, "e": 3326, "s": 3194, "text": "When you access that proxy, the object doesn't happen to be in the database, it can throw an ObjectNotFoundException at that point." }, { "code": null, "e": 3458, "s": 3326, "text": "When you access that proxy, the object doesn't happen to be in the database, it can throw an ObjectNotFoundException at that point." }, { "code": null, "e": 3661, "s": 3458, "text": "Conversely, with Get because of limitations of the CLR or Common Language Runtime and NHibernate must go to the database immediately, check if the objects are there and return null, if it's not present." }, { "code": null, "e": 3864, "s": 3661, "text": "Conversely, with Get because of limitations of the CLR or Common Language Runtime and NHibernate must go to the database immediately, check if the objects are there and return null, if it's not present." }, { "code": null, "e": 4096, "s": 3864, "text": "It doesn't have the object option of delaying that fetch, that roundtrip to the database to a later time because it cannot return a proxy object and that swapped that proxy object out for a null, when the user actually accesses it." }, { "code": null, "e": 4328, "s": 4096, "text": "It doesn't have the object option of delaying that fetch, that roundtrip to the database to a later time because it cannot return a proxy object and that swapped that proxy object out for a null, when the user actually accesses it." }, { "code": null, "e": 4582, "s": 4328, "text": "Let’s have a look into a simple example in which you will see how these are actually used and the difference between Get and Load. We will continue with same domain classes Customers and Orders and similarly the same mapping files from the last chapter." }, { "code": null, "e": 4660, "s": 4582, "text": "In this example, we will first use the Get as shown in the following program." }, { "code": null, "e": 6481, "s": 4660, "text": "using System; \nusing System.Data; \nusing System.Linq; \nusing System.Reflection; \n\nusing HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Criterion; \nusing NHibernate.Dialect; \nusing NHibernate.Driver;\nusing NHibernate.Linq; \n\nnamespace NHibernateDemo { \n\n internal class Program { \n\t\n private static void Main() { \n\t\t\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n using(var session = sessionFactory.OpenSession()) \n \n using(var tx = session.BeginTransaction()) { \n var id1 = Guid.Parse(\"4e97c816-6bce-11e1-b095-6cf049ee52be\"); \n var id2 = Guid.Parse(\"AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE\");\n\t\t\t\t\n var customer1 = session.Get<Customer>(id1); \n Console.WriteLine(\"Customer1 data\"); \n Console.WriteLine(customer1);\n\t\t\t\t\n var customer2 = session.Get<Customer>(id2); \n Console.WriteLine(\"Customer2 data\"); \n Console.WriteLine(customer2); \n\t\t\t\t\n tx.Commit(); \n }\n\t\t\t\n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine(); \n }\n\t\t\n private static Configuration ConfigureNHibernate() {\n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n \n cfg.DataBaseIntegration(x => { \n x.ConnectionStringName = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.IsolationLevel = IsolationLevel.RepeatableRead;\n x.Timeout = 10; \n x.BatchSize = 10; \n }); \n \n cfg.SessionFactory().GenerateStatistics();\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n return cfg; \n } \n } \n}" }, { "code": null, "e": 6768, "s": 6481, "text": "As you can see that we have two Guid ID’s, the first one is a good ID, it's the ID of a customer that we know is in the database. While the second ID is not present in the database. Both these ID’s are passed as a parameter to Get() method and then the result is printed on the console." }, { "code": null, "e": 6848, "s": 6768, "text": "When the above code is compiled and executed you will see the following output." }, { "code": null, "e": 7295, "s": 6848, "text": "Customer1 data\nLaverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be)\n Points: 74\n HasGoldStatus: True\n MemberSince: 4/4/2009 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\nOrders:\n Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be\n\t\nCustomer2 data\nPress <ENTER> to exit...\n" }, { "code": null, "e": 7445, "s": 7295, "text": "As you can see that Customer1 data is printed but the Customer2 data is empty, that is because the Customer2 record is not available in the database." }, { "code": null, "e": 7597, "s": 7445, "text": "When you run your application again, we can insert a break point before the commit statement and then let’s look at both customers in the Watch window." }, { "code": null, "e": 7720, "s": 7597, "text": "As you can see that Customer1 data is available, while Customer2 is null and the type is NHibernateDemo.Customer for both." }, { "code": null, "e": 7817, "s": 7720, "text": "Now let’s use the Load method instead of Get in the same example as shown in the following code." }, { "code": null, "e": 9635, "s": 7817, "text": "using System; \nusing System.Data; \nusing System.Linq; \nusing System.Reflection; \n\nusing HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Criterion; \nusing NHibernate.Dialect; \nusing NHibernate.Driver;\nusing NHibernate.Linq; \n\nnamespace NHibernateDemo { \n\n internal class Program { \n\t\n private static void Main() { \n\t\t\n var cfg = ConfigureNHibernate(); \n var sessionFactory = cfg.BuildSessionFactory();\n using(var session = sessionFactory.OpenSession()) \n \n using(var tx = session.BeginTransaction()) { \n var id1 = Guid.Parse(\"4e97c816-6bce-11e1-b095-6cf049ee52be\"); \n var id2 = Guid.Parse(\"AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE\");\n\t\t\t\t\n var customer1 = session.Load<Customer>(id1); \n Console.WriteLine(\"Customer1 data\"); \n Console.WriteLine(customer1);\n\t\t\t\t\n var customer2 = session.Load<Customer>(id2); \n Console.WriteLine(\"Customer2 data\"); \n Console.WriteLine(customer2); \n\t\t\t\t\n tx.Commit(); \n }\n\t\t\t\n Console.WriteLine(\"Press <ENTER> to exit...\"); \n Console.ReadLine(); \n }\n\t\t\n private static Configuration ConfigureNHibernate() { \n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n \n cfg.DataBaseIntegration(x => { \n x.ConnectionStringName = \"default\"; \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.IsolationLevel = IsolationLevel.RepeatableRead; \n x.Timeout = 10;\n x.BatchSize = 10; \n }); \n\t\t\t\n cfg.SessionFactory().GenerateStatistics();\n cfg.AddAssembly(Assembly.GetExecutingAssembly()); \n return cfg; \n } \n } \n}" }, { "code": null, "e": 9745, "s": 9635, "text": "Now let’s run this example and you will see that the following exception is thrown as seen in the screenshot." }, { "code": null, "e": 9908, "s": 9745, "text": "Now if you look at the Watch window, you will see the type is customer proxy for both objects. And you also see the same data for Customer1 on the console window." }, { "code": null, "e": 10347, "s": 9908, "text": "Customer1 data\nLaverne Hegmann (4e97c816-6bce-11e1-b095-6cf049ee52be)\n Points: 74\n HasGoldStatus: True\n MemberSince: 4/4/2009 12:00:00 AM (Utc)\n CreditRating: Neutral\n AverageRating: 0\n\n Orders:\n Order Id: 4ea14d96-6bce-11e1-b095-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b096-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b097-6cf049ee52be\n Order Id: 4ea14d96-6bce-11e1-b098-6cf049ee52be \n\t\t\nCustomer2 data\n" }, { "code": null, "e": 10354, "s": 10347, "text": " Print" }, { "code": null, "e": 10365, "s": 10354, "text": " Add Notes" } ]
SAP BPC - Configuring Elimination
In BPC, it is necessary to configure intercompany eliminations between subsidiaries or parents to avoid double counting. Intercompany eliminations is performed with help of script logic. If you have transactions between subsidiaries Co. XP02, XP03, these transactions should be eliminated. These transactions are for intercompany account payable and account receivables, and intercompany sales and cost. Before performing intercompany elimination, you should have the following prerequisites − A consolidation environment You should perform currency conversion before elimination. To start with, first create a dimension for IC elimination. Application where you have to perform IC elimination must have dimension of type “I” and “R” for account and rate. Account dimension must have an elimination account property to post IC transfer balances. Next is to have an Entity dimension with a property ELIM (Y/N) to post elimination entity results. This property is set to “Y” for elimination entity. Account Dimension “I” should have an ENTITY property and should be maintained − XP01_Input XP02 XP03 XP04 XP05 Your currency dimension “R” should have a property ‘Reporting’ and should be maintained − IC Elimination is managed by inbuilt procedures - INITIALIZE_ELIM and ELIMINATE_ORG. Both of these procedures are maintained in ICELIMWITHCURR.LGL file. The following logic should be entered in application ICELIM logic file and should be validated and saved. //Logic for Intercompany Elimination //======================================================== *INCLUDE SYSTEM_CONSTANTS.LGL *SYSLIB ICELIMWITHCURR.LGL //======================================================== //Elimination logic for organizations in the hierarchy H1 //======================================================== *INITIALIZE_ELIM() *ELIMINATE_ORG(H1) *COMMIT To validate this logic, go to Action pane and select “Validate and save” option. Once the above configuration is in place, you have to create an input schedule or import package to load the data to be eliminated. To run the import package for IC elimination, login to BPC Excel. Click on Manage Data and go to Run a Data Management Package. Go to Company folder of application, click on Financial Processes → Select Package IC Eliminations and click ‘Run’. Once this package is executed successfully, you can check the values of the following components in Profit and Loss statement and balance sheets. Ownership terms is managed by the Ownership Manager. The Ownership Manager is used to manage ownership-based hierarchies. These hierarchies combine groups and entities and these entities can be connected or disconnected from groups as per the category and time. Ownership-based hierarchies are used to meet the reporting requirements which can’t be managed using fixed hierarchies. To display the Ownership manager, login to BPC web portal home page. Go to consolidation Central on the left side of the screen → Ownership Manager. To create an Ownership-based hierarchy − Go to Ownership manager as mentioned above. Click on Edit option provided in the Ownership Manager. In the next window, you will get an option to add members to hierarchy. Click ‘Add’ button and you will have an option to select members. Once hierarchy members are added, click ‘Save’ option on the top right corner of the screen. Purchase method is sometimes also called the Global method. Business Planning and Consolidation supports the following consolidation methods − Global (Purchase) method Proportional method Equity method In this method of consolidation, balance sheet accounts and Profit and Loss accounts are fully included and minority interests are calculated if necessary. In this method, you include balance sheet and P&L accounts at the percentage of ownership. Example − Including P&L statement and balance sheet are included 50% at the percentage of ownership. In this method, you don’t include balance sheet and P&L accounts. However, Net Value and Result of the Period are included. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2361, "s": 2174, "text": "In BPC, it is necessary to configure intercompany eliminations between subsidiaries or parents to avoid double counting. Intercompany eliminations is performed with help of script logic." }, { "code": null, "e": 2578, "s": 2361, "text": "If you have transactions between subsidiaries Co. XP02, XP03, these transactions should be eliminated. These transactions are for intercompany account payable and account receivables, and intercompany sales and cost." }, { "code": null, "e": 2668, "s": 2578, "text": "Before performing intercompany elimination, you should have the following prerequisites −" }, { "code": null, "e": 2696, "s": 2668, "text": "A consolidation environment" }, { "code": null, "e": 2755, "s": 2696, "text": "You should perform currency conversion before elimination." }, { "code": null, "e": 3020, "s": 2755, "text": "To start with, first create a dimension for IC elimination. Application where you have to perform IC elimination must have dimension of type “I” and “R” for account and rate. Account dimension must have an elimination account property to post IC transfer balances." }, { "code": null, "e": 3171, "s": 3020, "text": "Next is to have an Entity dimension with a property ELIM (Y/N) to post elimination entity results. This property is set to “Y” for elimination entity." }, { "code": null, "e": 3251, "s": 3171, "text": "Account Dimension “I” should have an ENTITY property and should be maintained −" }, { "code": null, "e": 3262, "s": 3251, "text": "XP01_Input" }, { "code": null, "e": 3267, "s": 3262, "text": "XP02" }, { "code": null, "e": 3272, "s": 3267, "text": "XP03" }, { "code": null, "e": 3277, "s": 3272, "text": "XP04" }, { "code": null, "e": 3282, "s": 3277, "text": "XP05" }, { "code": null, "e": 3372, "s": 3282, "text": "Your currency dimension “R” should have a property ‘Reporting’ and should be maintained −" }, { "code": null, "e": 3525, "s": 3372, "text": "IC Elimination is managed by inbuilt procedures - INITIALIZE_ELIM and ELIMINATE_ORG. Both of these procedures are maintained in ICELIMWITHCURR.LGL file." }, { "code": null, "e": 3631, "s": 3525, "text": "The following logic should be entered in application ICELIM logic file and should be validated and saved." }, { "code": null, "e": 4007, "s": 3631, "text": "//Logic for Intercompany Elimination\n//========================================================\n*INCLUDE SYSTEM_CONSTANTS.LGL\n*SYSLIB ICELIMWITHCURR.LGL\n//========================================================\n//Elimination logic\nfor organizations in the hierarchy H1\n//========================================================\n*INITIALIZE_ELIM()\n*ELIMINATE_ORG(H1)\n*COMMIT\n" }, { "code": null, "e": 4088, "s": 4007, "text": "To validate this logic, go to Action pane and select “Validate and save” option." }, { "code": null, "e": 4220, "s": 4088, "text": "Once the above configuration is in place, you have to create an input schedule or import package to load the data to be eliminated." }, { "code": null, "e": 4348, "s": 4220, "text": "To run the import package for IC elimination, login to BPC Excel. Click on Manage Data and go to Run a Data Management Package." }, { "code": null, "e": 4464, "s": 4348, "text": "Go to Company folder of application, click on Financial Processes → Select Package IC Eliminations and click ‘Run’." }, { "code": null, "e": 4610, "s": 4464, "text": "Once this package is executed successfully, you can check the values of the following components in Profit and Loss statement and balance sheets." }, { "code": null, "e": 4872, "s": 4610, "text": "Ownership terms is managed by the Ownership Manager. The Ownership Manager is used to manage ownership-based hierarchies. These hierarchies combine groups and entities and these entities can be connected or disconnected from groups as per the category and time." }, { "code": null, "e": 4992, "s": 4872, "text": "Ownership-based hierarchies are used to meet the reporting requirements which can’t be managed using fixed hierarchies." }, { "code": null, "e": 5141, "s": 4992, "text": "To display the Ownership manager, login to BPC web portal home page. Go to consolidation Central on the left side of the screen → Ownership Manager." }, { "code": null, "e": 5282, "s": 5141, "text": "To create an Ownership-based hierarchy − Go to Ownership manager as mentioned above. Click on Edit option provided in the Ownership Manager." }, { "code": null, "e": 5420, "s": 5282, "text": "In the next window, you will get an option to add members to hierarchy. Click ‘Add’ button and you will have an option to select members." }, { "code": null, "e": 5513, "s": 5420, "text": "Once hierarchy members are added, click ‘Save’ option on the top right corner of the screen." }, { "code": null, "e": 5656, "s": 5513, "text": "Purchase method is sometimes also called the Global method. Business Planning and Consolidation supports the following consolidation methods −" }, { "code": null, "e": 5681, "s": 5656, "text": "Global (Purchase) method" }, { "code": null, "e": 5701, "s": 5681, "text": "Proportional method" }, { "code": null, "e": 5715, "s": 5701, "text": "Equity method" }, { "code": null, "e": 5871, "s": 5715, "text": "In this method of consolidation, balance sheet accounts and Profit and Loss accounts are fully included and minority interests are calculated if necessary." }, { "code": null, "e": 5962, "s": 5871, "text": "In this method, you include balance sheet and P&L accounts at the percentage of ownership." }, { "code": null, "e": 6063, "s": 5962, "text": "Example − Including P&L statement and balance sheet are included 50% at the percentage of ownership." }, { "code": null, "e": 6187, "s": 6063, "text": "In this method, you don’t include balance sheet and P&L accounts. However, Net Value and Result of the Period are included." }, { "code": null, "e": 6220, "s": 6187, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 6234, "s": 6220, "text": " Sanjo Thomas" }, { "code": null, "e": 6267, "s": 6234, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6279, "s": 6267, "text": " Neha Gupta" }, { "code": null, "e": 6314, "s": 6279, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6329, "s": 6314, "text": " Sumit Agarwal" }, { "code": null, "e": 6362, "s": 6329, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6377, "s": 6362, "text": " Sumit Agarwal" }, { "code": null, "e": 6412, "s": 6377, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6424, "s": 6412, "text": " Neha Malik" }, { "code": null, "e": 6459, "s": 6424, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6471, "s": 6459, "text": " Neha Malik" }, { "code": null, "e": 6478, "s": 6471, "text": " Print" }, { "code": null, "e": 6489, "s": 6478, "text": " Add Notes" } ]
When and where static blocks are executed in java?
A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading. Live Demo public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } } Hello this is a static block This is main method JVM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method. Live Demo public class Sample { static { System.out.println("Hello how are you"); } } Since the above program doesn’t have a main method, if you compile and execute it you will get an error message. C:\Sample>javac StaticBlockExample.java C:\Sample>java StaticBlockExample Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application If you want to execute static block you need to have Main method and, static blocks of the class get executed before main method. Live Demo public class StaticBlockExample { static { System.out.println("This is static block"); } public static void main(String args[]){ System.out.println("This is main method"); } } This is static block This is main method
[ { "code": null, "e": 1260, "s": 1062, "text": "A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading." }, { "code": null, "e": 1271, "s": 1260, "text": " Live Demo" }, { "code": null, "e": 1467, "s": 1271, "text": "public class MyClass {\n static{\n System.out.println(\"Hello this is a static block\");\n }\n public static void main(String args[]){\n System.out.println(\"This is main method\");\n }\n}" }, { "code": null, "e": 1516, "s": 1467, "text": "Hello this is a static block\nThis is main method" }, { "code": null, "e": 1712, "s": 1516, "text": "JVM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method." }, { "code": null, "e": 1723, "s": 1712, "text": " Live Demo" }, { "code": null, "e": 1811, "s": 1723, "text": "public class Sample {\n static {\n System.out.println(\"Hello how are you\");\n }\n}" }, { "code": null, "e": 1924, "s": 1811, "text": "Since the above program doesn’t have a main method, if you compile and execute it you will get an error message." }, { "code": null, "e": 2202, "s": 1924, "text": "C:\\Sample>javac StaticBlockExample.java\nC:\\Sample>java StaticBlockExample\nError: Main method not found in class StaticBlockExample, please define the main\nmethod as: public static void main(String[] args)\nor a JavaFX application class must extend javafx.application.Application" }, { "code": null, "e": 2332, "s": 2202, "text": "If you want to execute static block you need to have Main method and, static blocks of the class get executed before main method." }, { "code": null, "e": 2343, "s": 2332, "text": " Live Demo" }, { "code": null, "e": 2543, "s": 2343, "text": "public class StaticBlockExample {\n static {\n System.out.println(\"This is static block\");\n }\n public static void main(String args[]){\n System.out.println(\"This is main method\");\n }\n}" }, { "code": null, "e": 2584, "s": 2543, "text": "This is static block\nThis is main method" } ]
C++ Vector Library - resize() Function
The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val. Following is the declaration for std::vector::resize() function form std::vector header. void resize (size_type n, value_type val = value_type()); void resize (size_type n); void resize (size_type n, const value_type& val); n − New container size. n − New container size. val − Initial value for container elements. val − Initial value for container elements. None. If reallocation fails then bad_alloc exception is thrown. Linear i.e. O(n) The following example shows the usage of std::vector::resize() function. #include <iostream> #include <vector> using namespace std; int main(void) { vector<int> v; cout << "Initial vector size = " << v.size() << endl; v.resize(5, 10); cout << "Vector size after resize = " << v.size() << endl; cout << "Vector contains following elements" << endl; for (int i = 0; i < v.size(); ++i) cout << v[i] << endl; return 0; } Let us compile and run the above program, this will produce the following result − Initial vector size = 0 Vector size after resize = 5 Vector contains following elements 10 10 10 10 10 Print Add Notes Bookmark this page
[ { "code": null, "e": 2739, "s": 2603, "text": "The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed." }, { "code": null, "e": 2836, "s": 2739, "text": "If n is greater than current container size then new elements are inserted at the end of vector." }, { "code": null, "e": 2898, "s": 2836, "text": "If val is specified then new elements are initialed with val." }, { "code": null, "e": 2987, "s": 2898, "text": "Following is the declaration for std::vector::resize() function form std::vector header." }, { "code": null, "e": 3046, "s": 2987, "text": "void resize (size_type n, value_type val = value_type());\n" }, { "code": null, "e": 3124, "s": 3046, "text": "void resize (size_type n);\nvoid resize (size_type n, const value_type& val);\n" }, { "code": null, "e": 3148, "s": 3124, "text": "n − New container size." }, { "code": null, "e": 3172, "s": 3148, "text": "n − New container size." }, { "code": null, "e": 3216, "s": 3172, "text": "val − Initial value for container elements." }, { "code": null, "e": 3260, "s": 3216, "text": "val − Initial value for container elements." }, { "code": null, "e": 3266, "s": 3260, "text": "None." }, { "code": null, "e": 3324, "s": 3266, "text": "If reallocation fails then bad_alloc exception is thrown." }, { "code": null, "e": 3341, "s": 3324, "text": "Linear i.e. O(n)" }, { "code": null, "e": 3414, "s": 3341, "text": "The following example shows the usage of std::vector::resize() function." }, { "code": null, "e": 3791, "s": 3414, "text": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main(void) {\n vector<int> v;\n\n cout << \"Initial vector size = \" << v.size() << endl;\n\n v.resize(5, 10);\n cout << \"Vector size after resize = \" << v.size() << endl;\n\n cout << \"Vector contains following elements\" << endl;\n for (int i = 0; i < v.size(); ++i)\n cout << v[i] << endl;\n\n return 0;\n}" }, { "code": null, "e": 3874, "s": 3791, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3978, "s": 3874, "text": "Initial vector size = 0\nVector size after resize = 5\nVector contains following elements\n10\n10\n10\n10\n10\n" }, { "code": null, "e": 3985, "s": 3978, "text": " Print" }, { "code": null, "e": 3996, "s": 3985, "text": " Add Notes" } ]
Node.js URL.format(urlObject) API - GeeksforGeeks
14 Oct, 2021 The URL.format(urlObject) is the inbuilt API provided by URL class, which takes an object or string and return a formatted string derived from that object or string. Syntax: const url.format(urlObject) If the urlObject is not an object or string, then it will throw a TypeError.Return value: It returns string derieved from urlObject. The urlObject can have the following fields or keys: protocol slashes auth hostname host port pathname search query hash The formatting process is as follows: 1. Initially, an empty string (‘’ say result) is created and then following parameters are looked for in order. 2. urlObject.protocol: stringIf urlObject.protocol is a string it is appended to the result else if not undefined and not a string then Error is thrown.If urlObject.protocol do not end with ASCII colon ( : ) then, the literal ‘:’ is appended to the result. 2. urlObject.protocol: string If urlObject.protocol is a string it is appended to the result else if not undefined and not a string then Error is thrown. If urlObject.protocol do not end with ASCII colon ( : ) then, the literal ‘:’ is appended to the result. 3. urlObject.slashes: booleanIf either of the following property is true, then literals ‘//’ are appended to the result:urlObject.slashaes is true.urlObject.protocol is http, https, ftp, gopher, or file, then slashes will be automatically true even if slashes is false. If either of the following property is true, then literals ‘//’ are appended to the result:urlObject.slashaes is true.urlObject.protocol is http, https, ftp, gopher, or file, then slashes will be automatically true even if slashes is false. urlObject.slashaes is true. urlObject.protocol is http, https, ftp, gopher, or file, then slashes will be automatically true even if slashes is false. 4. urlObject.auth: stringIf the urlObject.auth is not undefined and urlObject.host or urlObject.hostname is also not undefined then auth is appended to the result with literal ‘@’ irrespective of whether the literal ‘@’ present or not at the end. If the urlObject.auth is not undefined and urlObject.host or urlObject.hostname is also not undefined then auth is appended to the result with literal ‘@’ irrespective of whether the literal ‘@’ present or not at the end. 5. urlObject.host: stringIf urlObject.host is a string it is appended to the result else if not undefined and not a string then Error is thrown.If it is undefined then urlObject.hostname is considered. If urlObject.host is a string it is appended to the result else if not undefined and not a string then Error is thrown. If it is undefined then urlObject.hostname is considered. 6. urlObject.hostname: stringIf urlObject.hostname is a string it is appended to the result else if not undefined and not a string then Error is thrown.If both host and hostname are defined then host will be given considered. If urlObject.hostname is a string it is appended to the result else if not undefined and not a string then Error is thrown. If both host and hostname are defined then host will be given considered. 7. urlObject.port: (number | string)If hostname is considered and urlObject.port is defined then literal ‘:’ will be appended to the result along with urlObject.port. If hostname is considered and urlObject.port is defined then literal ‘:’ will be appended to the result along with urlObject.port. 8. urlObject.pathname: stringIf urlObject.pathname is a string but not empty string and not starting with literal ‘/’, then literal ‘/’ is appended to the result.urlObject.pathname is appended to the result.Else UrlObject.pathname is not a string then Error is thrown. If urlObject.pathname is a string but not empty string and not starting with literal ‘/’, then literal ‘/’ is appended to the result. urlObject.pathname is appended to the result. Else UrlObject.pathname is not a string then Error is thrown. 9. urlObject.search: stringIf urlObject.search is a string but not empty string and not starting with literal ‘?’, then literal ‘?’ is appended to the result.urlObject.search is appended to the result.If urlObject.search is not a string then Error is thrown. If urlObject.search is a string but not empty string and not starting with literal ‘?’, then literal ‘?’ is appended to the result. urlObject.search is appended to the result. If urlObject.search is not a string then Error is thrown. 10. urlObject.query: ObjectIf urlObject.query is an Object then literal ‘?’ is appended to the result along with output of calling the querystring module’s stringify() method passing the value of urlObject.query.If both urlObject.search and urlObject.query are defined then urlObject.search will only be considered. If urlObject.query is an Object then literal ‘?’ is appended to the result along with output of calling the querystring module’s stringify() method passing the value of urlObject.query. If both urlObject.search and urlObject.query are defined then urlObject.search will only be considered. 11. urlObject.hash: stringIf urlObject.hash is a string but not empty string and not starting with literal ‘#’, then literal ‘#’ is appended to the result.urlObject.hash is appended to the result.Else urlObject.hash is not a string and is not undefined then Error is thrown. If urlObject.hash is a string but not empty string and not starting with literal ‘#’, then literal ‘#’ is appended to the result. urlObject.hash is appended to the result. Else urlObject.hash is not a string and is not undefined then Error is thrown. 12. Finally, the result is returned. Example 1 /* node program to demonstrate the URL.format API.*/ //importing the module 'url'const url = require('url'); //creating and initializing urlObjectvar urlObject={ protocol: 'https', hostname: 'example.com', port: 1800, pathname: 'sample/path', query: { page: 1, format: 'json' }, hash: 'first' } //getting the derieved URL from urlObject using the url.format functionvar sampleUrl=url.format(urlObject); //Display the returned valueconsole.log(sampleUrl.toString()); Output: https://example.com:1800/sample/path?page=1&format=json#first Example 2 /* node program to demonstrate the URL.format API.*/ //importing the module 'url'const url = require('url'); //creating and initializing urlObjectvar urlObject={ protocol: 'prct', slashes: false, host: 'example.com', auth: 'abc', pathname: '/sample/path', search: 'something', hash: 'first' } //getting the derieved URL from urlObject using the url.format functionvar sampleUrl=url.format(urlObject); //Display the returned valueconsole.log(sampleUrl.toString()); Output: prct:abc@example.com/sample/path?something#first NOTE: The above program will compile and run by using the node fileName.js command. Reference:https://nodejs.org/api/url.html#url_url_format_urlobject Node-URL Picked Node.js Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.writeFile() Method Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.sendFile() Function How to read and write Excel file in Node.js ? Mongoose | findByIdAndUpdate() Function Node.js fs.readdirSync() Method Express.js res.send() Function What are the differences between npm and npx ? Node.js fs.readdir() Method
[ { "code": null, "e": 24187, "s": 24159, "text": "\n14 Oct, 2021" }, { "code": null, "e": 24353, "s": 24187, "text": "The URL.format(urlObject) is the inbuilt API provided by URL class, which takes an object or string and return a formatted string derived from that object or string." }, { "code": null, "e": 24361, "s": 24353, "text": "Syntax:" }, { "code": null, "e": 24390, "s": 24361, "text": "const url.format(urlObject)\n" }, { "code": null, "e": 24523, "s": 24390, "text": "If the urlObject is not an object or string, then it will throw a TypeError.Return value: It returns string derieved from urlObject." }, { "code": null, "e": 24576, "s": 24523, "text": "The urlObject can have the following fields or keys:" }, { "code": null, "e": 24585, "s": 24576, "text": "protocol" }, { "code": null, "e": 24593, "s": 24585, "text": "slashes" }, { "code": null, "e": 24598, "s": 24593, "text": "auth" }, { "code": null, "e": 24607, "s": 24598, "text": "hostname" }, { "code": null, "e": 24612, "s": 24607, "text": "host" }, { "code": null, "e": 24617, "s": 24612, "text": "port" }, { "code": null, "e": 24626, "s": 24617, "text": "pathname" }, { "code": null, "e": 24633, "s": 24626, "text": "search" }, { "code": null, "e": 24639, "s": 24633, "text": "query" }, { "code": null, "e": 24644, "s": 24639, "text": "hash" }, { "code": null, "e": 24682, "s": 24644, "text": "The formatting process is as follows:" }, { "code": null, "e": 24794, "s": 24682, "text": "1. Initially, an empty string (‘’ say result) is created and then following parameters are looked for in order." }, { "code": null, "e": 25051, "s": 24794, "text": "2. urlObject.protocol: stringIf urlObject.protocol is a string it is appended to the result else if not undefined and not a string then Error is thrown.If urlObject.protocol do not end with ASCII colon ( : ) then, the literal ‘:’ is appended to the result." }, { "code": null, "e": 25081, "s": 25051, "text": "2. urlObject.protocol: string" }, { "code": null, "e": 25205, "s": 25081, "text": "If urlObject.protocol is a string it is appended to the result else if not undefined and not a string then Error is thrown." }, { "code": null, "e": 25310, "s": 25205, "text": "If urlObject.protocol do not end with ASCII colon ( : ) then, the literal ‘:’ is appended to the result." }, { "code": null, "e": 25580, "s": 25310, "text": "3. urlObject.slashes: booleanIf either of the following property is true, then literals ‘//’ are appended to the result:urlObject.slashaes is true.urlObject.protocol is http, https, ftp, gopher, or file, then slashes will be automatically true even if slashes is false." }, { "code": null, "e": 25821, "s": 25580, "text": "If either of the following property is true, then literals ‘//’ are appended to the result:urlObject.slashaes is true.urlObject.protocol is http, https, ftp, gopher, or file, then slashes will be automatically true even if slashes is false." }, { "code": null, "e": 25849, "s": 25821, "text": "urlObject.slashaes is true." }, { "code": null, "e": 25972, "s": 25849, "text": "urlObject.protocol is http, https, ftp, gopher, or file, then slashes will be automatically true even if slashes is false." }, { "code": null, "e": 26219, "s": 25972, "text": "4. urlObject.auth: stringIf the urlObject.auth is not undefined and urlObject.host or urlObject.hostname is also not undefined then auth is appended to the result with literal ‘@’ irrespective of whether the literal ‘@’ present or not at the end." }, { "code": null, "e": 26441, "s": 26219, "text": "If the urlObject.auth is not undefined and urlObject.host or urlObject.hostname is also not undefined then auth is appended to the result with literal ‘@’ irrespective of whether the literal ‘@’ present or not at the end." }, { "code": null, "e": 26643, "s": 26441, "text": "5. urlObject.host: stringIf urlObject.host is a string it is appended to the result else if not undefined and not a string then Error is thrown.If it is undefined then urlObject.hostname is considered." }, { "code": null, "e": 26763, "s": 26643, "text": "If urlObject.host is a string it is appended to the result else if not undefined and not a string then Error is thrown." }, { "code": null, "e": 26821, "s": 26763, "text": "If it is undefined then urlObject.hostname is considered." }, { "code": null, "e": 27047, "s": 26821, "text": "6. urlObject.hostname: stringIf urlObject.hostname is a string it is appended to the result else if not undefined and not a string then Error is thrown.If both host and hostname are defined then host will be given considered." }, { "code": null, "e": 27171, "s": 27047, "text": "If urlObject.hostname is a string it is appended to the result else if not undefined and not a string then Error is thrown." }, { "code": null, "e": 27245, "s": 27171, "text": "If both host and hostname are defined then host will be given considered." }, { "code": null, "e": 27412, "s": 27245, "text": "7. urlObject.port: (number | string)If hostname is considered and urlObject.port is defined then literal ‘:’ will be appended to the result along with urlObject.port." }, { "code": null, "e": 27543, "s": 27412, "text": "If hostname is considered and urlObject.port is defined then literal ‘:’ will be appended to the result along with urlObject.port." }, { "code": null, "e": 27812, "s": 27543, "text": "8. urlObject.pathname: stringIf urlObject.pathname is a string but not empty string and not starting with literal ‘/’, then literal ‘/’ is appended to the result.urlObject.pathname is appended to the result.Else UrlObject.pathname is not a string then Error is thrown." }, { "code": null, "e": 27946, "s": 27812, "text": "If urlObject.pathname is a string but not empty string and not starting with literal ‘/’, then literal ‘/’ is appended to the result." }, { "code": null, "e": 27992, "s": 27946, "text": "urlObject.pathname is appended to the result." }, { "code": null, "e": 28054, "s": 27992, "text": "Else UrlObject.pathname is not a string then Error is thrown." }, { "code": null, "e": 28313, "s": 28054, "text": "9. urlObject.search: stringIf urlObject.search is a string but not empty string and not starting with literal ‘?’, then literal ‘?’ is appended to the result.urlObject.search is appended to the result.If urlObject.search is not a string then Error is thrown." }, { "code": null, "e": 28445, "s": 28313, "text": "If urlObject.search is a string but not empty string and not starting with literal ‘?’, then literal ‘?’ is appended to the result." }, { "code": null, "e": 28489, "s": 28445, "text": "urlObject.search is appended to the result." }, { "code": null, "e": 28547, "s": 28489, "text": "If urlObject.search is not a string then Error is thrown." }, { "code": null, "e": 28863, "s": 28547, "text": "10. urlObject.query: ObjectIf urlObject.query is an Object then literal ‘?’ is appended to the result along with output of calling the querystring module’s stringify() method passing the value of urlObject.query.If both urlObject.search and urlObject.query are defined then urlObject.search will only be considered." }, { "code": null, "e": 29049, "s": 28863, "text": "If urlObject.query is an Object then literal ‘?’ is appended to the result along with output of calling the querystring module’s stringify() method passing the value of urlObject.query." }, { "code": null, "e": 29153, "s": 29049, "text": "If both urlObject.search and urlObject.query are defined then urlObject.search will only be considered." }, { "code": null, "e": 29428, "s": 29153, "text": "11. urlObject.hash: stringIf urlObject.hash is a string but not empty string and not starting with literal ‘#’, then literal ‘#’ is appended to the result.urlObject.hash is appended to the result.Else urlObject.hash is not a string and is not undefined then Error is thrown." }, { "code": null, "e": 29558, "s": 29428, "text": "If urlObject.hash is a string but not empty string and not starting with literal ‘#’, then literal ‘#’ is appended to the result." }, { "code": null, "e": 29600, "s": 29558, "text": "urlObject.hash is appended to the result." }, { "code": null, "e": 29679, "s": 29600, "text": "Else urlObject.hash is not a string and is not undefined then Error is thrown." }, { "code": null, "e": 29716, "s": 29679, "text": "12. Finally, the result is returned." }, { "code": null, "e": 29726, "s": 29716, "text": "Example 1" }, { "code": "/* node program to demonstrate the URL.format API.*/ //importing the module 'url'const url = require('url'); //creating and initializing urlObjectvar urlObject={ protocol: 'https', hostname: 'example.com', port: 1800, pathname: 'sample/path', query: { page: 1, format: 'json' }, hash: 'first' } //getting the derieved URL from urlObject using the url.format functionvar sampleUrl=url.format(urlObject); //Display the returned valueconsole.log(sampleUrl.toString()); ", "e": 30286, "s": 29726, "text": null }, { "code": null, "e": 30356, "s": 30286, "text": "Output: https://example.com:1800/sample/path?page=1&format=json#first" }, { "code": null, "e": 30366, "s": 30356, "text": "Example 2" }, { "code": "/* node program to demonstrate the URL.format API.*/ //importing the module 'url'const url = require('url'); //creating and initializing urlObjectvar urlObject={ protocol: 'prct', slashes: false, host: 'example.com', auth: 'abc', pathname: '/sample/path', search: 'something', hash: 'first' } //getting the derieved URL from urlObject using the url.format functionvar sampleUrl=url.format(urlObject); //Display the returned valueconsole.log(sampleUrl.toString());", "e": 30891, "s": 30366, "text": null }, { "code": null, "e": 30948, "s": 30891, "text": "Output: prct:abc@example.com/sample/path?something#first" }, { "code": null, "e": 31032, "s": 30948, "text": "NOTE: The above program will compile and run by using the node fileName.js command." }, { "code": null, "e": 31099, "s": 31032, "text": "Reference:https://nodejs.org/api/url.html#url_url_format_urlobject" }, { "code": null, "e": 31108, "s": 31099, "text": "Node-URL" }, { "code": null, "e": 31115, "s": 31108, "text": "Picked" }, { "code": null, "e": 31123, "s": 31115, "text": "Node.js" }, { "code": null, "e": 31221, "s": 31123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31230, "s": 31221, "text": "Comments" }, { "code": null, "e": 31243, "s": 31230, "text": "Old Comments" }, { "code": null, "e": 31273, "s": 31243, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 31327, "s": 31273, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 31364, "s": 31327, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 31399, "s": 31364, "text": "Express.js res.sendFile() Function" }, { "code": null, "e": 31445, "s": 31399, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 31485, "s": 31445, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 31517, "s": 31485, "text": "Node.js fs.readdirSync() Method" }, { "code": null, "e": 31548, "s": 31517, "text": "Express.js res.send() Function" }, { "code": null, "e": 31595, "s": 31548, "text": "What are the differences between npm and npx ?" } ]
XML - DTDs
The XML Document Type Declaration, commonly known as DTD, is a way to describe XML language precisely. DTDs check vocabulary and validity of the structure of XML documents against grammatical rules of appropriate XML language. An XML DTD can be either specified inside the document, or it can be kept in a separate document and then liked separately. Basic syntax of a DTD is as follows − <!DOCTYPE element DTD identifier [ declaration1 declaration2 ........ ]> In the above syntax, The DTD starts with <!DOCTYPE delimiter. The DTD starts with <!DOCTYPE delimiter. An element tells the parser to parse the document from the specified root element. An element tells the parser to parse the document from the specified root element. DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called External Subset. DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called External Subset. The square brackets [ ] enclose an optional list of entity declarations called Internal Subset. The square brackets [ ] enclose an optional list of entity declarations called Internal Subset. A DTD is referred to as an internal DTD if elements are declared within the XML files. To refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This means, the declaration works independent of an external source. Following is the syntax of internal DTD − <!DOCTYPE root-element [element-declarations]> where root-element is the name of root element and element-declarations is where you declare the elements. Following is a simple example of internal DTD − <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?> <!DOCTYPE address [ <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> ]> <address> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </address> Let us go through the above code − Start Declaration − Begin the XML declaration with the following statement. <?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?> DTD − Immediately after the XML header, the document type declaration follows, commonly referred to as the DOCTYPE − <!DOCTYPE address [ The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The DOCTYPE informs the parser that a DTD is associated with this XML document. DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare elements, attributes, entities, and notations. <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone_no (#PCDATA)> Several elements are declared here that make up the vocabulary of the <name> document. <!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA". Here #PCDATA means parse-able text data. End Declaration − Finally, the declaration section of the DTD is closed using a closing bracket and a closing angle bracket (]>). This effectively ends the definition, and thereafter, the XML document follows immediately. The document type declaration must appear at the start of the document (preceded only by the XML header) − it is not permitted anywhere else within the document. The document type declaration must appear at the start of the document (preceded only by the XML header) − it is not permitted anywhere else within the document. Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark. Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark. The Name in the document type declaration must match the element type of the root element. The Name in the document type declaration must match the element type of the root element. In external DTD elements are declared outside the XML file. They are accessed by specifying the system attributes which may be either the legal .dtd file or a valid URL. To refer it as external DTD, standalone attribute in the XML declaration must be set as no. This means, declaration includes information from the external source. Following is the syntax for external DTD − <!DOCTYPE root-element SYSTEM "file-name"> where file-name is the file with .dtd extension. The following example shows external DTD usage − <?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?> <!DOCTYPE address SYSTEM "address.dtd"> <address> <name>Tanmay Patil</name> <company>TutorialsPoint</company> <phone>(011) 123-4567</phone> </address> The content of the DTD file address.dtd is as shown − <!ELEMENT address (name,company,phone)> <!ELEMENT name (#PCDATA)> <!ELEMENT company (#PCDATA)> <!ELEMENT phone (#PCDATA)> You can refer to an external DTD by using either system identifiers or public identifiers. A system identifier enables you to specify the location of an external file containing DTD declarations. Syntax is as follows − <!DOCTYPE name SYSTEM "address.dtd" [...]> As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of the document. Public identifiers provide a mechanism to locate DTD resources and is written as follows − <!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN"> As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format, however, a commonly used format is called Formal Public Identifiers, or FPIs. 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2188, "s": 1961, "text": "The XML Document Type Declaration, commonly known as DTD, is a way to describe XML language precisely. DTDs check vocabulary and validity of the structure of XML documents against grammatical rules of appropriate XML language." }, { "code": null, "e": 2312, "s": 2188, "text": "An XML DTD can be either specified inside the document, or it can be kept in a separate document and then liked separately." }, { "code": null, "e": 2350, "s": 2312, "text": "Basic syntax of a DTD is as follows −" }, { "code": null, "e": 2432, "s": 2350, "text": "<!DOCTYPE element DTD identifier\n[\n declaration1\n declaration2\n ........\n]>" }, { "code": null, "e": 2453, "s": 2432, "text": "In the above syntax," }, { "code": null, "e": 2494, "s": 2453, "text": "The DTD starts with <!DOCTYPE delimiter." }, { "code": null, "e": 2535, "s": 2494, "text": "The DTD starts with <!DOCTYPE delimiter." }, { "code": null, "e": 2618, "s": 2535, "text": "An element tells the parser to parse the document from the specified root element." }, { "code": null, "e": 2701, "s": 2618, "text": "An element tells the parser to parse the document from the specified root element." }, { "code": null, "e": 2918, "s": 2701, "text": "DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called External Subset." }, { "code": null, "e": 3135, "s": 2918, "text": "DTD identifier is an identifier for the document type definition, which may be the path to a file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is called External Subset." }, { "code": null, "e": 3231, "s": 3135, "text": "The square brackets [ ] enclose an optional list of entity declarations called Internal Subset." }, { "code": null, "e": 3327, "s": 3231, "text": "The square brackets [ ] enclose an optional list of entity declarations called Internal Subset." }, { "code": null, "e": 3572, "s": 3327, "text": "A DTD is referred to as an internal DTD if elements are declared within the XML files. To refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This means, the declaration works independent of an external source." }, { "code": null, "e": 3614, "s": 3572, "text": "Following is the syntax of internal DTD −" }, { "code": null, "e": 3662, "s": 3614, "text": "<!DOCTYPE root-element [element-declarations]>\n" }, { "code": null, "e": 3769, "s": 3662, "text": "where root-element is the name of root element and element-declarations is where you declare the elements." }, { "code": null, "e": 3817, "s": 3769, "text": "Following is a simple example of internal DTD −" }, { "code": null, "e": 4158, "s": 3817, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\" ?>\n<!DOCTYPE address [\n <!ELEMENT address (name,company,phone)>\n <!ELEMENT name (#PCDATA)>\n <!ELEMENT company (#PCDATA)>\n <!ELEMENT phone (#PCDATA)>\n]>\n\n<address>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n</address>" }, { "code": null, "e": 4193, "s": 4158, "text": "Let us go through the above code −" }, { "code": null, "e": 4269, "s": 4193, "text": "Start Declaration − Begin the XML declaration with the following statement." }, { "code": null, "e": 4333, "s": 4269, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"yes\" ?>\n" }, { "code": null, "e": 4450, "s": 4333, "text": "DTD − Immediately after the XML header, the document type declaration follows, commonly referred to as the DOCTYPE −" }, { "code": null, "e": 4471, "s": 4450, "text": "<!DOCTYPE address [\n" }, { "code": null, "e": 4638, "s": 4471, "text": "The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The DOCTYPE informs the parser that a DTD is associated with this XML document. " }, { "code": null, "e": 4770, "s": 4638, "text": "DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare elements, attributes, entities, and notations." }, { "code": null, "e": 4895, "s": 4770, "text": "<!ELEMENT address (name,company,phone)>\n<!ELEMENT name (#PCDATA)>\n<!ELEMENT company (#PCDATA)>\n<!ELEMENT phone_no (#PCDATA)>" }, { "code": null, "e": 5099, "s": 4895, "text": "Several elements are declared here that make up the vocabulary of the <name> document. <!ELEMENT name (#PCDATA)> defines the element name to be of type \"#PCDATA\". Here #PCDATA means parse-able text data." }, { "code": null, "e": 5321, "s": 5099, "text": "End Declaration − Finally, the declaration section of the DTD is closed using a closing bracket and a closing angle bracket (]>). This effectively ends the definition, and thereafter, the XML document follows immediately." }, { "code": null, "e": 5483, "s": 5321, "text": "The document type declaration must appear at the start of the document (preceded only by the XML header) − it is not permitted anywhere else within the document." }, { "code": null, "e": 5645, "s": 5483, "text": "The document type declaration must appear at the start of the document (preceded only by the XML header) − it is not permitted anywhere else within the document." }, { "code": null, "e": 5743, "s": 5645, "text": "Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark." }, { "code": null, "e": 5841, "s": 5743, "text": "Similar to the DOCTYPE declaration, the element declarations must start with an exclamation mark." }, { "code": null, "e": 5932, "s": 5841, "text": "The Name in the document type declaration must match the element type of the root element." }, { "code": null, "e": 6023, "s": 5932, "text": "The Name in the document type declaration must match the element type of the root element." }, { "code": null, "e": 6356, "s": 6023, "text": "In external DTD elements are declared outside the XML file. They are accessed by specifying the system attributes which may be either the legal .dtd file or a valid URL. To refer it as external DTD, standalone attribute in the XML declaration must be set as no. This means, declaration includes information from the external source." }, { "code": null, "e": 6399, "s": 6356, "text": "Following is the syntax for external DTD −" }, { "code": null, "e": 6443, "s": 6399, "text": "<!DOCTYPE root-element SYSTEM \"file-name\">\n" }, { "code": null, "e": 6492, "s": 6443, "text": "where file-name is the file with .dtd extension." }, { "code": null, "e": 6541, "s": 6492, "text": "The following example shows external DTD usage −" }, { "code": null, "e": 6763, "s": 6541, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\" standalone = \"no\" ?>\n<!DOCTYPE address SYSTEM \"address.dtd\">\n<address>\n <name>Tanmay Patil</name>\n <company>TutorialsPoint</company>\n <phone>(011) 123-4567</phone>\n</address>" }, { "code": null, "e": 6817, "s": 6763, "text": "The content of the DTD file address.dtd is as shown −" }, { "code": null, "e": 6939, "s": 6817, "text": "<!ELEMENT address (name,company,phone)>\n<!ELEMENT name (#PCDATA)>\n<!ELEMENT company (#PCDATA)>\n<!ELEMENT phone (#PCDATA)>" }, { "code": null, "e": 7030, "s": 6939, "text": "You can refer to an external DTD by using either system identifiers or public identifiers." }, { "code": null, "e": 7158, "s": 7030, "text": "A system identifier enables you to specify the location of an external file containing DTD declarations. Syntax is as follows −" }, { "code": null, "e": 7202, "s": 7158, "text": "<!DOCTYPE name SYSTEM \"address.dtd\" [...]>\n" }, { "code": null, "e": 7307, "s": 7202, "text": "As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of the document." }, { "code": null, "e": 7398, "s": 7307, "text": "Public identifiers provide a mechanism to locate DTD resources and is written as follows −" }, { "code": null, "e": 7466, "s": 7398, "text": "<!DOCTYPE name PUBLIC \"-//Beginning XML//DTD Address Example//EN\">\n" }, { "code": null, "e": 7734, "s": 7466, "text": "As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public identifiers are used to identify an entry in a catalog. Public identifiers can follow any format, however, a commonly used format is called Formal Public Identifiers, or FPIs." }, { "code": null, "e": 7767, "s": 7734, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 7784, "s": 7767, "text": " Frahaan Hussain" }, { "code": null, "e": 7817, "s": 7784, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 7827, "s": 7817, "text": " YouAccel" }, { "code": null, "e": 7860, "s": 7827, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 7877, "s": 7860, "text": " Jordan Stanchev" }, { "code": null, "e": 7910, "s": 7877, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 7924, "s": 7910, "text": " Simon Sez IT" }, { "code": null, "e": 7931, "s": 7924, "text": " Print" }, { "code": null, "e": 7942, "s": 7931, "text": " Add Notes" } ]
Apex - Testing
Testing is the integrated part of Apex or any other application development. In Apex, we have separate test classes to develop for all the unit testing. In SFDC, the code must have 75% code coverage in order to be deployed to Production. This code coverage is performed by the test classes. Test classes are the code snippets which test the functionality of other Apex class. Let us write a test class for one of our codes which we have written previously. We will write test class to cover our Trigger and Helper class code. Below is the trigger and helper class which needs to be covered. // Trigger with Helper Class trigger Customer_After_Insert on APEX_Customer__c (after update) { CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap); //Trigger calls the helper class and does not have any code in Trigger } // Helper Class: public class CustomerTriggerHelper { public static void createInvoiceRecords (List<apex_customer__c> customerList, Map<id, apex_customer__c> oldMapCustomer) { List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>(); for (APEX_Customer__c objCustomer: customerList) { if (objCustomer.APEX_Customer_Status__c == 'Active' && oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') { // condition to check the old value and new value APEX_Invoice__c objInvoice = new APEX_Invoice__c(); objInvoice.APEX_Status__c = 'Pending'; objInvoice.APEX_Customer__c = objCustomer.id; InvoiceList.add(objInvoice); } } insert InvoiceList; // DML to insert the Invoice List in SFDC } } In this section, we will understand how to create a Test Class. We need to create data for test class in our test class itself. Test class by default does not have access to organization data but if you set @isTest(seeAllData = true), then it will have the access to organization's data as well. By using this annotation, you declared that this is a test class and it will not be counted against the organization's total code limit. Unit test methods are the methods which do not take arguments, commit no data to the database, send no emails, and are declared with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest. We have used the 'myUnitTest' test method in our examples. These are the standard test methods which are available for test classes. These methods contain the event or action for which we will be simulating our test. Like in this example, we will test our trigger and helper class to simulate the fire trigger by updating the records as we have done to start and stop block. This also provides separate governor limit to the code which is in start and stop block. This method checks the desired output with the actual. In this case, we are expecting an Invoice record to be inserted so we added assert to check the same. Example /** * This class contains unit tests for validating the behavior of Apex classes * and triggers. * * Unit tests are class methods that verify whether a particular piece * of code is working properly. Unit test methods take no arguments, * commit no data to the database, and are flagged with the testMethod * keyword in the method definition. * * All test methods in an organization are executed whenever Apex code is deployed * to a production organization to confirm correctness, ensure code * coverage, and prevent regressions. All Apex classes are * required to have at least 75% code coverage in order to be deployed * to a production organization. In addition, all triggers must have some code coverage. * * The @isTest class annotation indicates this class only contains test * methods. Classes defined with the @isTest annotation do not count against * the organization size limit for all Apex scripts. * * See the Apex Language Reference for more information about Testing and Code Coverage. */ @isTest private class CustomerTriggerTestClass { static testMethod void myUnitTest() { //Create Data for Customer Objet APEX_Customer__c objCust = new APEX_Customer__c(); objCust.Name = 'Test Customer'; objCust.APEX_Customer_Status__c = 'Inactive'; insert objCust; // Now, our trigger will fire on After update event so update the Records Test.startTest(); // Starts the scope of test objCust.APEX_Customer_Status__c = 'Active'; update objCust; Test.stopTest(); // Ends the scope of test // Now check if it is giving desired results using system.assert // Statement.New invoice should be created List<apex_invoice__c> invList = [SELECT Id, APEX_Customer__c FROM APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id]; system.assertEquals(1,invList.size()); // Check if one record is created in Invoivce sObject } } Follow the steps given below to run the test class − Step 1 − Go to Apex classes ⇒ click on the class name 'CustomerTriggerTestClass'. Step 2 − Click on Run Test button as shown. Step 3 − Check status Step 4 − Now check the class and trigger for which we have written the test Our testing is successful and completed. 14 Lectures 2 hours Vijay Thapa 7 Lectures 2 hours Uplatz 29 Lectures 6 hours Ramnarayan Ramakrishnan 49 Lectures 3 hours Ali Saleh Ali 10 Lectures 4 hours Soham Ghosh 48 Lectures 4.5 hours GUHARAJANM Print Add Notes Bookmark this page
[ { "code": null, "e": 2205, "s": 2052, "text": "Testing is the integrated part of Apex or any other application development. In Apex, we have separate test classes to develop for all the unit testing." }, { "code": null, "e": 2428, "s": 2205, "text": "In SFDC, the code must have 75% code coverage in order to be deployed to Production. This code coverage is performed by the test classes. Test classes are the code snippets which test the functionality of other Apex class." }, { "code": null, "e": 2643, "s": 2428, "text": "Let us write a test class for one of our codes which we have written previously. We will write test class to cover our Trigger and Helper class code. Below is the trigger and helper class which needs to be covered." }, { "code": null, "e": 3758, "s": 2643, "text": "// Trigger with Helper Class\ntrigger Customer_After_Insert on APEX_Customer__c (after update) {\n CustomerTriggerHelper.createInvoiceRecords(Trigger.new, trigger.oldMap);\n //Trigger calls the helper class and does not have any code in Trigger\n}\n\n// Helper Class:\npublic class CustomerTriggerHelper {\n public static void createInvoiceRecords (List<apex_customer__c>\n \n customerList, Map<id, apex_customer__c> oldMapCustomer) {\n List<apex_invoice__c> InvoiceList = new List<apex_invoice__c>();\n \n for (APEX_Customer__c objCustomer: customerList) {\n if (objCustomer.APEX_Customer_Status__c == 'Active' &&\n oldMapCustomer.get(objCustomer.id).APEX_Customer_Status__c == 'Inactive') {\n \n // condition to check the old value and new value\n APEX_Invoice__c objInvoice = new APEX_Invoice__c();\n objInvoice.APEX_Status__c = 'Pending';\n objInvoice.APEX_Customer__c = objCustomer.id;\n InvoiceList.add(objInvoice);\n }\n }\n insert InvoiceList; // DML to insert the Invoice List in SFDC\n }\n}" }, { "code": null, "e": 3822, "s": 3758, "text": "In this section, we will understand how to create a Test Class." }, { "code": null, "e": 4054, "s": 3822, "text": "We need to create data for test class in our test class itself. Test class by default does not have access to organization data but if you set @isTest(seeAllData = true), then it will have the access to organization's data as well." }, { "code": null, "e": 4191, "s": 4054, "text": "By using this annotation, you declared that this is a test class and it will not be counted against the organization's total code limit." }, { "code": null, "e": 4490, "s": 4191, "text": "Unit test methods are the methods which do not take arguments, commit no data to the database, send no emails, and are declared with the testMethod keyword or the isTest annotation in the method definition. Also, test methods must be defined in test classes, that is, classes annotated with isTest." }, { "code": null, "e": 4549, "s": 4490, "text": "We have used the 'myUnitTest' test method in our examples." }, { "code": null, "e": 4954, "s": 4549, "text": "These are the standard test methods which are available for test classes. These methods contain the event or action for which we will be simulating our test. Like in this example, we will test our trigger and helper class to simulate the fire trigger by updating the records as we have done to start and stop block. This also provides separate governor limit to the code which is in start and stop block." }, { "code": null, "e": 5111, "s": 4954, "text": "This method checks the desired output with the actual. In this case, we are expecting an Invoice record to be inserted so we added assert to check the same." }, { "code": null, "e": 5119, "s": 5111, "text": "Example" }, { "code": null, "e": 7064, "s": 5119, "text": "/**\n* This class contains unit tests for validating the behavior of Apex classes\n* and triggers.\n*\n* Unit tests are class methods that verify whether a particular piece\n* of code is working properly. Unit test methods take no arguments,\n* commit no data to the database, and are flagged with the testMethod\n* keyword in the method definition.\n*\n* All test methods in an organization are executed whenever Apex code is deployed\n* to a production organization to confirm correctness, ensure code\n* coverage, and prevent regressions. All Apex classes are\n* required to have at least 75% code coverage in order to be deployed\n* to a production organization. In addition, all triggers must have some code coverage.\n*\n* The @isTest class annotation indicates this class only contains test\n* methods. Classes defined with the @isTest annotation do not count against\n* the organization size limit for all Apex scripts.\n*\n* See the Apex Language Reference for more information about Testing and Code Coverage.\n*/\n\n@isTest\nprivate class CustomerTriggerTestClass {\n static testMethod void myUnitTest() {\n //Create Data for Customer Objet\n APEX_Customer__c objCust = new APEX_Customer__c();\n objCust.Name = 'Test Customer';\n objCust.APEX_Customer_Status__c = 'Inactive';\n insert objCust;\n \n // Now, our trigger will fire on After update event so update the Records\n Test.startTest(); // Starts the scope of test\n objCust.APEX_Customer_Status__c = 'Active';\n update objCust;\n Test.stopTest(); // Ends the scope of test\n \n // Now check if it is giving desired results using system.assert\n // Statement.New invoice should be created\n List<apex_invoice__c> invList = [SELECT Id, APEX_Customer__c FROM\n APEX_Invoice__c WHERE APEX_Customer__c = :objCust.id];\n system.assertEquals(1,invList.size());\n // Check if one record is created in Invoivce sObject\n }\n}" }, { "code": null, "e": 7117, "s": 7064, "text": "Follow the steps given below to run the test class −" }, { "code": null, "e": 7199, "s": 7117, "text": "Step 1 − Go to Apex classes ⇒ click on the class name 'CustomerTriggerTestClass'." }, { "code": null, "e": 7243, "s": 7199, "text": "Step 2 − Click on Run Test button as shown." }, { "code": null, "e": 7265, "s": 7243, "text": "Step 3 − Check status" }, { "code": null, "e": 7341, "s": 7265, "text": "Step 4 − Now check the class and trigger for which we have written the test" }, { "code": null, "e": 7382, "s": 7341, "text": "Our testing is successful and completed." }, { "code": null, "e": 7415, "s": 7382, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 7428, "s": 7415, "text": " Vijay Thapa" }, { "code": null, "e": 7460, "s": 7428, "text": "\n 7 Lectures \n 2 hours \n" }, { "code": null, "e": 7468, "s": 7460, "text": " Uplatz" }, { "code": null, "e": 7501, "s": 7468, "text": "\n 29 Lectures \n 6 hours \n" }, { "code": null, "e": 7526, "s": 7501, "text": " Ramnarayan Ramakrishnan" }, { "code": null, "e": 7559, "s": 7526, "text": "\n 49 Lectures \n 3 hours \n" }, { "code": null, "e": 7574, "s": 7559, "text": " Ali Saleh Ali" }, { "code": null, "e": 7607, "s": 7574, "text": "\n 10 Lectures \n 4 hours \n" }, { "code": null, "e": 7620, "s": 7607, "text": " Soham Ghosh" }, { "code": null, "e": 7655, "s": 7620, "text": "\n 48 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7667, "s": 7655, "text": " GUHARAJANM" }, { "code": null, "e": 7674, "s": 7667, "text": " Print" }, { "code": null, "e": 7685, "s": 7674, "text": " Add Notes" } ]
An Efficient Way to Read Data from the Web Directly into Python | by Luke Gloege, Ph.D. | Towards Data Science
Storage space on my hard drive is precious and I don’t want to download a bunch of data when I’m just going to process it down into something manageable. Sometimes we can paste a URL into pd.read_csv() or xr.read_dataset() and it will gladly read the data. For example, xarray includes support for OPeNDAP to access some, but not all, datasets over HTTP. This post will describe one solution you can use when things aren’t copacetic and directly pasting the URL into xarray fails. I will outline how to read data from a web server directly into Python, even from a zip file, all without writing anything to disk. The goal is to access data across HTTP or FTP, which uses a request and response structure. For example, we could request the contents of a URL and the server will (hopefully) send us back the data as a response. Here is how this structure works in the urllib.request Python package: url='https://google.com': this is the URL we want to access.req=urllib.request.Request(url): creates a Request object specifying the URL we want.resp=urllib.request.urlopen(resp): returns a response object from the server for the requested URL.data=resp.read(): the response object (resp) is file-like, which means we can read it. url='https://google.com': this is the URL we want to access. req=urllib.request.Request(url): creates a Request object specifying the URL we want. resp=urllib.request.urlopen(resp): returns a response object from the server for the requested URL. data=resp.read(): the response object (resp) is file-like, which means we can read it. Now let’s apply this basic idea to some real data. The code below accesses a specific year of air temperature from the NCEP reanalysis. I always prefer to use a context manager when opening a URL so I don’t forget to close it. The last line on this code returns a xarray dataset with our data. However, that line is a little busy, let’s unpack it: resp.read(): is our requested data. However, it is in bytes. io.BytesIO(): Keeps our requested data as bytes in an in-memory buffer. xr.open_dataset(): opens up the bytes file as a xarray dataset. I can do this because the URL I requested is a NetCDF file. This is great! With minimal effort, we were able to read data into memory without downloading it. If you get an error saying “can’t open NetCDF as bytes,” then you need to install h5netcdf. conda install -c conda-forge h5netcdf Not a problem, the Python zipfile package can take care of that. In the code below I am requesting a zip file from a server. I then use the zipfile package to list the files inside. Specifically, I use the namelist() method. Finally, I use xarray to read the contents of one of the NetCDF files contained inside into a dataset. If you ever request access and get this error message it means the server knows you are trying to access it from a program. However, we are smarter than a computer and can trick it into thinking we are a web browser instead. This can be done by attaching a User-Agent to our request so it looks like it is coming from a web browser. As an analogy, this is like knocking on a door and announcing who we are. Attaching a different User-Agent is analogous to impersonating somebody we’re not. When you find a dataset on the web there will usually be a button to download the dataset. We want to know the URL linking to that data. In most browsers, you can right-click and on the download link and “Copy Link Address.” Here is an example using Brave browser to get the link to an oceanographic dataset. This approach can streamline data pipelines and make your code easily reproducible by others. However, there are some drawbacks. For instance, you will not be able to access the data if the server is down. This approach may not work in all situations, such as if the dataset is too big to fit into memory. I haven’t run into any issues yet, but I’m not sure how well this approach would work for large datasets that can still fit into memory. All in all, I find this to be a clean way to make my code reproducible by other researchers. The benefit is I am not relying on them to first download the data. At the very least this is another trick to add to your toolbox. I am happy to help troubleshoot any issues you may have reading data into Python from a server. Thank you for reading and supporting Medium writers
[ { "code": null, "e": 326, "s": 172, "text": "Storage space on my hard drive is precious and I don’t want to download a bunch of data when I’m just going to process it down into something manageable." }, { "code": null, "e": 527, "s": 326, "text": "Sometimes we can paste a URL into pd.read_csv() or xr.read_dataset() and it will gladly read the data. For example, xarray includes support for OPeNDAP to access some, but not all, datasets over HTTP." }, { "code": null, "e": 785, "s": 527, "text": "This post will describe one solution you can use when things aren’t copacetic and directly pasting the URL into xarray fails. I will outline how to read data from a web server directly into Python, even from a zip file, all without writing anything to disk." }, { "code": null, "e": 1069, "s": 785, "text": "The goal is to access data across HTTP or FTP, which uses a request and response structure. For example, we could request the contents of a URL and the server will (hopefully) send us back the data as a response. Here is how this structure works in the urllib.request Python package:" }, { "code": null, "e": 1400, "s": 1069, "text": "url='https://google.com': this is the URL we want to access.req=urllib.request.Request(url): creates a Request object specifying the URL we want.resp=urllib.request.urlopen(resp): returns a response object from the server for the requested URL.data=resp.read(): the response object (resp) is file-like, which means we can read it." }, { "code": null, "e": 1461, "s": 1400, "text": "url='https://google.com': this is the URL we want to access." }, { "code": null, "e": 1547, "s": 1461, "text": "req=urllib.request.Request(url): creates a Request object specifying the URL we want." }, { "code": null, "e": 1647, "s": 1547, "text": "resp=urllib.request.urlopen(resp): returns a response object from the server for the requested URL." }, { "code": null, "e": 1734, "s": 1647, "text": "data=resp.read(): the response object (resp) is file-like, which means we can read it." }, { "code": null, "e": 1785, "s": 1734, "text": "Now let’s apply this basic idea to some real data." }, { "code": null, "e": 1961, "s": 1785, "text": "The code below accesses a specific year of air temperature from the NCEP reanalysis. I always prefer to use a context manager when opening a URL so I don’t forget to close it." }, { "code": null, "e": 2082, "s": 1961, "text": "The last line on this code returns a xarray dataset with our data. However, that line is a little busy, let’s unpack it:" }, { "code": null, "e": 2143, "s": 2082, "text": "resp.read(): is our requested data. However, it is in bytes." }, { "code": null, "e": 2215, "s": 2143, "text": "io.BytesIO(): Keeps our requested data as bytes in an in-memory buffer." }, { "code": null, "e": 2339, "s": 2215, "text": "xr.open_dataset(): opens up the bytes file as a xarray dataset. I can do this because the URL I requested is a NetCDF file." }, { "code": null, "e": 2437, "s": 2339, "text": "This is great! With minimal effort, we were able to read data into memory without downloading it." }, { "code": null, "e": 2529, "s": 2437, "text": "If you get an error saying “can’t open NetCDF as bytes,” then you need to install h5netcdf." }, { "code": null, "e": 2567, "s": 2529, "text": "conda install -c conda-forge h5netcdf" }, { "code": null, "e": 2895, "s": 2567, "text": "Not a problem, the Python zipfile package can take care of that. In the code below I am requesting a zip file from a server. I then use the zipfile package to list the files inside. Specifically, I use the namelist() method. Finally, I use xarray to read the contents of one of the NetCDF files contained inside into a dataset." }, { "code": null, "e": 3385, "s": 2895, "text": "If you ever request access and get this error message it means the server knows you are trying to access it from a program. However, we are smarter than a computer and can trick it into thinking we are a web browser instead. This can be done by attaching a User-Agent to our request so it looks like it is coming from a web browser. As an analogy, this is like knocking on a door and announcing who we are. Attaching a different User-Agent is analogous to impersonating somebody we’re not." }, { "code": null, "e": 3694, "s": 3385, "text": "When you find a dataset on the web there will usually be a button to download the dataset. We want to know the URL linking to that data. In most browsers, you can right-click and on the download link and “Copy Link Address.” Here is an example using Brave browser to get the link to an oceanographic dataset." }, { "code": null, "e": 4137, "s": 3694, "text": "This approach can streamline data pipelines and make your code easily reproducible by others. However, there are some drawbacks. For instance, you will not be able to access the data if the server is down. This approach may not work in all situations, such as if the dataset is too big to fit into memory. I haven’t run into any issues yet, but I’m not sure how well this approach would work for large datasets that can still fit into memory." }, { "code": null, "e": 4362, "s": 4137, "text": "All in all, I find this to be a clean way to make my code reproducible by other researchers. The benefit is I am not relying on them to first download the data. At the very least this is another trick to add to your toolbox." }, { "code": null, "e": 4458, "s": 4362, "text": "I am happy to help troubleshoot any issues you may have reading data into Python from a server." } ]
Logistic Regression Model Fitting and Finding the Correlation, P-Value, Z Score, Confidence Interval, and More | by Rashida Nasrin Sucky | Towards Data Science
Most data scientists who do not have strong statistics background may think of logistic regression as a machine learning model. That’s true. But it has been around for a long time in statistics. Statistics is a very important part of data science and machine learning. Because it is essential for any type of exploratory data analysis or machine learning algorithm to learn the features of a dataset, how they relate to each other, how one feature affects the other features and the overall output. Luckily python has this amazing library that is ‘statsmodels’ library. This library has great functionalities to understand the dataset and also we can use this library to make predictions. Statsmodels library already has models in-built that can be fitted to the data to find the correlation between the features, learn the coefficients, p-value, test-statistic, standard error, and confidence interval. This article will explain a statistical modeling technique with an example. I will explain a logistic regression modeling for binary outcome variables here. That means the outcome variable can have only two values, 0 or 1. We will also analyze: 1. the correlation amongst the predictor variables (the input variables that will be used to predict the outcome variable), 2. how to extract useful information from the model results, 3. the visualization techniques to better present and understand the data and 4. the prediction of the outcome. I am assuming that you have the basic knowledge of statistics and python. A basic logistic regression model fitting with one variableUnderstanding odds and log-odds with examplesLogistic regression model fitting with two variablesLogistic regression model fitting with three variablesVisualization of the fitted modelPrediction A basic logistic regression model fitting with one variable Understanding odds and log-odds with examples Logistic regression model fitting with two variables Logistic regression model fitting with three variables Visualization of the fitted model Prediction If you need a refresher on confidence interval and hypothesis testing, please check out these articles to clearly understand those topics: towardsdatascience.com? towardsdatascience.com For this tutorial, we will use: Numpy LibraryPandas LibraryMatplotlib LibrarySeaborn LibraryStatsmodels LibraryJupyter Notebook environment. Numpy Library Pandas Library Matplotlib Library Seaborn Library Statsmodels Library Jupyter Notebook environment. I used the Heart dataset from Kaggle. I have it in my GitHub repository. Please feel free download from this link if you want to follow along: github.com Let’s import the necessary packages and the dataset. %matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport statsmodels.api as smimport numpy as npdf = pd.read_csv('Heart.csv')df.head() The last column ‘AHD’ contains only ‘yes’ or ‘no’ which tells you if a person has heart disease or not. Replace ‘yes’ and ‘no’ with 1 and 0. df['AHD'] = df.AHD.replace({"No":0, "Yes": 1}) The logistic regression model provides the odds of an event. Let’s dive into the modeling. I will explain each step. I suggest, keep running the code for yourself as you read to better absorb the material. Logistic regression is an improved version of linear regression. As a reminder, here is the linear regression formula: Y = AX + B Here Y is the output and X is the input, A is the slope and B is the intercept. Let’s dive into the modeling part. We will use a Generalized Linear Model (GLM) for this example. There are so many variables. Which one could be that one variable? As we all know, generally heart disease occurs mostly to the older population. The younger population is less likely to get heart disease. I am taking “Age” as the only covariate now. We will add more covariates later. model = sm.GLM.from_formula("AHD ~ Age", family = sm.families.Binomial(), data=df)result = model.fit()result.summary() The result summary looks very complex and scary, right? We will focus mostly on this part. Now, let’s understand all the terms above. coef First, we have the coefficients where -3.0059 is the B, and 0.0520 is our A (think of the linear regression formula Y = AX + B). If a person’s age is 1 unit more s/he will have a 0.052 (coefficient with age in the table above) unit more chance of having heart disease based on the p-value in the table. std err There is a standard error of 0.014 that indicates the distance of the estimated slope from the true slope. z z-statistic of 3.803 means that the predicted slope is going to be 3.803 unit above the zero. Confidence intervals And the last two columns are the confidence intervals (95%). Here the confidence interval is 0.025 and 0.079. Later we will visualize the confidence intervals throughout the length of the data. A logistic regression model provides the ‘odds’ of an event. Remember that, ‘odds’ are the probability on a different scale. Here is the formula: If an event has a probability of p, the odds of that event are p/(1-p) Odds are the transformation of the probability. Based on this formula, if the probability is 1/2, the ‘odds’ is 1. To understand the odds and log-odds clearly, let’s work on an example. We will use the gender variable. Because a categorical variable is appropriate for this. Check the proportion of males and females having heart disease in the dataset. df["Sex1"] = df.Sex.replace({1: "Male", 0:"Female"})c = pd.crosstab(df.Sex1, df.AHD)c = c.apply(lambda x: x/x.sum(), axis=1) Let’s calculate the ‘odds’ of heart disease for males and females. c["odds"] = c.loc[:, 1] / c.loc[:, 0] The ‘odds’ show that the probability of a female having heart disease is substantially lower than a male(32% vs 53%) that reflects very well in the odds. Odds ratios are common to use while working with two population groups. c.odds.Male / c.odds.Female The ratio comes out to be 3.587 which indicates a man has a 3.587 times greater chance of having a heart disease. Remember that, an individual probability cannot be calculated from an odd ratio Another important convention is to work with log-odds which are odds in a logarithmic scale. Recall that the neutral point of the probability is 0.5. Using the formula for ‘odds’, odds for 0.5 is 1 and ‘log-odds’ is 0 (log of 1 is 0). In our exercise where men have a greater chance of having heart disease, have ‘odds’ between 1 and infinity. At the same time, the ‘odds’ of women having a greater chance of having heart disease is 0 to 1. Here is the log odds calculation: c['logodds'] = np.log(c.odds) Here, the log-odds of the female population are negative which indicates that less than 50% of females have heart disease. Log-odds of males are positive and a little more than 0 which means more than half of the males have heart disease. The relationship between log odds and logistic regression will be more clear from the model summary below. Let’s see the model summary using the gender variable only: model = sm.GLM.from_formula("AHD ~ Sex1", family = sm.families.Binomial(), data=df)result = model.fit()result.summary() Look at the coefficients above. The logistic regression coefficient of males is 1.2722 which should be the same as the log-odds of males minus the log-odds of females. c.logodds.Male - c.logodds.Female This difference is exactly 1.2722. We can use multiple covariates. I am using both ‘Age’ and ‘Sex1’ variables here. Before we dive into the model, we can conduct an initial analysis with the categorical variables. Check the proportion of males and females having heart disease in the dataset. df["Sex1"] = df.Sex.replace({1: "Male", 0:"Female"})c = pd.crosstab(df.Sex1, df.AHD)c = c.apply(lambda x: x/x.sum(), axis=1) Now, generate a model using both the ‘Age’ and ‘Sex’ variable. model = sm.GLM.from_formula("AHD ~ Age + Sex1", family = sm.families.Binomial(), data=df)result = model.fit()result.summary() Understand the coefficients better. Adding gender to the model changed the coefficient of the ‘Age’ parameter a little(0.0520 to 0.0657). According to this fitted model, older people are more likely to have heart disease than younger people. The log odds for heart disease increases by 0.0657 units for each year. If a person is 10 years older his or her chance of having heart disease increases by 0.0657 * 10 = 0.657 units. In the case of the gender variable, the female is the reference as it does not appear in the output. While comparing a male and a female of the same age, the male has a 1.4989 units higher chance of having a heart disease. Now, let’s see the effect of both gender and age. If a 40 years old female is compared to 50 years old male, the log odds for the male having heart disease is 1.4989 + 0.0657 * 10 = 2.15559 units greater than the female. All the coefficients are in log-odds scale. You can exponentiate the values to convert them to the odds Now, we will fit a logistic regression with three covariates. This time we will add ‘Chol’ or cholesterol variables with ‘Age’ and ‘Sex1’. model = sm.GLM.from_formula("AHD ~ Age + Sex1 + Chol", family = sm.families.Binomial(), data=df)result = model.fit()result.summary() As you can see, after adding the ‘Chol’ variable, the coefficient of the ‘Age’ variable reduced a little bit and the coefficient of the ‘Sex1’ variable went up a little. The change is more in ‘Sex1’ coefficients than the ‘Age’ coefficient. This is because ‘Chol’ is better correlated to the ‘Sex1’ covariate than the ‘Age’ covariate. Let’s check the correlations: df[['Age', 'Sex', 'Chol']].corr() We will begin by plotting the fitted proportion of the population that have heart disease for different subpopulations defined by the regression model. We will plot how the heart disease rate varies with the age. We will fix some values that we want to focus on in the visualization. We will visualize the effect of ‘Age’ on the female population having a cholesterol level of 250. from statsmodels.sandbox.predict_functional import predict_functionalvalues = {"Sex1": "Female", "Sex":0, "AHD": 1, "Chol": 250}pr, cb, fv = predict_functional(result, "Age", values=values, ci_method="simultaneous")ax = sns.lineplot(fv, pr, lw=4)ax.fill_between(fv, cb[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel("Age")ax.set_ylabel("Heart Disease") We just plotted the fitted log-odds probability of having heart disease and the 95% confidence intervals. The confidence band is more appropriate. The confidence band looks curvy which means that it’s not uniform throughout the age range. We can visualize in terms of probability instead of log-odds. The probability can be calculated from the log odds using the formula 1 / (1 + exp(-lo)), where lo is the log-odds. pr1 = 1 / (1 + np.exp(-pr))cb1 = 1 / (1 + np.exp(-cb))ax = sns.lineplot(fv, pr1, lw=4)ax.fill_between(fv, cb1[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel("Age", size=15)ax.set_ylabel("Heart Disease") Here is the problem with the probability scale sometimes. While the probability values are limited to 0 and 1, the confidence intervals are not. The plots above plotted the average. On average that was the probability of a female having heart disease given the cholesterol level of 250. Next, we will visualize in a different way that is called a partial residual plot. In this plot, it will show the effect of one covariate only while the other covariates are fixed. This shows even the smaller discrepancies. So, the plot will not be as smooth as before. Remember, the small discrepancies are not reliable if the sample size is not very large. from statsmodels.graphics.regressionplots import add_lowessfig = result.plot_partial_residuals("Age")ax = fig.get_axes()[0]ax.lines[0].set_alpha(0.5)_ = add_lowess(ax) This plot shows that the heart disease rate rises rapidly from the age of 53 to 60. Using the results from the model, we can predict if a person has heart disease or not. The models we fitted before were to explain the model parameters. For the prediction purpose, I will use all the variables in the DataFrame. Because we do not have too many variables. Let’s check the correlations amongst the variables. df['ChestPain'] = df.ChestPain.replace({"typical":1, "asymptomatic": 2, 'nonanginal': 3, 'nontypical':4})df['Thal'] = df.Thal.replace({'fixed': 1, 'normal': 2, 'reversable': 3})df[['Age', 'Sex1', 'Chol','RestBP', 'Fbs', 'RestECG', 'Slope', 'Oldpeak', 'Ca', 'ExAng', 'ChestPain', 'Thal']].corr() We can see that each variable has some correlations with other variables. I will use all the variables to get a better prediction. model = sm.GLM.from_formula("AHD ~ Age + Sex1 + Chol + RestBP+ Fbs + RestECG + Slope + Oldpeak + Ca + ExAng + ChestPain + Thal", family = sm.families.Binomial(), data=df)result = model.fit()result.summary() We can use the predict function to predict the outcome. But the predict function uses only the DataFrame. So, let’s prepare a DataFrame with the variables and then use the predict function. X = df[['Age', 'Sex1', 'Chol','RestBP', 'Fbs', 'RestECG', 'Slope', 'Oldpeak', 'Ca', 'ExAng', 'ChestPain', 'Thal']]predicted_output = result.predict(X) The predicted output should be either 0 or 1. It’s 1 when the output is greater than or equal to 0.5 and 0 otherwise. for i in range(0, len(predicted_output)): predicted_output = predicted_output.replace() if predicted_output[i] >= 0.5: predicted_output = predicted_output.replace(predicted_output[i], 1) else: predicted_output = predicted_output.replace(predicted_output[i], 0) Now, compare this predicted_output to the ‘AHD’ column of the DataFrame which indicates the heart disease to find the accuracy: accuracy = 0for i in range(0, len(predicted_output)): if df['AHD'][i] == predicted_output[i]: accuracy += 1accuracy/len(df) The accuracy comes out to be 0.81 or 81% which is very good. In this article, I tried to explain the statistical model fitting, how to interpret the result from the fitted model, some visualization technique to present the log-odds with the confidence band, and how to predict a binary variable using the fitted model results. I hope this was helpful. Feel free to follow me on Twitter and like my Facebook page.
[ { "code": null, "e": 366, "s": 171, "text": "Most data scientists who do not have strong statistics background may think of logistic regression as a machine learning model. That’s true. But it has been around for a long time in statistics." }, { "code": null, "e": 670, "s": 366, "text": "Statistics is a very important part of data science and machine learning. Because it is essential for any type of exploratory data analysis or machine learning algorithm to learn the features of a dataset, how they relate to each other, how one feature affects the other features and the overall output." }, { "code": null, "e": 1075, "s": 670, "text": "Luckily python has this amazing library that is ‘statsmodels’ library. This library has great functionalities to understand the dataset and also we can use this library to make predictions. Statsmodels library already has models in-built that can be fitted to the data to find the correlation between the features, learn the coefficients, p-value, test-statistic, standard error, and confidence interval." }, { "code": null, "e": 1298, "s": 1075, "text": "This article will explain a statistical modeling technique with an example. I will explain a logistic regression modeling for binary outcome variables here. That means the outcome variable can have only two values, 0 or 1." }, { "code": null, "e": 1320, "s": 1298, "text": "We will also analyze:" }, { "code": null, "e": 1444, "s": 1320, "text": "1. the correlation amongst the predictor variables (the input variables that will be used to predict the outcome variable)," }, { "code": null, "e": 1505, "s": 1444, "text": "2. how to extract useful information from the model results," }, { "code": null, "e": 1583, "s": 1505, "text": "3. the visualization techniques to better present and understand the data and" }, { "code": null, "e": 1691, "s": 1583, "text": "4. the prediction of the outcome. I am assuming that you have the basic knowledge of statistics and python." }, { "code": null, "e": 1945, "s": 1691, "text": "A basic logistic regression model fitting with one variableUnderstanding odds and log-odds with examplesLogistic regression model fitting with two variablesLogistic regression model fitting with three variablesVisualization of the fitted modelPrediction" }, { "code": null, "e": 2005, "s": 1945, "text": "A basic logistic regression model fitting with one variable" }, { "code": null, "e": 2051, "s": 2005, "text": "Understanding odds and log-odds with examples" }, { "code": null, "e": 2104, "s": 2051, "text": "Logistic regression model fitting with two variables" }, { "code": null, "e": 2159, "s": 2104, "text": "Logistic regression model fitting with three variables" }, { "code": null, "e": 2193, "s": 2159, "text": "Visualization of the fitted model" }, { "code": null, "e": 2204, "s": 2193, "text": "Prediction" }, { "code": null, "e": 2343, "s": 2204, "text": "If you need a refresher on confidence interval and hypothesis testing, please check out these articles to clearly understand those topics:" }, { "code": null, "e": 2367, "s": 2343, "text": "towardsdatascience.com?" }, { "code": null, "e": 2390, "s": 2367, "text": "towardsdatascience.com" }, { "code": null, "e": 2422, "s": 2390, "text": "For this tutorial, we will use:" }, { "code": null, "e": 2531, "s": 2422, "text": "Numpy LibraryPandas LibraryMatplotlib LibrarySeaborn LibraryStatsmodels LibraryJupyter Notebook environment." }, { "code": null, "e": 2545, "s": 2531, "text": "Numpy Library" }, { "code": null, "e": 2560, "s": 2545, "text": "Pandas Library" }, { "code": null, "e": 2579, "s": 2560, "text": "Matplotlib Library" }, { "code": null, "e": 2595, "s": 2579, "text": "Seaborn Library" }, { "code": null, "e": 2615, "s": 2595, "text": "Statsmodels Library" }, { "code": null, "e": 2645, "s": 2615, "text": "Jupyter Notebook environment." }, { "code": null, "e": 2788, "s": 2645, "text": "I used the Heart dataset from Kaggle. I have it in my GitHub repository. Please feel free download from this link if you want to follow along:" }, { "code": null, "e": 2799, "s": 2788, "text": "github.com" }, { "code": null, "e": 2852, "s": 2799, "text": "Let’s import the necessary packages and the dataset." }, { "code": null, "e": 3026, "s": 2852, "text": "%matplotlib inlineimport matplotlib.pyplot as pltimport seaborn as snsimport pandas as pdimport statsmodels.api as smimport numpy as npdf = pd.read_csv('Heart.csv')df.head()" }, { "code": null, "e": 3167, "s": 3026, "text": "The last column ‘AHD’ contains only ‘yes’ or ‘no’ which tells you if a person has heart disease or not. Replace ‘yes’ and ‘no’ with 1 and 0." }, { "code": null, "e": 3214, "s": 3167, "text": "df['AHD'] = df.AHD.replace({\"No\":0, \"Yes\": 1})" }, { "code": null, "e": 3275, "s": 3214, "text": "The logistic regression model provides the odds of an event." }, { "code": null, "e": 3420, "s": 3275, "text": "Let’s dive into the modeling. I will explain each step. I suggest, keep running the code for yourself as you read to better absorb the material." }, { "code": null, "e": 3485, "s": 3420, "text": "Logistic regression is an improved version of linear regression." }, { "code": null, "e": 3539, "s": 3485, "text": "As a reminder, here is the linear regression formula:" }, { "code": null, "e": 3550, "s": 3539, "text": "Y = AX + B" }, { "code": null, "e": 3630, "s": 3550, "text": "Here Y is the output and X is the input, A is the slope and B is the intercept." }, { "code": null, "e": 3728, "s": 3630, "text": "Let’s dive into the modeling part. We will use a Generalized Linear Model (GLM) for this example." }, { "code": null, "e": 3795, "s": 3728, "text": "There are so many variables. Which one could be that one variable?" }, { "code": null, "e": 4014, "s": 3795, "text": "As we all know, generally heart disease occurs mostly to the older population. The younger population is less likely to get heart disease. I am taking “Age” as the only covariate now. We will add more covariates later." }, { "code": null, "e": 4133, "s": 4014, "text": "model = sm.GLM.from_formula(\"AHD ~ Age\", family = sm.families.Binomial(), data=df)result = model.fit()result.summary()" }, { "code": null, "e": 4224, "s": 4133, "text": "The result summary looks very complex and scary, right? We will focus mostly on this part." }, { "code": null, "e": 4267, "s": 4224, "text": "Now, let’s understand all the terms above." }, { "code": null, "e": 4272, "s": 4267, "text": "coef" }, { "code": null, "e": 4401, "s": 4272, "text": "First, we have the coefficients where -3.0059 is the B, and 0.0520 is our A (think of the linear regression formula Y = AX + B)." }, { "code": null, "e": 4575, "s": 4401, "text": "If a person’s age is 1 unit more s/he will have a 0.052 (coefficient with age in the table above) unit more chance of having heart disease based on the p-value in the table." }, { "code": null, "e": 4583, "s": 4575, "text": "std err" }, { "code": null, "e": 4690, "s": 4583, "text": "There is a standard error of 0.014 that indicates the distance of the estimated slope from the true slope." }, { "code": null, "e": 4692, "s": 4690, "text": "z" }, { "code": null, "e": 4786, "s": 4692, "text": "z-statistic of 3.803 means that the predicted slope is going to be 3.803 unit above the zero." }, { "code": null, "e": 4807, "s": 4786, "text": "Confidence intervals" }, { "code": null, "e": 5001, "s": 4807, "text": "And the last two columns are the confidence intervals (95%). Here the confidence interval is 0.025 and 0.079. Later we will visualize the confidence intervals throughout the length of the data." }, { "code": null, "e": 5147, "s": 5001, "text": "A logistic regression model provides the ‘odds’ of an event. Remember that, ‘odds’ are the probability on a different scale. Here is the formula:" }, { "code": null, "e": 5183, "s": 5147, "text": "If an event has a probability of p," }, { "code": null, "e": 5218, "s": 5183, "text": "the odds of that event are p/(1-p)" }, { "code": null, "e": 5333, "s": 5218, "text": "Odds are the transformation of the probability. Based on this formula, if the probability is 1/2, the ‘odds’ is 1." }, { "code": null, "e": 5437, "s": 5333, "text": "To understand the odds and log-odds clearly, let’s work on an example. We will use the gender variable." }, { "code": null, "e": 5572, "s": 5437, "text": "Because a categorical variable is appropriate for this. Check the proportion of males and females having heart disease in the dataset." }, { "code": null, "e": 5697, "s": 5572, "text": "df[\"Sex1\"] = df.Sex.replace({1: \"Male\", 0:\"Female\"})c = pd.crosstab(df.Sex1, df.AHD)c = c.apply(lambda x: x/x.sum(), axis=1)" }, { "code": null, "e": 5764, "s": 5697, "text": "Let’s calculate the ‘odds’ of heart disease for males and females." }, { "code": null, "e": 5802, "s": 5764, "text": "c[\"odds\"] = c.loc[:, 1] / c.loc[:, 0]" }, { "code": null, "e": 6028, "s": 5802, "text": "The ‘odds’ show that the probability of a female having heart disease is substantially lower than a male(32% vs 53%) that reflects very well in the odds. Odds ratios are common to use while working with two population groups." }, { "code": null, "e": 6056, "s": 6028, "text": "c.odds.Male / c.odds.Female" }, { "code": null, "e": 6170, "s": 6056, "text": "The ratio comes out to be 3.587 which indicates a man has a 3.587 times greater chance of having a heart disease." }, { "code": null, "e": 6250, "s": 6170, "text": "Remember that, an individual probability cannot be calculated from an odd ratio" }, { "code": null, "e": 6343, "s": 6250, "text": "Another important convention is to work with log-odds which are odds in a logarithmic scale." }, { "code": null, "e": 6485, "s": 6343, "text": "Recall that the neutral point of the probability is 0.5. Using the formula for ‘odds’, odds for 0.5 is 1 and ‘log-odds’ is 0 (log of 1 is 0)." }, { "code": null, "e": 6691, "s": 6485, "text": "In our exercise where men have a greater chance of having heart disease, have ‘odds’ between 1 and infinity. At the same time, the ‘odds’ of women having a greater chance of having heart disease is 0 to 1." }, { "code": null, "e": 6725, "s": 6691, "text": "Here is the log odds calculation:" }, { "code": null, "e": 6755, "s": 6725, "text": "c['logodds'] = np.log(c.odds)" }, { "code": null, "e": 6878, "s": 6755, "text": "Here, the log-odds of the female population are negative which indicates that less than 50% of females have heart disease." }, { "code": null, "e": 6994, "s": 6878, "text": "Log-odds of males are positive and a little more than 0 which means more than half of the males have heart disease." }, { "code": null, "e": 7161, "s": 6994, "text": "The relationship between log odds and logistic regression will be more clear from the model summary below. Let’s see the model summary using the gender variable only:" }, { "code": null, "e": 7281, "s": 7161, "text": "model = sm.GLM.from_formula(\"AHD ~ Sex1\", family = sm.families.Binomial(), data=df)result = model.fit()result.summary()" }, { "code": null, "e": 7313, "s": 7281, "text": "Look at the coefficients above." }, { "code": null, "e": 7449, "s": 7313, "text": "The logistic regression coefficient of males is 1.2722 which should be the same as the log-odds of males minus the log-odds of females." }, { "code": null, "e": 7483, "s": 7449, "text": "c.logodds.Male - c.logodds.Female" }, { "code": null, "e": 7518, "s": 7483, "text": "This difference is exactly 1.2722." }, { "code": null, "e": 7776, "s": 7518, "text": "We can use multiple covariates. I am using both ‘Age’ and ‘Sex1’ variables here. Before we dive into the model, we can conduct an initial analysis with the categorical variables. Check the proportion of males and females having heart disease in the dataset." }, { "code": null, "e": 7901, "s": 7776, "text": "df[\"Sex1\"] = df.Sex.replace({1: \"Male\", 0:\"Female\"})c = pd.crosstab(df.Sex1, df.AHD)c = c.apply(lambda x: x/x.sum(), axis=1)" }, { "code": null, "e": 7964, "s": 7901, "text": "Now, generate a model using both the ‘Age’ and ‘Sex’ variable." }, { "code": null, "e": 8090, "s": 7964, "text": "model = sm.GLM.from_formula(\"AHD ~ Age + Sex1\", family = sm.families.Binomial(), data=df)result = model.fit()result.summary()" }, { "code": null, "e": 8228, "s": 8090, "text": "Understand the coefficients better. Adding gender to the model changed the coefficient of the ‘Age’ parameter a little(0.0520 to 0.0657)." }, { "code": null, "e": 8404, "s": 8228, "text": "According to this fitted model, older people are more likely to have heart disease than younger people. The log odds for heart disease increases by 0.0657 units for each year." }, { "code": null, "e": 8516, "s": 8404, "text": "If a person is 10 years older his or her chance of having heart disease increases by 0.0657 * 10 = 0.657 units." }, { "code": null, "e": 8617, "s": 8516, "text": "In the case of the gender variable, the female is the reference as it does not appear in the output." }, { "code": null, "e": 8739, "s": 8617, "text": "While comparing a male and a female of the same age, the male has a 1.4989 units higher chance of having a heart disease." }, { "code": null, "e": 8960, "s": 8739, "text": "Now, let’s see the effect of both gender and age. If a 40 years old female is compared to 50 years old male, the log odds for the male having heart disease is 1.4989 + 0.0657 * 10 = 2.15559 units greater than the female." }, { "code": null, "e": 9064, "s": 8960, "text": "All the coefficients are in log-odds scale. You can exponentiate the values to convert them to the odds" }, { "code": null, "e": 9203, "s": 9064, "text": "Now, we will fit a logistic regression with three covariates. This time we will add ‘Chol’ or cholesterol variables with ‘Age’ and ‘Sex1’." }, { "code": null, "e": 9336, "s": 9203, "text": "model = sm.GLM.from_formula(\"AHD ~ Age + Sex1 + Chol\", family = sm.families.Binomial(), data=df)result = model.fit()result.summary()" }, { "code": null, "e": 9506, "s": 9336, "text": "As you can see, after adding the ‘Chol’ variable, the coefficient of the ‘Age’ variable reduced a little bit and the coefficient of the ‘Sex1’ variable went up a little." }, { "code": null, "e": 9700, "s": 9506, "text": "The change is more in ‘Sex1’ coefficients than the ‘Age’ coefficient. This is because ‘Chol’ is better correlated to the ‘Sex1’ covariate than the ‘Age’ covariate. Let’s check the correlations:" }, { "code": null, "e": 9734, "s": 9700, "text": "df[['Age', 'Sex', 'Chol']].corr()" }, { "code": null, "e": 9947, "s": 9734, "text": "We will begin by plotting the fitted proportion of the population that have heart disease for different subpopulations defined by the regression model. We will plot how the heart disease rate varies with the age." }, { "code": null, "e": 10116, "s": 9947, "text": "We will fix some values that we want to focus on in the visualization. We will visualize the effect of ‘Age’ on the female population having a cholesterol level of 250." }, { "code": null, "e": 10477, "s": 10116, "text": "from statsmodels.sandbox.predict_functional import predict_functionalvalues = {\"Sex1\": \"Female\", \"Sex\":0, \"AHD\": 1, \"Chol\": 250}pr, cb, fv = predict_functional(result, \"Age\", values=values, ci_method=\"simultaneous\")ax = sns.lineplot(fv, pr, lw=4)ax.fill_between(fv, cb[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel(\"Age\")ax.set_ylabel(\"Heart Disease\")" }, { "code": null, "e": 10716, "s": 10477, "text": "We just plotted the fitted log-odds probability of having heart disease and the 95% confidence intervals. The confidence band is more appropriate. The confidence band looks curvy which means that it’s not uniform throughout the age range." }, { "code": null, "e": 10894, "s": 10716, "text": "We can visualize in terms of probability instead of log-odds. The probability can be calculated from the log odds using the formula 1 / (1 + exp(-lo)), where lo is the log-odds." }, { "code": null, "e": 11105, "s": 10894, "text": "pr1 = 1 / (1 + np.exp(-pr))cb1 = 1 / (1 + np.exp(-cb))ax = sns.lineplot(fv, pr1, lw=4)ax.fill_between(fv, cb1[:, 0], cb[:, 1], color='grey', alpha=0.4)ax.set_xlabel(\"Age\", size=15)ax.set_ylabel(\"Heart Disease\")" }, { "code": null, "e": 11163, "s": 11105, "text": "Here is the problem with the probability scale sometimes." }, { "code": null, "e": 11250, "s": 11163, "text": "While the probability values are limited to 0 and 1, the confidence intervals are not." }, { "code": null, "e": 11475, "s": 11250, "text": "The plots above plotted the average. On average that was the probability of a female having heart disease given the cholesterol level of 250. Next, we will visualize in a different way that is called a partial residual plot." }, { "code": null, "e": 11751, "s": 11475, "text": "In this plot, it will show the effect of one covariate only while the other covariates are fixed. This shows even the smaller discrepancies. So, the plot will not be as smooth as before. Remember, the small discrepancies are not reliable if the sample size is not very large." }, { "code": null, "e": 11919, "s": 11751, "text": "from statsmodels.graphics.regressionplots import add_lowessfig = result.plot_partial_residuals(\"Age\")ax = fig.get_axes()[0]ax.lines[0].set_alpha(0.5)_ = add_lowess(ax)" }, { "code": null, "e": 12003, "s": 11919, "text": "This plot shows that the heart disease rate rises rapidly from the age of 53 to 60." }, { "code": null, "e": 12326, "s": 12003, "text": "Using the results from the model, we can predict if a person has heart disease or not. The models we fitted before were to explain the model parameters. For the prediction purpose, I will use all the variables in the DataFrame. Because we do not have too many variables. Let’s check the correlations amongst the variables." }, { "code": null, "e": 12621, "s": 12326, "text": "df['ChestPain'] = df.ChestPain.replace({\"typical\":1, \"asymptomatic\": 2, 'nonanginal': 3, 'nontypical':4})df['Thal'] = df.Thal.replace({'fixed': 1, 'normal': 2, 'reversable': 3})df[['Age', 'Sex1', 'Chol','RestBP', 'Fbs', 'RestECG', 'Slope', 'Oldpeak', 'Ca', 'ExAng', 'ChestPain', 'Thal']].corr()" }, { "code": null, "e": 12752, "s": 12621, "text": "We can see that each variable has some correlations with other variables. I will use all the variables to get a better prediction." }, { "code": null, "e": 12959, "s": 12752, "text": "model = sm.GLM.from_formula(\"AHD ~ Age + Sex1 + Chol + RestBP+ Fbs + RestECG + Slope + Oldpeak + Ca + ExAng + ChestPain + Thal\", family = sm.families.Binomial(), data=df)result = model.fit()result.summary()" }, { "code": null, "e": 13149, "s": 12959, "text": "We can use the predict function to predict the outcome. But the predict function uses only the DataFrame. So, let’s prepare a DataFrame with the variables and then use the predict function." }, { "code": null, "e": 13300, "s": 13149, "text": "X = df[['Age', 'Sex1', 'Chol','RestBP', 'Fbs', 'RestECG', 'Slope', 'Oldpeak', 'Ca', 'ExAng', 'ChestPain', 'Thal']]predicted_output = result.predict(X)" }, { "code": null, "e": 13418, "s": 13300, "text": "The predicted output should be either 0 or 1. It’s 1 when the output is greater than or equal to 0.5 and 0 otherwise." }, { "code": null, "e": 13702, "s": 13418, "text": "for i in range(0, len(predicted_output)): predicted_output = predicted_output.replace() if predicted_output[i] >= 0.5: predicted_output = predicted_output.replace(predicted_output[i], 1) else: predicted_output = predicted_output.replace(predicted_output[i], 0)" }, { "code": null, "e": 13830, "s": 13702, "text": "Now, compare this predicted_output to the ‘AHD’ column of the DataFrame which indicates the heart disease to find the accuracy:" }, { "code": null, "e": 13964, "s": 13830, "text": "accuracy = 0for i in range(0, len(predicted_output)): if df['AHD'][i] == predicted_output[i]: accuracy += 1accuracy/len(df)" }, { "code": null, "e": 14025, "s": 13964, "text": "The accuracy comes out to be 0.81 or 81% which is very good." }, { "code": null, "e": 14316, "s": 14025, "text": "In this article, I tried to explain the statistical model fitting, how to interpret the result from the fitted model, some visualization technique to present the log-odds with the confidence band, and how to predict a binary variable using the fitted model results. I hope this was helpful." } ]
Understanding How Schools Work with Canonical Correlation Analysis | by Liana Mehrabyan | Towards Data Science
Us data scientists spend most of our time analysing relationships and patterns in our data. Most of our exploratory tools, however, focus on one-to-one relationships. But what if we want to have a more generalised view and find commonalities and patterns between certain groups of variables? This post includes: an introduction to Canonical Correlation Analysis that lets us identify associations among groups of variables at a time. a CCA tutorial in Python on how school environment affects students’ performance. Suppose we want to find out how a school’s ambience affects its students’ academic success. On one hand, we have variables about the level of support, trust and collaboration in their learning environment. On the other hand, we have students’ academic records and test results. CCA lets us explore associations between these two sets of variables as a whole, rather than considering them on an individual basis. Loosely speaking, we come up with a collective representation (a latent variable called canonical variate) for each of these variable sets in a way that the correlation between those variates is maximised. Before diving into a pile of equations, let’s see why it’s worth the effort. With CCA we can: Find out whether two sets of variables are independent or, measure the magnitude of their relationship if there is one. Interpret the nature of their relationship by assessing each variable’s contribution to the canonical variates (i.e. components) and find what dimensions are common between the two sets. Summarise relationships into a lesser number of statistics. Conduct a dimensionality reduction that takes into account the existence of certain variable groups. Given two sets of variables: We construct the first pair of Canonical Variates as linear combinations of the variables in each group: where the weights (a1, ... ap), (b1, ... , bq) are chosen in a way that the correlation between the two variates is maximised. Having our pair of covariates: The Canonical Correlation Coefficient is the correlation between the canonical variates CVX and CVY. To compute the second pair of covariates, we conduct the same process by adding one more constraint: each new variate should be orthogonal and uncorrelated to the previous ones. We compute min(p,q) pairs in a similar fashion and end up with min(p,q) components ready to explore. (Note that the number of variables in each set doesn’t have to be the same.) Just as in PCA, we project our data onto min(p,q) latent dimensions. However, not all of them might be informative and important. Let’s see the makeup and interpretation of our canonical variates in the example below. We’ll be using two variable groups from NYC schools dataset: Rigorous Instruction % Collaborative Teachers % Supportive Environment % Effective School Leadership % Family-Community Ties % Trust % Average ELA Proficiency Average Math Proficiency As for the tool, we’ll be using the pyrcca implementation. We start with separating each of our variable groups in a single dataframe: import pandas as pdimport numpy as npdf = pd.read_csv('2016 School Explorer.csv')# choose relevant featuresdf = df[['Rigorous Instruction %', 'Collaborative Teachers %', 'Supportive Environment %', 'Effective School Leadership %', 'Strong Family-Community Ties %', 'Trust %','Average ELA Proficiency', 'Average Math Proficiency']]# drop missing valuesdf = df.dropna()# separate X and Y groupsX = df[['Rigorous Instruction %', 'Collaborative Teachers %', 'Supportive Environment %', 'Effective School Leadership %', 'Strong Family-Community Ties %', 'Trust %' ]]Y = df[['Average ELA Proficiency', 'Average Math Proficiency']] Convert group X into numeric variables and standardise the data: for col in X.columns: X[col] = X[col].str.strip('%') X[col] = X[col].astype('int')# Standardise the datafrom sklearn.preprocessing import StandardScalersc = StandardScaler(with_mean=True, with_std=True)X_sc = sc.fit_transform(X)Y_sc = sc.fit_transform(Y) After relevant preprocessing, we’re ready to apply CCA. Note that we set the regularisation parameter to 0 as regularised CCA is out of the scope of this post (we will get back to this in future posts though). import pyrccanComponents = 2 # min(p,q) componentscca = pyrcca.CCA(kernelcca = False, reg = 0., numCC = nComponents,)# train on datacca.train([X_sc, Y_sc])print('Canonical Correlation Per Component Pair:',cca.cancorrs)print('% Shared Variance:',cca.cancorrs**2) Cannonical Correlations >> Canonical Correlation Per Component Pair: [0.46059902 0.18447786]>> % Shared Variance: [0.21215146 0.03403208] For our two pairs of canonical variates, we have canonical correlations of 0.46 and 0.18 respectively. So, latent representations of school ambience and students’ performance do have a positive correlation of 0.46 and share 21 percent of variance. Squared canonical correlation represents the shared variance by the latent representations of variable sets, and not the variance inferred from the sets of variables themselves. Canonical Weights In order to access the weights assigned to our standardised variables (a1, ... , ap) and (b1, ... , bq) we use cca.ws: cca.ws>> [array([[-0.00375779, 0.0078263 ], [ 0.00061439, -0.00357358], [-0.02054012, -0.0083491 ], [-0.01252477, 0.02976148], [ 0.00046503, -0.00905069], [ 0.01415084, -0.01264106]]), array([[ 0.00632283, 0.05721601], [-0.02606459, -0.05132531]])] Given these weights, the canonical variates of set Y, for example, were calculated with the following formula: where the weights can be interpreted as the coefficients in a linear regression model. We should take into account that it is not highly recommended to rely on weights when interpreting individual variable contribution to covariates. Here’s why: Weights are subject to variability from one sample to another. Weights can be highly affected by multicollinearity (which is quite common for same-context variable groups). Relying on canonical loadings instead is a more common practice. Canonical Loadings Canonical loadings are nothing more than the correlation between the original variable and the canonical variate of that set. For example, to assess the contribution of Trust in school environment representation, we calculate the correlation between the variable Trust and the resulting variate for variable set X. Calculating loadings for group Y in the first variate: print('Loading for Math Score:',np.corrcoef(cca.comps[0][:,0],Y_sc[:,0])[0,1])print('Loading for ELA Score:',np.corrcoef(cca.comps[0][:,0],Y_sc[:,1])[0,1])>> Loading for Math Score: -0.4106778140971078>> Loading for ELA Score: -0.4578120954218724 Canonical Covariates Finally, we might want to access the covariate values directly, be it for visualisation or any other purpose. To do so, we need: # CVX cca.comps[0]# First CV for X cca.comps[0][:,0]# Second CV for Xcca.comps[0][:,1]# CVYcca.comps[1]# First CV for Ycca.comps[1][:,0]# Second CV for Y cca.comps[1][:,1] Hope you find this helpful and use CCA more in your EDA routine. -Keep Exploring [1] Bilenko N., Gallan., 2016, Pyrcca: Regularized Kernel Canonical Correlation Analysis in Python and Its Applications to Neuroimaging, Frontiers in Neuroinfomatics [2] Dattalo, P.V., 2014, A Demonstration of Canonical Correlation Analysis with Orthogonal Rotation to Facilitate Interpretation
[ { "code": null, "e": 463, "s": 171, "text": "Us data scientists spend most of our time analysing relationships and patterns in our data. Most of our exploratory tools, however, focus on one-to-one relationships. But what if we want to have a more generalised view and find commonalities and patterns between certain groups of variables?" }, { "code": null, "e": 483, "s": 463, "text": "This post includes:" }, { "code": null, "e": 605, "s": 483, "text": "an introduction to Canonical Correlation Analysis that lets us identify associations among groups of variables at a time." }, { "code": null, "e": 687, "s": 605, "text": "a CCA tutorial in Python on how school environment affects students’ performance." }, { "code": null, "e": 965, "s": 687, "text": "Suppose we want to find out how a school’s ambience affects its students’ academic success. On one hand, we have variables about the level of support, trust and collaboration in their learning environment. On the other hand, we have students’ academic records and test results." }, { "code": null, "e": 1305, "s": 965, "text": "CCA lets us explore associations between these two sets of variables as a whole, rather than considering them on an individual basis. Loosely speaking, we come up with a collective representation (a latent variable called canonical variate) for each of these variable sets in a way that the correlation between those variates is maximised." }, { "code": null, "e": 1382, "s": 1305, "text": "Before diving into a pile of equations, let’s see why it’s worth the effort." }, { "code": null, "e": 1399, "s": 1382, "text": "With CCA we can:" }, { "code": null, "e": 1519, "s": 1399, "text": "Find out whether two sets of variables are independent or, measure the magnitude of their relationship if there is one." }, { "code": null, "e": 1706, "s": 1519, "text": "Interpret the nature of their relationship by assessing each variable’s contribution to the canonical variates (i.e. components) and find what dimensions are common between the two sets." }, { "code": null, "e": 1766, "s": 1706, "text": "Summarise relationships into a lesser number of statistics." }, { "code": null, "e": 1867, "s": 1766, "text": "Conduct a dimensionality reduction that takes into account the existence of certain variable groups." }, { "code": null, "e": 1896, "s": 1867, "text": "Given two sets of variables:" }, { "code": null, "e": 2001, "s": 1896, "text": "We construct the first pair of Canonical Variates as linear combinations of the variables in each group:" }, { "code": null, "e": 2128, "s": 2001, "text": "where the weights (a1, ... ap), (b1, ... , bq) are chosen in a way that the correlation between the two variates is maximised." }, { "code": null, "e": 2159, "s": 2128, "text": "Having our pair of covariates:" }, { "code": null, "e": 2260, "s": 2159, "text": "The Canonical Correlation Coefficient is the correlation between the canonical variates CVX and CVY." }, { "code": null, "e": 2438, "s": 2260, "text": "To compute the second pair of covariates, we conduct the same process by adding one more constraint: each new variate should be orthogonal and uncorrelated to the previous ones." }, { "code": null, "e": 2616, "s": 2438, "text": "We compute min(p,q) pairs in a similar fashion and end up with min(p,q) components ready to explore. (Note that the number of variables in each set doesn’t have to be the same.)" }, { "code": null, "e": 2834, "s": 2616, "text": "Just as in PCA, we project our data onto min(p,q) latent dimensions. However, not all of them might be informative and important. Let’s see the makeup and interpretation of our canonical variates in the example below." }, { "code": null, "e": 2895, "s": 2834, "text": "We’ll be using two variable groups from NYC schools dataset:" }, { "code": null, "e": 2918, "s": 2895, "text": "Rigorous Instruction %" }, { "code": null, "e": 2943, "s": 2918, "text": "Collaborative Teachers %" }, { "code": null, "e": 2968, "s": 2943, "text": "Supportive Environment %" }, { "code": null, "e": 2998, "s": 2968, "text": "Effective School Leadership %" }, { "code": null, "e": 3022, "s": 2998, "text": "Family-Community Ties %" }, { "code": null, "e": 3030, "s": 3022, "text": "Trust %" }, { "code": null, "e": 3054, "s": 3030, "text": "Average ELA Proficiency" }, { "code": null, "e": 3079, "s": 3054, "text": "Average Math Proficiency" }, { "code": null, "e": 3138, "s": 3079, "text": "As for the tool, we’ll be using the pyrcca implementation." }, { "code": null, "e": 3214, "s": 3138, "text": "We start with separating each of our variable groups in a single dataframe:" }, { "code": null, "e": 3896, "s": 3214, "text": "import pandas as pdimport numpy as npdf = pd.read_csv('2016 School Explorer.csv')# choose relevant featuresdf = df[['Rigorous Instruction %', 'Collaborative Teachers %', 'Supportive Environment %', 'Effective School Leadership %', 'Strong Family-Community Ties %', 'Trust %','Average ELA Proficiency', 'Average Math Proficiency']]# drop missing valuesdf = df.dropna()# separate X and Y groupsX = df[['Rigorous Instruction %', 'Collaborative Teachers %', 'Supportive Environment %', 'Effective School Leadership %', 'Strong Family-Community Ties %', 'Trust %' ]]Y = df[['Average ELA Proficiency', 'Average Math Proficiency']]" }, { "code": null, "e": 3961, "s": 3896, "text": "Convert group X into numeric variables and standardise the data:" }, { "code": null, "e": 4222, "s": 3961, "text": "for col in X.columns: X[col] = X[col].str.strip('%') X[col] = X[col].astype('int')# Standardise the datafrom sklearn.preprocessing import StandardScalersc = StandardScaler(with_mean=True, with_std=True)X_sc = sc.fit_transform(X)Y_sc = sc.fit_transform(Y)" }, { "code": null, "e": 4432, "s": 4222, "text": "After relevant preprocessing, we’re ready to apply CCA. Note that we set the regularisation parameter to 0 as regularised CCA is out of the scope of this post (we will get back to this in future posts though)." }, { "code": null, "e": 4694, "s": 4432, "text": "import pyrccanComponents = 2 # min(p,q) componentscca = pyrcca.CCA(kernelcca = False, reg = 0., numCC = nComponents,)# train on datacca.train([X_sc, Y_sc])print('Canonical Correlation Per Component Pair:',cca.cancorrs)print('% Shared Variance:',cca.cancorrs**2)" }, { "code": null, "e": 4718, "s": 4694, "text": "Cannonical Correlations" }, { "code": null, "e": 4832, "s": 4718, "text": ">> Canonical Correlation Per Component Pair: [0.46059902 0.18447786]>> % Shared Variance: [0.21215146 0.03403208]" }, { "code": null, "e": 5080, "s": 4832, "text": "For our two pairs of canonical variates, we have canonical correlations of 0.46 and 0.18 respectively. So, latent representations of school ambience and students’ performance do have a positive correlation of 0.46 and share 21 percent of variance." }, { "code": null, "e": 5258, "s": 5080, "text": "Squared canonical correlation represents the shared variance by the latent representations of variable sets, and not the variance inferred from the sets of variables themselves." }, { "code": null, "e": 5276, "s": 5258, "text": "Canonical Weights" }, { "code": null, "e": 5395, "s": 5276, "text": "In order to access the weights assigned to our standardised variables (a1, ... , ap) and (b1, ... , bq) we use cca.ws:" }, { "code": null, "e": 5711, "s": 5395, "text": "cca.ws>> [array([[-0.00375779, 0.0078263 ], [ 0.00061439, -0.00357358], [-0.02054012, -0.0083491 ], [-0.01252477, 0.02976148], [ 0.00046503, -0.00905069], [ 0.01415084, -0.01264106]]), array([[ 0.00632283, 0.05721601], [-0.02606459, -0.05132531]])]" }, { "code": null, "e": 5822, "s": 5711, "text": "Given these weights, the canonical variates of set Y, for example, were calculated with the following formula:" }, { "code": null, "e": 6056, "s": 5822, "text": "where the weights can be interpreted as the coefficients in a linear regression model. We should take into account that it is not highly recommended to rely on weights when interpreting individual variable contribution to covariates." }, { "code": null, "e": 6068, "s": 6056, "text": "Here’s why:" }, { "code": null, "e": 6131, "s": 6068, "text": "Weights are subject to variability from one sample to another." }, { "code": null, "e": 6241, "s": 6131, "text": "Weights can be highly affected by multicollinearity (which is quite common for same-context variable groups)." }, { "code": null, "e": 6306, "s": 6241, "text": "Relying on canonical loadings instead is a more common practice." }, { "code": null, "e": 6325, "s": 6306, "text": "Canonical Loadings" }, { "code": null, "e": 6640, "s": 6325, "text": "Canonical loadings are nothing more than the correlation between the original variable and the canonical variate of that set. For example, to assess the contribution of Trust in school environment representation, we calculate the correlation between the variable Trust and the resulting variate for variable set X." }, { "code": null, "e": 6695, "s": 6640, "text": "Calculating loadings for group Y in the first variate:" }, { "code": null, "e": 6942, "s": 6695, "text": "print('Loading for Math Score:',np.corrcoef(cca.comps[0][:,0],Y_sc[:,0])[0,1])print('Loading for ELA Score:',np.corrcoef(cca.comps[0][:,0],Y_sc[:,1])[0,1])>> Loading for Math Score: -0.4106778140971078>> Loading for ELA Score: -0.4578120954218724" }, { "code": null, "e": 6963, "s": 6942, "text": "Canonical Covariates" }, { "code": null, "e": 7073, "s": 6963, "text": "Finally, we might want to access the covariate values directly, be it for visualisation or any other purpose." }, { "code": null, "e": 7092, "s": 7073, "text": "To do so, we need:" }, { "code": null, "e": 7264, "s": 7092, "text": "# CVX cca.comps[0]# First CV for X cca.comps[0][:,0]# Second CV for Xcca.comps[0][:,1]# CVYcca.comps[1]# First CV for Ycca.comps[1][:,0]# Second CV for Y cca.comps[1][:,1]" }, { "code": null, "e": 7329, "s": 7264, "text": "Hope you find this helpful and use CCA more in your EDA routine." }, { "code": null, "e": 7345, "s": 7329, "text": "-Keep Exploring" }, { "code": null, "e": 7511, "s": 7345, "text": "[1] Bilenko N., Gallan., 2016, Pyrcca: Regularized Kernel Canonical Correlation Analysis in Python and Its Applications to Neuroimaging, Frontiers in Neuroinfomatics" } ]
Underscore.js _.contains Function
17 Dec, 2021 The Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _.contains() function is used to check whether a particular item is given in the list of not. This function needs to pass the list to this function. If the list contains a large of items then simply define the list earlier and pass the name of the list as an argument to the _.contains() function. Syntax: _.contains( list, value, [fromIndex] ) Parameters: This function accepts three parameters as mentioned above and described below: List: This parameter contains the list of items. value: This parameter is used to store the value which need to search in the list. fromIndex: It is an optional parameter that holds the index to start search. Return values: This function returns the value which is either true (when the element is present in the list) or false (when the element is not in the list). Passing an array to the _.contains function(): The ._contains() function takes the element from the list one by one and searches for the given element in the list. After the required element is found in the list while traversing the list, the contains() function ends and the answer is true otherwise answer is false. Example: HTML <html> <head> <title>_.contains() function</title> <script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> console.log(_.contains([1, 2, 3, 4, 5], 40) ); </script> </body></html> Output: Example: HTML <html> <head> <title>_.contains() function</title> <script type="text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> console.log(_.contains([1, 2, 3, 4, 5], 5) ); </script> </body></html> Output: Passing a list of strings to the _.contains() function: Pass the list of strings to the _.contains() function and check the given string is found in the list or not. If the string is present in the list then it returns true otherwise return false. Example: HTML <html> <head> <title>_.contains() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> console.log(_.contains(['steven', 'mack', 'jack'], 'steven')); </script> </body></html> Output: Passing an array of array to _.contains() function: Create an array of array and pass the array name to the function to specify the element. Example: HTML <html> <head> <title>_.contains() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs /underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var indexes = [ {'id': 1, 'name': 'simmy' }, {'id':3, 'name': 'sam'}, {'id': 5, 'name': 'sandeep'}, {'id': 1, 'name': 'sahil' }, {'id':3, 'name': 'shagun'} ]; console.log(_.contains(indexes, {'id':1, 'name': 'jake'})); </script> </body></html> Output: Passing an object and an array to the _.contains() function: Firstly, define an object variable and assign it {test:”test”}. then create an array that contains other elements like numbers and also add this object as an array element. pass this array and the object to the _.contains() function. Since added the object is to the array hence the answer will be true.Example: HTML <html> <head> <title>_.contains() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs /underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs /underscore.js/1.9.1/underscore.js"> </script> </head> <html> <body> <script type="text/javascript"> var testObject = {test:"test"}; var testArray = [1, 2, 3, testObject]; console.log(_.contains(testArray, testObject)); </script> </body></html> Output: arorakashish0911 sweetyty gulshankumarar231 JavaScript - Underscore.js JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2021" }, { "code": null, "e": 530, "s": 28, "text": "The Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _.contains() function is used to check whether a particular item is given in the list of not. This function needs to pass the list to this function. If the list contains a large of items then simply define the list earlier and pass the name of the list as an argument to the _.contains() function." }, { "code": null, "e": 539, "s": 530, "text": "Syntax: " }, { "code": null, "e": 578, "s": 539, "text": "_.contains( list, value, [fromIndex] )" }, { "code": null, "e": 671, "s": 578, "text": "Parameters: This function accepts three parameters as mentioned above and described below: " }, { "code": null, "e": 720, "s": 671, "text": "List: This parameter contains the list of items." }, { "code": null, "e": 803, "s": 720, "text": "value: This parameter is used to store the value which need to search in the list." }, { "code": null, "e": 880, "s": 803, "text": "fromIndex: It is an optional parameter that holds the index to start search." }, { "code": null, "e": 1039, "s": 880, "text": "Return values: This function returns the value which is either true (when the element is present in the list) or false (when the element is not in the list). " }, { "code": null, "e": 1357, "s": 1039, "text": "Passing an array to the _.contains function(): The ._contains() function takes the element from the list one by one and searches for the given element in the list. After the required element is found in the list while traversing the list, the contains() function ends and the answer is true otherwise answer is false." }, { "code": null, "e": 1367, "s": 1357, "text": "Example: " }, { "code": null, "e": 1372, "s": 1367, "text": "HTML" }, { "code": "<html> <head> <title>_.contains() function</title> <script type=\"text/javascript\" src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> console.log(_.contains([1, 2, 3, 4, 5], 40) ); </script> </body></html>", "e": 1886, "s": 1372, "text": null }, { "code": null, "e": 1895, "s": 1886, "text": "Output: " }, { "code": null, "e": 1905, "s": 1895, "text": "Example: " }, { "code": null, "e": 1910, "s": 1905, "text": "HTML" }, { "code": "<html> <head> <title>_.contains() function</title> <script type=\"text/javascript\" src = \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> console.log(_.contains([1, 2, 3, 4, 5], 5) ); </script> </body></html>", "e": 2423, "s": 1910, "text": null }, { "code": null, "e": 2432, "s": 2423, "text": "Output: " }, { "code": null, "e": 2680, "s": 2432, "text": "Passing a list of strings to the _.contains() function: Pass the list of strings to the _.contains() function and check the given string is found in the list or not. If the string is present in the list then it returns true otherwise return false." }, { "code": null, "e": 2690, "s": 2680, "text": "Example: " }, { "code": null, "e": 2695, "s": 2690, "text": "HTML" }, { "code": "<html> <head> <title>_.contains() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> console.log(_.contains(['steven', 'mack', 'jack'], 'steven')); </script> </body></html>", "e": 3250, "s": 2695, "text": null }, { "code": null, "e": 3259, "s": 3250, "text": "Output: " }, { "code": null, "e": 3400, "s": 3259, "text": "Passing an array of array to _.contains() function: Create an array of array and pass the array name to the function to specify the element." }, { "code": null, "e": 3410, "s": 3400, "text": "Example: " }, { "code": null, "e": 3415, "s": 3410, "text": "HTML" }, { "code": "<html> <head> <title>_.contains() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/ underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs /underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var indexes = [ {'id': 1, 'name': 'simmy' }, {'id':3, 'name': 'sam'}, {'id': 5, 'name': 'sandeep'}, {'id': 1, 'name': 'sahil' }, {'id':3, 'name': 'shagun'} ]; console.log(_.contains(indexes, {'id':1, 'name': 'jake'})); </script> </body></html>", "e": 4187, "s": 3415, "text": null }, { "code": null, "e": 4196, "s": 4187, "text": "Output: " }, { "code": null, "e": 4569, "s": 4196, "text": "Passing an object and an array to the _.contains() function: Firstly, define an object variable and assign it {test:”test”}. then create an array that contains other elements like numbers and also add this object as an array element. pass this array and the object to the _.contains() function. Since added the object is to the array hence the answer will be true.Example:" }, { "code": null, "e": 4574, "s": 4569, "text": "HTML" }, { "code": "<html> <head> <title>_.contains() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs /underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs /underscore.js/1.9.1/underscore.js\"> </script> </head> <html> <body> <script type=\"text/javascript\"> var testObject = {test:\"test\"}; var testArray = [1, 2, 3, testObject]; console.log(_.contains(testArray, testObject)); </script> </body></html>", "e": 5198, "s": 4574, "text": null }, { "code": null, "e": 5207, "s": 5198, "text": "Output: " }, { "code": null, "e": 5226, "s": 5209, "text": "arorakashish0911" }, { "code": null, "e": 5235, "s": 5226, "text": "sweetyty" }, { "code": null, "e": 5253, "s": 5235, "text": "gulshankumarar231" }, { "code": null, "e": 5280, "s": 5253, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 5291, "s": 5280, "text": "JavaScript" }, { "code": null, "e": 5298, "s": 5291, "text": "JQuery" }, { "code": null, "e": 5315, "s": 5298, "text": "Web Technologies" }, { "code": null, "e": 5413, "s": 5315, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5474, "s": 5413, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5546, "s": 5474, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5586, "s": 5546, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5639, "s": 5586, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5691, "s": 5639, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 5737, "s": 5691, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 5766, "s": 5737, "text": "Form validation using jQuery" }, { "code": null, "e": 5829, "s": 5766, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 5882, "s": 5829, "text": "How to add options to a select element using jQuery?" } ]
How to Use Italic Font in R?
04 Dec, 2021 In this article, we are going to see how to use italic font using various functionalities in the R programming language. In this approach to use the italic function, the user needs to use three different functions within each other, and the italic font will be applied to the given text, starting with the substitute() function; within this function, the user needs to call the paste function as the argument of the substitute function, further within the paste function the user needs to call the italic() function as the argument of the paste function and then in the italic function the user has to pass the text which is needed to be in the italic font in the R programming language. substitute(paste(italic(‘text’))) Substitute() function: This function will return the parse tree for the (unevaluated) expression expr, substituting any variables bound in env. Syntax: substitute(expr, env) Parameters: expr: any syntactically valid R expression env: an environment or a list object. Defaults to the current evaluation environment. Paste() function: This function is used to concatenate vectors after converting them to characters. Syntax: paste (..., sep = ” “, collapse = NULL) Parameters: ...: one or more R objects, to be converted to character vectors. sep: a character string to separate the terms. Not NA_character_. collapse: an optional character string to separate the results. Not NA_character_. Italic function: This function is used to change the font decoration of selected rows and columns of a flexible. Syntax: italic(x, i = NULL, j = NULL, italic = TRUE, part = “body”) Parameters: x: a flextable object I: rows selection j: columns selection italic: boolean value part: partname of the table (one of ‘all’, ‘body’, ‘header’, ‘footer’) In this example, we will be using all three functions to apply the italic font at the main of the bar plot given in the R programming language. R a = c(5,1,1,5,6,7,5,4,7,9)barplot(a,main = substitute( paste(italic( 'GeeksforGeeks is the best learning\platform for CSE Graduates.')))) Output: In this example, we will be using all three functions to apply the italic font at the given bar plot at the x-axis and the y-axis of the barplot in the R programming language. R a = c(5,1,1,5,6,7,5,4,7,9)barplot(a, xlab = substitute(paste(italic('X Label'))), ylab = substitute(paste(italic('Y Label')))) Output: In this example, we will be using all three functions to apply the italic font at the given bar plot in the R programming language. R a = c(5,1,1,5,6,7,5,4,7,9)barplot(a)text(6, 8, substitute(paste( italic('GeeksforGeeks is the best learning\platform for CSE Graduates.')))) Output: rajeev0719singh Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement Logistic Regression in R Programming How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2021" }, { "code": null, "e": 149, "s": 28, "text": "In this article, we are going to see how to use italic font using various functionalities in the R programming language." }, { "code": null, "e": 716, "s": 149, "text": "In this approach to use the italic function, the user needs to use three different functions within each other, and the italic font will be applied to the given text, starting with the substitute() function; within this function, the user needs to call the paste function as the argument of the substitute function, further within the paste function the user needs to call the italic() function as the argument of the paste function and then in the italic function the user has to pass the text which is needed to be in the italic font in the R programming language." }, { "code": null, "e": 750, "s": 716, "text": "substitute(paste(italic(‘text’)))" }, { "code": null, "e": 894, "s": 750, "text": "Substitute() function: This function will return the parse tree for the (unevaluated) expression expr, substituting any variables bound in env." }, { "code": null, "e": 924, "s": 894, "text": "Syntax: substitute(expr, env)" }, { "code": null, "e": 936, "s": 924, "text": "Parameters:" }, { "code": null, "e": 979, "s": 936, "text": "expr: any syntactically valid R expression" }, { "code": null, "e": 1065, "s": 979, "text": "env: an environment or a list object. Defaults to the current evaluation environment." }, { "code": null, "e": 1165, "s": 1065, "text": "Paste() function: This function is used to concatenate vectors after converting them to characters." }, { "code": null, "e": 1213, "s": 1165, "text": "Syntax: paste (..., sep = ” “, collapse = NULL)" }, { "code": null, "e": 1225, "s": 1213, "text": "Parameters:" }, { "code": null, "e": 1291, "s": 1225, "text": "...: one or more R objects, to be converted to character vectors." }, { "code": null, "e": 1357, "s": 1291, "text": "sep: a character string to separate the terms. Not NA_character_." }, { "code": null, "e": 1440, "s": 1357, "text": "collapse: an optional character string to separate the results. Not NA_character_." }, { "code": null, "e": 1553, "s": 1440, "text": "Italic function: This function is used to change the font decoration of selected rows and columns of a flexible." }, { "code": null, "e": 1621, "s": 1553, "text": "Syntax: italic(x, i = NULL, j = NULL, italic = TRUE, part = “body”)" }, { "code": null, "e": 1633, "s": 1621, "text": "Parameters:" }, { "code": null, "e": 1655, "s": 1633, "text": "x: a flextable object" }, { "code": null, "e": 1673, "s": 1655, "text": "I: rows selection" }, { "code": null, "e": 1694, "s": 1673, "text": "j: columns selection" }, { "code": null, "e": 1716, "s": 1694, "text": "italic: boolean value" }, { "code": null, "e": 1787, "s": 1716, "text": "part: partname of the table (one of ‘all’, ‘body’, ‘header’, ‘footer’)" }, { "code": null, "e": 1931, "s": 1787, "text": "In this example, we will be using all three functions to apply the italic font at the main of the bar plot given in the R programming language." }, { "code": null, "e": 1933, "s": 1931, "text": "R" }, { "code": "a = c(5,1,1,5,6,7,5,4,7,9)barplot(a,main = substitute( paste(italic( 'GeeksforGeeks is the best learning\\platform for CSE Graduates.'))))", "e": 2075, "s": 1933, "text": null }, { "code": null, "e": 2083, "s": 2075, "text": "Output:" }, { "code": null, "e": 2259, "s": 2083, "text": "In this example, we will be using all three functions to apply the italic font at the given bar plot at the x-axis and the y-axis of the barplot in the R programming language." }, { "code": null, "e": 2261, "s": 2259, "text": "R" }, { "code": "a = c(5,1,1,5,6,7,5,4,7,9)barplot(a, xlab = substitute(paste(italic('X Label'))), ylab = substitute(paste(italic('Y Label'))))", "e": 2402, "s": 2261, "text": null }, { "code": null, "e": 2410, "s": 2402, "text": "Output:" }, { "code": null, "e": 2542, "s": 2410, "text": "In this example, we will be using all three functions to apply the italic font at the given bar plot in the R programming language." }, { "code": null, "e": 2544, "s": 2542, "text": "R" }, { "code": "a = c(5,1,1,5,6,7,5,4,7,9)barplot(a)text(6, 8, substitute(paste( italic('GeeksforGeeks is the best learning\\platform for CSE Graduates.'))))", "e": 2686, "s": 2544, "text": null }, { "code": null, "e": 2694, "s": 2686, "text": "Output:" }, { "code": null, "e": 2710, "s": 2694, "text": "rajeev0719singh" }, { "code": null, "e": 2717, "s": 2710, "text": "Picked" }, { "code": null, "e": 2726, "s": 2717, "text": "R-Charts" }, { "code": null, "e": 2735, "s": 2726, "text": "R-Graphs" }, { "code": null, "e": 2743, "s": 2735, "text": "R-plots" }, { "code": null, "e": 2754, "s": 2743, "text": "R Language" }, { "code": null, "e": 2852, "s": 2754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2904, "s": 2852, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2962, "s": 2904, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2997, "s": 2962, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3035, "s": 2997, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3052, "s": 3035, "text": "R - if statement" }, { "code": null, "e": 3089, "s": 3052, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 3138, "s": 3089, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3181, "s": 3138, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3218, "s": 3181, "text": "How to import an Excel File into R ?" } ]