title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
ReactJS Reactstrap Form Component
02 Sep, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Form component is used when the user needs to create an instance or collect information. We can use the following approach in ReactJS to use the ReactJS Reactstrap Form Component. Input Props: children: It is used to pass the children element to this component. type: It is used to denote the type like radio, checkbox, select, etc. size: It is used to denote the size of this component. bsSize: It is used to denote the bs size like large, small, etc. state: It is used to denote the state for this component. valid: It is used to apply the is-valid class when this is set to true. invalid: It is used to apply the is-invalid class when this is set to true. tag: It is used to pass in custom elements to use. innerRef: It is used to get a reference to the DOM element. static: It is used to indicate whether the static class is applied or not. plaintext: It is used to indicate whether the plaintext class is applied or not. addon: It is used to indicate whether the addon is added or not. className: It is used to denote the class name for styling. cssModule: It is used to denote the CSS module for styling. CustomInput Props: children: It is used to pass the children element to this component. id: It is used to denote the id attribute for the unique identification. type: It is used to denote the type like radio, checkbox, select, etc. label: It is used for checkbox and radios. inline: It is used to apply the linline class when this is set to true. valid: It is used to apply the is-valid class when this is set to true. invalid: It is used to apply the is-invalid class when this is set to true. bsSize: It is used to denote the bs size like large, small, etc. cssModule: It is used to denote the CSS module for styling. children: It is used to pass the children element to this component. innerRef: It is used to get a reference to the DOM element. Form Props: children: It is used to pass the children element to this component. inline: It is used to apply the linline class when this is set to true. tag: It is used to pass in custom elements to use. innerRef: It is used to get a reference to the DOM element. className: It is used to denote the class name for styling. cssModule: It is used to denote the CSS module for styling. FormFeedback Props: children: It is used to pass the children element to this component. tag: It is used to pass in custom elements to use. className: It is used to denote the class name for styling. cssModule: It is used to denote the CSS module for styling. valid: It is used to apply the is-valid class when this is set to true. tooltip: It is used to show the tooltip but the condition is that the parent element must contain the relative position style. FormGroup Props: children: It is used to pass the children element to this component. row: It is used to apply the row class when this is set to true. check: It is used to apply the form-check class when this is set to true. inline: It is used to apply the linline class when this is set to true. disabled: Applied the disabled class when the check and disabled props are true, does nothing when false. tag: It is used to pass in custom elements to use. className: It is used to denote the class name for styling. cssModule: It is used to denote the CSS module for styling. FormText Props: children: It is used to pass the children element to this component. inline: It is used to apply the linline class when this is set to true. tag: It is used to pass in custom elements to use. color: It is used to denote the color for this component. className: It is used to denote the class name for styling. cssModule: It is used to denote the CSS module for styling. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here, we have shown the Form Component without the use of the Col component and row prop. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { FormGroup, Label, Input, Button, Form} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap Form Component</h5> <Form> <FormGroup> <Label for="emailField">EMAIL:</Label> <Input type="email" name="email" id="emailField" placeholder="Enter your email" /> </FormGroup> <FormGroup> <Label for="passwordField">PASSWORD:</Label> <Input type="password" name="password" id="passwordField" placeholder="Enter your password" /> </FormGroup> <Button>Submit</Button> </Form> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here, we have shown the Form Component with the use of the Col component and row prop. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { FormGroup, Label, Input, Button, Form, Col} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 950, padding: 30 }}> <h5>ReactJS Reactstrap Form Component</h5> <Form inline> <FormGroup row className="mb-2 mr-sm-2 mb-sm-0"> <Col sm={4}> <Label for="emailField">EMAIL:</Label> <Input type="email" name="email" id="emailField" placeholder="Enter your email" /> </Col> <Col sm={4}> <Label for="passwordField">PASSWORD:</Label> <Input type="password" name="password" id="passwordField" placeholder="Enter your password" /> </Col> </FormGroup> <Button>Submit</Button> </Form> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/form/ clintra Reactstrap JavaScript ReactJS 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 Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2021" }, { "code": null, "e": 374, "s": 28, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Form component is used when the user needs to create an instance or collect information. We can use the following approach in ReactJS to use the ReactJS Reactstrap Form Component." }, { "code": null, "e": 387, "s": 374, "text": "Input Props:" }, { "code": null, "e": 456, "s": 387, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 527, "s": 456, "text": "type: It is used to denote the type like radio, checkbox, select, etc." }, { "code": null, "e": 582, "s": 527, "text": "size: It is used to denote the size of this component." }, { "code": null, "e": 647, "s": 582, "text": "bsSize: It is used to denote the bs size like large, small, etc." }, { "code": null, "e": 705, "s": 647, "text": "state: It is used to denote the state for this component." }, { "code": null, "e": 777, "s": 705, "text": "valid: It is used to apply the is-valid class when this is set to true." }, { "code": null, "e": 853, "s": 777, "text": "invalid: It is used to apply the is-invalid class when this is set to true." }, { "code": null, "e": 904, "s": 853, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 964, "s": 904, "text": "innerRef: It is used to get a reference to the DOM element." }, { "code": null, "e": 1039, "s": 964, "text": "static: It is used to indicate whether the static class is applied or not." }, { "code": null, "e": 1120, "s": 1039, "text": "plaintext: It is used to indicate whether the plaintext class is applied or not." }, { "code": null, "e": 1185, "s": 1120, "text": "addon: It is used to indicate whether the addon is added or not." }, { "code": null, "e": 1245, "s": 1185, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 1305, "s": 1245, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 1324, "s": 1305, "text": "CustomInput Props:" }, { "code": null, "e": 1393, "s": 1324, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 1466, "s": 1393, "text": "id: It is used to denote the id attribute for the unique identification." }, { "code": null, "e": 1537, "s": 1466, "text": "type: It is used to denote the type like radio, checkbox, select, etc." }, { "code": null, "e": 1581, "s": 1537, "text": "label: It is used for checkbox and radios." }, { "code": null, "e": 1653, "s": 1581, "text": "inline: It is used to apply the linline class when this is set to true." }, { "code": null, "e": 1725, "s": 1653, "text": "valid: It is used to apply the is-valid class when this is set to true." }, { "code": null, "e": 1801, "s": 1725, "text": "invalid: It is used to apply the is-invalid class when this is set to true." }, { "code": null, "e": 1866, "s": 1801, "text": "bsSize: It is used to denote the bs size like large, small, etc." }, { "code": null, "e": 1926, "s": 1866, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 1995, "s": 1926, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 2055, "s": 1995, "text": "innerRef: It is used to get a reference to the DOM element." }, { "code": null, "e": 2067, "s": 2055, "text": "Form Props:" }, { "code": null, "e": 2136, "s": 2067, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 2208, "s": 2136, "text": "inline: It is used to apply the linline class when this is set to true." }, { "code": null, "e": 2259, "s": 2208, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 2319, "s": 2259, "text": "innerRef: It is used to get a reference to the DOM element." }, { "code": null, "e": 2379, "s": 2319, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 2439, "s": 2379, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 2461, "s": 2441, "text": "FormFeedback Props:" }, { "code": null, "e": 2530, "s": 2461, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 2581, "s": 2530, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 2641, "s": 2581, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 2701, "s": 2641, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 2773, "s": 2701, "text": "valid: It is used to apply the is-valid class when this is set to true." }, { "code": null, "e": 2900, "s": 2773, "text": "tooltip: It is used to show the tooltip but the condition is that the parent element must contain the relative position style." }, { "code": null, "e": 2917, "s": 2900, "text": "FormGroup Props:" }, { "code": null, "e": 2986, "s": 2917, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 3051, "s": 2986, "text": "row: It is used to apply the row class when this is set to true." }, { "code": null, "e": 3125, "s": 3051, "text": "check: It is used to apply the form-check class when this is set to true." }, { "code": null, "e": 3197, "s": 3125, "text": "inline: It is used to apply the linline class when this is set to true." }, { "code": null, "e": 3303, "s": 3197, "text": "disabled: Applied the disabled class when the check and disabled props are true, does nothing when false." }, { "code": null, "e": 3354, "s": 3303, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 3414, "s": 3354, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 3474, "s": 3414, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 3490, "s": 3474, "text": "FormText Props:" }, { "code": null, "e": 3559, "s": 3490, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 3631, "s": 3559, "text": "inline: It is used to apply the linline class when this is set to true." }, { "code": null, "e": 3682, "s": 3631, "text": "tag: It is used to pass in custom elements to use." }, { "code": null, "e": 3740, "s": 3682, "text": "color: It is used to denote the color for this component." }, { "code": null, "e": 3800, "s": 3740, "text": "className: It is used to denote the class name for styling." }, { "code": null, "e": 3860, "s": 3800, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 3910, "s": 3860, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 4005, "s": 3910, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 4069, "s": 4005, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 4101, "s": 4069, "text": "npx create-react-app foldername" }, { "code": null, "e": 4214, "s": 4101, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 4314, "s": 4214, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 4328, "s": 4314, "text": "cd foldername" }, { "code": null, "e": 4465, "s": 4328, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap" }, { "code": null, "e": 4570, "s": 4465, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 4603, "s": 4570, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 4657, "s": 4605, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 4675, "s": 4657, "text": "Project Structure" }, { "code": null, "e": 4830, "s": 4675, "text": "Example 1: Now write down the following code in the App.js file. Here, we have shown the Form Component without the use of the Col component and row prop." }, { "code": null, "e": 4837, "s": 4830, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { FormGroup, Label, Input, Button, Form} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 550, padding: 30 }}> <h5>ReactJS Reactstrap Form Component</h5> <Form> <FormGroup> <Label for=\"emailField\">EMAIL:</Label> <Input type=\"email\" name=\"email\" id=\"emailField\" placeholder=\"Enter your email\" /> </FormGroup> <FormGroup> <Label for=\"passwordField\">PASSWORD:</Label> <Input type=\"password\" name=\"password\" id=\"passwordField\" placeholder=\"Enter your password\" /> </FormGroup> <Button>Submit</Button> </Form> </div > );} export default App;", "e": 5789, "s": 4837, "text": null }, { "code": null, "e": 5902, "s": 5789, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 5912, "s": 5902, "text": "npm start" }, { "code": null, "e": 6011, "s": 5912, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6163, "s": 6011, "text": "Example 2: Now write down the following code in the App.js file. Here, we have shown the Form Component with the use of the Col component and row prop." }, { "code": null, "e": 6170, "s": 6163, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { FormGroup, Label, Input, Button, Form, Col} from 'reactstrap'; function App() { return ( <div style={{ display: 'block', width: 950, padding: 30 }}> <h5>ReactJS Reactstrap Form Component</h5> <Form inline> <FormGroup row className=\"mb-2 mr-sm-2 mb-sm-0\"> <Col sm={4}> <Label for=\"emailField\">EMAIL:</Label> <Input type=\"email\" name=\"email\" id=\"emailField\" placeholder=\"Enter your email\" /> </Col> <Col sm={4}> <Label for=\"passwordField\">PASSWORD:</Label> <Input type=\"password\" name=\"password\" id=\"passwordField\" placeholder=\"Enter your password\" /> </Col> </FormGroup> <Button>Submit</Button> </Form> </div > );} export default App;", "e": 7260, "s": 6170, "text": null }, { "code": null, "e": 7373, "s": 7260, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 7383, "s": 7373, "text": "npm start" }, { "code": null, "e": 7482, "s": 7383, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 7539, "s": 7482, "text": "Reference: https://reactstrap.github.io/components/form/" }, { "code": null, "e": 7547, "s": 7539, "text": "clintra" }, { "code": null, "e": 7558, "s": 7547, "text": "Reactstrap" }, { "code": null, "e": 7569, "s": 7558, "text": "JavaScript" }, { "code": null, "e": 7577, "s": 7569, "text": "ReactJS" }, { "code": null, "e": 7594, "s": 7577, "text": "Web Technologies" }, { "code": null, "e": 7692, "s": 7594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7753, "s": 7692, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7793, "s": 7753, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7834, "s": 7793, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 7876, "s": 7834, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 7898, "s": 7876, "text": "JavaScript | Promises" }, { "code": null, "e": 7941, "s": 7898, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7986, "s": 7941, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 8024, "s": 7986, "text": "Axios in React: A Guide for Beginners" } ]
Node.js | package.json
21 Jan, 2022 The package.json file is the heart of Node.js system. It is the manifest file of any Node.js project and contains the metadata of the project. The package.json file is the essential part to understand, learn and work with the Node.js. It is the first step to learn about development in Node.js. What does package.json file consist of? The metadata information in package.json file can be categorized into below categories: 1. Identifying metadata properties: It basically consist of the properties to identify the module/project such as the name of the project, current version of the module, license, author of the project, description about the project etc. 2. Functional metadata properties: As the name suggests, it consists of the functional values/properties of the project/module such as the entry/starting point of the module, dependencies in project, scripts being used, repository links of Node project etc. Creating a package.json file: A package.json file can be created in two ways: 1. Using npm init : Running this command, system expects user to fill the vital information required as discussed above. It provides users with default values which are editable by the user. Syntax: npm init 2. Writing directly to file : One can directly write into file with all the required information and can include it in the Node project. Example: A demo package.json file with the required information. { "name": "GeeksForGeeks", "version": "1.0.0", "description": "GeeksForGeeks", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node start.js", }, "engines": { "node": ">=7.6.0", "npm": ">=4.1.2" }, "author": "GeeksForGeeks", "license": "ISC", "dependencies": { "body-parser": "^1.17.1", "express": "^4.15.2", "express-validator": "^3.1.2", "mongoose": "^4.8.7", "nodemon": "^1.14.12", }, "devDependencies": {}, "repository": { "type": "git", "url": "https://github.com/gfg/gfg.git" //sample git repo url }, "bugs": { "url": "https://github.com/gfg/gfg/issues" }, "homepage": "https://github.com/gfg/gfg#readme" } Explanation: name: The name of the application/project. version: The version of application. The version should follow semantic versioning rules. description: The description about the application, purpose of the application, technology used like React, MongoDB, etc. main: This is the entry/starting point of the app. It specifies the main file of the application that triggers when the application starts. Application can be started using npm start. scripts: The scripts which needs to be included in the application to run properly. engines: The versions of the node and npm used. These versions are specified in case the application is deployed on cloud like heroku or google-cloud. keywords: It specifies the array of strings that characterizes the application. author: It consist of the information about the author like name, email and other author related information. license: The license to which the application confirms are mentioned in this key-value pair. dependencies: The third party package or modules installed using npm are specified in this segment. devDependencies: The dependencies that are used only in the development part of the application are specified in this segment. These dependencies do not get rolled out when the application is in production stage. repository: It contain the information about the type and url of the repository where the code of the application lives is mentioned here in this segment. bugs: The url and email where the bugs in the application should be reported are mentioned in this segment. Note: Here, “body-parser”, “express”, “express-validator”, “mongoose” and “nodemon” are the modules/packages installed using npm (Node Package Manager). References: http://nodesource.com/blog/the-basics-of-package-json-in-node-js-and-npm/ https://dzone.com/articles/the-basics-of-packagejson-in-nodejs-and-npm kk9826225 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jan, 2022" }, { "code": null, "e": 324, "s": 28, "text": "The package.json file is the heart of Node.js system. It is the manifest file of any Node.js project and contains the metadata of the project. The package.json file is the essential part to understand, learn and work with the Node.js. It is the first step to learn about development in Node.js. " }, { "code": null, "e": 948, "s": 324, "text": "What does package.json file consist of? The metadata information in package.json file can be categorized into below categories: 1. Identifying metadata properties: It basically consist of the properties to identify the module/project such as the name of the project, current version of the module, license, author of the project, description about the project etc. 2. Functional metadata properties: As the name suggests, it consists of the functional values/properties of the project/module such as the entry/starting point of the module, dependencies in project, scripts being used, repository links of Node project etc. " }, { "code": null, "e": 1227, "s": 948, "text": "Creating a package.json file: A package.json file can be created in two ways: 1. Using npm init : Running this command, system expects user to fill the vital information required as discussed above. It provides users with default values which are editable by the user. Syntax: " }, { "code": null, "e": 1236, "s": 1227, "text": "npm init" }, { "code": null, "e": 1374, "s": 1236, "text": "2. Writing directly to file : One can directly write into file with all the required information and can include it in the Node project. " }, { "code": null, "e": 1441, "s": 1374, "text": "Example: A demo package.json file with the required information. " }, { "code": null, "e": 2188, "s": 1441, "text": "{\n \"name\": \"GeeksForGeeks\",\n \"version\": \"1.0.0\",\n \"description\": \"GeeksForGeeks\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"start\": \"node start.js\",\n },\n \"engines\": {\n \"node\": \">=7.6.0\",\n \"npm\": \">=4.1.2\"\n },\n \"author\": \"GeeksForGeeks\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"body-parser\": \"^1.17.1\",\n \"express\": \"^4.15.2\",\n \"express-validator\": \"^3.1.2\",\n \"mongoose\": \"^4.8.7\",\n \"nodemon\": \"^1.14.12\",\n },\n \"devDependencies\": {},\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/gfg/gfg.git\" //sample git repo url\n },\n \"bugs\": {\n \"url\": \"https://github.com/gfg/gfg/issues\"\n },\n \"homepage\": \"https://github.com/gfg/gfg#readme\"\n}" }, { "code": null, "e": 3735, "s": 2188, "text": "Explanation: name: The name of the application/project. version: The version of application. The version should follow semantic versioning rules. description: The description about the application, purpose of the application, technology used like React, MongoDB, etc. main: This is the entry/starting point of the app. It specifies the main file of the application that triggers when the application starts. Application can be started using npm start. scripts: The scripts which needs to be included in the application to run properly. engines: The versions of the node and npm used. These versions are specified in case the application is deployed on cloud like heroku or google-cloud. keywords: It specifies the array of strings that characterizes the application. author: It consist of the information about the author like name, email and other author related information. license: The license to which the application confirms are mentioned in this key-value pair. dependencies: The third party package or modules installed using npm are specified in this segment. devDependencies: The dependencies that are used only in the development part of the application are specified in this segment. These dependencies do not get rolled out when the application is in production stage. repository: It contain the information about the type and url of the repository where the code of the application lives is mentioned here in this segment. bugs: The url and email where the bugs in the application should be reported are mentioned in this segment. " }, { "code": null, "e": 3889, "s": 3735, "text": "Note: Here, “body-parser”, “express”, “express-validator”, “mongoose” and “nodemon” are the modules/packages installed using npm (Node Package Manager). " }, { "code": null, "e": 4047, "s": 3889, "text": "References: http://nodesource.com/blog/the-basics-of-package-json-in-node-js-and-npm/ https://dzone.com/articles/the-basics-of-packagejson-in-nodejs-and-npm " }, { "code": null, "e": 4057, "s": 4047, "text": "kk9826225" }, { "code": null, "e": 4065, "s": 4057, "text": "Node.js" }, { "code": null, "e": 4084, "s": 4065, "text": "Technical Scripter" }, { "code": null, "e": 4101, "s": 4084, "text": "Web Technologies" } ]
strtol() function in C++ STL
01 Jun, 2022 The strtol() function is a builtin function in C++ STL which converts the contents of a string as an integral number of the specified base and return its value as a long int. Syntax: strtol(s, &end, b) Parameters: The function accepts three mandatory parameters which are described as below: s: specifies the string which has the representation of an integral number. end: indicates where the conversion stopped, refers to an already allocated object of type char*. The value of the end is set by the function to the next character in s after the last valid character.It can also be a null pointer, in which case it is not used. b: specifies to the base of the integral value. Return Value: The function returns value of two types: If a valid conversion occurs, then a long int value is returned. If no valid conversion happens, then 0 is returned. Below programs illustrate the above function. Program 1: CPP // C++ program to illustrate the// strtol() function when decimal base#include <cstdlib>#include <cstring>#include <iostream>#include <string>using namespace std; int main(){ int b = 10; char s[] = "6010IG_2016p"; char* end; long int n; n = strtol(s, &end, b); cout << "Number in String = " << s << endl; cout << "Number in Long Int = " << n << endl; cout << "End String = " << end << endl << endl; // the pointer to invalid // characters can be null strcpy(s, "47"); cout << "Number in String = " << s << endl; n = strtol(s, &end, b); cout << "Number in Long Int = " << n << endl; if (*end) { cout << end; } else { cout << "Null pointer"; } return 0;} Number in String = 6010IG_2016p Number in Long Int = 6010 End String = IG_2016p Number in String = 47 Number in Long Int = 47 Null pointer Program 2: CPP // C++ program to illustrate the// strtol() function#include <cstdlib>#include <cstring>#include <iostream>using namespace std; int main(){ char* end; cout << "489bc" << " to Long Int with base-4 = " << strtol("489bc", &end, 4) << endl; cout << "End String = " << end << endl; cout << "123s" << " to Long Int with base-11 = " << strtol("123s", &end, 11) << endl; cout << "End String = " << end << endl; cout << "56xyz" << " to Long Int with base-36 = " << strtol("56xyz", &end, 36) << endl;} 489bc to Long Int with base-4 = 0 End String = 489bc 123s to Long Int with base-11 = 146 End String = s 56xyz to Long Int with base-36 = 8722043 Program 3: CPP // C++ program to illustrate the// strtol() function when base is 0#include <cstdlib>#include <iostream> using namespace std; int main(){ char* end; // octal base cout << "312gfg" << " to Long Int with base-0 = " << strtol("312gfg", &end, 0) << endl; cout << "End String = " << end << endl << endl; // hexadecimal base cout << "0q15axtz" << " to Long Int with base-0 = " << strtol("0q15axtz", &end, 0) << endl; cout << "End String = " << end << endl << endl; // decimal base cout << "33ffn" << " to Long Int with base-0 = " << strtol("33ffn", &end, 0) << endl; cout << "End String = "; return 0;} 312gfg to Long Int with base-0 = 312 End String = gfg 0q15axtz to Long Int with base-0 = 0 End String = q15axtz 33ffn to Long Int with base-0 = 33 End String = Program 4 CPP // C++ program to illustrate the// strtol() function for invalid// conversions and leading whitespaces.#include <cstdlib>#include <iostream>using namespace std; int main(){ char* end; cout << "22abcd" << " to Long Int with base-6 = " << strtol(" 22abcd", &end, 6) << endl; cout << "End String = " << end << endl << endl; cout << "114cd" << " to Long Int with base-2 = " << strtol(" 114cd", &end, 2) << endl; cout << "End String = " << end << endl << endl; cout << "e10.79" << " to Long Int with base-10 = " << strtol("e10.79", &end, 10) << endl; cout << "End String = " << end << endl << endl; return 0;} 22abcd to Long Int with base-6 = 14 End String = abcd 114cd to Long Int with base-2 = 3 End String = 4cd e10.79 to Long Int with base-10 = 0 End String = e10.79 harry4951 CPP-Functions CPP-Library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) unordered_map in C++ STL Inheritance in C++ vector erase() and clear() in C++ The C++ Standard Template Library (STL) C++ Classes and Objects Substring in C++ Object Oriented Programming in C++ Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2022" }, { "code": null, "e": 211, "s": 28, "text": "The strtol() function is a builtin function in C++ STL which converts the contents of a string as an integral number of the specified base and return its value as a long int. Syntax:" }, { "code": null, "e": 230, "s": 211, "text": "strtol(s, &end, b)" }, { "code": null, "e": 320, "s": 230, "text": "Parameters: The function accepts three mandatory parameters which are described as below:" }, { "code": null, "e": 396, "s": 320, "text": "s: specifies the string which has the representation of an integral number." }, { "code": null, "e": 657, "s": 396, "text": "end: indicates where the conversion stopped, refers to an already allocated object of type char*. The value of the end is set by the function to the next character in s after the last valid character.It can also be a null pointer, in which case it is not used." }, { "code": null, "e": 705, "s": 657, "text": "b: specifies to the base of the integral value." }, { "code": null, "e": 760, "s": 705, "text": "Return Value: The function returns value of two types:" }, { "code": null, "e": 825, "s": 760, "text": "If a valid conversion occurs, then a long int value is returned." }, { "code": null, "e": 877, "s": 825, "text": "If no valid conversion happens, then 0 is returned." }, { "code": null, "e": 935, "s": 877, "text": "Below programs illustrate the above function. Program 1: " }, { "code": null, "e": 939, "s": 935, "text": "CPP" }, { "code": "// C++ program to illustrate the// strtol() function when decimal base#include <cstdlib>#include <cstring>#include <iostream>#include <string>using namespace std; int main(){ int b = 10; char s[] = \"6010IG_2016p\"; char* end; long int n; n = strtol(s, &end, b); cout << \"Number in String = \" << s << endl; cout << \"Number in Long Int = \" << n << endl; cout << \"End String = \" << end << endl << endl; // the pointer to invalid // characters can be null strcpy(s, \"47\"); cout << \"Number in String = \" << s << endl; n = strtol(s, &end, b); cout << \"Number in Long Int = \" << n << endl; if (*end) { cout << end; } else { cout << \"Null pointer\"; } return 0;}", "e": 1675, "s": 939, "text": null }, { "code": null, "e": 1817, "s": 1675, "text": "Number in String = 6010IG_2016p\nNumber in Long Int = 6010\nEnd String = IG_2016p\n\nNumber in String = 47\nNumber in Long Int = 47\nNull pointer" }, { "code": null, "e": 1829, "s": 1817, "text": "Program 2: " }, { "code": null, "e": 1833, "s": 1829, "text": "CPP" }, { "code": "// C++ program to illustrate the// strtol() function#include <cstdlib>#include <cstring>#include <iostream>using namespace std; int main(){ char* end; cout << \"489bc\" << \" to Long Int with base-4 = \" << strtol(\"489bc\", &end, 4) << endl; cout << \"End String = \" << end << endl; cout << \"123s\" << \" to Long Int with base-11 = \" << strtol(\"123s\", &end, 11) << endl; cout << \"End String = \" << end << endl; cout << \"56xyz\" << \" to Long Int with base-36 = \" << strtol(\"56xyz\", &end, 36) << endl;}", "e": 2394, "s": 1833, "text": null }, { "code": null, "e": 2539, "s": 2394, "text": "489bc to Long Int with base-4 = 0\nEnd String = 489bc\n123s to Long Int with base-11 = 146\nEnd String = s\n56xyz to Long Int with base-36 = 8722043" }, { "code": null, "e": 2551, "s": 2539, "text": "Program 3: " }, { "code": null, "e": 2555, "s": 2551, "text": "CPP" }, { "code": "// C++ program to illustrate the// strtol() function when base is 0#include <cstdlib>#include <iostream> using namespace std; int main(){ char* end; // octal base cout << \"312gfg\" << \" to Long Int with base-0 = \" << strtol(\"312gfg\", &end, 0) << endl; cout << \"End String = \" << end << endl << endl; // hexadecimal base cout << \"0q15axtz\" << \" to Long Int with base-0 = \" << strtol(\"0q15axtz\", &end, 0) << endl; cout << \"End String = \" << end << endl << endl; // decimal base cout << \"33ffn\" << \" to Long Int with base-0 = \" << strtol(\"33ffn\", &end, 0) << endl; cout << \"End String = \"; return 0;}", "e": 3253, "s": 2555, "text": null }, { "code": null, "e": 3415, "s": 3253, "text": "312gfg to Long Int with base-0 = 312\nEnd String = gfg\n\n0q15axtz to Long Int with base-0 = 0\nEnd String = q15axtz\n\n33ffn to Long Int with base-0 = 33\nEnd String =" }, { "code": null, "e": 3426, "s": 3415, "text": "Program 4 " }, { "code": null, "e": 3430, "s": 3426, "text": "CPP" }, { "code": "// C++ program to illustrate the// strtol() function for invalid// conversions and leading whitespaces.#include <cstdlib>#include <iostream>using namespace std; int main(){ char* end; cout << \"22abcd\" << \" to Long Int with base-6 = \" << strtol(\" 22abcd\", &end, 6) << endl; cout << \"End String = \" << end << endl << endl; cout << \"114cd\" << \" to Long Int with base-2 = \" << strtol(\" 114cd\", &end, 2) << endl; cout << \"End String = \" << end << endl << endl; cout << \"e10.79\" << \" to Long Int with base-10 = \" << strtol(\"e10.79\", &end, 10) << endl; cout << \"End String = \" << end << endl << endl; return 0;}", "e": 4139, "s": 3430, "text": null }, { "code": null, "e": 4302, "s": 4139, "text": "22abcd to Long Int with base-6 = 14\nEnd String = abcd\n\n114cd to Long Int with base-2 = 3\nEnd String = 4cd\n\ne10.79 to Long Int with base-10 = 0\nEnd String = e10.79" }, { "code": null, "e": 4312, "s": 4302, "text": "harry4951" }, { "code": null, "e": 4326, "s": 4312, "text": "CPP-Functions" }, { "code": null, "e": 4338, "s": 4326, "text": "CPP-Library" }, { "code": null, "e": 4342, "s": 4338, "text": "STL" }, { "code": null, "e": 4346, "s": 4342, "text": "C++" }, { "code": null, "e": 4350, "s": 4346, "text": "STL" }, { "code": null, "e": 4354, "s": 4350, "text": "CPP" }, { "code": null, "e": 4452, "s": 4354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4479, "s": 4452, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 4522, "s": 4479, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4547, "s": 4522, "text": "unordered_map in C++ STL" }, { "code": null, "e": 4566, "s": 4547, "text": "Inheritance in C++" }, { "code": null, "e": 4600, "s": 4566, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 4640, "s": 4600, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 4664, "s": 4640, "text": "C++ Classes and Objects" }, { "code": null, "e": 4681, "s": 4664, "text": "Substring in C++" }, { "code": null, "e": 4716, "s": 4681, "text": "Object Oriented Programming in C++" } ]
When to use an abstract class and when to use an interface in Java?
An interface can be used to define a contract behavior and it can also act as a contract between two systems to interact while an abstract class is mainly used to define default behavior for subclasses, it means that all child classes should have performed the same functionality. An abstract class is a good choice if we are using the inheritance concept since it provides a common base class implementation to derived classes. An abstract class is also good if we want to declare non-public members. In an interface, all methods must be public. If we want to add new methods in the future, then an abstract class is a better choice. Because if we add new methods to an interface, then all of the classes that already implemented that interface will have to be changed to implement the new methods. If we want to create multiple versions of our component, create an abstract class. Abstract classes provide a simple and easy way to version our components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, we must create a whole new interface. Abstract classes have the advantage of allowing better forward compatibility. Once clients use an interface, we cannot change it; if they use an abstract class, we can still add behavior without breaking the existing code. If we want to provide common, implemented functionality among all implementations of our component, use an abstract class. Abstract classes allow us to partially implement our class, whereas interfaces contain no implementation for any members. abstract class Car { public void accelerate() { System.out.println("Do something to accelerate"); } public void applyBrakes() { System.out.println("Do something to apply brakes"); } public abstract void changeGears(); } Now, any Car that wants to be instantiated must implement the changeGears () method. class Alto extends Car { public void changeGears() { System.out.println("Implement changeGears() method for Alto Car"); } } class Santro extends Car { public void changeGears() { System.out.println("Implement changeGears() method for Santro Car"); } } If the functionality we are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while. Interfaces are also good when we want to have something similar to multiple inheritances since we can implement multiple interfaces. If we are designing small, concise bits of functionality, use interfaces. If we are designing large functional units, use an abstract class. public interface Actor { void perform(); } public interface Producer { void invest(); } Nowadays most of the actors are rich enough to produce their own movie. If we are using interfaces rather than abstract classes, we can implement both Actor and Producer. Also, we can define a new ActorProducer interface that extends both. public interface ActorProducer extends Actor, Producer{ // some statements }
[ { "code": null, "e": 1468, "s": 1187, "text": "An interface can be used to define a contract behavior and it can also act as a contract between two systems to interact while an abstract class is mainly used to define default behavior for subclasses, it means that all child classes should have performed the same functionality." }, { "code": null, "e": 1616, "s": 1468, "text": "An abstract class is a good choice if we are using the inheritance concept since it provides a common base class implementation to derived classes." }, { "code": null, "e": 1734, "s": 1616, "text": "An abstract class is also good if we want to declare non-public members. In an interface, all methods must be public." }, { "code": null, "e": 1987, "s": 1734, "text": "If we want to add new methods in the future, then an abstract class is a better choice. Because if we add new methods to an interface, then all of the classes that already implemented that interface will have to be changed to implement the new methods." }, { "code": null, "e": 2385, "s": 1987, "text": "If we want to create multiple versions of our component, create an abstract class. Abstract classes provide a simple and easy way to version our components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, we must create a whole new interface." }, { "code": null, "e": 2608, "s": 2385, "text": "Abstract classes have the advantage of allowing better forward compatibility. Once clients use an interface, we cannot change it; if they use an abstract class, we can still add behavior without breaking the existing code." }, { "code": null, "e": 2853, "s": 2608, "text": "If we want to provide common, implemented functionality among all implementations of our component, use an abstract class. Abstract classes allow us to partially implement our class, whereas interfaces contain no implementation for any members." }, { "code": null, "e": 3100, "s": 2853, "text": "abstract class Car {\n public void accelerate() {\n System.out.println(\"Do something to accelerate\");\n }\n public void applyBrakes() {\n System.out.println(\"Do something to apply brakes\");\n }\n public abstract void changeGears();\n}" }, { "code": null, "e": 3185, "s": 3100, "text": "Now, any Car that wants to be instantiated must implement the changeGears () method." }, { "code": null, "e": 3461, "s": 3185, "text": "class Alto extends Car {\n public void changeGears() {\n System.out.println(\"Implement changeGears() method for Alto Car\");\n }\n}\nclass Santro extends Car {\n public void changeGears() {\n System.out.println(\"Implement changeGears() method for Santro Car\");\n }\n}" }, { "code": null, "e": 3747, "s": 3461, "text": "If the functionality we are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes." }, { "code": null, "e": 3832, "s": 3747, "text": "Interfaces are a good choice when we think that the API will not change for a while." }, { "code": null, "e": 3965, "s": 3832, "text": "Interfaces are also good when we want to have something similar to multiple inheritances since we can implement multiple interfaces." }, { "code": null, "e": 4106, "s": 3965, "text": "If we are designing small, concise bits of functionality, use interfaces. If we are designing large functional units, use an abstract class." }, { "code": null, "e": 4200, "s": 4106, "text": "public interface Actor {\n void perform();\n}\npublic interface Producer {\n void invest();\n}" }, { "code": null, "e": 4440, "s": 4200, "text": "Nowadays most of the actors are rich enough to produce their own movie. If we are using interfaces rather than abstract classes, we can implement both Actor and Producer. Also, we can define a new ActorProducer interface that extends both." }, { "code": null, "e": 4520, "s": 4440, "text": "public interface ActorProducer extends Actor, Producer{\n // some statements\n}" } ]
Python program to convert Dict of list to CSV
28 Nov, 2021 Given a dictionary of list d, the task is to write a Python program to write a dictionary into a CSV file. The idea to solve this problem is to zip the dictionary and then write it into a CSV file. Python provides an in-built module called ‘csv’ for working with CSV files. csv.writer class is used to write into CSV file. csv.writer class provide two methods for writing into csv file. writerow(): writerow() method is used to write single row. writerows(): writerows() method is used to write multiple rows. Python3 # Program to write a dictionary of list to csvimport csv # dictionary of listd = {"key1": ['a', 'b', 'c'], "key2": ['d', 'e', 'f'], "key3": ['g', 'h', 'i']} # writing to csv filewith open("test.csv", "w") as outfile: # creating a csv writer object writerfile = csv.writer(outfile) # writing dictionary keys as headings of csv writerfile.writerow(d.keys()) # writing list of dictionary writerfile.writerows(zip(*d.values())) Output: Python’s zip() function takes iterable as input and returns an iterator object. This iterator generates a series of tuples with each tuple having elements from each of the iterable. Here lists in the dictionary are provided as input to the zip() and it will return a series of tuples with each tuple having elements from all lists these tuples will be treated as rows for CSV file. Example: Python3 # Program to write a dictionary of list to csvimport csv # dictionary of listd = {"key1": ['a', 'b', 'c'], "key2": ['d', 'e', 'f'], "key3": ['g', 'h', 'i']} # writing to csv filewith open("test.csv", "w") as outfile: # creating a csv writer object writerfile = csv.writer(outfile) # writing dictionary keys as headings of csv writerfile.writerow(d.keys()) # writing list of dictionary writerfile.writerows(zip(*d.values())) Output: Picked Python dictionary-programs python-dict Python Python Programs 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": "\n28 Nov, 2021" }, { "code": null, "e": 135, "s": 28, "text": "Given a dictionary of list d, the task is to write a Python program to write a dictionary into a CSV file." }, { "code": null, "e": 415, "s": 135, "text": "The idea to solve this problem is to zip the dictionary and then write it into a CSV file. Python provides an in-built module called ‘csv’ for working with CSV files. csv.writer class is used to write into CSV file. csv.writer class provide two methods for writing into csv file." }, { "code": null, "e": 474, "s": 415, "text": "writerow(): writerow() method is used to write single row." }, { "code": null, "e": 538, "s": 474, "text": "writerows(): writerows() method is used to write multiple rows." }, { "code": null, "e": 546, "s": 538, "text": "Python3" }, { "code": "# Program to write a dictionary of list to csvimport csv # dictionary of listd = {\"key1\": ['a', 'b', 'c'], \"key2\": ['d', 'e', 'f'], \"key3\": ['g', 'h', 'i']} # writing to csv filewith open(\"test.csv\", \"w\") as outfile: # creating a csv writer object writerfile = csv.writer(outfile) # writing dictionary keys as headings of csv writerfile.writerow(d.keys()) # writing list of dictionary writerfile.writerows(zip(*d.values()))", "e": 1016, "s": 546, "text": null }, { "code": null, "e": 1024, "s": 1016, "text": "Output:" }, { "code": null, "e": 1207, "s": 1024, "text": "Python’s zip() function takes iterable as input and returns an iterator object. This iterator generates a series of tuples with each tuple having elements from each of the iterable. " }, { "code": null, "e": 1407, "s": 1207, "text": "Here lists in the dictionary are provided as input to the zip() and it will return a series of tuples with each tuple having elements from all lists these tuples will be treated as rows for CSV file." }, { "code": null, "e": 1416, "s": 1407, "text": "Example:" }, { "code": null, "e": 1424, "s": 1416, "text": "Python3" }, { "code": "# Program to write a dictionary of list to csvimport csv # dictionary of listd = {\"key1\": ['a', 'b', 'c'], \"key2\": ['d', 'e', 'f'], \"key3\": ['g', 'h', 'i']} # writing to csv filewith open(\"test.csv\", \"w\") as outfile: # creating a csv writer object writerfile = csv.writer(outfile) # writing dictionary keys as headings of csv writerfile.writerow(d.keys()) # writing list of dictionary writerfile.writerows(zip(*d.values()))", "e": 1894, "s": 1424, "text": null }, { "code": null, "e": 1902, "s": 1894, "text": "Output:" }, { "code": null, "e": 1909, "s": 1902, "text": "Picked" }, { "code": null, "e": 1936, "s": 1909, "text": "Python dictionary-programs" }, { "code": null, "e": 1948, "s": 1936, "text": "python-dict" }, { "code": null, "e": 1955, "s": 1948, "text": "Python" }, { "code": null, "e": 1971, "s": 1955, "text": "Python Programs" }, { "code": null, "e": 1983, "s": 1971, "text": "python-dict" } ]
How to Draw 3D Cube using Matplotlib in Python?
06 Jul, 2022 In this article, we will deal with the 3d plots of cubes using matplotlib and Numpy. Cubes are one of the most basic of 3D shapes. A cube is a 3-dimensional solid object bounded by 6 identical square faces. The cube has 6-faces, 12-edges, and 8-corners. All faces are squares of the same size. The total surface area of a cube is the sum of the area of the 6 identical squares. Matplotlib comes with a wide variety of plots. Graphs help to understand trends, patterns to make correlations. Matplotlib was introduced for two-dimensional plotting. The 3d plot is enabled by importing the mplot3d toolkit., which comes with your standard Matplotlib. After importing, 3D plots can be created by passing the keyword projection=”3d” to any of the regular axes creation functions in Matplotlib. Matplotlib: It is a plotting library for Python programming it serves as a visualization utility library, Matplotlib is built on NumPy arrays, and designed to work with the broader SciPy stack. Numpy: It is a general-purpose array-processing package. It provides a high-performance multidimensional array and matrices along with a large collection of high-level mathematical functions. mpl_toolkits: It provides some basic 3d plotting (scatter, surf, line, mesh) tools. It is a collection of helper classes for displaying 3d axes in Matplotlib. Step 1: Import libraries. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np Step 2: In this step, we are selecting the 3D axis of the dimension X =5, Y=5, Z=5, and in np.ones() we are passing the dimensions of the cube. # Create axis axes = [5, 5, 5] # Create Data data = np.ones(axes) Step 3: In this step, we are selecting color opacity as alpha = 0.9 ( vary from 0.0 – 1.0 ). In the next step, we are passing the dimension of axes( i.e 5, 5, 5) + number of faces for the cube ( i.e 0-4 ) in np.empty() function after that we are passing color combination and opacity for each face of the cube. # control Tranperency alpha = 0.9 # control colour colors = np.empty(axes + [4]) colors[0] = [1, 0, 0, alpha] # red colors[1] = [0, 1, 0, alpha] # green colors[2] = [0, 0, 1, alpha] # blue colors[3] = [1, 1, 0, alpha] # yellow colors[4] = [1, 1, 1, alpha] # grey Step 4: In this step, we used figure() function of the matplotlib library which is used to create a new figure, After that, we used add_subplot() method to add an Axes to the figure as 3-Dimensional(i.e Projection = ‘3d’) part of a subplot arrangement. It has 3 arguments. The number of rows in the grid, The number of columns in the grid and, The position at which the new subplot must be placed. It is to be noted that fig.add_subplot(1, 1, 1) is equivalent to fig.add_subplot(111). # Plot figure fig = plt.figure() ax = fig.add_subplot(111, projection='3d') Step 5: And in this last step Voxels is used for customizations of the size, position, and grid color. The proper syntax is provided above. # Voxels is used to customizations of the # sizes, positions and colors. ax.voxels(data, facecolors=colors, edgecolors='grey') Example 1: Simple cube of one color. Here changing colors[ : ], means we are selecting all the array elements as one color (i.e red) and to remove the grid we deleted ‘edgecolor’ parameter from voxels method to have simply one color cube. Python3 # Import librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # Create axisaxes = [5, 5, 5] # Create Datadata = np.ones(axes, dtype=np.bool) # Control Tranperencyalpha = 0.9 # Control colourcolors = np.empty(axes + [4], dtype=np.float32) colors[:] = [1, 0, 0, alpha] # red # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Voxels is used to customizations of the# sizes, positions and colors.ax.voxels(data, facecolors=colors) Output: Example 2: Cube with Grid and different color Python3 # Import librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # Create axisaxes = [5, 5, 5] # Create Datadata = np.ones(axes, dtype=np.bool) # Control Tranperencyalpha = 0.9 # Control colourcolors = np.empty(axes + [4], dtype=np.float32) colors[0] = [1, 0, 0, alpha] # redcolors[1] = [0, 1, 0, alpha] # greencolors[2] = [0, 0, 1, alpha] # bluecolors[3] = [1, 1, 0, alpha] # yellowcolors[4] = [1, 1, 1, alpha] # grey # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Voxels is used to customizations of# the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='grey') Output: Example 3: Faced cube along Y – axes In this example, we will add one more line of code view_init( ) to change the axis view as we want. The view_init() can be used to change the axes view programmatically. Here we are using elev=100 and azim=0. Syntax: view_init(elev, azim) Parameters: ‘elev’ stores the elevation angle in the z plane. ‘azim’ stores the azimuth angle in the x,y plane. Python3 import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np axes = [5, 5, 5]data = np.ones(axes, dtype=np.bool) colors = np.empty(axes + [4], dtype=np.float32) # Control Tranperencyalpha = .7 # Control colorscolors[0] = [1, 0, 0, alpha]colors[1] = [0, 1, 0, alpha]colors[2] = [0, 0, 1, alpha]colors[3] = [1, 1, 0, alpha]colors[4] = [0, 1, 1, alpha] # set all internal colors to# black with alpha=1colors[1:-1, 1:-1, 1:-1, 0:3] = 0colors[1:-1, 1:-1, 1:-1, 3] = 1 # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Control number of slicedata[-1] = Truedata[-2] = Falsedata[-3] = Falsedata[-4] = Falsedata[-5] = True # Voxels is used to customizations of# the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='pink') # it can be used to change the axes viewax.view_init(100, 0) Output: Example 4: Faced cube along X-axes The view_init() can be used to change the axes view programmatically. Here we are using elev=100 and azim=90. Python3 import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np axes = [5, 5, 5]data = np.ones(axes, dtype=np.bool) colors = np.empty(axes + [4], dtype=np.float32) # Control Tranperencyalpha = .7 # Control colorscolors[0] = [1, 0, 0, alpha]colors[1] = [0, 1, 0, alpha]colors[2] = [0, 0, 1, alpha]colors[3] = [1, 1, 0, alpha]colors[4] = [0, 1, 1, alpha] # set all internal colors to# black with alpha=1colors[1:-1, 1:-1, 1:-1, 0:3] = 0colors[1:-1, 1:-1, 1:-1, 3] = 1 # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Control number of slicedata[-1] = 1data[-2] = Falsedata[-3] = Falsedata[-4] = Falsedata[-5] = True # Voxels is used to customizations# of the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='pink') # it can be used to change the axes viewax.view_init(100, 90) Output: vinayedula Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2022" }, { "code": null, "e": 406, "s": 28, "text": "In this article, we will deal with the 3d plots of cubes using matplotlib and Numpy. Cubes are one of the most basic of 3D shapes. A cube is a 3-dimensional solid object bounded by 6 identical square faces. The cube has 6-faces, 12-edges, and 8-corners. All faces are squares of the same size. The total surface area of a cube is the sum of the area of the 6 identical squares." }, { "code": null, "e": 816, "s": 406, "text": "Matplotlib comes with a wide variety of plots. Graphs help to understand trends, patterns to make correlations. Matplotlib was introduced for two-dimensional plotting. The 3d plot is enabled by importing the mplot3d toolkit., which comes with your standard Matplotlib. After importing, 3D plots can be created by passing the keyword projection=”3d” to any of the regular axes creation functions in Matplotlib." }, { "code": null, "e": 1010, "s": 816, "text": "Matplotlib: It is a plotting library for Python programming it serves as a visualization utility library, Matplotlib is built on NumPy arrays, and designed to work with the broader SciPy stack." }, { "code": null, "e": 1202, "s": 1010, "text": "Numpy: It is a general-purpose array-processing package. It provides a high-performance multidimensional array and matrices along with a large collection of high-level mathematical functions." }, { "code": null, "e": 1361, "s": 1202, "text": "mpl_toolkits: It provides some basic 3d plotting (scatter, surf, line, mesh) tools. It is a collection of helper classes for displaying 3d axes in Matplotlib." }, { "code": null, "e": 1387, "s": 1361, "text": "Step 1: Import libraries." }, { "code": null, "e": 1479, "s": 1387, "text": "import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D \nimport numpy as np" }, { "code": null, "e": 1623, "s": 1479, "text": "Step 2: In this step, we are selecting the 3D axis of the dimension X =5, Y=5, Z=5, and in np.ones() we are passing the dimensions of the cube." }, { "code": null, "e": 1690, "s": 1623, "text": "# Create axis\naxes = [5, 5, 5]\n\n# Create Data\ndata = np.ones(axes)" }, { "code": null, "e": 2001, "s": 1690, "text": "Step 3: In this step, we are selecting color opacity as alpha = 0.9 ( vary from 0.0 – 1.0 ). In the next step, we are passing the dimension of axes( i.e 5, 5, 5) + number of faces for the cube ( i.e 0-4 ) in np.empty() function after that we are passing color combination and opacity for each face of the cube." }, { "code": null, "e": 2267, "s": 2001, "text": "# control Tranperency\nalpha = 0.9\n\n# control colour \ncolors = np.empty(axes + [4])\n\ncolors[0] = [1, 0, 0, alpha] # red\ncolors[1] = [0, 1, 0, alpha] # green\ncolors[2] = [0, 0, 1, alpha] # blue\ncolors[3] = [1, 1, 0, alpha] # yellow\ncolors[4] = [1, 1, 1, alpha] # grey" }, { "code": null, "e": 2540, "s": 2267, "text": "Step 4: In this step, we used figure() function of the matplotlib library which is used to create a new figure, After that, we used add_subplot() method to add an Axes to the figure as 3-Dimensional(i.e Projection = ‘3d’) part of a subplot arrangement. It has 3 arguments." }, { "code": null, "e": 2572, "s": 2540, "text": "The number of rows in the grid," }, { "code": null, "e": 2611, "s": 2572, "text": "The number of columns in the grid and," }, { "code": null, "e": 2665, "s": 2611, "text": "The position at which the new subplot must be placed." }, { "code": null, "e": 2752, "s": 2665, "text": "It is to be noted that fig.add_subplot(1, 1, 1) is equivalent to fig.add_subplot(111)." }, { "code": null, "e": 2828, "s": 2752, "text": "# Plot figure\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')" }, { "code": null, "e": 2968, "s": 2828, "text": "Step 5: And in this last step Voxels is used for customizations of the size, position, and grid color. The proper syntax is provided above." }, { "code": null, "e": 3096, "s": 2968, "text": "# Voxels is used to customizations of the \n# sizes, positions and colors.\nax.voxels(data, facecolors=colors, edgecolors='grey')" }, { "code": null, "e": 3133, "s": 3096, "text": "Example 1: Simple cube of one color." }, { "code": null, "e": 3335, "s": 3133, "text": "Here changing colors[ : ], means we are selecting all the array elements as one color (i.e red) and to remove the grid we deleted ‘edgecolor’ parameter from voxels method to have simply one color cube." }, { "code": null, "e": 3343, "s": 3335, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # Create axisaxes = [5, 5, 5] # Create Datadata = np.ones(axes, dtype=np.bool) # Control Tranperencyalpha = 0.9 # Control colourcolors = np.empty(axes + [4], dtype=np.float32) colors[:] = [1, 0, 0, alpha] # red # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Voxels is used to customizations of the# sizes, positions and colors.ax.voxels(data, facecolors=colors)", "e": 3843, "s": 3343, "text": null }, { "code": null, "e": 3851, "s": 3843, "text": "Output:" }, { "code": null, "e": 3862, "s": 3851, "text": "Example 2:" }, { "code": null, "e": 3897, "s": 3862, "text": "Cube with Grid and different color" }, { "code": null, "e": 3905, "s": 3897, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # Create axisaxes = [5, 5, 5] # Create Datadata = np.ones(axes, dtype=np.bool) # Control Tranperencyalpha = 0.9 # Control colourcolors = np.empty(axes + [4], dtype=np.float32) colors[0] = [1, 0, 0, alpha] # redcolors[1] = [0, 1, 0, alpha] # greencolors[2] = [0, 0, 1, alpha] # bluecolors[3] = [1, 1, 0, alpha] # yellowcolors[4] = [1, 1, 1, alpha] # grey # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Voxels is used to customizations of# the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='grey')", "e": 4571, "s": 3905, "text": null }, { "code": null, "e": 4579, "s": 4571, "text": "Output:" }, { "code": null, "e": 4616, "s": 4579, "text": "Example 3: Faced cube along Y – axes" }, { "code": null, "e": 4826, "s": 4616, "text": "In this example, we will add one more line of code view_init( ) to change the axis view as we want. The view_init() can be used to change the axes view programmatically. Here we are using elev=100 and azim=0." }, { "code": null, "e": 4856, "s": 4826, "text": "Syntax: view_init(elev, azim)" }, { "code": null, "e": 4870, "s": 4856, "text": "Parameters: " }, { "code": null, "e": 4920, "s": 4870, "text": "‘elev’ stores the elevation angle in the z plane." }, { "code": null, "e": 4970, "s": 4920, "text": "‘azim’ stores the azimuth angle in the x,y plane." }, { "code": null, "e": 4978, "s": 4970, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np axes = [5, 5, 5]data = np.ones(axes, dtype=np.bool) colors = np.empty(axes + [4], dtype=np.float32) # Control Tranperencyalpha = .7 # Control colorscolors[0] = [1, 0, 0, alpha]colors[1] = [0, 1, 0, alpha]colors[2] = [0, 0, 1, alpha]colors[3] = [1, 1, 0, alpha]colors[4] = [0, 1, 1, alpha] # set all internal colors to# black with alpha=1colors[1:-1, 1:-1, 1:-1, 0:3] = 0colors[1:-1, 1:-1, 1:-1, 3] = 1 # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Control number of slicedata[-1] = Truedata[-2] = Falsedata[-3] = Falsedata[-4] = Falsedata[-5] = True # Voxels is used to customizations of# the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='pink') # it can be used to change the axes viewax.view_init(100, 0)", "e": 5833, "s": 4978, "text": null }, { "code": null, "e": 5841, "s": 5833, "text": "Output:" }, { "code": null, "e": 5876, "s": 5841, "text": "Example 4: Faced cube along X-axes" }, { "code": null, "e": 5987, "s": 5876, "text": "The view_init() can be used to change the axes view programmatically. Here we are using elev=100 and azim=90." }, { "code": null, "e": 5995, "s": 5987, "text": "Python3" }, { "code": "import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np axes = [5, 5, 5]data = np.ones(axes, dtype=np.bool) colors = np.empty(axes + [4], dtype=np.float32) # Control Tranperencyalpha = .7 # Control colorscolors[0] = [1, 0, 0, alpha]colors[1] = [0, 1, 0, alpha]colors[2] = [0, 0, 1, alpha]colors[3] = [1, 1, 0, alpha]colors[4] = [0, 1, 1, alpha] # set all internal colors to# black with alpha=1colors[1:-1, 1:-1, 1:-1, 0:3] = 0colors[1:-1, 1:-1, 1:-1, 3] = 1 # Plot figurefig = plt.figure()ax = fig.add_subplot(111, projection='3d') # Control number of slicedata[-1] = 1data[-2] = Falsedata[-3] = Falsedata[-4] = Falsedata[-5] = True # Voxels is used to customizations# of the sizes, positions and colors.ax.voxels(data, facecolors=colors, edgecolors='pink') # it can be used to change the axes viewax.view_init(100, 90)", "e": 6848, "s": 5995, "text": null }, { "code": null, "e": 6856, "s": 6848, "text": "Output:" }, { "code": null, "e": 6867, "s": 6856, "text": "vinayedula" }, { "code": null, "e": 6885, "s": 6867, "text": "Python-matplotlib" }, { "code": null, "e": 6892, "s": 6885, "text": "Python" } ]
Select into and temporary tables in MS SQL Server
23 Sep, 2020 1. Select into :Suppose a table has some particular rows that has to be transferred to another table of the same database. It can be done using select into statement as follows – select list into destination from source (where condition) Example :There are two tables named student and marks. The marks of the students has to be transferred from marks to student table. This has to be done as : Select * from student; Select * from marks; Select mks into student from marks; The marks will be added into the student table. The ‘where’ clause can be used for condition. It is optional. 2. Temporary tables :The user at times wants to create a separate table from the given table values. It has to be done using the temporary tables concept. Temporary tables can be created in two ways: using create table syntax or select into syntax. Select into :A new table has to created from the student table using select into statement as follows : Select * from student; Select name, rollno into temp_table #details from student; Create table :A new table can be created using create table statement : Create table #details( name varchar2(30), rollno int); A new table is created. The values can be copied from the other table as follows : Insert into #details select name, rollno from student; SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2020" }, { "code": null, "e": 207, "s": 28, "text": "1. Select into :Suppose a table has some particular rows that has to be transferred to another table of the same database. It can be done using select into statement as follows –" }, { "code": null, "e": 267, "s": 207, "text": "select list into destination from source (where condition) " }, { "code": null, "e": 424, "s": 267, "text": "Example :There are two tables named student and marks. The marks of the students has to be transferred from marks to student table. This has to be done as :" }, { "code": null, "e": 447, "s": 424, "text": "Select *\nfrom student;" }, { "code": null, "e": 468, "s": 447, "text": "Select *\nfrom marks;" }, { "code": null, "e": 505, "s": 468, "text": "Select mks into student \nfrom marks;" }, { "code": null, "e": 615, "s": 505, "text": "The marks will be added into the student table. The ‘where’ clause can be used for condition. It is optional." }, { "code": null, "e": 864, "s": 615, "text": "2. Temporary tables :The user at times wants to create a separate table from the given table values. It has to be done using the temporary tables concept. Temporary tables can be created in two ways: using create table syntax or select into syntax." }, { "code": null, "e": 968, "s": 864, "text": "Select into :A new table has to created from the student table using select into statement as follows :" }, { "code": null, "e": 991, "s": 968, "text": "Select *\nfrom student;" }, { "code": null, "e": 1051, "s": 991, "text": "Select name, rollno into temp_table #details \nfrom student;" }, { "code": null, "e": 1123, "s": 1051, "text": "Create table :A new table can be created using create table statement :" }, { "code": null, "e": 1178, "s": 1123, "text": "Create table #details( name varchar2(30), rollno int);" }, { "code": null, "e": 1261, "s": 1178, "text": "A new table is created. The values can be copied from the other table as follows :" }, { "code": null, "e": 1316, "s": 1261, "text": "Insert into #details select name, rollno from student;" }, { "code": null, "e": 1327, "s": 1316, "text": "SQL-Server" }, { "code": null, "e": 1331, "s": 1327, "text": "SQL" }, { "code": null, "e": 1335, "s": 1331, "text": "SQL" }, { "code": null, "e": 1433, "s": 1335, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1499, "s": 1433, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1523, "s": 1499, "text": "Window functions in SQL" }, { "code": null, "e": 1555, "s": 1523, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1588, "s": 1555, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1605, "s": 1588, "text": "SQL using Python" }, { "code": null, "e": 1683, "s": 1605, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1713, "s": 1683, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1749, "s": 1713, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 1780, "s": 1749, "text": "SQL Query to Compare Two Dates" } ]
Copy set bits in a range
16 Jun, 2022 Given two numbers x and y, and a range [l, r] where 1 <= l, r <= 32. The task is consider set bits of y in range [l, r] and set these bits in x also.Examples : Input : x = 10, y = 13, l = 2, r = 3 Output : x = 14 Binary representation of 10 is 1010 and that of y is 1101. There is one set bit in y at 3'rd position (in given range). After we copy this bit to x, x becomes 1110 which is binary representation of 14. Input : x = 8, y = 7, l = 1, r = 2 Output : x = 11 Source : D E Shaw Interview Method 1 (One by one copy bits) We can one by one find set bits of y by traversing given range. For every set bit, we OR it to existing bit of x, so that the becomes set in x, if it was not set. Below is C++ implementation. CPP Java Python3 C# Javascript // C++ program to rearrange array in alternating// C++ program to copy set bits in a given// range [l, r] from y to x.#include <bits/stdc++.h>using namespace std; // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.void copySetBits(unsigned &x, unsigned y, unsigned l, unsigned r){ // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return ; // Traverse in given range for (int i=l; i<=r; i++) { // Find a mask (A number whose // only set bit is at i'th position) int mask = 1 << (i-1); // If i'th bit is set in y, set i'th // bit in x also. if (y & mask) x = x | mask; }} // Driver codeint main(){ unsigned x = 10, y = 13, l = 1, r = 32; copySetBits(x, y, l, r); cout << "Modified x is " << x; return 0;} // Java program to rearrange array in alternating// Java program to copy set bits in a given// range [l, r] from y to x.import java.util.*; class GFG{ // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.static int copySetBits(int x, int y, int l, int r){ // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return x; // Traverse in given range for (int i = l; i <= r; i++) { // Find a mask (A number whose // only set bit is at i'th position) int mask = 1 << (i-1); // If i'th bit is set in y, set i'th // bit in x also. if ((y & mask)!=0) x = x | mask; } return x;} // Driver codepublic static void main(String[] args){ int x = 10, y = 13, l = 1, r = 32; x = copySetBits(x, y, l, r); System.out.print("Modified x is " + x);}} // This code is contributed by umadevi9616 # Python program to rearrange array in alternating# Python program to copy set bits in a given# range [l, r] from y to x. # Copy set bits in range [l, r] from y to x.# Note that x is passed by reference and modified# by this function.def copySetBits(x, y, l, r): # l and r must be between 1 to 32 # (assuming ints are stored using # 32 bits) if (l < 1 or r > 32): return x; # Traverse in given range for i in range(l, r + 1): # Find a mask (A number whose # only set bit is at i'th position) mask = 1 << (i - 1); # If i'th bit is set in y, set i'th # bit in x also. if ((y & mask) != 0): x = x | mask; return x; # Driver codeif __name__ == '__main__': x = 10; y = 13; l = 1; r = 32; x = copySetBits(x, y, l, r); print("Modified x is ", x); # This code is contributed by gauravrajput1 // C# program to rearrange array in alternating// C# program to copy set bits in a given// range [l, r] from y to x.using System; public class GFG { // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. static int copySetBits(int x, int y, int l, int r) { // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return x; // Traverse in given range for (int i = l; i <= r; i++) { // Find a mask (A number whose // only set bit is at i'th position) int mask = 1 << (i - 1); // If i'th bit is set in y, set i'th // bit in x also. if ((y & mask) != 0) x = x | mask; } return x; } // Driver code public static void Main(String[] args) { int x = 10, y = 13, l = 1, r = 32; x = copySetBits(x, y, l, r); Console.Write("Modified x is " + x); }} // This code is contributed by umadevi9616 <script>// javascript program to rearrange array in alternating// javascript program to copy set bits in a given// range [l, r] from y to x. // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. function copySetBits(x , y , l , r) { // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return x; // Traverse in given range for (i = l; i <= r; i++) { // Find a mask (A number whose // only set bit is at i'th position) var mask = 1 << (i - 1); // If i'th bit is set in y, set i'th // bit in x also. if ((y & mask) != 0) x = x | mask; } return x; } // Driver code var x = 10, y = 13, l = 1, r = 32; x = copySetBits(x, y, l, r); document.write("Modified x is " + x); // This code is contributed by gauravrajput1</script> Modified x is 15 Time Complexity: O(r) Auxiliary Space: O(1) Method 2 (Copy all bits using one bit mask) CPP Java Python3 C# Javascript // C++ program to copy set bits in a given// range [l, r] from y to x.#include <bits/stdc++.h>using namespace std; // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.void copySetBits(unsigned &x, unsigned y, unsigned l, unsigned r){ // l and r must be between 1 to 32 if (l < 1 || r > 32) return ; // get the length of the mask int maskLength = (1ll<<(r-l+1)) - 1; // Shift the mask to the required position // "&" with y to get the set bits at between // l ad r in y int mask = ((maskLength)<<(l-1)) & y ; x = x | mask;} // Driver codeint main(){ unsigned x = 10, y = 13, l = 2, r = 3; copySetBits(x, y, l, r); cout << "Modified x is " << x; return 0;} // Java program to copy set bits in a given// range [l, r] from y to x.import java.util.*; class GFG{ // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.static int copySetBits(int x, int y, int l, int r){ // l and r must be between 1 to 32 if (l < 1 || r > 32) return x; // get the length of the mask int maskLength = (int)((1L<<(r-l+1)) - 1); // Shift the mask to the required position // "&" with y to get the set bits at between // l ad r in y int mask = ((maskLength)<<(l-1)) & y ; x = x | mask; return x;} // Driver codepublic static void main(String[] args){ int x = 10, y = 13, l = 2, r = 3; x = copySetBits(x, y, l, r); System.out.print("Modified x is " + x);}} // This code is contributed by umadevi9616 # Python program to copy set bits in a given# range [l, r] from y to x. # Copy set bits in range [l, r] from y to x.# Note that x is passed by reference and modified# by this function.def copySetBits(x, y, l, r): # l and r must be between 1 to 32 if (l < 1 or r > 32): return x; # get the length of the mask maskLength = (int) ((1 << (r - l + 1)) - 1); # Shift the mask to the required position # "&" with y to get the set bits at between # l ad r in y mask = ((maskLength) << (l - 1)) & y; x = x | mask; return x; # Driver codeif __name__ == '__main__': x = 10; y = 13; l = 2; r = 3; x = copySetBits(x, y, l, r); print("Modified x is " , x); # This code is contributed by gauravrajput1 // C# program to copy set bits in a given// range [l, r] from y to x.using System; public class GFG{ // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. static int copySetBits(int x, int y, int l, int r) { // l and r must be between 1 to 32 if (l < 1 || r > 32) return x; // get the length of the mask int maskLength = (int) ((1L << (r - l + 1)) - 1); // Shift the mask to the required position // "&" with y to get the set bits at between // l ad r in y int mask = ((maskLength) << (l - 1)) & y; x = x | mask; return x; } // Driver code public static void Main(String[] args) { int x = 10, y = 13, l = 2, r = 3; x = copySetBits(x, y, l, r); Console.Write("Modified x is " + x); }} // This code is contributed by gauravrajput1 <script>// javascript program to copy set bits in a given// range [l, r] from y to x. // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. function copySetBits(x , y , l , r) { // l and r must be between 1 to 32 if (l < 1 || r > 32) return x; // get the length of the mask var maskLength = parseInt( ((1 << (r - l + 1)) - 1)); // Shift the mask to the required position // "&" with y to get the set bits at between // l ad r in y var mask = ((maskLength) << (l - 1)) & y; x = x | mask; return x; } // Driver code var x = 10, y = 13, l = 2, r = 3; x = copySetBits(x, y, l, r); document.write("Modified x is " + x); // This code is contributed by gauravrajput1</script> Modified x is 14 Time Complexity: O(1) Auxiliary Space: O(1) Thanks to Ashish Rathi for suggesting this solution in a comment.This article is contributed by Rishi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above chandrimaroychowdhury1999 anikaseth98 aniketkumar20 adityajain19 subham348 umadevi9616 GauravRajput1 sankt Adobe D-E-Shaw Bit Magic D-E-Shaw Adobe Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 215, "s": 54, "text": "Given two numbers x and y, and a range [l, r] where 1 <= l, r <= 32. The task is consider set bits of y in range [l, r] and set these bits in x also.Examples : " }, { "code": null, "e": 526, "s": 215, "text": "Input : x = 10, y = 13, l = 2, r = 3\nOutput : x = 14\nBinary representation of 10 is 1010 and \nthat of y is 1101. There is one set bit\nin y at 3'rd position (in given range). \nAfter we copy this bit to x, x becomes 1110\nwhich is binary representation of 14.\n\nInput : x = 8, y = 7, l = 1, r = 2\nOutput : x = 11" }, { "code": null, "e": 555, "s": 526, "text": "Source : D E Shaw Interview " }, { "code": null, "e": 780, "s": 555, "text": "Method 1 (One by one copy bits) We can one by one find set bits of y by traversing given range. For every set bit, we OR it to existing bit of x, so that the becomes set in x, if it was not set. Below is C++ implementation. " }, { "code": null, "e": 784, "s": 780, "text": "CPP" }, { "code": null, "e": 789, "s": 784, "text": "Java" }, { "code": null, "e": 797, "s": 789, "text": "Python3" }, { "code": null, "e": 800, "s": 797, "text": "C#" }, { "code": null, "e": 811, "s": 800, "text": "Javascript" }, { "code": "// C++ program to rearrange array in alternating// C++ program to copy set bits in a given// range [l, r] from y to x.#include <bits/stdc++.h>using namespace std; // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.void copySetBits(unsigned &x, unsigned y, unsigned l, unsigned r){ // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return ; // Traverse in given range for (int i=l; i<=r; i++) { // Find a mask (A number whose // only set bit is at i'th position) int mask = 1 << (i-1); // If i'th bit is set in y, set i'th // bit in x also. if (y & mask) x = x | mask; }} // Driver codeint main(){ unsigned x = 10, y = 13, l = 1, r = 32; copySetBits(x, y, l, r); cout << \"Modified x is \" << x; return 0;}", "e": 1725, "s": 811, "text": null }, { "code": "// Java program to rearrange array in alternating// Java program to copy set bits in a given// range [l, r] from y to x.import java.util.*; class GFG{ // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.static int copySetBits(int x, int y, int l, int r){ // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return x; // Traverse in given range for (int i = l; i <= r; i++) { // Find a mask (A number whose // only set bit is at i'th position) int mask = 1 << (i-1); // If i'th bit is set in y, set i'th // bit in x also. if ((y & mask)!=0) x = x | mask; } return x;} // Driver codepublic static void main(String[] args){ int x = 10, y = 13, l = 1, r = 32; x = copySetBits(x, y, l, r); System.out.print(\"Modified x is \" + x);}} // This code is contributed by umadevi9616", "e": 2706, "s": 1725, "text": null }, { "code": "# Python program to rearrange array in alternating# Python program to copy set bits in a given# range [l, r] from y to x. # Copy set bits in range [l, r] from y to x.# Note that x is passed by reference and modified# by this function.def copySetBits(x, y, l, r): # l and r must be between 1 to 32 # (assuming ints are stored using # 32 bits) if (l < 1 or r > 32): return x; # Traverse in given range for i in range(l, r + 1): # Find a mask (A number whose # only set bit is at i'th position) mask = 1 << (i - 1); # If i'th bit is set in y, set i'th # bit in x also. if ((y & mask) != 0): x = x | mask; return x; # Driver codeif __name__ == '__main__': x = 10; y = 13; l = 1; r = 32; x = copySetBits(x, y, l, r); print(\"Modified x is \", x); # This code is contributed by gauravrajput1", "e": 3601, "s": 2706, "text": null }, { "code": "// C# program to rearrange array in alternating// C# program to copy set bits in a given// range [l, r] from y to x.using System; public class GFG { // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. static int copySetBits(int x, int y, int l, int r) { // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return x; // Traverse in given range for (int i = l; i <= r; i++) { // Find a mask (A number whose // only set bit is at i'th position) int mask = 1 << (i - 1); // If i'th bit is set in y, set i'th // bit in x also. if ((y & mask) != 0) x = x | mask; } return x; } // Driver code public static void Main(String[] args) { int x = 10, y = 13, l = 1, r = 32; x = copySetBits(x, y, l, r); Console.Write(\"Modified x is \" + x); }} // This code is contributed by umadevi9616", "e": 4718, "s": 3601, "text": null }, { "code": "<script>// javascript program to rearrange array in alternating// javascript program to copy set bits in a given// range [l, r] from y to x. // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. function copySetBits(x , y , l , r) { // l and r must be between 1 to 32 // (assuming ints are stored using // 32 bits) if (l < 1 || r > 32) return x; // Traverse in given range for (i = l; i <= r; i++) { // Find a mask (A number whose // only set bit is at i'th position) var mask = 1 << (i - 1); // If i'th bit is set in y, set i'th // bit in x also. if ((y & mask) != 0) x = x | mask; } return x; } // Driver code var x = 10, y = 13, l = 1, r = 32; x = copySetBits(x, y, l, r); document.write(\"Modified x is \" + x); // This code is contributed by gauravrajput1</script>", "e": 5766, "s": 4718, "text": null }, { "code": null, "e": 5783, "s": 5766, "text": "Modified x is 15" }, { "code": null, "e": 5805, "s": 5783, "text": "Time Complexity: O(r)" }, { "code": null, "e": 5827, "s": 5805, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5873, "s": 5827, "text": " Method 2 (Copy all bits using one bit mask) " }, { "code": null, "e": 5877, "s": 5873, "text": "CPP" }, { "code": null, "e": 5882, "s": 5877, "text": "Java" }, { "code": null, "e": 5890, "s": 5882, "text": "Python3" }, { "code": null, "e": 5893, "s": 5890, "text": "C#" }, { "code": null, "e": 5904, "s": 5893, "text": "Javascript" }, { "code": "// C++ program to copy set bits in a given// range [l, r] from y to x.#include <bits/stdc++.h>using namespace std; // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.void copySetBits(unsigned &x, unsigned y, unsigned l, unsigned r){ // l and r must be between 1 to 32 if (l < 1 || r > 32) return ; // get the length of the mask int maskLength = (1ll<<(r-l+1)) - 1; // Shift the mask to the required position // \"&\" with y to get the set bits at between // l ad r in y int mask = ((maskLength)<<(l-1)) & y ; x = x | mask;} // Driver codeint main(){ unsigned x = 10, y = 13, l = 2, r = 3; copySetBits(x, y, l, r); cout << \"Modified x is \" << x; return 0;}", "e": 6682, "s": 5904, "text": null }, { "code": "// Java program to copy set bits in a given// range [l, r] from y to x.import java.util.*; class GFG{ // Copy set bits in range [l, r] from y to x.// Note that x is passed by reference and modified// by this function.static int copySetBits(int x, int y, int l, int r){ // l and r must be between 1 to 32 if (l < 1 || r > 32) return x; // get the length of the mask int maskLength = (int)((1L<<(r-l+1)) - 1); // Shift the mask to the required position // \"&\" with y to get the set bits at between // l ad r in y int mask = ((maskLength)<<(l-1)) & y ; x = x | mask; return x;} // Driver codepublic static void main(String[] args){ int x = 10, y = 13, l = 2, r = 3; x = copySetBits(x, y, l, r); System.out.print(\"Modified x is \" + x);}} // This code is contributed by umadevi9616", "e": 7524, "s": 6682, "text": null }, { "code": "# Python program to copy set bits in a given# range [l, r] from y to x. # Copy set bits in range [l, r] from y to x.# Note that x is passed by reference and modified# by this function.def copySetBits(x, y, l, r): # l and r must be between 1 to 32 if (l < 1 or r > 32): return x; # get the length of the mask maskLength = (int) ((1 << (r - l + 1)) - 1); # Shift the mask to the required position # \"&\" with y to get the set bits at between # l ad r in y mask = ((maskLength) << (l - 1)) & y; x = x | mask; return x; # Driver codeif __name__ == '__main__': x = 10; y = 13; l = 2; r = 3; x = copySetBits(x, y, l, r); print(\"Modified x is \" , x); # This code is contributed by gauravrajput1", "e": 8269, "s": 7524, "text": null }, { "code": "// C# program to copy set bits in a given// range [l, r] from y to x.using System; public class GFG{ // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. static int copySetBits(int x, int y, int l, int r) { // l and r must be between 1 to 32 if (l < 1 || r > 32) return x; // get the length of the mask int maskLength = (int) ((1L << (r - l + 1)) - 1); // Shift the mask to the required position // \"&\" with y to get the set bits at between // l ad r in y int mask = ((maskLength) << (l - 1)) & y; x = x | mask; return x; } // Driver code public static void Main(String[] args) { int x = 10, y = 13, l = 2, r = 3; x = copySetBits(x, y, l, r); Console.Write(\"Modified x is \" + x); }} // This code is contributed by gauravrajput1", "e": 9193, "s": 8269, "text": null }, { "code": "<script>// javascript program to copy set bits in a given// range [l, r] from y to x. // Copy set bits in range [l, r] from y to x. // Note that x is passed by reference and modified // by this function. function copySetBits(x , y , l , r) { // l and r must be between 1 to 32 if (l < 1 || r > 32) return x; // get the length of the mask var maskLength = parseInt( ((1 << (r - l + 1)) - 1)); // Shift the mask to the required position // \"&\" with y to get the set bits at between // l ad r in y var mask = ((maskLength) << (l - 1)) & y; x = x | mask; return x; } // Driver code var x = 10, y = 13, l = 2, r = 3; x = copySetBits(x, y, l, r); document.write(\"Modified x is \" + x); // This code is contributed by gauravrajput1</script>", "e": 10055, "s": 9193, "text": null }, { "code": null, "e": 10072, "s": 10055, "text": "Modified x is 14" }, { "code": null, "e": 10094, "s": 10072, "text": "Time Complexity: O(1)" }, { "code": null, "e": 10116, "s": 10094, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 10344, "s": 10116, "text": "Thanks to Ashish Rathi for suggesting this solution in a comment.This article is contributed by Rishi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10370, "s": 10344, "text": "chandrimaroychowdhury1999" }, { "code": null, "e": 10382, "s": 10370, "text": "anikaseth98" }, { "code": null, "e": 10396, "s": 10382, "text": "aniketkumar20" }, { "code": null, "e": 10409, "s": 10396, "text": "adityajain19" }, { "code": null, "e": 10419, "s": 10409, "text": "subham348" }, { "code": null, "e": 10431, "s": 10419, "text": "umadevi9616" }, { "code": null, "e": 10445, "s": 10431, "text": "GauravRajput1" }, { "code": null, "e": 10451, "s": 10445, "text": "sankt" }, { "code": null, "e": 10457, "s": 10451, "text": "Adobe" }, { "code": null, "e": 10466, "s": 10457, "text": "D-E-Shaw" }, { "code": null, "e": 10476, "s": 10466, "text": "Bit Magic" }, { "code": null, "e": 10485, "s": 10476, "text": "D-E-Shaw" }, { "code": null, "e": 10491, "s": 10485, "text": "Adobe" }, { "code": null, "e": 10501, "s": 10491, "text": "Bit Magic" } ]
When Does Compiler Create Default and Copy Constructors in C++?
24 May, 2022 A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++ Default Constructor Copy constructor Parameterized Constructor In C++, the compiler creates a default constructor if we don’t define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn’t assign default values to data members. However, in Java default constructors assign default values. Syntax: Class_name() It is possible to pass arguments to constructors in the form of a parameterized constructor. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object Syntax: Class_name(Parameters) The compiler also creates a copy constructor if we don’t write our own copy constructor. Unlike the default constructor, the body of the copy constructor created by the compiler is not empty, it copies all data members of the passed object to the object which is being created. Syntax: Class_name(const Class_name& object) What happens when we write only a copy constructor – does the compiler create a default constructor? The compiler doesn’t create a default constructor if we write any constructor even if it is a copy constructor. For example, the following program doesn’t compile. CPP // C++ Program to demonstrate what// happens when we write// only a copy constructor#include <iostream>using namespace std; class Point { int x, y; public: Point(const Point& p) // Copy Constructor { x = p.x; y = p.y; }}; int main(){ Point p1; // Compiler Error Point p2 = p1; return 0;} Output: Compiler Error: no matching function for call to 'Point::Point() What happens when we write a normal constructor and don’t write a copy constructor? The compiler creates a copy constructor if we don’t write our own. The compiler creates it even if we have written other constructors in a class. For example, the below program works fine. CPP // CPP Program to demonstrate what happens when we write a// normal constructor and don't write a copy constructor#include <iostream>using namespace std; class Point { int x, y; public: Point(int i, int j) { x = 10; y = 20; } int getX() { return x; } int getY() { return y; }}; int main(){ Point p1(10, 20); Point p2 = p1; // This compiles fine cout << "x = " << p2.getX() << " y = " << p2.getY(); return 0;} x = 10 y = 20 So, we need to write a copy constructor only when we have pointers or run-time allocation of resources like filehandle, a network connection, etc. Must Read: When should we write our own copy constructor? Does the C++ compiler create a default constructor when we write our own? Shun Xian Cai anshikajain26 harsh_shokeen cpp-constructor C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. vector erase() and clear() in C++ Substring in C++ unordered_map in C++ STL Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ 2D Vector In C++ With User Defined Size Templates in C++ with Examples Multidimensional Arrays in C / C++ Operator Overloading in C++ Polymorphism in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2022" }, { "code": null, "e": 286, "s": 54, "text": "A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++" }, { "code": null, "e": 306, "s": 286, "text": "Default Constructor" }, { "code": null, "e": 323, "s": 306, "text": "Copy constructor" }, { "code": null, "e": 349, "s": 323, "text": "Parameterized Constructor" }, { "code": null, "e": 621, "s": 349, "text": "In C++, the compiler creates a default constructor if we don’t define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn’t assign default values to data members. However, in Java default constructors assign default values." }, { "code": null, "e": 629, "s": 621, "text": "Syntax:" }, { "code": null, "e": 646, "s": 629, "text": " Class_name()" }, { "code": null, "e": 998, "s": 646, "text": "It is possible to pass arguments to constructors in the form of a parameterized constructor. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object " }, { "code": null, "e": 1006, "s": 998, "text": "Syntax:" }, { "code": null, "e": 1033, "s": 1006, "text": " Class_name(Parameters)" }, { "code": null, "e": 1311, "s": 1033, "text": "The compiler also creates a copy constructor if we don’t write our own copy constructor. Unlike the default constructor, the body of the copy constructor created by the compiler is not empty, it copies all data members of the passed object to the object which is being created." }, { "code": null, "e": 1319, "s": 1311, "text": "Syntax:" }, { "code": null, "e": 1360, "s": 1319, "text": " Class_name(const Class_name& object)" }, { "code": null, "e": 1626, "s": 1360, "text": "What happens when we write only a copy constructor – does the compiler create a default constructor? The compiler doesn’t create a default constructor if we write any constructor even if it is a copy constructor. For example, the following program doesn’t compile. " }, { "code": null, "e": 1630, "s": 1626, "text": "CPP" }, { "code": "// C++ Program to demonstrate what// happens when we write// only a copy constructor#include <iostream>using namespace std; class Point { int x, y; public: Point(const Point& p) // Copy Constructor { x = p.x; y = p.y; }}; int main(){ Point p1; // Compiler Error Point p2 = p1; return 0;}", "e": 1959, "s": 1630, "text": null }, { "code": null, "e": 1967, "s": 1959, "text": "Output:" }, { "code": null, "e": 2032, "s": 1967, "text": "Compiler Error: no matching function for call to 'Point::Point()" }, { "code": null, "e": 2116, "s": 2032, "text": "What happens when we write a normal constructor and don’t write a copy constructor?" }, { "code": null, "e": 2306, "s": 2116, "text": "The compiler creates a copy constructor if we don’t write our own. The compiler creates it even if we have written other constructors in a class. For example, the below program works fine. " }, { "code": null, "e": 2310, "s": 2306, "text": "CPP" }, { "code": "// CPP Program to demonstrate what happens when we write a// normal constructor and don't write a copy constructor#include <iostream>using namespace std; class Point { int x, y; public: Point(int i, int j) { x = 10; y = 20; } int getX() { return x; } int getY() { return y; }}; int main(){ Point p1(10, 20); Point p2 = p1; // This compiles fine cout << \"x = \" << p2.getX() << \" y = \" << p2.getY(); return 0;}", "e": 2766, "s": 2310, "text": null }, { "code": null, "e": 2780, "s": 2766, "text": "x = 10 y = 20" }, { "code": null, "e": 2927, "s": 2780, "text": "So, we need to write a copy constructor only when we have pointers or run-time allocation of resources like filehandle, a network connection, etc." }, { "code": null, "e": 2938, "s": 2927, "text": "Must Read:" }, { "code": null, "e": 2985, "s": 2938, "text": "When should we write our own copy constructor?" }, { "code": null, "e": 3059, "s": 2985, "text": "Does the C++ compiler create a default constructor when we write our own?" }, { "code": null, "e": 3073, "s": 3059, "text": "Shun Xian Cai" }, { "code": null, "e": 3087, "s": 3073, "text": "anshikajain26" }, { "code": null, "e": 3101, "s": 3087, "text": "harsh_shokeen" }, { "code": null, "e": 3117, "s": 3101, "text": "cpp-constructor" }, { "code": null, "e": 3121, "s": 3117, "text": "C++" }, { "code": null, "e": 3125, "s": 3121, "text": "CPP" }, { "code": null, "e": 3223, "s": 3125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3257, "s": 3223, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3274, "s": 3257, "text": "Substring in C++" }, { "code": null, "e": 3299, "s": 3274, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3353, "s": 3299, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3377, "s": 3353, "text": "Sorting a vector in C++" }, { "code": null, "e": 3417, "s": 3377, "text": "2D Vector In C++ With User Defined Size" }, { "code": null, "e": 3448, "s": 3417, "text": "Templates in C++ with Examples" }, { "code": null, "e": 3483, "s": 3448, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 3511, "s": 3483, "text": "Operator Overloading in C++" } ]
Check if a point is inside, outside or on the ellipse
29 Jun, 2022 Given an ellipse centered at (h, k), with semi-major axis a, semi-minor axis b, both aligned with the Cartesian plane. The task is to determine if the point (x, y) is within the area bounded by the ellipse.Examples: Input: h = 0, k = 0, x = 2, y = 1, a = 4, b = 5 Output: Inside Input: h = 1, k = 2, x = 200, y = 100, a = 6, b = 5 Output: Outside Approach: We have to solve the equation of ellipse for the given point (x, y), (x-h)^2/a^2 + (y-k)^2/b^2 <= 1 If in the inequation, results comes less than 1 then the point lies within, else if it comes exact 1 then the point lies on the ellipse, and if the inequation is unsatisfied then point lies outside of the ellipse.Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ Program to check if the point// lies within the ellipse or not#include <bits/stdc++.h>using namespace std; // Function to check the pointint checkpoint(int h, int k, int x, int y, int a, int b){ // checking the equation of // ellipse with the given point int p = (pow((x - h), 2) / pow(a, 2)) + (pow((y - k), 2) / pow(b, 2)); return p;} // Driver codeint main(){ int h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) cout << "Outside" << endl; else if (checkpoint(h, k, x, y, a, b) == 1) cout << "On the ellipse" << endl; else cout << "Inside" << endl; return 0;} // Java Program to check if the point// lies within the ellipse or notimport java.util.*; class solution{ // Function to check the pointstatic int checkpoint(int h, int k, int x, int y, int a, int b){ // checking the equation of // ellipse with the given point int p = ((int)Math.pow((x - h), 2) / (int)Math.pow(a, 2)) + ((int)Math.pow((y - k), 2) / (int)Math.pow(b, 2)); return p;} //Driver codepublic static void main(String arr[]){ int h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) System.out.println("Outside"); else if (checkpoint(h, k, x, y, a, b) == 1) System.out.println("On the ellipse"); else System.out.println("Inside"); }} //This code is contributed by Surendra_Gangwar # Python 3 Program to check if# the point lies within the# ellipse or notimport math # Function to check the pointdef checkpoint( h, k, x, y, a, b): # checking the equation of # ellipse with the given point p = ((math.pow((x - h), 2) // math.pow(a, 2)) + (math.pow((y - k), 2) // math.pow(b, 2))) return p # Driver codeif __name__ == "__main__": h = 0 k = 0 x = 2 y = 1 a = 4 b = 5 if (checkpoint(h, k, x, y, a, b) > 1): print ("Outside") elif (checkpoint(h, k, x, y, a, b) == 1): print("On the ellipse") else: print("Inside") # This code is contributed# by ChitraNayal // C# Program to check if the point// lies within the ellipse or notusing System; class GFG{ // Function to check the pointstatic int checkpoint(int h, int k, int x, int y, int a, int b){ // checking the equation of // ellipse with the given point int p = ((int)Math.Pow((x - h), 2) / (int)Math.Pow(a, 2)) + ((int)Math.Pow((y - k), 2) / (int)Math.Pow(b, 2)); return p;} // Driver codepublic static void Main(){ int h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) Console.WriteLine("Outside"); else if (checkpoint(h, k, x, y, a, b) == 1) Console.WriteLine("On the ellipse"); else Console.WriteLine("Inside");}} // This code is contributed by inder_verma <?php// PHP Program to check if the point// lies within the ellipse or not // Function to check the pointfunction checkpoint($h, $k, $x, $y, $a, $b){ // checking the equation of // ellipse with the given point $p = (pow(($x - $h), 2) / pow($a, 2)) + (pow(($y - $k), 2) / pow($b, 2)); return $p;} // Driver code$h = 0;$k = 0;$x = 2;$y = 1;$a = 4;$b = 5; if (checkpoint($h, $k, $x, $y, $a, $b) > 1) echo ("Outside"); else if (checkpoint($h, $k, $x, $y, $a, $b) == 1) echo("On the ellipse" ); else echo ("Inside") ; // This code is contributed by Shivi_Aggarwal?> <script> // javascript Program to check if the point// lies within the ellipse or not // Function to check the pointfunction checkpoint(h , k , x , y , a , b){ // checking the equation of // ellipse with the given point var p = (parseInt(Math.pow((x - h), 2)) / parseInt(Math.pow(a, 2))) + (parseInt(Math.pow((y - k), 2)) / parseInt(Math.pow(b, 2))); return p;} // Driver code var h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) document.write("Outside"); else if (checkpoint(h, k, x, y, a, b) == 1) document.write("On the ellipse"); else document.write("Inside"); // This code is contributed by 29AjayKumar </script> Inside Time complexity: O(1) Auxiliary Space: O(1) Shivi_Aggarwal SURENDRA_GANGWAR inderDuMCA ukasp 29AjayKumar krishnav4 Technical Scripter 2018 Geometric Mathematical Technical Scripter Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Jun, 2022" }, { "code": null, "e": 271, "s": 53, "text": "Given an ellipse centered at (h, k), with semi-major axis a, semi-minor axis b, both aligned with the Cartesian plane. The task is to determine if the point (x, y) is within the area bounded by the ellipse.Examples: " }, { "code": null, "e": 404, "s": 271, "text": "Input: h = 0, k = 0, x = 2, y = 1, a = 4, b = 5 \nOutput: Inside\n\nInput: h = 1, k = 2, x = 200, y = 100, a = 6, b = 5\nOutput: Outside" }, { "code": null, "e": 489, "s": 408, "text": "Approach: We have to solve the equation of ellipse for the given point (x, y), " }, { "code": null, "e": 520, "s": 489, "text": "(x-h)^2/a^2 + (y-k)^2/b^2 <= 1" }, { "code": null, "e": 787, "s": 520, "text": " If in the inequation, results comes less than 1 then the point lies within, else if it comes exact 1 then the point lies on the ellipse, and if the inequation is unsatisfied then point lies outside of the ellipse.Below is the implementation of the above approach: " }, { "code": null, "e": 791, "s": 787, "text": "C++" }, { "code": null, "e": 796, "s": 791, "text": "Java" }, { "code": null, "e": 805, "s": 796, "text": "Python 3" }, { "code": null, "e": 808, "s": 805, "text": "C#" }, { "code": null, "e": 812, "s": 808, "text": "PHP" }, { "code": null, "e": 823, "s": 812, "text": "Javascript" }, { "code": "// C++ Program to check if the point// lies within the ellipse or not#include <bits/stdc++.h>using namespace std; // Function to check the pointint checkpoint(int h, int k, int x, int y, int a, int b){ // checking the equation of // ellipse with the given point int p = (pow((x - h), 2) / pow(a, 2)) + (pow((y - k), 2) / pow(b, 2)); return p;} // Driver codeint main(){ int h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) cout << \"Outside\" << endl; else if (checkpoint(h, k, x, y, a, b) == 1) cout << \"On the ellipse\" << endl; else cout << \"Inside\" << endl; return 0;}", "e": 1489, "s": 823, "text": null }, { "code": "// Java Program to check if the point// lies within the ellipse or notimport java.util.*; class solution{ // Function to check the pointstatic int checkpoint(int h, int k, int x, int y, int a, int b){ // checking the equation of // ellipse with the given point int p = ((int)Math.pow((x - h), 2) / (int)Math.pow(a, 2)) + ((int)Math.pow((y - k), 2) / (int)Math.pow(b, 2)); return p;} //Driver codepublic static void main(String arr[]){ int h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) System.out.println(\"Outside\"); else if (checkpoint(h, k, x, y, a, b) == 1) System.out.println(\"On the ellipse\"); else System.out.println(\"Inside\"); }} //This code is contributed by Surendra_Gangwar", "e": 2269, "s": 1489, "text": null }, { "code": "# Python 3 Program to check if# the point lies within the# ellipse or notimport math # Function to check the pointdef checkpoint( h, k, x, y, a, b): # checking the equation of # ellipse with the given point p = ((math.pow((x - h), 2) // math.pow(a, 2)) + (math.pow((y - k), 2) // math.pow(b, 2))) return p # Driver codeif __name__ == \"__main__\": h = 0 k = 0 x = 2 y = 1 a = 4 b = 5 if (checkpoint(h, k, x, y, a, b) > 1): print (\"Outside\") elif (checkpoint(h, k, x, y, a, b) == 1): print(\"On the ellipse\") else: print(\"Inside\") # This code is contributed# by ChitraNayal", "e": 2913, "s": 2269, "text": null }, { "code": "// C# Program to check if the point// lies within the ellipse or notusing System; class GFG{ // Function to check the pointstatic int checkpoint(int h, int k, int x, int y, int a, int b){ // checking the equation of // ellipse with the given point int p = ((int)Math.Pow((x - h), 2) / (int)Math.Pow(a, 2)) + ((int)Math.Pow((y - k), 2) / (int)Math.Pow(b, 2)); return p;} // Driver codepublic static void Main(){ int h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) Console.WriteLine(\"Outside\"); else if (checkpoint(h, k, x, y, a, b) == 1) Console.WriteLine(\"On the ellipse\"); else Console.WriteLine(\"Inside\");}} // This code is contributed by inder_verma", "e": 3703, "s": 2913, "text": null }, { "code": "<?php// PHP Program to check if the point// lies within the ellipse or not // Function to check the pointfunction checkpoint($h, $k, $x, $y, $a, $b){ // checking the equation of // ellipse with the given point $p = (pow(($x - $h), 2) / pow($a, 2)) + (pow(($y - $k), 2) / pow($b, 2)); return $p;} // Driver code$h = 0;$k = 0;$x = 2;$y = 1;$a = 4;$b = 5; if (checkpoint($h, $k, $x, $y, $a, $b) > 1) echo (\"Outside\"); else if (checkpoint($h, $k, $x, $y, $a, $b) == 1) echo(\"On the ellipse\" ); else echo (\"Inside\") ; // This code is contributed by Shivi_Aggarwal?>", "e": 4318, "s": 3703, "text": null }, { "code": "<script> // javascript Program to check if the point// lies within the ellipse or not // Function to check the pointfunction checkpoint(h , k , x , y , a , b){ // checking the equation of // ellipse with the given point var p = (parseInt(Math.pow((x - h), 2)) / parseInt(Math.pow(a, 2))) + (parseInt(Math.pow((y - k), 2)) / parseInt(Math.pow(b, 2))); return p;} // Driver code var h = 0, k = 0, x = 2, y = 1, a = 4, b = 5; if (checkpoint(h, k, x, y, a, b) > 1) document.write(\"Outside\"); else if (checkpoint(h, k, x, y, a, b) == 1) document.write(\"On the ellipse\"); else document.write(\"Inside\"); // This code is contributed by 29AjayKumar </script>", "e": 5028, "s": 4318, "text": null }, { "code": null, "e": 5035, "s": 5028, "text": "Inside" }, { "code": null, "e": 5059, "s": 5037, "text": "Time complexity: O(1)" }, { "code": null, "e": 5081, "s": 5059, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5096, "s": 5081, "text": "Shivi_Aggarwal" }, { "code": null, "e": 5113, "s": 5096, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5124, "s": 5113, "text": "inderDuMCA" }, { "code": null, "e": 5130, "s": 5124, "text": "ukasp" }, { "code": null, "e": 5142, "s": 5130, "text": "29AjayKumar" }, { "code": null, "e": 5152, "s": 5142, "text": "krishnav4" }, { "code": null, "e": 5176, "s": 5152, "text": "Technical Scripter 2018" }, { "code": null, "e": 5186, "s": 5176, "text": "Geometric" }, { "code": null, "e": 5199, "s": 5186, "text": "Mathematical" }, { "code": null, "e": 5218, "s": 5199, "text": "Technical Scripter" }, { "code": null, "e": 5231, "s": 5218, "text": "Mathematical" }, { "code": null, "e": 5241, "s": 5231, "text": "Geometric" } ]
Introduction to Beam Search Algorithm
18 Jul, 2021 Introduction :A heuristic technique is a set of criteria for determining which of multiple options will be the most effective in achieving a particular goal. This strategy increases the efficiency of a search process by surrendering claims of systematic and completeness of the best.We can hope to achieve a good solution to difficult problems (such as the traveling salesman problem) in less than exponent time if we use appropriate heuristics. Beam Search :A heuristic search algorithm that examines a graph by extending the most promising node in a limited set is known as beam search. Beam search is a heuristic search technique that always expands the W number of the best nodes at each level. It progresses level by level and moves downwards only from the best W nodes at each level. Beam Search uses breadth-first search to build its search tree. Beam Search constructs its search tree using breadth-first search. It generates all the successors of the current level’s state at each level of the tree. However, at each level, it only evaluates a W number of states. Other nodes are not taken into account. The heuristic cost associated with the node is used to choose the best nodes. The width of the beam search is denoted by W. If B is the branching factor, at every depth, there will always be W × B nodes under consideration, but only W will be chosen. More states are trimmed when the beam width is reduced. When W = 1, the search becomes a hill-climbing search in which the best node is always chosen from the successor nodes. No states are pruned if the beam width is unlimited, and the beam search is identified as a breadth-first search. The beamwidth bounds the amount of memory needed to complete the search, but it comes at the cost of completeness and optimality (possibly that it will not find the best solution). The reason for this danger is that the desired state could have been pruned. Example: The search tree generated using this algorithm with W = 2 & B = 3 is given below : Beam Search The black nodes are selected based on their heuristic values for further expansion. The algorithm for beam search is given as : Input: Start & Goal States.Local Variables: OPEN, NODE, SUCCS, W_OPEN, FOUNDOutput: Yes or No (yes if the search is successfully done) Start Take the inputs NODE = Root_Node & Found = False If : Node is the Goal Node, Then Found = True, Else : Find SUCCs of NODE if any, with its estimated cost& store it in OPEN List While (Found == false & not able to proceed further), do { Sort OPEN List Select top W elements from OPEN list and put it in W_OPEN list and empty the OPEN list. for each NODE from W_OPEN list { if NODE = Goal, then FOUND = true else Find SUCCs of NODE. If any with its estimated cost & Store it in OPEN list } } If FOUND = True, then return Yes else return No Stop Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Information Retrieval? Introduction to Recurrent Neural Network Support Vector Machine Algorithm Sequential Covering Algorithm ML | Expectation-Maximization Algorithm Regression and Classification | Supervised Machine Learning Python | Linear Regression using sklearn k-nearest neighbor algorithm in Python Difference between K means and Hierarchical Clustering Markov Decision Process
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 475, "s": 28, "text": "Introduction :A heuristic technique is a set of criteria for determining which of multiple options will be the most effective in achieving a particular goal. This strategy increases the efficiency of a search process by surrendering claims of systematic and completeness of the best.We can hope to achieve a good solution to difficult problems (such as the traveling salesman problem) in less than exponent time if we use appropriate heuristics. " }, { "code": null, "e": 2033, "s": 475, "text": "Beam Search :A heuristic search algorithm that examines a graph by extending the most promising node in a limited set is known as beam search. Beam search is a heuristic search technique that always expands the W number of the best nodes at each level. It progresses level by level and moves downwards only from the best W nodes at each level. Beam Search uses breadth-first search to build its search tree. Beam Search constructs its search tree using breadth-first search. It generates all the successors of the current level’s state at each level of the tree. However, at each level, it only evaluates a W number of states. Other nodes are not taken into account. The heuristic cost associated with the node is used to choose the best nodes. The width of the beam search is denoted by W. If B is the branching factor, at every depth, there will always be W × B nodes under consideration, but only W will be chosen. More states are trimmed when the beam width is reduced. When W = 1, the search becomes a hill-climbing search in which the best node is always chosen from the successor nodes. No states are pruned if the beam width is unlimited, and the beam search is identified as a breadth-first search. The beamwidth bounds the amount of memory needed to complete the search, but it comes at the cost of completeness and optimality (possibly that it will not find the best solution). The reason for this danger is that the desired state could have been pruned. Example: The search tree generated using this algorithm with W = 2 & B = 3 is given below :" }, { "code": null, "e": 2045, "s": 2033, "text": "Beam Search" }, { "code": null, "e": 2129, "s": 2045, "text": "The black nodes are selected based on their heuristic values for further expansion." }, { "code": null, "e": 2173, "s": 2129, "text": "The algorithm for beam search is given as :" }, { "code": null, "e": 2308, "s": 2173, "text": "Input: Start & Goal States.Local Variables: OPEN, NODE, SUCCS, W_OPEN, FOUNDOutput: Yes or No (yes if the search is successfully done)" }, { "code": null, "e": 2973, "s": 2308, "text": "Start \nTake the inputs \nNODE = Root_Node & Found = False\nIf : Node is the Goal Node,\n Then Found = True, \nElse : \n Find SUCCs of NODE if any, with its estimated cost&\n store it in OPEN List \nWhile (Found == false & not able to proceed further), do\n{\n Sort OPEN List\n Select top W elements from OPEN list and put it in\n W_OPEN list and empty the OPEN list.\n for each NODE from W_OPEN list\n {\n if NODE = Goal,\n then FOUND = true \n else\n Find SUCCs of NODE. If any with its estimated\n cost & Store it in OPEN list\n }\n}\nIf FOUND = True,\n then return Yes\nelse\n return No\nStop" }, { "code": null, "e": 2990, "s": 2973, "text": "Machine Learning" }, { "code": null, "e": 3007, "s": 2990, "text": "Machine Learning" }, { "code": null, "e": 3105, "s": 3007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3136, "s": 3105, "text": "What is Information Retrieval?" }, { "code": null, "e": 3177, "s": 3136, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3210, "s": 3177, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 3240, "s": 3210, "text": "Sequential Covering Algorithm" }, { "code": null, "e": 3280, "s": 3240, "text": "ML | Expectation-Maximization Algorithm" }, { "code": null, "e": 3340, "s": 3280, "text": "Regression and Classification | Supervised Machine Learning" }, { "code": null, "e": 3381, "s": 3340, "text": "Python | Linear Regression using sklearn" }, { "code": null, "e": 3420, "s": 3381, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 3475, "s": 3420, "text": "Difference between K means and Hierarchical Clustering" } ]
OS Path module in Python
29 Nov, 2020 This module contains some useful functions on pathnames. The path parameters are either strings or bytes . These functions here are used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned. As there are different versions of operating system so there are several versions of this module in the standard library.Following are some functions of OS Path module.1. os.path.basename(path) : It is used to return the basename of the file . This function basically return the file name from the path given. Python3 # basename functionimport osout = os.path.basename("/baz/foo")print(out) Output: 'foo' 2. os.path.dirname(path) : It is used to return the directory name from the path given. This function returns the name from the path except the path name. Python3 # dirname functionimport osout = os.path.dirname("/baz/foo")print(out) Output: '/baz' 3. os.path.isabs(path) : It specifies whether the path is absolute or not. In Unix system absolute path means path begins with the slash(‘/’) and in Windows that it begins with a (back)slash after chopping off a potential drive letter. Python # isabs functionimport osout = os.path.isabs("/baz/foo")print(out) Output: True 4. os.path.isdir(path) : This function specifies whether the path is existing directory or not. Python # isdir functionimport osout = os.path.isdir("C:\\Users")print(out) Output: True 5. os.path.isfile(path) : This function specifies whether the path is existing file or not. Python # isfile functionimport osout = os.path.isfile("C:\\Users\foo.csv")print(out) Output: True 6. os.path.normcase(path) : This function normalizes the case of the pathname specified. In Unix and Mac OS X system it returns the pathname as it is . But in Windows it converts the path to lowercase and forward slashes to backslashes. Python # normcase function in windowsimport osout = os.path.normcase("/BAz")print(out) Output: '\\baz' 7. os.path.normpath(path) : This function normalizes the path names by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. On Windows, it converts forward slashes to backward slashes . Python # normpath function in Uniximport osout = os.path.normpath("foo/./bar")print(out) Output: 'foo/bar' There are many more functions , you can refer that in python.References : Python Documentation Yashadatt rajavpandian Python-Library python-modules python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Nov, 2020" }, { "code": null, "e": 766, "s": 53, "text": "This module contains some useful functions on pathnames. The path parameters are either strings or bytes . These functions here are used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned. As there are different versions of operating system so there are several versions of this module in the standard library.Following are some functions of OS Path module.1. os.path.basename(path) : It is used to return the basename of the file . This function basically return the file name from the path given. " }, { "code": null, "e": 774, "s": 766, "text": "Python3" }, { "code": "# basename functionimport osout = os.path.basename(\"/baz/foo\")print(out)", "e": 847, "s": 774, "text": null }, { "code": null, "e": 857, "s": 847, "text": "Output: " }, { "code": null, "e": 863, "s": 857, "text": "'foo'" }, { "code": null, "e": 1020, "s": 863, "text": "2. os.path.dirname(path) : It is used to return the directory name from the path given. This function returns the name from the path except the path name. " }, { "code": null, "e": 1028, "s": 1020, "text": "Python3" }, { "code": "# dirname functionimport osout = os.path.dirname(\"/baz/foo\")print(out)", "e": 1099, "s": 1028, "text": null }, { "code": null, "e": 1109, "s": 1099, "text": "Output: " }, { "code": null, "e": 1116, "s": 1109, "text": "'/baz'" }, { "code": null, "e": 1354, "s": 1116, "text": "3. os.path.isabs(path) : It specifies whether the path is absolute or not. In Unix system absolute path means path begins with the slash(‘/’) and in Windows that it begins with a (back)slash after chopping off a potential drive letter. " }, { "code": null, "e": 1361, "s": 1354, "text": "Python" }, { "code": "# isabs functionimport osout = os.path.isabs(\"/baz/foo\")print(out)", "e": 1428, "s": 1361, "text": null }, { "code": null, "e": 1438, "s": 1428, "text": "Output: " }, { "code": null, "e": 1443, "s": 1438, "text": "True" }, { "code": null, "e": 1541, "s": 1443, "text": "4. os.path.isdir(path) : This function specifies whether the path is existing directory or not. " }, { "code": null, "e": 1548, "s": 1541, "text": "Python" }, { "code": "# isdir functionimport osout = os.path.isdir(\"C:\\\\Users\")print(out)", "e": 1616, "s": 1548, "text": null }, { "code": null, "e": 1626, "s": 1616, "text": "Output: " }, { "code": null, "e": 1631, "s": 1626, "text": "True" }, { "code": null, "e": 1725, "s": 1631, "text": "5. os.path.isfile(path) : This function specifies whether the path is existing file or not. " }, { "code": null, "e": 1732, "s": 1725, "text": "Python" }, { "code": "# isfile functionimport osout = os.path.isfile(\"C:\\\\Users\\foo.csv\")print(out)", "e": 1810, "s": 1732, "text": null }, { "code": null, "e": 1820, "s": 1810, "text": "Output: " }, { "code": null, "e": 1825, "s": 1820, "text": "True" }, { "code": null, "e": 2064, "s": 1825, "text": "6. os.path.normcase(path) : This function normalizes the case of the pathname specified. In Unix and Mac OS X system it returns the pathname as it is . But in Windows it converts the path to lowercase and forward slashes to backslashes. " }, { "code": null, "e": 2071, "s": 2064, "text": "Python" }, { "code": "# normcase function in windowsimport osout = os.path.normcase(\"/BAz\")print(out)", "e": 2151, "s": 2071, "text": null }, { "code": null, "e": 2161, "s": 2151, "text": "Output: " }, { "code": null, "e": 2169, "s": 2161, "text": "'\\\\baz'" }, { "code": null, "e": 2417, "s": 2169, "text": "7. os.path.normpath(path) : This function normalizes the path names by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. On Windows, it converts forward slashes to backward slashes . " }, { "code": null, "e": 2424, "s": 2417, "text": "Python" }, { "code": "# normpath function in Uniximport osout = os.path.normpath(\"foo/./bar\")print(out)", "e": 2506, "s": 2424, "text": null }, { "code": null, "e": 2516, "s": 2506, "text": "Output: " }, { "code": null, "e": 2526, "s": 2516, "text": "'foo/bar'" }, { "code": null, "e": 2622, "s": 2526, "text": "There are many more functions , you can refer that in python.References : Python Documentation " }, { "code": null, "e": 2632, "s": 2622, "text": "Yashadatt" }, { "code": null, "e": 2645, "s": 2632, "text": "rajavpandian" }, { "code": null, "e": 2660, "s": 2645, "text": "Python-Library" }, { "code": null, "e": 2675, "s": 2660, "text": "python-modules" }, { "code": null, "e": 2692, "s": 2675, "text": "python-os-module" }, { "code": null, "e": 2699, "s": 2692, "text": "Python" }, { "code": null, "e": 2797, "s": 2699, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2815, "s": 2797, "text": "Python Dictionary" }, { "code": null, "e": 2857, "s": 2815, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2879, "s": 2857, "text": "Enumerate() in Python" }, { "code": null, "e": 2914, "s": 2879, "text": "Read a file line by line in Python" }, { "code": null, "e": 2946, "s": 2914, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2972, "s": 2946, "text": "Python String | replace()" }, { "code": null, "e": 3001, "s": 2972, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3028, "s": 3001, "text": "Python Classes and Objects" }, { "code": null, "e": 3049, "s": 3028, "text": "Python OOPs Concepts" } ]
TestNG - Suite Test
A test suite is a collection of test cases intended to test a behavior or a set of behaviors of software program. In TestNG, we cannot define a suite in testing source code, but it is represented by one XML file, as suite is the feature of execution. It also allows flexible configuration of the tests to be run. A suite can contain one or more tests and is defined by the <suite> tag. <suite> is the root tag of your testng.xml. It describes a test suite, which in turn is made of several <test> sections. The following table lists all the legal attributes that <suite> accepts. name The name of this suite. It is a mandatory attribute. verbose The level or verbosity for this run. parallel Whether TestNG should run different threads to run this suite. thread-count The number of threads to use, if parallel mode is enabled (ignored other-wise). annotations The type of annotations you are using in your tests. time-out The default timeout that will be used on all the test methods found in this test. In this chapter, we will show you an example having two test classes, Test1 & Test2, to run together using Test Suite. Create a java class to be tested, say, MessageUtil.java in /work/testng/src. /* * This class prints the given message on console. */ public class MessageUtil { private String message; // Constructor // @param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } // add "Hi!" to the message public String salutationMessage() { message = "Hi!" + message; System.out.println(message); return message; } } Create a java class file named Test1.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class Test1 { String message = "Manisha"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println("Inside testPrintMessage()"); Assert.assertEquals(message, messageUtil.printMessage()); } } Create a java class file named Test2.java in /work/testng/src . import org.testng.Assert; import org.testng.annotations.Test; public class Test2 { String message = "Manisha"; MessageUtil messageUtil = new MessageUtil(message); @Test public void testSalutationMessage() { System.out.println("Inside testSalutationMessage()"); message = "Hi!" + "Manisha"; Assert.assertEquals(message,messageUtil.salutationMessage()); } } Now, let's write the testng.xml in /work/testng/src , which would contain the <suite> tag as follows − <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "exampletest1"> <classes> <class name = "Test1" /> </classes> </test> <test name = "exampletest2"> <classes> <class name = "Test2" /> </classes> </test> </suite> Suite1 includes exampletest1 and exampletest2. Compile all java classes using javac. /work/testng/src$ javac MessageUtil.java Test1.java Test2.java Now, run the testng.xml, which will run the test case defined in the provided Test Case class. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 =============================================== You can also check the test-output folder. Under the Suite1 folder, you can see two html files created, exampletest1.html and exampletest2.html, which would look as follows −
[ { "code": null, "e": 2580, "s": 2194, "text": "A test suite is a collection of test cases intended to test a behavior or a set of behaviors of software program. In TestNG, we cannot define a suite in testing source code, but it is represented by one XML file, as suite is the feature of execution. It also allows flexible configuration of the tests to be run. A suite can contain one or more tests and is defined by the <suite> tag." }, { "code": null, "e": 2701, "s": 2580, "text": "<suite> is the root tag of your testng.xml. It describes a test suite, which in turn is made of several <test> sections." }, { "code": null, "e": 2774, "s": 2701, "text": "The following table lists all the legal attributes that <suite> accepts." }, { "code": null, "e": 2779, "s": 2774, "text": "name" }, { "code": null, "e": 2832, "s": 2779, "text": "The name of this suite. It is a mandatory attribute." }, { "code": null, "e": 2840, "s": 2832, "text": "verbose" }, { "code": null, "e": 2877, "s": 2840, "text": "The level or verbosity for this run." }, { "code": null, "e": 2886, "s": 2877, "text": "parallel" }, { "code": null, "e": 2949, "s": 2886, "text": "Whether TestNG should run different threads to run this suite." }, { "code": null, "e": 2962, "s": 2949, "text": "thread-count" }, { "code": null, "e": 3042, "s": 2962, "text": "The number of threads to use, if parallel mode is enabled (ignored other-wise)." }, { "code": null, "e": 3054, "s": 3042, "text": "annotations" }, { "code": null, "e": 3107, "s": 3054, "text": "The type of annotations you are using in your tests." }, { "code": null, "e": 3116, "s": 3107, "text": "time-out" }, { "code": null, "e": 3198, "s": 3116, "text": "The default timeout that will be used on all the test methods found in this test." }, { "code": null, "e": 3317, "s": 3198, "text": "In this chapter, we will show you an example having two test classes, Test1 & Test2, to run together using Test Suite." }, { "code": null, "e": 3394, "s": 3317, "text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src." }, { "code": null, "e": 3924, "s": 3394, "text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n private String message;\n\n // Constructor\n // @param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public String printMessage() {\n System.out.println(message);\n return message;\n }\n\n // add \"Hi!\" to the message\n public String salutationMessage() {\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n }\n}" }, { "code": null, "e": 3987, "s": 3924, "text": "Create a java class file named Test1.java in /work/testng/src." }, { "code": null, "e": 4329, "s": 3987, "text": "import org.testng.Assert;\nimport org.testng.annotations.Test;\n\npublic class Test1 {\n String message = \"Manisha\";\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testPrintMessage() {\n System.out.println(\"Inside testPrintMessage()\");\n Assert.assertEquals(message, messageUtil.printMessage());\n }\n}" }, { "code": null, "e": 4393, "s": 4329, "text": "Create a java class file named Test2.java in /work/testng/src ." }, { "code": null, "e": 4784, "s": 4393, "text": "import org.testng.Assert;\nimport org.testng.annotations.Test;\n\npublic class Test2 {\n String message = \"Manisha\";\n MessageUtil messageUtil = new MessageUtil(message);\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Manisha\";\n Assert.assertEquals(message,messageUtil.salutationMessage());\n }\n}" }, { "code": null, "e": 4887, "s": 4784, "text": "Now, let's write the testng.xml in /work/testng/src , which would contain the <suite> tag as follows −" }, { "code": null, "e": 5247, "s": 4887, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n\n<suite name = \"Suite1\">\n\n <test name = \"exampletest1\">\n <classes>\n <class name = \"Test1\" />\n </classes>\n </test>\n\n <test name = \"exampletest2\">\n <classes>\n <class name = \"Test2\" />\n </classes>\n </test>\n\n</suite>" }, { "code": null, "e": 5294, "s": 5247, "text": "Suite1 includes exampletest1 and exampletest2." }, { "code": null, "e": 5332, "s": 5294, "text": "Compile all java classes using javac." }, { "code": null, "e": 5396, "s": 5332, "text": "/work/testng/src$ javac MessageUtil.java Test1.java Test2.java\n" }, { "code": null, "e": 5491, "s": 5396, "text": "Now, run the testng.xml, which will run the test case defined in the provided Test Case class." }, { "code": null, "e": 5544, "s": 5491, "text": "/work/testng/src$ java org.testng.TestNG testng.xml\n" }, { "code": null, "e": 5563, "s": 5544, "text": "Verify the output." }, { "code": null, "e": 5785, "s": 5563, "text": " Manisha\n Inside testSalutationMessage()\n Hi!Manisha\n\n ===============================================\n Suite1\n Total tests run: 2, Passes: 2, Failures: 0, Skips: 0\n ===============================================\n" } ]
How to check a key exists in an array in PHP ?
01 Jun, 2020 We have given an array arr and a Key key, the task is to check if a key exists in an array or not in PHP. Examples: Input : arr = ["Geek1", "Geek2", "1", "2","3"] key = "2" Output : Found the Key Input : arr = ["Geek1", "Geek2", "1", "2","3"] key = 9 Output : Key not Found The problem can be solved using PHP inbuilt function for checking key exists in a given array. The in-built function used for the given problem are: Method 1: Using array_key_exists() Method: The array_key_exists() function checks whether a specific key or index is present inside an array or not. Syntax: boolean array_key_exists( $index, $array ) Example: PHP <?php// PHP program to check if a key // exists in an array or not $array = array( 'names' => array("Geek1", "Geek2", "Geek3"), 'rank' => array('1', '2', '3')); // Use of array_key_exists() functionif(array_key_exists("rank", $array)) { echo "Found the Key"; } else{ echo "Key not Found"; } ?> Found the Key Method 2: Using isset() Method: The isset() function checks whether a specific key or index is present inside an array or not. Syntax: bool isset( mixed $var, mixed $... ) PHP <?php// PHP program to check if a key // exists in an array or not $array = array( 'names' => array("Geek1", "Geek2", "Geek3"), 'rank' => array('1', '2', '3')); // Use of array_key_exists() functionif(isset($array["rank"])){ echo "Found the Key"; } else{ echo "Key not Found"; } ?> Found the Key PHP-array PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2020" }, { "code": null, "e": 134, "s": 28, "text": "We have given an array arr and a Key key, the task is to check if a key exists in an array or not in PHP." }, { "code": null, "e": 144, "s": 134, "text": "Examples:" }, { "code": null, "e": 323, "s": 144, "text": "Input : arr = [\"Geek1\", \"Geek2\", \"1\", \"2\",\"3\"] \n key = \"2\"\nOutput : Found the Key\n\nInput : arr = [\"Geek1\", \"Geek2\", \"1\", \"2\",\"3\"] \n key = 9\nOutput : Key not Found\n\n" }, { "code": null, "e": 472, "s": 323, "text": "The problem can be solved using PHP inbuilt function for checking key exists in a given array. The in-built function used for the given problem are:" }, { "code": null, "e": 621, "s": 472, "text": "Method 1: Using array_key_exists() Method: The array_key_exists() function checks whether a specific key or index is present inside an array or not." }, { "code": null, "e": 629, "s": 621, "text": "Syntax:" }, { "code": null, "e": 673, "s": 629, "text": "boolean array_key_exists( $index, $array )\n" }, { "code": null, "e": 682, "s": 673, "text": "Example:" }, { "code": null, "e": 686, "s": 682, "text": "PHP" }, { "code": "<?php// PHP program to check if a key // exists in an array or not $array = array( 'names' => array(\"Geek1\", \"Geek2\", \"Geek3\"), 'rank' => array('1', '2', '3')); // Use of array_key_exists() functionif(array_key_exists(\"rank\", $array)) { echo \"Found the Key\"; } else{ echo \"Key not Found\"; } ?>", "e": 1001, "s": 686, "text": null }, { "code": null, "e": 1015, "s": 1001, "text": "Found the Key" }, { "code": null, "e": 1142, "s": 1015, "text": "Method 2: Using isset() Method: The isset() function checks whether a specific key or index is present inside an array or not." }, { "code": null, "e": 1150, "s": 1142, "text": "Syntax:" }, { "code": null, "e": 1188, "s": 1150, "text": "bool isset( mixed $var, mixed $... )\n" }, { "code": null, "e": 1192, "s": 1188, "text": "PHP" }, { "code": "<?php// PHP program to check if a key // exists in an array or not $array = array( 'names' => array(\"Geek1\", \"Geek2\", \"Geek3\"), 'rank' => array('1', '2', '3')); // Use of array_key_exists() functionif(isset($array[\"rank\"])){ echo \"Found the Key\"; } else{ echo \"Key not Found\"; } ?>", "e": 1495, "s": 1192, "text": null }, { "code": null, "e": 1510, "s": 1495, "text": "Found the Key " }, { "code": null, "e": 1520, "s": 1510, "text": "PHP-array" }, { "code": null, "e": 1524, "s": 1520, "text": "PHP" }, { "code": null, "e": 1537, "s": 1524, "text": "PHP Programs" }, { "code": null, "e": 1554, "s": 1537, "text": "Web Technologies" }, { "code": null, "e": 1581, "s": 1554, "text": "Web technologies Questions" }, { "code": null, "e": 1585, "s": 1581, "text": "PHP" } ]
Reading an excel file using Python openpyxl module
08 Jun, 2021 Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.For example, users might have to go through thousands of rows and pick out a few handful of information to make small changes based on some criteria. Using Openpyxl module, these tasks can be done very efficiently and easily.Use this command to install openpyxl module : sudo pip3 install openpyxl Input file : Code #1 : Program to print the particular cell value Python3 # Python program to read an excel file # import openpyxl moduleimport openpyxl # Give the location of the filepath = "C:\\Users\\Admin\\Desktop\\demo.xlsx" # To open the workbook# workbook object is createdwb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object# from the active attributesheet_obj = wb_obj.active # Cell objects also have a row, column,# and coordinate attributes that provide# location information for the cell. # Note: The first row or# column integer is 1, not 0. # Cell object is created by using# sheet object's cell() method.cell_obj = sheet_obj.cell(row = 1, column = 1) # Print value of cell object# using the value attributeprint(cell_obj.value) Output : STUDENT 'S NAME Code #2 : Determine total number of rows Python3 # import openpyxl moduleimport openpyxl # Give the location of the filepath = "C:\\Users\\Admin\\Desktop\\demo.xlsx" # to open the workbook# workbook object is createdwb_obj = openpyxl.load_workbook(path)sheet_obj = wb_obj.active # print the total number of rowsprint(sheet_obj.max_row) Output : 6 Code #3 : Determine total number of columns Python3 # importing openpyxl moduleimport openpyxl # Give the location of the filepath = "C:\\Users\\Admin\\Desktop\\demo.xlsx" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active # print total number of columnprint(sheet_obj.max_column) Output : 4 Code #4 : Print all columns name Python3 # importing openpyxl moduleimport openpyxl # Give the location of the filepath = "C:\\Users\\Admin\\Desktop\\demo.xlsx" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.activemax_col = sheet_obj.max_column # Loop will print all columns namefor i in range(1, max_col + 1): cell_obj = sheet_obj.cell(row = 1, column = i) print(cell_obj.value) Output : STUDENT 'S NAME COURSE BRANCH SEMESTER Code #5 : Print first column value Python3 # importing openpyxl moduleimport openpyxl # Give the location of the filepath = "C:\\Users\\Admin\\Desktop\\demo.xlsx" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.activem_row = sheet_obj.max_row # Loop will print all values# of first columnfor i in range(1, m_row + 1): cell_obj = sheet_obj.cell(row = i, column = 1) print(cell_obj.value) Output : STUDENT 'S NAME ANKIT RAI RAHUL RAI PRIYA RAI AISHWARYA HARSHITA JAISWAL Code #6 : Print a particular row value Python3 # importing openpyxl moduleimport openpyxl # Give the location of the filepath = "C:\\Users\\Admin\\Desktop\\demo.xlsx" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active max_col = sheet_obj.max_column # Will print a particular row valuefor i in range(1, max_col + 1): cell_obj = sheet_obj.cell(row = 2, column = i) print(cell_obj.value, end = " ") Output : ANKIT RAI B.TECH CSE 4 surinderdawra388 python-modules Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2021" }, { "code": null, "e": 502, "s": 53, "text": "Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.For example, users might have to go through thousands of rows and pick out a few handful of information to make small changes based on some criteria. Using Openpyxl module, these tasks can be done very efficiently and easily.Use this command to install openpyxl module : " }, { "code": null, "e": 530, "s": 502, "text": "sudo pip3 install openpyxl " }, { "code": null, "e": 546, "s": 530, "text": " Input file : " }, { "code": null, "e": 601, "s": 546, "text": "Code #1 : Program to print the particular cell value " }, { "code": null, "e": 609, "s": 601, "text": "Python3" }, { "code": "# Python program to read an excel file # import openpyxl moduleimport openpyxl # Give the location of the filepath = \"C:\\\\Users\\\\Admin\\\\Desktop\\\\demo.xlsx\" # To open the workbook# workbook object is createdwb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object# from the active attributesheet_obj = wb_obj.active # Cell objects also have a row, column,# and coordinate attributes that provide# location information for the cell. # Note: The first row or# column integer is 1, not 0. # Cell object is created by using# sheet object's cell() method.cell_obj = sheet_obj.cell(row = 1, column = 1) # Print value of cell object# using the value attributeprint(cell_obj.value)", "e": 1298, "s": 609, "text": null }, { "code": null, "e": 1309, "s": 1298, "text": "Output : " }, { "code": null, "e": 1325, "s": 1309, "text": "STUDENT 'S NAME" }, { "code": null, "e": 1370, "s": 1325, "text": " Code #2 : Determine total number of rows " }, { "code": null, "e": 1378, "s": 1370, "text": "Python3" }, { "code": "# import openpyxl moduleimport openpyxl # Give the location of the filepath = \"C:\\\\Users\\\\Admin\\\\Desktop\\\\demo.xlsx\" # to open the workbook# workbook object is createdwb_obj = openpyxl.load_workbook(path)sheet_obj = wb_obj.active # print the total number of rowsprint(sheet_obj.max_row)", "e": 1665, "s": 1378, "text": null }, { "code": null, "e": 1676, "s": 1665, "text": "Output : " }, { "code": null, "e": 1678, "s": 1676, "text": "6" }, { "code": null, "e": 1726, "s": 1678, "text": " Code #3 : Determine total number of columns " }, { "code": null, "e": 1734, "s": 1726, "text": "Python3" }, { "code": "# importing openpyxl moduleimport openpyxl # Give the location of the filepath = \"C:\\\\Users\\\\Admin\\\\Desktop\\\\demo.xlsx\" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active # print total number of columnprint(sheet_obj.max_column)", "e": 2004, "s": 1734, "text": null }, { "code": null, "e": 2015, "s": 2004, "text": "Output : " }, { "code": null, "e": 2017, "s": 2015, "text": "4" }, { "code": null, "e": 2054, "s": 2017, "text": " Code #4 : Print all columns name " }, { "code": null, "e": 2062, "s": 2054, "text": "Python3" }, { "code": "# importing openpyxl moduleimport openpyxl # Give the location of the filepath = \"C:\\\\Users\\\\Admin\\\\Desktop\\\\demo.xlsx\" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.activemax_col = sheet_obj.max_column # Loop will print all columns namefor i in range(1, max_col + 1): cell_obj = sheet_obj.cell(row = 1, column = i) print(cell_obj.value)", "e": 2445, "s": 2062, "text": null }, { "code": null, "e": 2456, "s": 2445, "text": "Output : " }, { "code": null, "e": 2495, "s": 2456, "text": "STUDENT 'S NAME\nCOURSE\nBRANCH\nSEMESTER" }, { "code": null, "e": 2534, "s": 2495, "text": " Code #5 : Print first column value " }, { "code": null, "e": 2542, "s": 2534, "text": "Python3" }, { "code": "# importing openpyxl moduleimport openpyxl # Give the location of the filepath = \"C:\\\\Users\\\\Admin\\\\Desktop\\\\demo.xlsx\" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.activem_row = sheet_obj.max_row # Loop will print all values# of first columnfor i in range(1, m_row + 1): cell_obj = sheet_obj.cell(row = i, column = 1) print(cell_obj.value)", "e": 2929, "s": 2542, "text": null }, { "code": null, "e": 2940, "s": 2929, "text": "Output : " }, { "code": null, "e": 3013, "s": 2940, "text": "STUDENT 'S NAME\nANKIT RAI\nRAHUL RAI\nPRIYA RAI\nAISHWARYA\nHARSHITA JAISWAL" }, { "code": null, "e": 3056, "s": 3013, "text": " Code #6 : Print a particular row value " }, { "code": null, "e": 3064, "s": 3056, "text": "Python3" }, { "code": "# importing openpyxl moduleimport openpyxl # Give the location of the filepath = \"C:\\\\Users\\\\Admin\\\\Desktop\\\\demo.xlsx\" # workbook object is createdwb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active max_col = sheet_obj.max_column # Will print a particular row valuefor i in range(1, max_col + 1): cell_obj = sheet_obj.cell(row = 2, column = i) print(cell_obj.value, end = \" \")", "e": 3460, "s": 3064, "text": null }, { "code": null, "e": 3471, "s": 3460, "text": "Output : " }, { "code": null, "e": 3494, "s": 3471, "text": "ANKIT RAI B.TECH CSE 4" }, { "code": null, "e": 3513, "s": 3496, "text": "surinderdawra388" }, { "code": null, "e": 3528, "s": 3513, "text": "python-modules" }, { "code": null, "e": 3535, "s": 3528, "text": "Python" }, { "code": null, "e": 3551, "s": 3535, "text": "Python Programs" }, { "code": null, "e": 3649, "s": 3551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3691, "s": 3649, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3713, "s": 3691, "text": "Enumerate() in Python" }, { "code": null, "e": 3739, "s": 3713, "text": "Python String | replace()" }, { "code": null, "e": 3771, "s": 3739, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3800, "s": 3771, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3822, "s": 3800, "text": "Defaultdict in Python" }, { "code": null, "e": 3861, "s": 3822, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3899, "s": 3861, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3936, "s": 3899, "text": "Python Program for Fibonacci numbers" } ]
numpy.extract() in Python
09 Mar, 2022 The numpy.extract() function returns elements of input_array if they satisfy some specified condition. Syntax: numpy.extract(condition, array) Parameters : array : Input array. User apply conditions on input_array elements condition : [array_like]Condition on the basis of which user extract elements. Applying condition on input_array, if we print condition, it will return an array filled with either True or False. Array elements are extracted from the Indices having True value. Returns : Array elements that satisfy the condition. Python # Python Program illustrating# numpy.compress method import numpy as geek array = geek.arange(10).reshape(5, 2)print("Original array : \n", array) a = geek.mod(array, 4) !=0# This will show element status of satisfying conditionprint("\nArray Condition a : \n", a) # This will return elements that satisfy condition "a" conditionprint("\nElements that satisfy condition a : \n", geek.extract(a, array)) b = array - 4 == 1# This will show element status of satisfying conditionprint("\nArray Condition b : \n", b) # This will return elements that satisfy condition "b" conditionprint("\nElements that satisfy condition b : \n", geek.extract(b, array)) Output : Original array : [[0 1] [2 3] [4 5] [6 7] [8 9]] Array Condition a : [[False True] [ True True] [False True] [ True True] [False True]] Elements that satisfy condition a : [1 2 3 5 6 7 9] Array Condition b : [[False False] [False False] [False True] [False False] [False False]] Elements that satisfy condition b : [5] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.extract.html#numpy.extract Note : Also, these codes won’t run on online IDE’s. So please, run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Code_r nidhi_biet simmytarika5 vinayedula Python numpy-Sorting Searching Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2022" }, { "code": null, "e": 132, "s": 28, "text": "The numpy.extract() function returns elements of input_array if they satisfy some specified condition. " }, { "code": null, "e": 172, "s": 132, "text": "Syntax: numpy.extract(condition, array)" }, { "code": null, "e": 187, "s": 172, "text": "Parameters : " }, { "code": null, "e": 538, "s": 187, "text": "array : Input array. User apply conditions on input_array elements\ncondition : [array_like]Condition on the basis of which user extract elements. \n Applying condition on input_array, if we print condition, it will return an array\n filled with either True or False. Array elements are extracted from the Indices having \n True value." }, { "code": null, "e": 549, "s": 538, "text": "Returns : " }, { "code": null, "e": 592, "s": 549, "text": "Array elements that satisfy the condition." }, { "code": null, "e": 599, "s": 592, "text": "Python" }, { "code": "# Python Program illustrating# numpy.compress method import numpy as geek array = geek.arange(10).reshape(5, 2)print(\"Original array : \\n\", array) a = geek.mod(array, 4) !=0# This will show element status of satisfying conditionprint(\"\\nArray Condition a : \\n\", a) # This will return elements that satisfy condition \"a\" conditionprint(\"\\nElements that satisfy condition a : \\n\", geek.extract(a, array)) b = array - 4 == 1# This will show element status of satisfying conditionprint(\"\\nArray Condition b : \\n\", b) # This will return elements that satisfy condition \"b\" conditionprint(\"\\nElements that satisfy condition b : \\n\", geek.extract(b, array))", "e": 1254, "s": 599, "text": null }, { "code": null, "e": 1264, "s": 1254, "text": "Output : " }, { "code": null, "e": 1617, "s": 1264, "text": "Original array : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]\n [8 9]]\n\nArray Condition a : \n [[False True]\n [ True True]\n [False True]\n [ True True]\n [False True]]\n\nElements that satisfy condition a : \n [1 2 3 5 6 7 9]\n\nArray Condition b : \n [[False False]\n [False False]\n [False True]\n [False False]\n [False False]]\n\nElements that satisfy condition b : \n [5]" }, { "code": null, "e": 2255, "s": 1617, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.extract.html#numpy.extract Note : Also, these codes won’t run on online IDE’s. So please, run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2262, "s": 2255, "text": "Code_r" }, { "code": null, "e": 2273, "s": 2262, "text": "nidhi_biet" }, { "code": null, "e": 2286, "s": 2273, "text": "simmytarika5" }, { "code": null, "e": 2297, "s": 2286, "text": "vinayedula" }, { "code": null, "e": 2328, "s": 2297, "text": "Python numpy-Sorting Searching" }, { "code": null, "e": 2341, "s": 2328, "text": "Python-numpy" }, { "code": null, "e": 2348, "s": 2341, "text": "Python" }, { "code": null, "e": 2446, "s": 2348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2464, "s": 2446, "text": "Python Dictionary" }, { "code": null, "e": 2506, "s": 2464, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2528, "s": 2506, "text": "Enumerate() in Python" }, { "code": null, "e": 2563, "s": 2528, "text": "Read a file line by line in Python" }, { "code": null, "e": 2595, "s": 2563, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2624, "s": 2595, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2654, "s": 2624, "text": "Iterate over a list in Python" }, { "code": null, "e": 2681, "s": 2654, "text": "Python Classes and Objects" }, { "code": null, "e": 2717, "s": 2681, "text": "Convert integer to string in Python" } ]
C Program to multiply two matrices
26 Dec, 2021 Given two matrices, the task to multiply them. Matrices can either be square or rectangular. Examples: Input : mat1[][] = {{1, 2}, {3, 4}} mat2[][] = {{1, 1}, {1, 1}} Output : {{3, 3}, {7, 7}} Input : mat1[][] = {{2, 4}, {3, 4}} mat2[][] = {{1, 2}, {1, 3}} Output : {{6, 16}, {7, 18}} Multiplication of Square Matrices : The below program multiplies two square matrices of size 4*4, we can change N for different dimensions. C // C program to multiply two square matrices.#include <stdio.h>#define N 4 // This function multiplies mat1[][] and mat2[][],// and stores the result in res[][]void multiply(int mat1[][N], int mat2[][N], int res[][N]){ int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} int main(){ int mat1[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int res[N][N]; // To store result int i, j; multiply(mat1, mat2, res); printf("Result matrix is "); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", res[i][j]); printf(""); } return 0;} Result matrix is 10 10 10 10 20 20 20 20 30 30 30 30 40 40 40 40 Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication Auxiliary Space: O(n2) Multiplication of Rectangular Matrices : We use pointers in C to multiply to matrices. Please refer to the following post as a prerequisite of the code.How to pass a 2D array as a parameter in C? C // C program to multiply two rectangular matrices#include <stdio.h> // Multiplies two matrices mat1[][] and mat2[][]// and prints result.// (m1) x (m2) and (n1) x (n2) are dimensions// of given matrices.void multiply(int m1, int m2, int mat1[][m2], int n1, int n2, int mat2[][n2]){ int x, i, j; int res[m1][n2]; for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { *(*(res + i) + j) += *(*(mat1 + i) + x) * *(*(mat2 + x) + j); } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { printf("%d ", *(*(res + i) + j)); } printf(""); }} // Driver codeint main(){ int mat1[][2] = { { 2, 4 }, { 3, 4 } }; int mat2[][2] = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); return 0;} 6 16 7 18 Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication Auxiliary Space: O(m1 * n2) Please refer complete article on Program to multiply two matrices for more details! Paytm C Programs Mathematical Matrix School Programming Paytm Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Difference between break and continue statement in C Exit codes in C/C++ with Examples C Hello World Program Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Dec, 2021" }, { "code": null, "e": 121, "s": 28, "text": "Given two matrices, the task to multiply them. Matrices can either be square or rectangular." }, { "code": null, "e": 132, "s": 121, "text": "Examples: " }, { "code": null, "e": 442, "s": 132, "text": "Input : mat1[][] = {{1, 2}, \n {3, 4}}\n mat2[][] = {{1, 1}, \n {1, 1}}\nOutput : {{3, 3}, \n {7, 7}}\nInput : mat1[][] = {{2, 4}, \n {3, 4}}\n mat2[][] = {{1, 2}, \n {1, 3}} \nOutput : {{6, 16}, \n {7, 18}}" }, { "code": null, "e": 583, "s": 442, "text": "Multiplication of Square Matrices : The below program multiplies two square matrices of size 4*4, we can change N for different dimensions. " }, { "code": null, "e": 585, "s": 583, "text": "C" }, { "code": "// C program to multiply two square matrices.#include <stdio.h>#define N 4 // This function multiplies mat1[][] and mat2[][],// and stores the result in res[][]void multiply(int mat1[][N], int mat2[][N], int res[][N]){ int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { res[i][j] = 0; for (k = 0; k < N; k++) res[i][j] += mat1[i][k] * mat2[k][j]; } }} int main(){ int mat1[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int mat2[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int res[N][N]; // To store result int i, j; multiply(mat1, mat2, res); printf(\"Result matrix is \"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf(\"%d \", res[i][j]); printf(\"\"); } return 0;}", "e": 1588, "s": 585, "text": null }, { "code": null, "e": 1657, "s": 1588, "text": "Result matrix is \n10 10 10 10 \n20 20 20 20 \n30 30 30 30 \n40 40 40 40" }, { "code": null, "e": 1740, "s": 1657, "text": "Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication" }, { "code": null, "e": 1763, "s": 1740, "text": "Auxiliary Space: O(n2)" }, { "code": null, "e": 1960, "s": 1763, "text": "Multiplication of Rectangular Matrices : We use pointers in C to multiply to matrices. Please refer to the following post as a prerequisite of the code.How to pass a 2D array as a parameter in C? " }, { "code": null, "e": 1962, "s": 1960, "text": "C" }, { "code": "// C program to multiply two rectangular matrices#include <stdio.h> // Multiplies two matrices mat1[][] and mat2[][]// and prints result.// (m1) x (m2) and (n1) x (n2) are dimensions// of given matrices.void multiply(int m1, int m2, int mat1[][m2], int n1, int n2, int mat2[][n2]){ int x, i, j; int res[m1][n2]; for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { res[i][j] = 0; for (x = 0; x < m2; x++) { *(*(res + i) + j) += *(*(mat1 + i) + x) * *(*(mat2 + x) + j); } } } for (i = 0; i < m1; i++) { for (j = 0; j < n2; j++) { printf(\"%d \", *(*(res + i) + j)); } printf(\"\"); }} // Driver codeint main(){ int mat1[][2] = { { 2, 4 }, { 3, 4 } }; int mat2[][2] = { { 1, 2 }, { 1, 3 } }; int m1 = 2, m2 = 2, n1 = 2, n2 = 2; // Function call multiply(m1, m2, mat1, n1, n2, mat2); return 0;}", "e": 2972, "s": 1962, "text": null }, { "code": null, "e": 2983, "s": 2972, "text": "6 16 \n7 18" }, { "code": null, "e": 3066, "s": 2983, "text": "Time complexity: O(n3). It can be optimized using Strassen’s Matrix Multiplication" }, { "code": null, "e": 3094, "s": 3066, "text": "Auxiliary Space: O(m1 * n2)" }, { "code": null, "e": 3178, "s": 3094, "text": "Please refer complete article on Program to multiply two matrices for more details!" }, { "code": null, "e": 3184, "s": 3178, "text": "Paytm" }, { "code": null, "e": 3195, "s": 3184, "text": "C Programs" }, { "code": null, "e": 3208, "s": 3195, "text": "Mathematical" }, { "code": null, "e": 3215, "s": 3208, "text": "Matrix" }, { "code": null, "e": 3234, "s": 3215, "text": "School Programming" }, { "code": null, "e": 3240, "s": 3234, "text": "Paytm" }, { "code": null, "e": 3253, "s": 3240, "text": "Mathematical" }, { "code": null, "e": 3260, "s": 3253, "text": "Matrix" }, { "code": null, "e": 3358, "s": 3260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3399, "s": 3358, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 3430, "s": 3399, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 3483, "s": 3430, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 3517, "s": 3483, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 3539, "s": 3517, "text": "C Hello World Program" }, { "code": null, "e": 3569, "s": 3539, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 3612, "s": 3569, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3672, "s": 3612, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 3687, "s": 3672, "text": "C++ Data Types" } ]
How to Create Time-Table schedule using HTML ?
10 May, 2022 A Table is an arrangement of rows and columns. Anyone can create a table by knowing the basics of HTML(HyperText Markup Language). A table is defined by using <table> tag in HTML. Steps to Create a Table: Create a <html> tag.Create a table using the tags <table></table>.Create rows in the table using <tr>This is the row tag</tr>.Insert the data into rows using <td> Table Data</td> tags.Close the table tag. Close the html tag </html>. Create a <html> tag. Create a table using the tags <table></table>. Create rows in the table using <tr>This is the row tag</tr>. Insert the data into rows using <td> Table Data</td> tags. Close the table tag. Close the html tag </html>. This is the basic Time table created in HTML without the usage of font color and background colors. Example: html <!DOCTYPE html><html> <body> <h1>TIME TABLE</h1> <table border="5" cellspacing="0" align="center"> <!--<caption>Timetable</caption>--> <tr> <td align="center" height="50" width="100"><br> <b>Day/Period</b></br> </td> <td align="center" height="50" width="100"> <b>I<br>9:30-10:20</b> </td> <td align="center" height="50" width="100"> <b>II<br>10:20-11:10</b> </td> <td align="center" height="50" width="100"> <b>III<br>11:10-12:00</b> </td> <td align="center" height="50" width="100"> <b>12:00-12:40</b> </td> <td align="center" height="50" width="100"> <b>IV<br>12:40-1:30</b> </td> <td align="center" height="50" width="100"> <b>V<br>1:30-2:20</b> </td> <td align="center" height="50" width="100"> <b>VI<br>2:20-3:10</b> </td> <td align="center" height="50" width="100"> <b>VII<br>3:10-4:00</b> </td> </tr> <tr> <td align="center" height="50"> <b>Monday</b></td> <td align="center" height="50">Eng</td> <td align="center" height="50">Mat</td> <td align="center" height="50">Che</td> <td rowspan="6" align="center" height="50"> <h2>L<br>U<br>N<br>C<br>H</h2> </td> <td colspan="3" align="center" height="50">LAB</td> <td align="center" height="50">Phy</td> </tr> <tr> <td align="center" height="50"> <b>Tuesday</b> </td> <td colspan="3" align="center" height="50">LAB </td> <td align="center" height="50">Eng</td> <td align="center" height="50">Che</td> <td align="center" height="50">Mat</td> <td align="center" height="50">SPORTS</td> </tr> <tr> <td align="center" height="50"> <b>Wednesday</b> </td> <td align="center" height="50">Mat</td> <td align="center" height="50">phy</td> <td align="center" height="50">Eng</td> <td align="center" height="50">Che</td> <td colspan="3" align="center" height="50">LIBRARY </td> </tr> <tr> <td align="center" height="50"> <b>Thursday</b> </td> <td align="center" height="50">Phy</td> <td align="center" height="50">Eng</td> <td align="center" height="50">Che</td> <td colspan="3" align="center" height="50">LAB </td> <td align="center" height="50">Mat</td> </tr> <tr> <td align="center" height="50"> <b>Friday</b> </td> <td colspan="3" align="center" height="50">LAB </td> <td align="center" height="50">Mat</td> <td align="center" height="50">Che</td> <td align="center" height="50">Eng</td> <td align="center" height="50">Phy</td> </tr> <tr> <td align="center" height="50"> <b>Saturday</b> </td> <td align="center" height="50">Eng</td> <td align="center" height="50">Che</td> <td align="center" height="50">Mat</td> <td colspan="3" align="center" height="50">SEMINAR </td> <td align="center" height="50">SPORTS</td> </tr> </table></body> </html> Output: We can also add the styling elements such as font color, back ground color, back ground image, etc. to the above Time table. The attributes that can be added to table are: align: Aligns left, right and center.border: Sets the border of a table(table border width)bgcolor: Sets the background color for a cell or whole table.colspan: Sets the number of columns to be spanned.rowspan: Sets the number of columns to be spanned.cellspacing: Creates space between the cells.cellpadding: Creates space within the cells.background: Sets the table background with an image.width: Sets width of the table.height: Sets height of the table. align: Aligns left, right and center. border: Sets the border of a table(table border width) bgcolor: Sets the background color for a cell or whole table. colspan: Sets the number of columns to be spanned. rowspan: Sets the number of columns to be spanned. cellspacing: Creates space between the cells. cellpadding: Creates space within the cells. background: Sets the table background with an image. width: Sets width of the table. height: Sets height of the table. HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. hardikkoriintern CSS-Misc 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. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 54, "s": 26, "text": "\n10 May, 2022" }, { "code": null, "e": 234, "s": 54, "text": "A Table is an arrangement of rows and columns. Anyone can create a table by knowing the basics of HTML(HyperText Markup Language). A table is defined by using <table> tag in HTML." }, { "code": null, "e": 259, "s": 234, "text": "Steps to Create a Table:" }, { "code": null, "e": 492, "s": 259, "text": "Create a <html> tag.Create a table using the tags <table></table>.Create rows in the table using <tr>This is the row tag</tr>.Insert the data into rows using <td> Table Data</td> tags.Close the table tag. Close the html tag </html>." }, { "code": null, "e": 513, "s": 492, "text": "Create a <html> tag." }, { "code": null, "e": 560, "s": 513, "text": "Create a table using the tags <table></table>." }, { "code": null, "e": 621, "s": 560, "text": "Create rows in the table using <tr>This is the row tag</tr>." }, { "code": null, "e": 680, "s": 621, "text": "Insert the data into rows using <td> Table Data</td> tags." }, { "code": null, "e": 702, "s": 680, "text": "Close the table tag. " }, { "code": null, "e": 730, "s": 702, "text": "Close the html tag </html>." }, { "code": null, "e": 830, "s": 730, "text": "This is the basic Time table created in HTML without the usage of font color and background colors." }, { "code": null, "e": 840, "s": 830, "text": "Example: " }, { "code": null, "e": 845, "s": 840, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>TIME TABLE</h1> <table border=\"5\" cellspacing=\"0\" align=\"center\"> <!--<caption>Timetable</caption>--> <tr> <td align=\"center\" height=\"50\" width=\"100\"><br> <b>Day/Period</b></br> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>I<br>9:30-10:20</b> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>II<br>10:20-11:10</b> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>III<br>11:10-12:00</b> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>12:00-12:40</b> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>IV<br>12:40-1:30</b> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>V<br>1:30-2:20</b> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>VI<br>2:20-3:10</b> </td> <td align=\"center\" height=\"50\" width=\"100\"> <b>VII<br>3:10-4:00</b> </td> </tr> <tr> <td align=\"center\" height=\"50\"> <b>Monday</b></td> <td align=\"center\" height=\"50\">Eng</td> <td align=\"center\" height=\"50\">Mat</td> <td align=\"center\" height=\"50\">Che</td> <td rowspan=\"6\" align=\"center\" height=\"50\"> <h2>L<br>U<br>N<br>C<br>H</h2> </td> <td colspan=\"3\" align=\"center\" height=\"50\">LAB</td> <td align=\"center\" height=\"50\">Phy</td> </tr> <tr> <td align=\"center\" height=\"50\"> <b>Tuesday</b> </td> <td colspan=\"3\" align=\"center\" height=\"50\">LAB </td> <td align=\"center\" height=\"50\">Eng</td> <td align=\"center\" height=\"50\">Che</td> <td align=\"center\" height=\"50\">Mat</td> <td align=\"center\" height=\"50\">SPORTS</td> </tr> <tr> <td align=\"center\" height=\"50\"> <b>Wednesday</b> </td> <td align=\"center\" height=\"50\">Mat</td> <td align=\"center\" height=\"50\">phy</td> <td align=\"center\" height=\"50\">Eng</td> <td align=\"center\" height=\"50\">Che</td> <td colspan=\"3\" align=\"center\" height=\"50\">LIBRARY </td> </tr> <tr> <td align=\"center\" height=\"50\"> <b>Thursday</b> </td> <td align=\"center\" height=\"50\">Phy</td> <td align=\"center\" height=\"50\">Eng</td> <td align=\"center\" height=\"50\">Che</td> <td colspan=\"3\" align=\"center\" height=\"50\">LAB </td> <td align=\"center\" height=\"50\">Mat</td> </tr> <tr> <td align=\"center\" height=\"50\"> <b>Friday</b> </td> <td colspan=\"3\" align=\"center\" height=\"50\">LAB </td> <td align=\"center\" height=\"50\">Mat</td> <td align=\"center\" height=\"50\">Che</td> <td align=\"center\" height=\"50\">Eng</td> <td align=\"center\" height=\"50\">Phy</td> </tr> <tr> <td align=\"center\" height=\"50\"> <b>Saturday</b> </td> <td align=\"center\" height=\"50\">Eng</td> <td align=\"center\" height=\"50\">Che</td> <td align=\"center\" height=\"50\">Mat</td> <td colspan=\"3\" align=\"center\" height=\"50\">SEMINAR </td> <td align=\"center\" height=\"50\">SPORTS</td> </tr> </table></body> </html>", "e": 4740, "s": 845, "text": null }, { "code": null, "e": 4748, "s": 4740, "text": "Output:" }, { "code": null, "e": 4920, "s": 4748, "text": "We can also add the styling elements such as font color, back ground color, back ground image, etc. to the above Time table. The attributes that can be added to table are:" }, { "code": null, "e": 5378, "s": 4920, "text": "align: Aligns left, right and center.border: Sets the border of a table(table border width)bgcolor: Sets the background color for a cell or whole table.colspan: Sets the number of columns to be spanned.rowspan: Sets the number of columns to be spanned.cellspacing: Creates space between the cells.cellpadding: Creates space within the cells.background: Sets the table background with an image.width: Sets width of the table.height: Sets height of the table." }, { "code": null, "e": 5416, "s": 5378, "text": "align: Aligns left, right and center." }, { "code": null, "e": 5471, "s": 5416, "text": "border: Sets the border of a table(table border width)" }, { "code": null, "e": 5533, "s": 5471, "text": "bgcolor: Sets the background color for a cell or whole table." }, { "code": null, "e": 5584, "s": 5533, "text": "colspan: Sets the number of columns to be spanned." }, { "code": null, "e": 5635, "s": 5584, "text": "rowspan: Sets the number of columns to be spanned." }, { "code": null, "e": 5681, "s": 5635, "text": "cellspacing: Creates space between the cells." }, { "code": null, "e": 5726, "s": 5681, "text": "cellpadding: Creates space within the cells." }, { "code": null, "e": 5779, "s": 5726, "text": "background: Sets the table background with an image." }, { "code": null, "e": 5811, "s": 5779, "text": "width: Sets width of the table." }, { "code": null, "e": 5845, "s": 5811, "text": "height: Sets height of the table." }, { "code": null, "e": 6039, "s": 5845, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 6056, "s": 6039, "text": "hardikkoriintern" }, { "code": null, "e": 6065, "s": 6056, "text": "CSS-Misc" }, { "code": null, "e": 6075, "s": 6065, "text": "HTML-Misc" }, { "code": null, "e": 6079, "s": 6075, "text": "CSS" }, { "code": null, "e": 6084, "s": 6079, "text": "HTML" }, { "code": null, "e": 6101, "s": 6084, "text": "Web Technologies" }, { "code": null, "e": 6128, "s": 6101, "text": "Web technologies Questions" }, { "code": null, "e": 6133, "s": 6128, "text": "HTML" }, { "code": null, "e": 6231, "s": 6133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6268, "s": 6231, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 6307, "s": 6268, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 6346, "s": 6307, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 6410, "s": 6346, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 6471, "s": 6410, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 6495, "s": 6471, "text": "REST API (Introduction)" }, { "code": null, "e": 6548, "s": 6495, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 6608, "s": 6548, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 6669, "s": 6608, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Operator Precedence and Associativity in C
24 Feb, 2022 Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence.For example: Solve 10 + 20 * 30 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30 Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”. Operators Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub-expressions in absence of brackets For example: Solve 100 + 200 / 10 - 3 * 10 1) Associativity is only used when there are two or more operators of same precedence. The point to note is associativity doesn’t define the order in which operands of a single operator are evaluated. For example, consider the following program, associativity of the + operator is left to right, but it doesn’t mean f1() is always called before f2(). The output of the following program is in-fact compiler dependent. See this for details. C // Associativity is not used in the below program.// Output is compiler dependent. #include <stdio.h> int x = 0;int f1(){ x = 5; return x;}int f2() { x = 10; return x;}int main(){ int p = f1() + f2(); printf("%d ", x); return 0;} 2) All operators with the same precedence have same associativity This is necessary, otherwise, there won’t be any way for the compiler to decide evaluation order of expressions which have two operators of same precedence and different associativity. For example + and – have the same associativity.3) Precedence and associativity of postfix ++ and prefix ++ are different Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left. See this for examples.4) Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1. See this and this for more details. C #include <stdio.h>int main(){ int a; a = 1, 2, 3; // Evaluated as (a = 1), 2, 3 printf("%d", a); return 0;} 5) There is no chaining of comparison operators in C In Python, expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining doesn’t happen in C. For example consider the following program. The output of following program is “FALSE”. C #include <stdio.h>int main(){ int a = 10, b = 20, c = 30; // (c > b > a) is treated as ((c > b) > a), associativity of '>' // is left to right. Therefore the value becomes ((30 > 20) > 10) // which becomes (1 > 10) if (c > b > a) printf("TRUE"); else printf("FALSE"); return 0;} Please see the following precedence and associativity table for reference. Associativity It is good to know precedence and associativity rules, but the best thing is to use brackets, especially for less commonly used operators (operators other than +, -, *.. etc). Brackets increase the readability of the code as the reader doesn’t have to see the table to find out the order. sirraghavgupta vishal07das bhartik021 spsomarcayam C-Operators cpp-operator C Quiz cpp-operator Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C | Dynamic Memory Allocation | Question 5 C | Advanced Pointer | Question 9 C | File Handling | Question 5 C | Loops & Control Structure | Question 5 C | Advanced Pointer | Question 2 C | Storage Classes and Type Qualifiers | Question 9 C | Advanced Pointer | Question 3 C | Advanced Pointer | Question 4 C | Pointer Basics | Question 7 C | Advanced Pointer | Question 7
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Feb, 2022" }, { "code": null, "e": 210, "s": 52, "text": "Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence.For example: Solve " }, { "code": null, "e": 223, "s": 210, "text": "10 + 20 * 30" }, { "code": null, "e": 298, "s": 227, "text": "10 + 20 * 30 is calculated as 10 + (20 * 30)\nand not as (10 + 20) * 30" }, { "code": null, "e": 609, "s": 298, "text": "Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”. " }, { "code": null, "e": 765, "s": 611, "text": "Operators Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub-expressions in absence of brackets" }, { "code": null, "e": 786, "s": 765, "text": "For example: Solve " }, { "code": null, "e": 810, "s": 786, "text": "100 + 200 / 10 - 3 * 10" }, { "code": null, "e": 1253, "s": 812, "text": "1) Associativity is only used when there are two or more operators of same precedence. The point to note is associativity doesn’t define the order in which operands of a single operator are evaluated. For example, consider the following program, associativity of the + operator is left to right, but it doesn’t mean f1() is always called before f2(). The output of the following program is in-fact compiler dependent. See this for details. " }, { "code": null, "e": 1255, "s": 1253, "text": "C" }, { "code": "// Associativity is not used in the below program.// Output is compiler dependent. #include <stdio.h> int x = 0;int f1(){ x = 5; return x;}int f2() { x = 10; return x;}int main(){ int p = f1() + f2(); printf(\"%d \", x); return 0;}", "e": 1506, "s": 1255, "text": null }, { "code": null, "e": 2265, "s": 1506, "text": "2) All operators with the same precedence have same associativity This is necessary, otherwise, there won’t be any way for the compiler to decide evaluation order of expressions which have two operators of same precedence and different associativity. For example + and – have the same associativity.3) Precedence and associativity of postfix ++ and prefix ++ are different Precedence of postfix ++ is more than prefix ++, their associativity is also different. Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left. See this for examples.4) Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1. See this and this for more details. " }, { "code": null, "e": 2267, "s": 2265, "text": "C" }, { "code": "#include <stdio.h>int main(){ int a; a = 1, 2, 3; // Evaluated as (a = 1), 2, 3 printf(\"%d\", a); return 0;}", "e": 2387, "s": 2267, "text": null }, { "code": null, "e": 2650, "s": 2387, "text": "5) There is no chaining of comparison operators in C In Python, expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining doesn’t happen in C. For example consider the following program. The output of following program is “FALSE”. " }, { "code": null, "e": 2652, "s": 2650, "text": "C" }, { "code": "#include <stdio.h>int main(){ int a = 10, b = 20, c = 30; // (c > b > a) is treated as ((c > b) > a), associativity of '>' // is left to right. Therefore the value becomes ((30 > 20) > 10) // which becomes (1 > 10) if (c > b > a) printf(\"TRUE\"); else printf(\"FALSE\"); return 0;}", "e": 2968, "s": 2652, "text": null }, { "code": null, "e": 3049, "s": 2968, "text": "Please see the following precedence and associativity table for reference. " }, { "code": null, "e": 3067, "s": 3053, "text": "Associativity" }, { "code": null, "e": 3359, "s": 3069, "text": "It is good to know precedence and associativity rules, but the best thing is to use brackets, especially for less commonly used operators (operators other than +, -, *.. etc). Brackets increase the readability of the code as the reader doesn’t have to see the table to find out the order. " }, { "code": null, "e": 3376, "s": 3361, "text": "sirraghavgupta" }, { "code": null, "e": 3388, "s": 3376, "text": "vishal07das" }, { "code": null, "e": 3399, "s": 3388, "text": "bhartik021" }, { "code": null, "e": 3412, "s": 3399, "text": "spsomarcayam" }, { "code": null, "e": 3424, "s": 3412, "text": "C-Operators" }, { "code": null, "e": 3437, "s": 3424, "text": "cpp-operator" }, { "code": null, "e": 3444, "s": 3437, "text": "C Quiz" }, { "code": null, "e": 3457, "s": 3444, "text": "cpp-operator" }, { "code": null, "e": 3555, "s": 3457, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3598, "s": 3555, "text": "C | Dynamic Memory Allocation | Question 5" }, { "code": null, "e": 3632, "s": 3598, "text": "C | Advanced Pointer | Question 9" }, { "code": null, "e": 3663, "s": 3632, "text": "C | File Handling | Question 5" }, { "code": null, "e": 3706, "s": 3663, "text": "C | Loops & Control Structure | Question 5" }, { "code": null, "e": 3740, "s": 3706, "text": "C | Advanced Pointer | Question 2" }, { "code": null, "e": 3793, "s": 3740, "text": "C | Storage Classes and Type Qualifiers | Question 9" }, { "code": null, "e": 3827, "s": 3793, "text": "C | Advanced Pointer | Question 3" }, { "code": null, "e": 3861, "s": 3827, "text": "C | Advanced Pointer | Question 4" }, { "code": null, "e": 3893, "s": 3861, "text": "C | Pointer Basics | Question 7" } ]
numpy.reshape() in Python
06 Jul, 2022 The numpy.reshape() function shapes an array without changing the data of the array. Syntax: numpy.reshape(array, shape, order = 'C') Parameters : array : [array_like]Input array shape : [int or tuples of int] e.g. if we are arranging an array with 10 elements then shaping it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2) order : [C-contiguous, F-contiguous, A-contiguous; optional] C-contiguous order in memory(last index varies the fastest) C order means that operating row-rise on the array will be slightly quicker FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster. ‘A’ means to read / write the elements in Fortran-like index order if, array is Fortran contiguous in memory, C-like order otherwise Return Type: Array which is reshaped without changing the data. Example Python # Python Program illustrating# numpy.reshape() method import numpy as geek # array = geek.arrange(8)# The 'numpy' module has no attribute 'arrange'array1 = geek.arange(8)print("Original array : \n", array1) # shape array with 2 rows and 4 columnsarray2 = geek.arange(8).reshape(2, 4)print("\narray reshaped with 2 rows and 4 columns : \n", array2) # shape array with 4 rows and 2 columnsarray3 = geek.arange(8).reshape(4, 2)print("\narray reshaped with 4 rows and 2 columns : \n", array3) # Constructs 3D arrayarray4 = geek.arange(8).reshape(2, 2, 2)print("\nOriginal array reshaped to 3D : \n", array4) Output : Original array : [0 1 2 3 4 5 6 7] array reshaped with 2 rows and 4 columns : [[0 1 2 3] [4 5 6 7]] array reshaped with 4 rows and 2 columns : [[0 1] [2 3] [4 5] [6 7]] Original array reshaped to 3D : [[[0 1] [2 3]] [[4 5] [6 7]]] [[0 1 2 3] [4 5 6 7]] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html Note: These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. AditiGoyal1 saurabh1990aror jeetasitsarkar sooda367 knspavankumar subhajitghosh1997 vinayedula vasanth2754 simmytarika5 Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 139, "s": 54, "text": "The numpy.reshape() function shapes an array without changing the data of the array." }, { "code": null, "e": 147, "s": 139, "text": "Syntax:" }, { "code": null, "e": 188, "s": 147, "text": "numpy.reshape(array, shape, order = 'C')" }, { "code": null, "e": 202, "s": 188, "text": "Parameters : " }, { "code": null, "e": 937, "s": 202, "text": "array : [array_like]Input array\nshape : [int or tuples of int] e.g. if we are arranging an array with 10 elements then shaping\n it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2)\norder : [C-contiguous, F-contiguous, A-contiguous; optional] \n C-contiguous order in memory(last index varies the fastest)\n C order means that operating row-rise on the array will be slightly quicker\n FORTRAN-contiguous order in memory (first index varies the fastest).\n F order means that column-wise operations will be faster. \n ‘A’ means to read / write the elements in Fortran-like index order if,\n array is Fortran contiguous in memory, C-like order otherwise" }, { "code": null, "e": 951, "s": 937, "text": "Return Type: " }, { "code": null, "e": 1002, "s": 951, "text": "Array which is reshaped without changing the data." }, { "code": null, "e": 1010, "s": 1002, "text": "Example" }, { "code": null, "e": 1017, "s": 1010, "text": "Python" }, { "code": "# Python Program illustrating# numpy.reshape() method import numpy as geek # array = geek.arrange(8)# The 'numpy' module has no attribute 'arrange'array1 = geek.arange(8)print(\"Original array : \\n\", array1) # shape array with 2 rows and 4 columnsarray2 = geek.arange(8).reshape(2, 4)print(\"\\narray reshaped with 2 rows and 4 columns : \\n\", array2) # shape array with 4 rows and 2 columnsarray3 = geek.arange(8).reshape(4, 2)print(\"\\narray reshaped with 4 rows and 2 columns : \\n\", array3) # Constructs 3D arrayarray4 = geek.arange(8).reshape(2, 2, 2)print(\"\\nOriginal array reshaped to 3D : \\n\", array4)", "e": 1636, "s": 1017, "text": null }, { "code": null, "e": 1646, "s": 1636, "text": "Output : " }, { "code": null, "e": 1926, "s": 1646, "text": "Original array : \n [0 1 2 3 4 5 6 7]\n\narray reshaped with 2 rows and 4 columns : \n [[0 1 2 3]\n [4 5 6 7]]\n\narray reshaped with 4 rows and 2 columns : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]]\n\nOriginal array reshaped to 3D : \n [[[0 1]\n [2 3]]\n [[4 5]\n [6 7]]]\n \n \n [[0 1 2 3]\n [4 5 6 7]]" }, { "code": null, "e": 1940, "s": 1926, "text": "References : " }, { "code": null, "e": 2016, "s": 1940, "text": "https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html" }, { "code": null, "e": 2121, "s": 2016, "text": "Note: These codes won’t run on online IDE’s. So please, run them on your systems to explore the working." }, { "code": null, "e": 2421, "s": 2121, "text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2546, "s": 2421, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2558, "s": 2546, "text": "AditiGoyal1" }, { "code": null, "e": 2574, "s": 2558, "text": "saurabh1990aror" }, { "code": null, "e": 2589, "s": 2574, "text": "jeetasitsarkar" }, { "code": null, "e": 2598, "s": 2589, "text": "sooda367" }, { "code": null, "e": 2612, "s": 2598, "text": "knspavankumar" }, { "code": null, "e": 2630, "s": 2612, "text": "subhajitghosh1997" }, { "code": null, "e": 2641, "s": 2630, "text": "vinayedula" }, { "code": null, "e": 2653, "s": 2641, "text": "vasanth2754" }, { "code": null, "e": 2666, "s": 2653, "text": "simmytarika5" }, { "code": null, "e": 2697, "s": 2666, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2710, "s": 2697, "text": "Python-numpy" }, { "code": null, "e": 2717, "s": 2710, "text": "Python" } ]
What are non negative real numbers?
30 Nov, 2021 Algebra is a branch of mathematics that is concerned with the analysis of symbols which represent unknown quantities and constants which represent known quantities. The expressions of algebra are made up of terms and each term may consist of variables (an unknown value), coefficient, constants along with mathematical operations attached to them. The below-written article is a study of real numbers. The article briefly describes non-negative real numbers along with some sample questions for doubt clearance. Real numbers are the set of numbers that consists of both rational and irrational numbers. They can either count to be positive or negative. Generally, real numbers are denoted by the alphabetical symbol ‘R’. Some examples of real numbers are -1/2, -5, -11, -0.5, etc. The set of real numbers, whole numbers, rational numbers, and as well as irrational numbers can be expressed in the form of p/q. Answer: The set of positive real numbers which are greater than 0 (zero) are the non-negative real numbers. The statement can be written as, R ≥ 0 Which means the real numbers are either positive or zero. The set will include numbers like {0,1, 2, 3, 4, 5,...}. Question 1: Which numbers are not included in the set of real numbers? Answer: The imaginary numbers and the irrational numbers which can not be expressed in the form of p/q are not included in the set of real numbers. Question 2: Is zero included in non-negative real numbers? Answer: Yes, all the positive numbers along with zero are included in non-negative real numbers. Question 3: What are imaginary numbers? Answer: The complex numbers which are represented by letters and do not have a constant value are imaginary numbers. They are basically unreal numbers with no constant numerical value. Picked Maths MAQ School Learning School Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 377, "s": 28, "text": "Algebra is a branch of mathematics that is concerned with the analysis of symbols which represent unknown quantities and constants which represent known quantities. The expressions of algebra are made up of terms and each term may consist of variables (an unknown value), coefficient, constants along with mathematical operations attached to them. " }, { "code": null, "e": 541, "s": 377, "text": "The below-written article is a study of real numbers. The article briefly describes non-negative real numbers along with some sample questions for doubt clearance." }, { "code": null, "e": 939, "s": 541, "text": "Real numbers are the set of numbers that consists of both rational and irrational numbers. They can either count to be positive or negative. Generally, real numbers are denoted by the alphabetical symbol ‘R’. Some examples of real numbers are -1/2, -5, -11, -0.5, etc. The set of real numbers, whole numbers, rational numbers, and as well as irrational numbers can be expressed in the form of p/q." }, { "code": null, "e": 947, "s": 939, "text": "Answer:" }, { "code": null, "e": 1047, "s": 947, "text": "The set of positive real numbers which are greater than 0 (zero) are the non-negative real numbers." }, { "code": null, "e": 1080, "s": 1047, "text": "The statement can be written as," }, { "code": null, "e": 1086, "s": 1080, "text": "R ≥ 0" }, { "code": null, "e": 1201, "s": 1086, "text": "Which means the real numbers are either positive or zero. The set will include numbers like {0,1, 2, 3, 4, 5,...}." }, { "code": null, "e": 1272, "s": 1201, "text": "Question 1: Which numbers are not included in the set of real numbers?" }, { "code": null, "e": 1280, "s": 1272, "text": "Answer:" }, { "code": null, "e": 1420, "s": 1280, "text": "The imaginary numbers and the irrational numbers which can not be expressed in the form of p/q are not included in the set of real numbers." }, { "code": null, "e": 1479, "s": 1420, "text": "Question 2: Is zero included in non-negative real numbers?" }, { "code": null, "e": 1487, "s": 1479, "text": "Answer:" }, { "code": null, "e": 1576, "s": 1487, "text": "Yes, all the positive numbers along with zero are included in non-negative real numbers." }, { "code": null, "e": 1616, "s": 1576, "text": "Question 3: What are imaginary numbers?" }, { "code": null, "e": 1624, "s": 1616, "text": "Answer:" }, { "code": null, "e": 1801, "s": 1624, "text": "The complex numbers which are represented by letters and do not have a constant value are imaginary numbers. They are basically unreal numbers with no constant numerical value." }, { "code": null, "e": 1808, "s": 1801, "text": "Picked" }, { "code": null, "e": 1818, "s": 1808, "text": "Maths MAQ" }, { "code": null, "e": 1834, "s": 1818, "text": "School Learning" }, { "code": null, "e": 1853, "s": 1834, "text": "School Mathematics" } ]
How to View Data Stored in Shared Preferences in Android Studio?
24 May, 2021 Shared Preferences in Android is local storage where we can save our data using a key and value pair. It is generally used to store data in users’ devices. Shared Preferences is also used for session management in Android apps where we are using login functionality. In this article, we will take a look at how we can view the data store in Shared Preferences in Android Studio. We will be building a simple application in which we will be simply saving data in shared preferences using a simple EditText field. After that, we will see this data stored in this file in Android Studio. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/idNestedSV" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--Edit text for getting user input--> <EditText android:id="@+id/idEdtMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="50dp" android:layout_marginEnd="10dp" android:hint="Enter your message" /> <!--button for saving data--> <Button android:id="@+id/idBtnSaveData" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="40dp" android:layout_marginEnd="10dp" android:text="Save Data" android:textAllCaps="false" /> </LinearLayout> Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java package com.example.gfgpagination; import android.content.Context;import android.content.SharedPreferences;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // creating constant keys for shared preferences. public static final String SHARED_PREFS = "shared_prefs"; // key for storing email. public static final String MESSAGE_KEY = "message_key"; // variable for shared preferences. SharedPreferences sharedpreferences; // creating variables for our edit text and button. private EditText messageEdt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // getting the data which is stored in shared preferences. sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); // initializing our variables. messageEdt = findViewById(R.id.idEdtMessage); Button saveBtn = findViewById(R.id.idBtnSaveData); // adding on click listener for our button. saveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click we are checking if the entered data // by user is empty or not. String msg = messageEdt.getText().toString(); if (TextUtils.isEmpty(msg)) { // if the input is empty we are displaying a toast message. Toast.makeText(MainActivity.this, "Please enter your message", Toast.LENGTH_SHORT).show(); } else { // if the input is not empty we are calling a method to save // data to shared prefs. saveMessage(msg); } } }); } private void saveMessage(String msg) { SharedPreferences.Editor editor = sharedpreferences.edit(); // below lines will put values for // message in shared preferences. editor.putString(MESSAGE_KEY, msg); // to save our data with key and value. editor.apply(); // on below line we are displaying a toast message after adding data to shared prefs. Toast.makeText(this, "Message saved to Shared Preferences", Toast.LENGTH_SHORT).show(); // after that we are setting our edit text to empty messageEdt.setText(""); }} Now run your application and add some data in the edit text filed and click on the button to save data to shared preferences. You can get to see the process in the video below : Output: Step 4: View the data stored in shared preferences Now inside Android studio in the right bottom corner, you will get to see the option as Device File Explorer. Click on that option you will get to see the below screen. Inside this screen Navigate to data > data folder. Step 5: Opening the file containing shared preferences Now inside that check for your app’s package name. Click on the package name for your application. After that click on the shared_prefs folder and inside that open the shared_prefs.xml file. Now you will get to see the data which we stored in our shared preferences from our application. gabaa406 Android-Studio Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2021" }, { "code": null, "e": 408, "s": 28, "text": "Shared Preferences in Android is local storage where we can save our data using a key and value pair. It is generally used to store data in users’ devices. Shared Preferences is also used for session management in Android apps where we are using login functionality. In this article, we will take a look at how we can view the data store in Shared Preferences in Android Studio. " }, { "code": null, "e": 615, "s": 408, "text": "We will be building a simple application in which we will be simply saving data in shared preferences using a simple EditText field. After that, we will see this data stored in this file in Android Studio. " }, { "code": null, "e": 644, "s": 615, "text": "Step 1: Create a New Project" }, { "code": null, "e": 806, "s": 644, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 854, "s": 806, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 997, "s": 854, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1001, "s": 997, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/idNestedSV\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--Edit text for getting user input--> <EditText android:id=\"@+id/idEdtMessage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"50dp\" android:layout_marginEnd=\"10dp\" android:hint=\"Enter your message\" /> <!--button for saving data--> <Button android:id=\"@+id/idBtnSaveData\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"40dp\" android:layout_marginEnd=\"10dp\" android:text=\"Save Data\" android:textAllCaps=\"false\" /> </LinearLayout>", "e": 2065, "s": 1001, "text": null }, { "code": null, "e": 2117, "s": 2069, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 2309, "s": 2119, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2316, "s": 2311, "text": "Java" }, { "code": "package com.example.gfgpagination; import android.content.Context;import android.content.SharedPreferences;import android.os.Bundle;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // creating constant keys for shared preferences. public static final String SHARED_PREFS = \"shared_prefs\"; // key for storing email. public static final String MESSAGE_KEY = \"message_key\"; // variable for shared preferences. SharedPreferences sharedpreferences; // creating variables for our edit text and button. private EditText messageEdt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // getting the data which is stored in shared preferences. sharedpreferences = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE); // initializing our variables. messageEdt = findViewById(R.id.idEdtMessage); Button saveBtn = findViewById(R.id.idBtnSaveData); // adding on click listener for our button. saveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // inside on click we are checking if the entered data // by user is empty or not. String msg = messageEdt.getText().toString(); if (TextUtils.isEmpty(msg)) { // if the input is empty we are displaying a toast message. Toast.makeText(MainActivity.this, \"Please enter your message\", Toast.LENGTH_SHORT).show(); } else { // if the input is not empty we are calling a method to save // data to shared prefs. saveMessage(msg); } } }); } private void saveMessage(String msg) { SharedPreferences.Editor editor = sharedpreferences.edit(); // below lines will put values for // message in shared preferences. editor.putString(MESSAGE_KEY, msg); // to save our data with key and value. editor.apply(); // on below line we are displaying a toast message after adding data to shared prefs. Toast.makeText(this, \"Message saved to Shared Preferences\", Toast.LENGTH_SHORT).show(); // after that we are setting our edit text to empty messageEdt.setText(\"\"); }}", "e": 4928, "s": 2316, "text": null }, { "code": null, "e": 5112, "s": 4932, "text": "Now run your application and add some data in the edit text filed and click on the button to save data to shared preferences. You can get to see the process in the video below : " }, { "code": null, "e": 5122, "s": 5114, "text": "Output:" }, { "code": null, "e": 5177, "s": 5126, "text": "Step 4: View the data stored in shared preferences" }, { "code": null, "e": 5399, "s": 5179, "text": "Now inside Android studio in the right bottom corner, you will get to see the option as Device File Explorer. Click on that option you will get to see the below screen. Inside this screen Navigate to data > data folder." }, { "code": null, "e": 5459, "s": 5403, "text": "Step 5: Opening the file containing shared preferences " }, { "code": null, "e": 5754, "s": 5461, "text": "Now inside that check for your app’s package name. Click on the package name for your application. After that click on the shared_prefs folder and inside that open the shared_prefs.xml file. Now you will get to see the data which we stored in our shared preferences from our application. " }, { "code": null, "e": 5767, "s": 5758, "text": "gabaa406" }, { "code": null, "e": 5782, "s": 5767, "text": "Android-Studio" }, { "code": null, "e": 5790, "s": 5782, "text": "Android" }, { "code": null, "e": 5795, "s": 5790, "text": "Java" }, { "code": null, "e": 5800, "s": 5795, "text": "Java" }, { "code": null, "e": 5808, "s": 5800, "text": "Android" } ]
Does BERT Need Clean Data? Part 1: Data Cleaning. | by Alexander Bricken | Towards Data Science
If I describe Beyoncé’s Met Gala dress as a “hurricane”, does Hurricane Beyoncé become a thing? Not interested in cleaning data and just want to learn about the varying levels of data cleaning and how this affects BERT? Skip to Part 2. In this article, we use the Disaster Tweets Competition dataset on Kaggle to learn typical data science & machine learning practices, and more specifically about Natural Language Processing (NLP). By applying different methods of text cleaning and then running Bidirectional Encoder Representations from Transformers (BERT) to predict disasters from regular Tweets, we can compare models and see how much text cleaning affects accuracy. The end result is a top 50 submission in the competition at ~84%. What I hope you’ll learn about by reading this post includes the following: Exploring typical data science and machine learning practices by doing the following: importing, exploring, cleaning, and preparing data for machine learning. Applying specific NLP data preparation techniques such as feature engineering by creating meta-features and text cleaning using tokenisation. Applying BERT, a state-of-the-art language model for NLP, and figuring out what the best input for a BERT model is. The main objective of this project is to distinguish Tweets that indicate a world disaster, from those that include disaster words but are about other things outside of disasters. By doing so, we can understand the way input text affects BERT; specifically if the text being more or less cleaned makes a difference! It’s a difficult problem to solve because a lot of “disaster words” can often be used to describe daily life. For example, someone might describe shoes as “fire” which could confuse our model and result in us not picking up on actual fires that are happening around the world! So, without further ado, let’s dive into our method for tackling this exciting problem! To summarise, the project is broken down into four notebooks. The first one contains essential data preparation, and the the subsequent notebooks (2, 3, & 4) are all different methods for obtaining our predictions. Notebook 1 (Data Preparation): Importing LibrariesImporting DataData ExplorationData PreparationCalculating Meta-Features Importing Libraries Importing Data Data Exploration Data Preparation Calculating Meta-Features Notebook 2 (Meta-Feature CNN): Import Prepared DataNormalisationConvolutional Neural NetworkModel Evaluation & Submission Import Prepared Data Normalisation Convolutional Neural Network Model Evaluation & Submission Notebook 3 (Heavy Cleaning BERT): Import Prepared DataHeavy Clean Text With Regular ExpressionsLemmatizationTokenizationBERT ModellingModel Evaluation & Submission Import Prepared Data Heavy Clean Text With Regular Expressions Lemmatization Tokenization BERT Modelling Model Evaluation & Submission Notebook 4 (Light Cleaning BERT): Import Prepared DataLight Clean Text With Regular ExpressionsTokenizationBERT ModellingModel Evaluation & Submission Import Prepared Data Light Clean Text With Regular Expressions Tokenization BERT Modelling Model Evaluation & Submission Note: to see the full code for this project, see the GitHub repository here. To import our data, we write the following after downloading it and placing it in the correct directory: raw_test_data = pd.read_csv("../data/raw/test.csv") raw_train_data = pd.read_csv("../data/raw/train.csv") # check your output by just running the following: raw_train_data To explore our data, we use Pandas Profiling. This is a useful library for quickly getting a lot of descriptive statistics for the data we just imported. profile = ProfileReport(raw_train_data, title="Pandas Profiling Report")profile.to_notebook_iframe() This should load up a nice widget to explore within your Jupyter Notebook. It will provide you with some great descriptive statistics, such as this! Specifically, by using Pandas Profiling we can check through some essential features of the dataset: Class distribution of target variable in the train dataset. This is a 4342 (0), 3271 (1) split. This near equal separation is ok for training our model. Missing data. We see that the location and keyword columns contain missing data. This will be handled below. Cardinality. Our location values are particularly distinct. This is also discussed and handled below. From here, we can move on to our data preparation and deal with these problems we have highlighted! location and keyword contain null values, as demonstrated by the pandas profiling report. We handle this by first examining the number of null values deeper. foo = [(raw_train_data[['keyword', 'location']].isnull().sum().values, raw_test_data[['keyword', 'location']].isnull().sum().values)]out = np.concatenate(foo).ravel()null_counts = pd.DataFrame({"column": ['keyword', 'location', 'keyword', 'location'],"label": ['train', 'train', 'test', 'test'],"count": out})sns.catplot(x="column", y="count", data=null_counts, hue="label", kind="bar", height=8.27, aspect=11.7/8.27)plt.title('Number of Null Values')plt.show() Locations from Twitter are user-populated and are thus too arbitrary. There are too many unique values and no standardization of input. We can remove this feature. # drop location dataclean_train_data = raw_train_data.drop(columns="location")clean_test_data = raw_test_data.drop(columns="location") Keywords, on the other hand, are interesting to consider as a way of identifying disasters. This is because some keywords really are only used in a certain context. What do our keywords look like? We can output word clouds for our train and test datasets to examine this. We see that there is a good level of overlap between the keywords in treatment and control. Keyword is just one way of looking at the data, and if we just examine keywords there is not enough context to generate accurate predictions. Likewise, because we are implementing a BERT model which is all about the context of a word in a sentence, we don’t want to do anything like add the keyword to the end of the associated Tweet to increase the weight of that word. One clever way to leverage the keyword in our model is to convert the keyword into a sentiment score. This way, we have a value that acts as a meta-feature, without altering the important information contained in the Tweets. We do this by using NLTK library’s built-in, pre-trained sentiment analyzer called VADER (Valence Aware Dictionary and sEntiment Reasoner). # drop nan keyword rows in train datasetclean_train_data = clean_train_data.dropna(subset=['keyword']).reset_index(drop=True)# we fill none into the Nan Values of the test dataset, to give 0 sentimentclean_test_data['keyword'] = clean_test_data['keyword'].fillna("None")# collect keywords into arraystrain_keywords = clean_train_data['keyword']test_keywords = clean_test_data['keyword']# use sentiment analysersia = SentimentIntensityAnalyzer()train_keyword_sia = [sia.polarity_scores(i)['compound'] for i in train_keywords]test_keyword_sia = [sia.polarity_scores(i)['compound'] for i in test_keywords]# update keyword columnclean_train_data['keyword'] = train_keyword_siaclean_test_data['keyword'] = test_keyword_sia Finally, we check for duplicate data and the corresponding labels of the duplicates. # check for duplicates using groupbydf_nondupes = clean_train_data.groupby(['text']).nunique().sort_values(by='target', ascending=False)# find duplicates with target > 1 as a way of flagging if they are duplicatedf_dupes = df_nondupes[df_nondupes['target'] > 1]df_dupes.rename(columns={'id':'# of duplicates', 'target':'sum of target var'}) We see there are some duplicates. We don’t want any duplicates when training our model because it can bias our output. These would be particularly bad if they are labelled differently as well. From the output, we can see they are. This is extra confusing for the model to have something with the same features but a different label. If we iterate through these duplicates we can individually label them by hand so we keep the data. This is necessary because some of them are mislabeled as well as being duplicate. For example, there are three duplicates of the first row, but 2 of them have the target label 1, and one of them has target label 0. This is seen throughout the table via the difference in the the # of duplicates against the sum of target var, as seen above. # take index which is the texts themselvesdupe_text_list = df_dupes.index dupe_text_list = list(dupe_text_list)# manually make label list to iterateright_labels = [0,0,0,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0]# drop duplicates except for oneclean_train_data = clean_train_data.drop_duplicates(subset=['text'], keep='last').reset_index(drop=True)# relabel duplicate rowsfor i in range(len(dupe_text_list)):clean_train_data.loc[clean_train_data['text'] == dupe_text_list[i], 'target'] = right_labels[i] Now that our data is cleaned and prepared, we are on to the fun stuff! We need ways to learn more about our data and separate it out into additional features. By thinking about different variables we can generate that might help us distinguish disasters from non-disasters, we can train our model on more features. This will provide more visibility for our model. The best way to think about Tweets indicating disaster is that they are likely from higher quality sources that are more serious in nature. Thus, following stricter grammatical rules, fully reporting on the situation, and sharing links. The following meta-features, alongside our sentiment score calculated from the keywords column, will be proxies for the types of Tweets we are looking for (cherry-picked from here). num_hashtags - count of hashtags (#) (hypothesis (H): hashtags are used by normal users rather than new agencies) num_mentions - count of mentions (@) (H: more tags could be used by normal users rather than news agencies) num_words - count of words (H: more words in proper reports on Twitter than normal user tweets) num_stop_words - number of stop words (H: more stop words used via proper grammar from news agencies) num_urls - count of urls (H: urls shared by news agencies reporting disaster more often than not) avg_word_length - average character count in words (H: longer words that aren't abbreviated used by news agencies) num_chars - count of characters (H: more characters used in news agency tweets to report full story) num_punctuation - count of punctuations (H: more punctuation in news agency tweets following correct grammar) We use this code to construct these features. ### num_hashtags clean_train_data['num_hashtags'] = clean_train_data['text'].apply(lambda x: len([c for c in str(x) if c == '#'])) clean_test_data['num_hashtags'] = clean_test_data['text'].apply(lambda x: len([c for c in str(x) if c == '#'])) ### num_mentions clean_train_data['num_mentions'] = clean_train_data['text'].apply(lambda x: len([c for c in str(x) if c == '@'])) clean_test_data['num_mentions'] = clean_test_data['text'].apply(lambda x: len([c for c in str(x) if c == '@'])) ### num_words clean_train_data['num_words'] = clean_train_data['text'].apply(lambda x: len(str(x).split())) clean_test_data['num_words'] = clean_test_data['text'].apply(lambda x: len(str(x).split())) ### num_stop_words clean_train_data['num_stop_words'] = clean_train_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if w in STOPWORDS])) clean_test_data['num_stop_words'] = clean_test_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if w in STOPWORDS])) ### num_urls clean_train_data['num_urls'] = clean_train_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if 'http' in w or 'https' in w])) clean_test_data['num_urls'] = clean_test_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if 'http' in w or 'https' in w])) ### avg_word_length clean_train_data['avg_word_length'] = clean_train_data['text'].apply(lambda x: np.mean([len(w) for w in str(x).split()])) clean_test_data['avg_word_length'] = clean_test_data['text'].apply(lambda x: np.mean([len(w) for w in str(x).split()])) ### num_chars clean_train_data['num_chars'] = clean_train_data['text'].apply(lambda x: len(str(x))) clean_test_data['num_chars'] = clean_test_data['text'].apply(lambda x: len(str(x))) ### num_punctuation clean_train_data['num_punctuation'] = clean_train_data['text'].apply(lambda x: len([c for c in str(x) if c in string.punctuation])) clean_test_data['num_punctuation'] = clean_test_data['text'].apply(lambda x: len([c for c in str(x) if c in string.punctuation])) Remember, you can write clean_train_data and run the cell to see what our current pandas dataframe looks like! At this point, we have cleaned up the null variables from the dataset, calculated our meta-features, and gotten rid of mislabels and duplicates. We should save our datasets. We do this by using pickles! # we save these as picklesclean_train_data.to_pickle(“../data/pickles/clean_train_data.pkl”)clean_test_data.to_pickle(“../data/pickles/clean_test_data.pkl”) We can now do the following: Lightly clean the text data, without removing stopwords or other contextual pieces of the Tweets, and then run BERT. Heavily clean the text data, removing stopwords and other features that might confused the model, and then run BERT. Separate the meta-features from the text data and try running a CNN. From there, we can compare the accuracy of our models appropriately. Because BERT is a language model that utilises the structure of the sentence from both directions to connect every output element to every input element, and dynamically adjust weightings depending on this connection (this process is called attention), my hypothesis is that the lighter pre-processing will do better. This is because stopwords and other grammatical features of sentences may have a part to play in helping the model’s attention. In other words, BERT avoids assigning words fixed meanings independent of context. Rather, words are defined by their surroundings words. Where we generate predictions and learn more about BERT, machine learning, and how our data cleaning process affects outcomes, see Part 2 on Medium or Part 2 on my personal website. If you liked this article follow me on Twitter! I am building every day. Thanks for reading! A. Pai, What is tokenization?, (2020), Analytics Vidhya G. Evitan, NLP with Disaster Tweets: EDA, cleaning and BERT, (2019), Kaggle Notebooks G. Giacaglia, How Transformers Work, (2019), Towards Data Science I A. Khalid, Cleaning text data with Python, (2020), Towards Data Science J. Devlin and M-W. Chang, Google AI Blog: Open Sourcing BERT, (2018), Google Blog J. Zhu, SQuAD Model Comparison, (n.d.), Stanford University Kaggle Team, Natural Language Processing with Disaster Tweets (2021), Kaggle Competitions P. Prakash, An Explanatory Guide to BERT Tokenizer, (2021), Analytics Vidhya S. Theiler, Basics of using pre-trained GloVe Vectors, (2019), Analytics Vidhya Wikipedia, F-Score, (n.d.), Wikipedia
[ { "code": null, "e": 270, "s": 172, "text": "If I describe Beyoncé’s Met Gala dress as a “hurricane”, does Hurricane Beyoncé become a thing?" }, { "code": null, "e": 410, "s": 270, "text": "Not interested in cleaning data and just want to learn about the varying levels of data cleaning and how this affects BERT? Skip to Part 2." }, { "code": null, "e": 913, "s": 410, "text": "In this article, we use the Disaster Tweets Competition dataset on Kaggle to learn typical data science & machine learning practices, and more specifically about Natural Language Processing (NLP). By applying different methods of text cleaning and then running Bidirectional Encoder Representations from Transformers (BERT) to predict disasters from regular Tweets, we can compare models and see how much text cleaning affects accuracy. The end result is a top 50 submission in the competition at ~84%." }, { "code": null, "e": 989, "s": 913, "text": "What I hope you’ll learn about by reading this post includes the following:" }, { "code": null, "e": 1148, "s": 989, "text": "Exploring typical data science and machine learning practices by doing the following: importing, exploring, cleaning, and preparing data for machine learning." }, { "code": null, "e": 1290, "s": 1148, "text": "Applying specific NLP data preparation techniques such as feature engineering by creating meta-features and text cleaning using tokenisation." }, { "code": null, "e": 1406, "s": 1290, "text": "Applying BERT, a state-of-the-art language model for NLP, and figuring out what the best input for a BERT model is." }, { "code": null, "e": 1722, "s": 1406, "text": "The main objective of this project is to distinguish Tweets that indicate a world disaster, from those that include disaster words but are about other things outside of disasters. By doing so, we can understand the way input text affects BERT; specifically if the text being more or less cleaned makes a difference!" }, { "code": null, "e": 1999, "s": 1722, "text": "It’s a difficult problem to solve because a lot of “disaster words” can often be used to describe daily life. For example, someone might describe shoes as “fire” which could confuse our model and result in us not picking up on actual fires that are happening around the world!" }, { "code": null, "e": 2087, "s": 1999, "text": "So, without further ado, let’s dive into our method for tackling this exciting problem!" }, { "code": null, "e": 2302, "s": 2087, "text": "To summarise, the project is broken down into four notebooks. The first one contains essential data preparation, and the the subsequent notebooks (2, 3, & 4) are all different methods for obtaining our predictions." }, { "code": null, "e": 2333, "s": 2302, "text": "Notebook 1 (Data Preparation):" }, { "code": null, "e": 2424, "s": 2333, "text": "Importing LibrariesImporting DataData ExplorationData PreparationCalculating Meta-Features" }, { "code": null, "e": 2444, "s": 2424, "text": "Importing Libraries" }, { "code": null, "e": 2459, "s": 2444, "text": "Importing Data" }, { "code": null, "e": 2476, "s": 2459, "text": "Data Exploration" }, { "code": null, "e": 2493, "s": 2476, "text": "Data Preparation" }, { "code": null, "e": 2519, "s": 2493, "text": "Calculating Meta-Features" }, { "code": null, "e": 2550, "s": 2519, "text": "Notebook 2 (Meta-Feature CNN):" }, { "code": null, "e": 2641, "s": 2550, "text": "Import Prepared DataNormalisationConvolutional Neural NetworkModel Evaluation & Submission" }, { "code": null, "e": 2662, "s": 2641, "text": "Import Prepared Data" }, { "code": null, "e": 2676, "s": 2662, "text": "Normalisation" }, { "code": null, "e": 2705, "s": 2676, "text": "Convolutional Neural Network" }, { "code": null, "e": 2735, "s": 2705, "text": "Model Evaluation & Submission" }, { "code": null, "e": 2769, "s": 2735, "text": "Notebook 3 (Heavy Cleaning BERT):" }, { "code": null, "e": 2899, "s": 2769, "text": "Import Prepared DataHeavy Clean Text With Regular ExpressionsLemmatizationTokenizationBERT ModellingModel Evaluation & Submission" }, { "code": null, "e": 2920, "s": 2899, "text": "Import Prepared Data" }, { "code": null, "e": 2962, "s": 2920, "text": "Heavy Clean Text With Regular Expressions" }, { "code": null, "e": 2976, "s": 2962, "text": "Lemmatization" }, { "code": null, "e": 2989, "s": 2976, "text": "Tokenization" }, { "code": null, "e": 3004, "s": 2989, "text": "BERT Modelling" }, { "code": null, "e": 3034, "s": 3004, "text": "Model Evaluation & Submission" }, { "code": null, "e": 3068, "s": 3034, "text": "Notebook 4 (Light Cleaning BERT):" }, { "code": null, "e": 3185, "s": 3068, "text": "Import Prepared DataLight Clean Text With Regular ExpressionsTokenizationBERT ModellingModel Evaluation & Submission" }, { "code": null, "e": 3206, "s": 3185, "text": "Import Prepared Data" }, { "code": null, "e": 3248, "s": 3206, "text": "Light Clean Text With Regular Expressions" }, { "code": null, "e": 3261, "s": 3248, "text": "Tokenization" }, { "code": null, "e": 3276, "s": 3261, "text": "BERT Modelling" }, { "code": null, "e": 3306, "s": 3276, "text": "Model Evaluation & Submission" }, { "code": null, "e": 3383, "s": 3306, "text": "Note: to see the full code for this project, see the GitHub repository here." }, { "code": null, "e": 3488, "s": 3383, "text": "To import our data, we write the following after downloading it and placing it in the correct directory:" }, { "code": null, "e": 3661, "s": 3488, "text": "raw_test_data = pd.read_csv(\"../data/raw/test.csv\") raw_train_data = pd.read_csv(\"../data/raw/train.csv\") # check your output by just running the following: raw_train_data" }, { "code": null, "e": 3815, "s": 3661, "text": "To explore our data, we use Pandas Profiling. This is a useful library for quickly getting a lot of descriptive statistics for the data we just imported." }, { "code": null, "e": 3916, "s": 3815, "text": "profile = ProfileReport(raw_train_data, title=\"Pandas Profiling Report\")profile.to_notebook_iframe()" }, { "code": null, "e": 4065, "s": 3916, "text": "This should load up a nice widget to explore within your Jupyter Notebook. It will provide you with some great descriptive statistics, such as this!" }, { "code": null, "e": 4166, "s": 4065, "text": "Specifically, by using Pandas Profiling we can check through some essential features of the dataset:" }, { "code": null, "e": 4319, "s": 4166, "text": "Class distribution of target variable in the train dataset. This is a 4342 (0), 3271 (1) split. This near equal separation is ok for training our model." }, { "code": null, "e": 4428, "s": 4319, "text": "Missing data. We see that the location and keyword columns contain missing data. This will be handled below." }, { "code": null, "e": 4530, "s": 4428, "text": "Cardinality. Our location values are particularly distinct. This is also discussed and handled below." }, { "code": null, "e": 4630, "s": 4530, "text": "From here, we can move on to our data preparation and deal with these problems we have highlighted!" }, { "code": null, "e": 4720, "s": 4630, "text": "location and keyword contain null values, as demonstrated by the pandas profiling report." }, { "code": null, "e": 4788, "s": 4720, "text": "We handle this by first examining the number of null values deeper." }, { "code": null, "e": 5250, "s": 4788, "text": "foo = [(raw_train_data[['keyword', 'location']].isnull().sum().values, raw_test_data[['keyword', 'location']].isnull().sum().values)]out = np.concatenate(foo).ravel()null_counts = pd.DataFrame({\"column\": ['keyword', 'location', 'keyword', 'location'],\"label\": ['train', 'train', 'test', 'test'],\"count\": out})sns.catplot(x=\"column\", y=\"count\", data=null_counts, hue=\"label\", kind=\"bar\", height=8.27, aspect=11.7/8.27)plt.title('Number of Null Values')plt.show()" }, { "code": null, "e": 5414, "s": 5250, "text": "Locations from Twitter are user-populated and are thus too arbitrary. There are too many unique values and no standardization of input. We can remove this feature." }, { "code": null, "e": 5549, "s": 5414, "text": "# drop location dataclean_train_data = raw_train_data.drop(columns=\"location\")clean_test_data = raw_test_data.drop(columns=\"location\")" }, { "code": null, "e": 5714, "s": 5549, "text": "Keywords, on the other hand, are interesting to consider as a way of identifying disasters. This is because some keywords really are only used in a certain context." }, { "code": null, "e": 5821, "s": 5714, "text": "What do our keywords look like? We can output word clouds for our train and test datasets to examine this." }, { "code": null, "e": 6284, "s": 5821, "text": "We see that there is a good level of overlap between the keywords in treatment and control. Keyword is just one way of looking at the data, and if we just examine keywords there is not enough context to generate accurate predictions. Likewise, because we are implementing a BERT model which is all about the context of a word in a sentence, we don’t want to do anything like add the keyword to the end of the associated Tweet to increase the weight of that word." }, { "code": null, "e": 6649, "s": 6284, "text": "One clever way to leverage the keyword in our model is to convert the keyword into a sentiment score. This way, we have a value that acts as a meta-feature, without altering the important information contained in the Tweets. We do this by using NLTK library’s built-in, pre-trained sentiment analyzer called VADER (Valence Aware Dictionary and sEntiment Reasoner)." }, { "code": null, "e": 7367, "s": 6649, "text": "# drop nan keyword rows in train datasetclean_train_data = clean_train_data.dropna(subset=['keyword']).reset_index(drop=True)# we fill none into the Nan Values of the test dataset, to give 0 sentimentclean_test_data['keyword'] = clean_test_data['keyword'].fillna(\"None\")# collect keywords into arraystrain_keywords = clean_train_data['keyword']test_keywords = clean_test_data['keyword']# use sentiment analysersia = SentimentIntensityAnalyzer()train_keyword_sia = [sia.polarity_scores(i)['compound'] for i in train_keywords]test_keyword_sia = [sia.polarity_scores(i)['compound'] for i in test_keywords]# update keyword columnclean_train_data['keyword'] = train_keyword_siaclean_test_data['keyword'] = test_keyword_sia" }, { "code": null, "e": 7452, "s": 7367, "text": "Finally, we check for duplicate data and the corresponding labels of the duplicates." }, { "code": null, "e": 7793, "s": 7452, "text": "# check for duplicates using groupbydf_nondupes = clean_train_data.groupby(['text']).nunique().sort_values(by='target', ascending=False)# find duplicates with target > 1 as a way of flagging if they are duplicatedf_dupes = df_nondupes[df_nondupes['target'] > 1]df_dupes.rename(columns={'id':'# of duplicates', 'target':'sum of target var'})" }, { "code": null, "e": 8126, "s": 7793, "text": "We see there are some duplicates. We don’t want any duplicates when training our model because it can bias our output. These would be particularly bad if they are labelled differently as well. From the output, we can see they are. This is extra confusing for the model to have something with the same features but a different label." }, { "code": null, "e": 8566, "s": 8126, "text": "If we iterate through these duplicates we can individually label them by hand so we keep the data. This is necessary because some of them are mislabeled as well as being duplicate. For example, there are three duplicates of the first row, but 2 of them have the target label 1, and one of them has target label 0. This is seen throughout the table via the difference in the the # of duplicates against the sum of target var, as seen above." }, { "code": null, "e": 9058, "s": 8566, "text": "# take index which is the texts themselvesdupe_text_list = df_dupes.index dupe_text_list = list(dupe_text_list)# manually make label list to iterateright_labels = [0,0,0,1,0,0,1,0,1,1,1,0,1,1,1,0,0,0]# drop duplicates except for oneclean_train_data = clean_train_data.drop_duplicates(subset=['text'], keep='last').reset_index(drop=True)# relabel duplicate rowsfor i in range(len(dupe_text_list)):clean_train_data.loc[clean_train_data['text'] == dupe_text_list[i], 'target'] = right_labels[i]" }, { "code": null, "e": 9129, "s": 9058, "text": "Now that our data is cleaned and prepared, we are on to the fun stuff!" }, { "code": null, "e": 9841, "s": 9129, "text": "We need ways to learn more about our data and separate it out into additional features. By thinking about different variables we can generate that might help us distinguish disasters from non-disasters, we can train our model on more features. This will provide more visibility for our model. The best way to think about Tweets indicating disaster is that they are likely from higher quality sources that are more serious in nature. Thus, following stricter grammatical rules, fully reporting on the situation, and sharing links. The following meta-features, alongside our sentiment score calculated from the keywords column, will be proxies for the types of Tweets we are looking for (cherry-picked from here)." }, { "code": null, "e": 9955, "s": 9841, "text": "num_hashtags - count of hashtags (#) (hypothesis (H): hashtags are used by normal users rather than new agencies)" }, { "code": null, "e": 10063, "s": 9955, "text": "num_mentions - count of mentions (@) (H: more tags could be used by normal users rather than news agencies)" }, { "code": null, "e": 10159, "s": 10063, "text": "num_words - count of words (H: more words in proper reports on Twitter than normal user tweets)" }, { "code": null, "e": 10261, "s": 10159, "text": "num_stop_words - number of stop words (H: more stop words used via proper grammar from news agencies)" }, { "code": null, "e": 10359, "s": 10261, "text": "num_urls - count of urls (H: urls shared by news agencies reporting disaster more often than not)" }, { "code": null, "e": 10474, "s": 10359, "text": "avg_word_length - average character count in words (H: longer words that aren't abbreviated used by news agencies)" }, { "code": null, "e": 10575, "s": 10474, "text": "num_chars - count of characters (H: more characters used in news agency tweets to report full story)" }, { "code": null, "e": 10685, "s": 10575, "text": "num_punctuation - count of punctuations (H: more punctuation in news agency tweets following correct grammar)" }, { "code": null, "e": 10731, "s": 10685, "text": "We use this code to construct these features." }, { "code": null, "e": 12746, "s": 10731, "text": "### num_hashtags clean_train_data['num_hashtags'] = clean_train_data['text'].apply(lambda x: len([c for c in str(x) if c == '#'])) clean_test_data['num_hashtags'] = clean_test_data['text'].apply(lambda x: len([c for c in str(x) if c == '#'])) ### num_mentions clean_train_data['num_mentions'] = clean_train_data['text'].apply(lambda x: len([c for c in str(x) if c == '@'])) clean_test_data['num_mentions'] = clean_test_data['text'].apply(lambda x: len([c for c in str(x) if c == '@'])) ### num_words clean_train_data['num_words'] = clean_train_data['text'].apply(lambda x: len(str(x).split())) clean_test_data['num_words'] = clean_test_data['text'].apply(lambda x: len(str(x).split())) ### num_stop_words clean_train_data['num_stop_words'] = clean_train_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if w in STOPWORDS])) clean_test_data['num_stop_words'] = clean_test_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if w in STOPWORDS])) ### num_urls clean_train_data['num_urls'] = clean_train_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if 'http' in w or 'https' in w])) clean_test_data['num_urls'] = clean_test_data['text'].apply(lambda x: len([w for w in str(x).lower().split() if 'http' in w or 'https' in w])) ### avg_word_length clean_train_data['avg_word_length'] = clean_train_data['text'].apply(lambda x: np.mean([len(w) for w in str(x).split()])) clean_test_data['avg_word_length'] = clean_test_data['text'].apply(lambda x: np.mean([len(w) for w in str(x).split()])) ### num_chars clean_train_data['num_chars'] = clean_train_data['text'].apply(lambda x: len(str(x))) clean_test_data['num_chars'] = clean_test_data['text'].apply(lambda x: len(str(x))) ### num_punctuation clean_train_data['num_punctuation'] = clean_train_data['text'].apply(lambda x: len([c for c in str(x) if c in string.punctuation])) clean_test_data['num_punctuation'] = clean_test_data['text'].apply(lambda x: len([c for c in str(x) if c in string.punctuation]))" }, { "code": null, "e": 12857, "s": 12746, "text": "Remember, you can write clean_train_data and run the cell to see what our current pandas dataframe looks like!" }, { "code": null, "e": 13002, "s": 12857, "text": "At this point, we have cleaned up the null variables from the dataset, calculated our meta-features, and gotten rid of mislabels and duplicates." }, { "code": null, "e": 13060, "s": 13002, "text": "We should save our datasets. We do this by using pickles!" }, { "code": null, "e": 13217, "s": 13060, "text": "# we save these as picklesclean_train_data.to_pickle(“../data/pickles/clean_train_data.pkl”)clean_test_data.to_pickle(“../data/pickles/clean_test_data.pkl”)" }, { "code": null, "e": 13246, "s": 13217, "text": "We can now do the following:" }, { "code": null, "e": 13363, "s": 13246, "text": "Lightly clean the text data, without removing stopwords or other contextual pieces of the Tweets, and then run BERT." }, { "code": null, "e": 13480, "s": 13363, "text": "Heavily clean the text data, removing stopwords and other features that might confused the model, and then run BERT." }, { "code": null, "e": 13549, "s": 13480, "text": "Separate the meta-features from the text data and try running a CNN." }, { "code": null, "e": 14202, "s": 13549, "text": "From there, we can compare the accuracy of our models appropriately. Because BERT is a language model that utilises the structure of the sentence from both directions to connect every output element to every input element, and dynamically adjust weightings depending on this connection (this process is called attention), my hypothesis is that the lighter pre-processing will do better. This is because stopwords and other grammatical features of sentences may have a part to play in helping the model’s attention. In other words, BERT avoids assigning words fixed meanings independent of context. Rather, words are defined by their surroundings words." }, { "code": null, "e": 14384, "s": 14202, "text": "Where we generate predictions and learn more about BERT, machine learning, and how our data cleaning process affects outcomes, see Part 2 on Medium or Part 2 on my personal website." }, { "code": null, "e": 14457, "s": 14384, "text": "If you liked this article follow me on Twitter! I am building every day." }, { "code": null, "e": 14477, "s": 14457, "text": "Thanks for reading!" }, { "code": null, "e": 14533, "s": 14477, "text": "A. Pai, What is tokenization?, (2020), Analytics Vidhya" }, { "code": null, "e": 14619, "s": 14533, "text": "G. Evitan, NLP with Disaster Tweets: EDA, cleaning and BERT, (2019), Kaggle Notebooks" }, { "code": null, "e": 14685, "s": 14619, "text": "G. Giacaglia, How Transformers Work, (2019), Towards Data Science" }, { "code": null, "e": 14759, "s": 14685, "text": "I A. Khalid, Cleaning text data with Python, (2020), Towards Data Science" }, { "code": null, "e": 14841, "s": 14759, "text": "J. Devlin and M-W. Chang, Google AI Blog: Open Sourcing BERT, (2018), Google Blog" }, { "code": null, "e": 14901, "s": 14841, "text": "J. Zhu, SQuAD Model Comparison, (n.d.), Stanford University" }, { "code": null, "e": 14991, "s": 14901, "text": "Kaggle Team, Natural Language Processing with Disaster Tweets (2021), Kaggle Competitions" }, { "code": null, "e": 15068, "s": 14991, "text": "P. Prakash, An Explanatory Guide to BERT Tokenizer, (2021), Analytics Vidhya" }, { "code": null, "e": 15148, "s": 15068, "text": "S. Theiler, Basics of using pre-trained GloVe Vectors, (2019), Analytics Vidhya" } ]
How to remove certain characters from a string in C++?
In this section, we will see how to remove some characters from a string in C++. In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed. Input: A number string “ABAABACCABA” Output: “BBCCB” Step 1:Take a string Step 2: Remove each occurrence of a specific character using remove() function Step 3: Print the result. Step 4: End Live Demo #include<iostream> #include<algorithm> using namespace std; main() { string my_str = "ABAABACCABA"; cout << "Initial string: " << my_str << endl; my_str.erase(remove(my_str.begin(), my_str.end(), 'A'), my_str.end()); //remove A from string cout << "Final string: " << my_str; } Initial string: ABAABACCABA Final string: BBCCB
[ { "code": null, "e": 1330, "s": 1062, "text": "In this section, we will see how to remove some characters from a string in C++. In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed." }, { "code": null, "e": 1383, "s": 1330, "text": "Input: A number string “ABAABACCABA”\nOutput: “BBCCB”" }, { "code": null, "e": 1521, "s": 1383, "text": "Step 1:Take a string\nStep 2: Remove each occurrence of a specific character using remove() function\nStep 3: Print the result.\nStep 4: End" }, { "code": null, "e": 1532, "s": 1521, "text": " Live Demo" }, { "code": null, "e": 1825, "s": 1532, "text": "#include<iostream>\n#include<algorithm>\n\nusing namespace std;\nmain() {\n string my_str = \"ABAABACCABA\";\n\n cout << \"Initial string: \" << my_str << endl;\n\n my_str.erase(remove(my_str.begin(), my_str.end(), 'A'), my_str.end()); //remove A from string\n cout << \"Final string: \" << my_str;\n}" }, { "code": null, "e": 1873, "s": 1825, "text": "Initial string: ABAABACCABA\nFinal string: BBCCB" } ]
C++ Memory Library - dynamic_pointer_cast
It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*. Following is the declaration for std::dynamic_pointer_cast. template <class T, class U> shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept; template <class T, class U> shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept; sp − Its a shared pointer. It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*. noexcep − It doesn't throw any exceptions. In below example explains about std::dynamic_pointer_cast. #include <iostream> #include <memory> struct A { static const char* static_type; const char* dynamic_type; A() { dynamic_type = static_type; } }; struct B: A { static const char* static_type; B() { dynamic_type = static_type; } }; const char* A::static_type = "sample text A"; const char* B::static_type = "sample text B"; int main () { std::shared_ptr<A> foo; std::shared_ptr<B> bar; bar = std::make_shared<B>(); foo = std::dynamic_pointer_cast<A>(bar); std::cout << "foo's static type: " << foo->static_type << '\n'; std::cout << "foo's dynamic type: " << foo->dynamic_type << '\n'; std::cout << "bar's static type: " << bar->static_type << '\n'; std::cout << "bar's dynamic type: " << bar->dynamic_type << '\n'; return 0; } Let us compile and run the above program, this will produce the following result − foo's static type: sample text A foo's dynamic type: sample text B bar's static type: sample text B bar's dynamic type: sample text B Print Add Notes Bookmark this page
[ { "code": null, "e": 2704, "s": 2603, "text": "It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*." }, { "code": null, "e": 2764, "s": 2704, "text": "Following is the declaration for std::dynamic_pointer_cast." }, { "code": null, "e": 2865, "s": 2764, "text": "template <class T, class U>\n shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;" }, { "code": null, "e": 2966, "s": 2865, "text": "template <class T, class U>\n shared_ptr<T> dynamic_pointer_cast (const shared_ptr<U>& sp) noexcept;" }, { "code": null, "e": 2993, "s": 2966, "text": "sp − Its a shared pointer." }, { "code": null, "e": 3094, "s": 2993, "text": "It returns a copy of sp of the proper type with its stored pointer casted dynamically from U* to T*." }, { "code": null, "e": 3137, "s": 3094, "text": "noexcep − It doesn't throw any exceptions." }, { "code": null, "e": 3196, "s": 3137, "text": "In below example explains about std::dynamic_pointer_cast." }, { "code": null, "e": 3972, "s": 3196, "text": "#include <iostream>\n#include <memory>\n\nstruct A {\n static const char* static_type;\n const char* dynamic_type;\n A() { dynamic_type = static_type; }\n};\nstruct B: A {\n static const char* static_type;\n B() { dynamic_type = static_type; }\n};\n\nconst char* A::static_type = \"sample text A\";\nconst char* B::static_type = \"sample text B\";\n\nint main () {\n std::shared_ptr<A> foo;\n std::shared_ptr<B> bar;\n\n bar = std::make_shared<B>();\n\n foo = std::dynamic_pointer_cast<A>(bar);\n\n std::cout << \"foo's static type: \" << foo->static_type << '\\n';\n std::cout << \"foo's dynamic type: \" << foo->dynamic_type << '\\n';\n std::cout << \"bar's static type: \" << bar->static_type << '\\n';\n std::cout << \"bar's dynamic type: \" << bar->dynamic_type << '\\n';\n\n return 0;\n}" }, { "code": null, "e": 4055, "s": 3972, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 4190, "s": 4055, "text": "foo's static type: sample text A\nfoo's dynamic type: sample text B\nbar's static type: sample text B\nbar's dynamic type: sample text B\n" }, { "code": null, "e": 4197, "s": 4190, "text": " Print" }, { "code": null, "e": 4208, "s": 4197, "text": " Add Notes" } ]
fmt.Fprintf() Function in Golang With Examples - GeeksforGeeks
26 Feb, 2021 In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Fprintf() function in Go language formats according to a format specifier and writes to w. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. Syntax: func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) Parameters: This function accepts three parameters which are illustrated below- w io.Writer: This is the specified standard input or output. format string: This is containing some strings including verbs. a ...interface{}: This is the specified constant variables used in the code. Return Value: It returns the number of bytes written and any write error encountered.Example 1: C // Golang program to illustrate the usage of// fmt.Fprintf() function // Including the main packagepackage main // Importing fmt and osimport ( "fmt" "os") // Calling mainfunc main() { // Declaring some const variables const name, dept = "GeeksforGeeks", "CS" // Calling Fprintf() function which returns // "n" as the number of bytes written and // "err" as any error ancountered n, err := fmt.Fprintf(os.Stdout, "%s is a %s portal.\n", name, dept) // Printing the number of bytes written fmt.Print(n, " bytes written.\n") // Printing if any error encountered fmt.Print(err) } Output: GeeksforGeeks is a CS portal. 30 bytes written. <nil> Example 2: C // Golang program to illustrate the usage of// fmt.Fprintf() function // Including the main packagepackage main // Importing fmt and osimport ( "fmt" "os") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = 5, 10, 15 // Calling Fprintf() function which returns // "n" as the number of bytes written and // "err" as any error encountered n, err := fmt.Fprintf(os.Stdout, "%d + %d = %d.\n", num1, num2, num3) // Printing the number of bytes written fmt.Print(n, " bytes written.\n") // Printing if any error encountered fmt.Print(err) } Output: 5 + 10 = 15. 13 bytes written. <nil> arorakashish0911 Golang-fmt Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language Strings in Golang Time Durations in Golang How to Parse JSON in Golang? Structures in Golang Defer Keyword in Golang How to iterate over an Array using for loop in Golang? Loops in Go Language Rune in Golang Class and Object in Golang
[ { "code": null, "e": 25703, "s": 25675, "text": "\n26 Feb, 2021" }, { "code": null, "e": 26053, "s": 25703, "text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Fprintf() function in Go language formats according to a format specifier and writes to w. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. " }, { "code": null, "e": 26063, "s": 26053, "text": "Syntax: " }, { "code": null, "e": 26141, "s": 26063, "text": "func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)" }, { "code": null, "e": 26223, "s": 26141, "text": "Parameters: This function accepts three parameters which are illustrated below- " }, { "code": null, "e": 26284, "s": 26223, "text": "w io.Writer: This is the specified standard input or output." }, { "code": null, "e": 26348, "s": 26284, "text": "format string: This is containing some strings including verbs." }, { "code": null, "e": 26425, "s": 26348, "text": "a ...interface{}: This is the specified constant variables used in the code." }, { "code": null, "e": 26522, "s": 26425, "text": "Return Value: It returns the number of bytes written and any write error encountered.Example 1: " }, { "code": null, "e": 26524, "s": 26522, "text": "C" }, { "code": "// Golang program to illustrate the usage of// fmt.Fprintf() function // Including the main packagepackage main // Importing fmt and osimport ( \"fmt\" \"os\") // Calling mainfunc main() { // Declaring some const variables const name, dept = \"GeeksforGeeks\", \"CS\" // Calling Fprintf() function which returns // \"n\" as the number of bytes written and // \"err\" as any error ancountered n, err := fmt.Fprintf(os.Stdout, \"%s is a %s portal.\\n\", name, dept) // Printing the number of bytes written fmt.Print(n, \" bytes written.\\n\") // Printing if any error encountered fmt.Print(err) }", "e": 27188, "s": 26524, "text": null }, { "code": null, "e": 27198, "s": 27188, "text": "Output: " }, { "code": null, "e": 27252, "s": 27198, "text": "GeeksforGeeks is a CS portal.\n30 bytes written.\n<nil>" }, { "code": null, "e": 27264, "s": 27252, "text": "Example 2: " }, { "code": null, "e": 27266, "s": 27264, "text": "C" }, { "code": "// Golang program to illustrate the usage of// fmt.Fprintf() function // Including the main packagepackage main // Importing fmt and osimport ( \"fmt\" \"os\") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3 = 5, 10, 15 // Calling Fprintf() function which returns // \"n\" as the number of bytes written and // \"err\" as any error encountered n, err := fmt.Fprintf(os.Stdout, \"%d + %d = %d.\\n\", num1, num2, num3) // Printing the number of bytes written fmt.Print(n, \" bytes written.\\n\") // Printing if any error encountered fmt.Print(err) }", "e": 27915, "s": 27266, "text": null }, { "code": null, "e": 27925, "s": 27915, "text": "Output: " }, { "code": null, "e": 27962, "s": 27925, "text": "5 + 10 = 15.\n13 bytes written.\n<nil>" }, { "code": null, "e": 27981, "s": 27964, "text": "arorakashish0911" }, { "code": null, "e": 27992, "s": 27981, "text": "Golang-fmt" }, { "code": null, "e": 28004, "s": 27992, "text": "Go Language" }, { "code": null, "e": 28102, "s": 28004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28148, "s": 28102, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28166, "s": 28148, "text": "Strings in Golang" }, { "code": null, "e": 28191, "s": 28166, "text": "Time Durations in Golang" }, { "code": null, "e": 28220, "s": 28191, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 28241, "s": 28220, "text": "Structures in Golang" }, { "code": null, "e": 28265, "s": 28241, "text": "Defer Keyword in Golang" }, { "code": null, "e": 28320, "s": 28265, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 28341, "s": 28320, "text": "Loops in Go Language" }, { "code": null, "e": 28356, "s": 28341, "text": "Rune in Golang" } ]
Math.Truncate() Method in C#
The Math.Truncate() method in C# is used to compute an integral part of a number, which is Double or Decimal. public static decimal Truncate(decimal val1) public static double Truncate(double val2) Above, there are two syntaxes. The value val1 is the decimal number to truncate, whereas val2 is the double number to truncate. Let us now see an example to implement Math.Truncate() method − using System; public class Demo { public static void Main(){ Decimal val1 = 25.46467m; Decimal val2 = 45.9989m; Decimal val3 = 678.325m; Console.WriteLine(Math.Truncate(val1)); Console.WriteLine(Math.Truncate(val2)); Console.WriteLine(Math.Truncate(val3)); } } This will produce the following output − 25 45 678 Let us see another example to implement Math.Truncate() method − using System; public class Demo { public static void Main(){ Double val1 = 95.86467; Double val2 = 25.11; Double val3 = 878.325; Console.WriteLine(Math.Truncate(val1)); Console.WriteLine(Math.Truncate(val2)); Console.WriteLine(Math.Truncate(val3)); } } This will produce the following output − 95 25 878
[ { "code": null, "e": 1172, "s": 1062, "text": "The Math.Truncate() method in C# is used to compute an integral part of a number, which is Double or Decimal." }, { "code": null, "e": 1260, "s": 1172, "text": "public static decimal Truncate(decimal val1)\npublic static double Truncate(double val2)" }, { "code": null, "e": 1388, "s": 1260, "text": "Above, there are two syntaxes. The value val1 is the decimal number to truncate, whereas val2 is the double number to truncate." }, { "code": null, "e": 1452, "s": 1388, "text": "Let us now see an example to implement Math.Truncate() method −" }, { "code": null, "e": 1755, "s": 1452, "text": "using System;\npublic class Demo {\n public static void Main(){\n Decimal val1 = 25.46467m;\n Decimal val2 = 45.9989m;\n Decimal val3 = 678.325m;\n Console.WriteLine(Math.Truncate(val1));\n Console.WriteLine(Math.Truncate(val2));\n Console.WriteLine(Math.Truncate(val3));\n }\n}" }, { "code": null, "e": 1796, "s": 1755, "text": "This will produce the following output −" }, { "code": null, "e": 1806, "s": 1796, "text": "25\n45\n678" }, { "code": null, "e": 1871, "s": 1806, "text": "Let us see another example to implement Math.Truncate() method −" }, { "code": null, "e": 2166, "s": 1871, "text": "using System;\npublic class Demo {\n public static void Main(){\n Double val1 = 95.86467;\n Double val2 = 25.11;\n Double val3 = 878.325;\n Console.WriteLine(Math.Truncate(val1));\n Console.WriteLine(Math.Truncate(val2));\n Console.WriteLine(Math.Truncate(val3));\n }\n}" }, { "code": null, "e": 2207, "s": 2166, "text": "This will produce the following output −" }, { "code": null, "e": 2217, "s": 2207, "text": "95\n25\n878" } ]
Count number of digits after decimal on dividing a number in C++
We are given two integer numbers let’s say num1 and num2 and the task is to divide the num1 with num2 and calculate the count of digits after decimal on dividing these given numbers. Input − num1 = 2, num2 = 5 Output − count is 1 Explanation − when we divide 2 with 5 i.e. ? = 0.4, so digits after decimal is 1 therefore count is 1. Input − num1 = 2, num2 = 0 Output − Floating point exception (core dumped) Explanation − when we divide any number with 0 it will return an error and terminate the program abnormally. Input − num1 = 2, num2 = 3 Output − Infinite Explanation − when we divide 2 with 3 i.e. 2/3 = 0.666..., digits after decimal is infinite therefore we will print infinite. Input two variables let’s say, num1 and num2 Input two variables let’s say, num1 and num2 Create a variable count to store the count of decimal numbers and initializes it with 0 Create a variable count to store the count of decimal numbers and initializes it with 0 Create a variable um of unordered_map type Create a variable um of unordered_map type Start loop while num1%num2 != 0 Start loop while num1%num2 != 0 Inside the loop, set num1 with num1%num2 Inside the loop, set num1 with num1%num2 Increment the value of count by 1 Increment the value of count by 1 Check if um.find(num1) != um.end() then return -1 Check if um.find(num1) != um.end() then return -1 Outside the loop, return the value in count. Outside the loop, return the value in count. Print the result. Print the result. Live Demo #include <iostream> #include <unordered_map> using namespace std; int countdigits(int x, int y){ int result = 0; // result variable unordered_map<int, int> mymap; // calculating remainder while (x % y != 0){ x = x % y; result++; if (mymap.find(x) != mymap.end()){ return -1; } mymap[x] = 1; x = x * 10; } return result; } int main(){ int res = countdigits(2, 5); (res == -1)? cout << "count is Infinty" : cout <<"count is "<<res; return 0; } If we run the above code we will get the following output − count is 1
[ { "code": null, "e": 1245, "s": 1062, "text": "We are given two integer numbers let’s say num1 and num2 and the task is to divide the num1 with num2 and calculate the count of digits after decimal on dividing these given numbers." }, { "code": null, "e": 1292, "s": 1245, "text": "Input − num1 = 2, num2 = 5\nOutput − count is 1" }, { "code": null, "e": 1395, "s": 1292, "text": "Explanation − when we divide 2 with 5 i.e. ? = 0.4, so digits after decimal is 1 therefore count is 1." }, { "code": null, "e": 1470, "s": 1395, "text": "Input − num1 = 2, num2 = 0\nOutput − Floating point exception (core dumped)" }, { "code": null, "e": 1579, "s": 1470, "text": "Explanation − when we divide any number with 0 it will return an error and terminate the program abnormally." }, { "code": null, "e": 1624, "s": 1579, "text": "Input − num1 = 2, num2 = 3\nOutput − Infinite" }, { "code": null, "e": 1750, "s": 1624, "text": "Explanation − when we divide 2 with 3 i.e. 2/3 = 0.666..., digits after decimal is infinite therefore we will print infinite." }, { "code": null, "e": 1795, "s": 1750, "text": "Input two variables let’s say, num1 and num2" }, { "code": null, "e": 1840, "s": 1795, "text": "Input two variables let’s say, num1 and num2" }, { "code": null, "e": 1928, "s": 1840, "text": "Create a variable count to store the count of decimal numbers and initializes it with 0" }, { "code": null, "e": 2016, "s": 1928, "text": "Create a variable count to store the count of decimal numbers and initializes it with 0" }, { "code": null, "e": 2059, "s": 2016, "text": "Create a variable um of unordered_map type" }, { "code": null, "e": 2102, "s": 2059, "text": "Create a variable um of unordered_map type" }, { "code": null, "e": 2134, "s": 2102, "text": "Start loop while num1%num2 != 0" }, { "code": null, "e": 2166, "s": 2134, "text": "Start loop while num1%num2 != 0" }, { "code": null, "e": 2207, "s": 2166, "text": "Inside the loop, set num1 with num1%num2" }, { "code": null, "e": 2248, "s": 2207, "text": "Inside the loop, set num1 with num1%num2" }, { "code": null, "e": 2282, "s": 2248, "text": "Increment the value of count by 1" }, { "code": null, "e": 2316, "s": 2282, "text": "Increment the value of count by 1" }, { "code": null, "e": 2366, "s": 2316, "text": "Check if um.find(num1) != um.end() then return -1" }, { "code": null, "e": 2416, "s": 2366, "text": "Check if um.find(num1) != um.end() then return -1" }, { "code": null, "e": 2461, "s": 2416, "text": "Outside the loop, return the value in count." }, { "code": null, "e": 2506, "s": 2461, "text": "Outside the loop, return the value in count." }, { "code": null, "e": 2524, "s": 2506, "text": "Print the result." }, { "code": null, "e": 2542, "s": 2524, "text": "Print the result." }, { "code": null, "e": 2553, "s": 2542, "text": " Live Demo" }, { "code": null, "e": 3067, "s": 2553, "text": "#include <iostream>\n#include <unordered_map>\nusing namespace std;\nint countdigits(int x, int y){\n int result = 0; // result variable\n unordered_map<int, int> mymap;\n // calculating remainder\n while (x % y != 0){\n x = x % y;\n result++;\n if (mymap.find(x) != mymap.end()){\n return -1;\n }\n mymap[x] = 1;\n x = x * 10;\n }\n return result;\n}\nint main(){\n int res = countdigits(2, 5);\n (res == -1)? cout << \"count is Infinty\" : cout <<\"count is \"<<res;\n return 0;\n}" }, { "code": null, "e": 3127, "s": 3067, "text": "If we run the above code we will get the following output −" }, { "code": null, "e": 3138, "s": 3127, "text": "count is 1" } ]
Exploring the UN General Debates with Dynamic Topic Models | by Luke Lefebure | Towards Data Science
In this article, I introduce the intuition behind Dynamic Topic Models and demonstrate this method’s ability to discover evolving narratives in unstructured text through an application to a corpus of speeches. By reading, I hope you will pick up an understanding of Dynamic Topic Models, the problem that they try to solve, practical tips for working through a project with text data, and some insights about modern world affairs! If you would like to follow along with the code, you can find that here. Each fall, world leaders gather in New York to participate in the General Debate of the United Nations General Assembly. This year’s session concluded earlier this month after discussion around issues such as nuclear weapons and the war in Syria. Speeches given at the General Debate form a historical record of the issues that have commanded the attention of the international community. Hidden in this text data are insights about how the dialogue changes over time, and Dynamic Topic Models can help us quantitatively model that evolution. Topic modeling is a generic term used to describe the process of finding topics in a corpus of unstructured text. A popular method for this is Latent Dirichlet Allocation (LDA) which is a generative model that learns a predefined number of latent topics, where each topic is represented as a distribution over terms and each document as a distribution over topics. The article below does a good job at explaining the idea, and the Wikipedia page is also a good reference. medium.com LDA is a very powerful technique for the qualitative analysis of large corpora because of its highly interpretable topics, and it is also useful for dimensionality reduction as it transforms sparse document-term matrices into fixed low dimensional document-topic matrices. However, LDA ignores the temporal aspect present in many document collections. Consider a topic about US politics found by LDA in a corpus of news from the past decade. You might expect the most probable terms to be “congress”, “election”, “vote”, etc. However, the model treats a document from 2010 the same as one from 2018 with respect to the term probabilities, so it is unable to learn that the term “trump”, for example, was almost nonexistent in the context of politics until relatively recently. Dynamic Topic Models (DTMs), as presented by Blei and Lafferty here, address this problem by extending the idea of LDA to allow topic representations to evolve over fixed time intervals such as years. Specifically, the documents within each time slice are modeled with a topic model of the same dimension, and each topic in time slice t evolves from a corresponding topic in time slice t-1. The generative process of LDA remains more or less the same aside from the key difference that the overall topic distribution and the term distribution for each topic differ depending on the time slice. In particular, the parameters for these distributions “evolve” at each time slice by being drawn from distributions centered around the corresponding values from the previous time slice. The end result of this is a series of LDA-like topic models that are sequentially tied together. A topic learned by a DTM is thus a sequence of related distributions over terms. With this intuition, I move now to its application. A corpus consisting of speeches at the General Debate from 1970 through 2015 is hosted on Kaggle (7,507 in total). The dataset was originally released last year (see here for the paper) by researchers in the UK and Ireland who used it to study the position of different countries on various policy dimensions. Each speech is tagged with the year and session it was given and the ISO Alpha-3 code of the country that the speaker represented. A key observation in this dataset is that each of these speeches consists of discussion on a multitude of topics. If every speech contains discussion on poverty and terrorism, a topic model trained on entire speeches as documents in a bag of words representation will have no way of understanding that terms like “poverty” and “terrorism” should be representative of different topics. To counter this problem, I tokenize each speech into paragraphs and treat each paragraph as a separate document for the analysis. A simple rule based approach that looks for sentences separated by a newline character performs reasonably well on the task of paragraph tokenization for this dataset. After this step, the number of documents jumps from 7,507 (full speeches) to 283,593 (paragraphs). After expanding each speech into multiple documents, I word tokenize, normalize each term by lowercasing and lemmatizing, and trim low frequency terms from the vocabulary. The end result is a vocabulary of 7,054 terms and a bag of words representation for each document that can be used as input to the DTM. To determine the number of topics to use, I ran LDA on a few different time slices individually with different numbers of topics (10, 15, 20, 30) to get a feel for the problem. Through manual inspection, 15 seemed to produce the most interpretable topics, so that is what I settled on for the DTM. More experimentation and rigorous quantitative evaluation could certainly improve this. Using gensim's Python wrapper to the original DTM C++ code, inferring the parameters of a DTM is then straightforward, albeit slow. Inference took about 8 hours on an n1-standard-2 (2 vCPUs, 7.5 GB memory) instance on Google Cloud Platform. However, I ran on a single core, so this time can probably be cut down if you can get the parallelized version of the original C++ to compile. The model discovered very interpretable topics, and I examine a few in depth here. Specifically, I show for a few topics the top terms at a sample of time slices as well as plots of probabilities of notable terms over time. A complete list of the topics discovered by the model and their top terms can be found in the appendix at the end of this article. The Preamble of the UN Charter states: We the peoples of the United Nations determined ... to reaffirm faith in fundamental human rights, in the dignity and worth of the human person, in the equal rights of men and women and of nations large and small. It is no surprise then that human rights is a perennial topic at the General Debate and one that the model was able to discover. Despite the notion of gender equality appearing in the charter quoted above, the model shows that it still took quite some time for the terms “woman” and “gender” to really catch on. Also, note the rising use of “humankind” coupled with the decline of the use of “mankind”. Ever since the creation of modern Israel in 1948, there has been a constant debate in which the UN has been intimately involved around Arab-Israeli conflict, borders, settlements, and the treatment of the Palestinian people. In fact, there is an entire Wikipedia page devoted to the matter. The model shows an increasing focus on Gaza after its blockade by Israel and Egypt in 2007 and a constant discussion around Israeli settlements, a practice the UN has deemed illegal under international law. The rise of the term “two” is interesting, likely coming from growing discussion around a “two-state solution”. The discussion on Africa has evolved from its colonial past to independence, the era of apartheid, and finally the birth of new governments, elections, and democracy. The Cold War era brought an arms race between the US and the Soviet Union and subsequent discussion on disarmament. More recently, the focus has been on Iran. The Millennium Development Goals and the Sustainable Development Goals are UN initiatives introduced in 2000 and 2015 respectively to focus on solutions to issues such as poverty, education, and gender equality. This topic seems to have evolved from generic discussion around international development towards these structured programs. This exercise demonstrated how DTMs represent topics and this method’s incredible ability to discover narratives in unstructured text. Remember, the model did all of the above without any human intelligence! I could potentially improve the methods used by experimenting with a larger vocabulary size, different numbers of topics and evaluation thereof, phrase extraction (e.g. “human_rights” could be one token instead of having “human” and “rights” separately), and different stemmers or lemmatizers. Other methods that go beyond the bag of words representation and use word embeddings could be interesting to explore as well. One aspect of DTMs not leveraged here (but one that I would like to explore further) is the learned vector representations for documents. These are not only useful for computing similarity values between documents but also for finding representative documents for each topic. For example, it would be interesting to get all of the speeches from US representatives, pick out the most representative paragraphs for each time slice for, say, the human rights topic, and use those paragraphs to construct a thread on the evolution on US discourse on human rights. Overall, this turned out to be a fascinating exercise. If you would like to experiment yourself or dive deeper into the implementation details, all of the code for this analysis can again be found in the repo here. Thanks for following along, and if you have additional ideas or questions, please leave a comment! Below is a complete list of the topics discovered by the DTM. For each topic, the top ten terms from the 1975, 1995, and 2015 time slices are shown. Topic 0 1975 1995 20150 security council council1 non security security2 state member member3 council state reform4 cyprus general united5 international reform nation6 principle nation permanent7 nation united state8 aligned international must9 charter must internationalTopic 1 1975 1995 20150 sea international state1 law state island2 state island small3 latin drug international4 america country country5 resource small sids6 american america crime7 country caribbean caribbean8 conference convention developing9 international crime pacificTopic 2 1975 1995 20150 nuclear nuclear weapon1 disarmament weapon nuclear2 weapon treaty iran3 arm disarmament treaty4 state proliferation arm5 soviet non agreement6 treaty arm international7 power state use8 union test non9 race international chemicalTopic 3 1975 1995 20150 right right right1 human human human2 people respect law3 international democracy woman4 freedom people people5 principle international respect6 justice law freedom7 political freedom rule8 respect principle international9 must society peaceTopic 4 1975 1995 20150 economic economic economic1 international development country2 world international world3 country world global4 new new international5 order social social6 development political development7 relation country political8 political global crisis9 co cooperation newTopic 5 1975 1995 20150 east peace state1 middle east peace2 arab middle solution3 israel resolution palestinian4 peace people conflict5 palestinian palestinian international6 people israel syria7 right process people8 territory region east9 palestine agreement israelTopic 6 1975 1995 20150 republic united united1 people nation nation2 united peace international3 state operation peace4 nation keeping conflict5 government republic role6 korea conflict peacekeeping7 peaceful bosnia mission8 viet organization support9 country herzegovina republicTopic 7 1975 1995 20150 operation cooperation region1 co region cooperation2 peace regional international3 country european country4 europe country security5 security europe regional6 relation union european7 european state terrorism8 region security union9 detente stability effortTopic 8 1975 1995 20150 africa africa african1 south african country2 african country people3 people government government4 regime peace republic5 southern community africa6 namibia people political7 apartheid democratic community8 independence process democratic9 racist effort peaceTopic 9 1975 1995 20150 world war climate1 u world change2 one conflict world3 war cold global4 problem many threat5 time u challenge6 situation peace must7 peace one country8 power problem crisis9 conflict must conflictTopic 10 1975 1995 20150 people people people1 struggle country war2 country refugee year3 independence year world4 national state country5 force force one6 liberation war terrorist7 state government today8 imperialist one state9 imperialism life manyTopic 11 1975 1995 20150 nation nation nation1 united united united2 organization organization world3 world world u4 peace must must5 member international challenge6 international u future7 charter role peace8 role peace year9 state new globalTopic 12 1975 1995 20150 country country development1 developing development country2 development economic goal3 economic developing sustainable4 world trade per5 developed resource agenda6 resource economy cent7 trade financial poverty8 price programme health9 assistance assistance educationTopic 13 1975 1995 20150 mr general general1 general session assembly2 president assembly session3 assembly mr president4 session president mr5 delegation secretary like6 also also would7 like like secretary8 wish election also9 election wish sixtyTopic 14 1975 1995 20150 session conference development1 assembly development 20152 general general 703 conference year agenda4 resolution agenda year5 year assembly sustainable6 special meeting conference7 government summit pv8 united held 159 meeting last post
[ { "code": null, "e": 382, "s": 172, "text": "In this article, I introduce the intuition behind Dynamic Topic Models and demonstrate this method’s ability to discover evolving narratives in unstructured text through an application to a corpus of speeches." }, { "code": null, "e": 676, "s": 382, "text": "By reading, I hope you will pick up an understanding of Dynamic Topic Models, the problem that they try to solve, practical tips for working through a project with text data, and some insights about modern world affairs! If you would like to follow along with the code, you can find that here." }, { "code": null, "e": 923, "s": 676, "text": "Each fall, world leaders gather in New York to participate in the General Debate of the United Nations General Assembly. This year’s session concluded earlier this month after discussion around issues such as nuclear weapons and the war in Syria." }, { "code": null, "e": 1219, "s": 923, "text": "Speeches given at the General Debate form a historical record of the issues that have commanded the attention of the international community. Hidden in this text data are insights about how the dialogue changes over time, and Dynamic Topic Models can help us quantitatively model that evolution." }, { "code": null, "e": 1691, "s": 1219, "text": "Topic modeling is a generic term used to describe the process of finding topics in a corpus of unstructured text. A popular method for this is Latent Dirichlet Allocation (LDA) which is a generative model that learns a predefined number of latent topics, where each topic is represented as a distribution over terms and each document as a distribution over topics. The article below does a good job at explaining the idea, and the Wikipedia page is also a good reference." }, { "code": null, "e": 1702, "s": 1691, "text": "medium.com" }, { "code": null, "e": 2054, "s": 1702, "text": "LDA is a very powerful technique for the qualitative analysis of large corpora because of its highly interpretable topics, and it is also useful for dimensionality reduction as it transforms sparse document-term matrices into fixed low dimensional document-topic matrices. However, LDA ignores the temporal aspect present in many document collections." }, { "code": null, "e": 2479, "s": 2054, "text": "Consider a topic about US politics found by LDA in a corpus of news from the past decade. You might expect the most probable terms to be “congress”, “election”, “vote”, etc. However, the model treats a document from 2010 the same as one from 2018 with respect to the term probabilities, so it is unable to learn that the term “trump”, for example, was almost nonexistent in the context of politics until relatively recently." }, { "code": null, "e": 2870, "s": 2479, "text": "Dynamic Topic Models (DTMs), as presented by Blei and Lafferty here, address this problem by extending the idea of LDA to allow topic representations to evolve over fixed time intervals such as years. Specifically, the documents within each time slice are modeled with a topic model of the same dimension, and each topic in time slice t evolves from a corresponding topic in time slice t-1." }, { "code": null, "e": 3260, "s": 2870, "text": "The generative process of LDA remains more or less the same aside from the key difference that the overall topic distribution and the term distribution for each topic differ depending on the time slice. In particular, the parameters for these distributions “evolve” at each time slice by being drawn from distributions centered around the corresponding values from the previous time slice." }, { "code": null, "e": 3490, "s": 3260, "text": "The end result of this is a series of LDA-like topic models that are sequentially tied together. A topic learned by a DTM is thus a sequence of related distributions over terms. With this intuition, I move now to its application." }, { "code": null, "e": 3800, "s": 3490, "text": "A corpus consisting of speeches at the General Debate from 1970 through 2015 is hosted on Kaggle (7,507 in total). The dataset was originally released last year (see here for the paper) by researchers in the UK and Ireland who used it to study the position of different countries on various policy dimensions." }, { "code": null, "e": 3931, "s": 3800, "text": "Each speech is tagged with the year and session it was given and the ISO Alpha-3 code of the country that the speaker represented." }, { "code": null, "e": 4316, "s": 3931, "text": "A key observation in this dataset is that each of these speeches consists of discussion on a multitude of topics. If every speech contains discussion on poverty and terrorism, a topic model trained on entire speeches as documents in a bag of words representation will have no way of understanding that terms like “poverty” and “terrorism” should be representative of different topics." }, { "code": null, "e": 4713, "s": 4316, "text": "To counter this problem, I tokenize each speech into paragraphs and treat each paragraph as a separate document for the analysis. A simple rule based approach that looks for sentences separated by a newline character performs reasonably well on the task of paragraph tokenization for this dataset. After this step, the number of documents jumps from 7,507 (full speeches) to 283,593 (paragraphs)." }, { "code": null, "e": 5021, "s": 4713, "text": "After expanding each speech into multiple documents, I word tokenize, normalize each term by lowercasing and lemmatizing, and trim low frequency terms from the vocabulary. The end result is a vocabulary of 7,054 terms and a bag of words representation for each document that can be used as input to the DTM." }, { "code": null, "e": 5407, "s": 5021, "text": "To determine the number of topics to use, I ran LDA on a few different time slices individually with different numbers of topics (10, 15, 20, 30) to get a feel for the problem. Through manual inspection, 15 seemed to produce the most interpretable topics, so that is what I settled on for the DTM. More experimentation and rigorous quantitative evaluation could certainly improve this." }, { "code": null, "e": 5791, "s": 5407, "text": "Using gensim's Python wrapper to the original DTM C++ code, inferring the parameters of a DTM is then straightforward, albeit slow. Inference took about 8 hours on an n1-standard-2 (2 vCPUs, 7.5 GB memory) instance on Google Cloud Platform. However, I ran on a single core, so this time can probably be cut down if you can get the parallelized version of the original C++ to compile." }, { "code": null, "e": 6146, "s": 5791, "text": "The model discovered very interpretable topics, and I examine a few in depth here. Specifically, I show for a few topics the top terms at a sample of time slices as well as plots of probabilities of notable terms over time. A complete list of the topics discovered by the model and their top terms can be found in the appendix at the end of this article." }, { "code": null, "e": 6185, "s": 6146, "text": "The Preamble of the UN Charter states:" }, { "code": null, "e": 6399, "s": 6185, "text": "We the peoples of the United Nations determined ... to reaffirm faith in fundamental human rights, in the dignity and worth of the human person, in the equal rights of men and women and of nations large and small." }, { "code": null, "e": 6802, "s": 6399, "text": "It is no surprise then that human rights is a perennial topic at the General Debate and one that the model was able to discover. Despite the notion of gender equality appearing in the charter quoted above, the model shows that it still took quite some time for the terms “woman” and “gender” to really catch on. Also, note the rising use of “humankind” coupled with the decline of the use of “mankind”." }, { "code": null, "e": 7093, "s": 6802, "text": "Ever since the creation of modern Israel in 1948, there has been a constant debate in which the UN has been intimately involved around Arab-Israeli conflict, borders, settlements, and the treatment of the Palestinian people. In fact, there is an entire Wikipedia page devoted to the matter." }, { "code": null, "e": 7412, "s": 7093, "text": "The model shows an increasing focus on Gaza after its blockade by Israel and Egypt in 2007 and a constant discussion around Israeli settlements, a practice the UN has deemed illegal under international law. The rise of the term “two” is interesting, likely coming from growing discussion around a “two-state solution”." }, { "code": null, "e": 7579, "s": 7412, "text": "The discussion on Africa has evolved from its colonial past to independence, the era of apartheid, and finally the birth of new governments, elections, and democracy." }, { "code": null, "e": 7738, "s": 7579, "text": "The Cold War era brought an arms race between the US and the Soviet Union and subsequent discussion on disarmament. More recently, the focus has been on Iran." }, { "code": null, "e": 8075, "s": 7738, "text": "The Millennium Development Goals and the Sustainable Development Goals are UN initiatives introduced in 2000 and 2015 respectively to focus on solutions to issues such as poverty, education, and gender equality. This topic seems to have evolved from generic discussion around international development towards these structured programs." }, { "code": null, "e": 8283, "s": 8075, "text": "This exercise demonstrated how DTMs represent topics and this method’s incredible ability to discover narratives in unstructured text. Remember, the model did all of the above without any human intelligence!" }, { "code": null, "e": 8703, "s": 8283, "text": "I could potentially improve the methods used by experimenting with a larger vocabulary size, different numbers of topics and evaluation thereof, phrase extraction (e.g. “human_rights” could be one token instead of having “human” and “rights” separately), and different stemmers or lemmatizers. Other methods that go beyond the bag of words representation and use word embeddings could be interesting to explore as well." }, { "code": null, "e": 9263, "s": 8703, "text": "One aspect of DTMs not leveraged here (but one that I would like to explore further) is the learned vector representations for documents. These are not only useful for computing similarity values between documents but also for finding representative documents for each topic. For example, it would be interesting to get all of the speeches from US representatives, pick out the most representative paragraphs for each time slice for, say, the human rights topic, and use those paragraphs to construct a thread on the evolution on US discourse on human rights." }, { "code": null, "e": 9577, "s": 9263, "text": "Overall, this turned out to be a fascinating exercise. If you would like to experiment yourself or dive deeper into the implementation details, all of the code for this analysis can again be found in the repo here. Thanks for following along, and if you have additional ideas or questions, please leave a comment!" }, { "code": null, "e": 9726, "s": 9577, "text": "Below is a complete list of the topics discovered by the DTM. For each topic, the top ten terms from the 1975, 1995, and 2015 time slices are shown." } ]
MySQL truncate text with ellipsis?
You can truncate the text with ellipsis using LENGTH() with CASE statement. If your length is greater than 7 then truncate the text and add some number otherwise print the number as it is. To understand the above syntax, let us create a table. The query to create a table is as follows: mysql> create table TruncateText -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Number longtext, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.66 sec) Insert some records in the table using insert command. The query is as follows: mysql> insert into TruncateText(Number) values('64575868667687'); Query OK, 1 row affected (0.11 sec) mysql> insert into TruncateText(Number) values('7654332'); Query OK, 1 row affected (0.17 sec) mysql> insert into TruncateText(Number) values('25434656'); Query OK, 1 row affected (0.19 sec) mysql> insert into TruncateText(Number) values('6457586'); Query OK, 1 row affected (0.17 sec) mysql> insert into TruncateText(Number) values('958567686868675757574'); Query OK, 1 row affected (0.13 sec) mysql> insert into TruncateText(Number) values('374785868968787'); Query OK, 1 row affected (0.21 sec) mysql> insert into TruncateText(Number) values('58969678685858585858585858585'); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows: mysql> select *from TruncateText; The following is the output: +----+-------------------------------+ | Id | Number | +----+-------------------------------+ | 1 | 64575868667687 | | 2 | 7654332 | | 3 | 25434656 | | 4 | 6457586 | | 5 | 958567686868675757574 | | 6 | 374785868968787 | | 7 | 58969678685858585858585858585 | +----+-------------------------------+ 7 rows in set (0.00 sec) In the above sample output, we have some numbers whose length is greater than 7. If the length is greater than 7 then we need to append a numeric number after 7th digit. If the length is 7 or equal to 7 then there is no need to append the numeric number. The query is as follows: mysql> SELECT *, CASE WHEN LENGTH(Number) > 7 -> THEN CONCAT(SUBSTRING(Number, 1, 7), '99999999') -> ELSE Number END AS AddNumber -> FROM TruncateText; The following is the output: +----+-------------------------------+-----------------+ | Id | Number | AddNumber | +----+-------------------------------+-----------------+ | 1 | 64575868667687 | 645758699999999 | | 2 | 7654332 | 7654332 | | 3 | 25434656 | 254346599999999 | | 4 | 6457586 | 6457586 | | 5 | 958567686868675757574 | 958567699999999 | | 6 | 374785868968787 | 374785899999999 | | 7 | 58969678685858585858585858585 | 589696799999999 | +----+-------------------------------+-----------------+ 7 rows in set (0.00 sec) Look at the above sample output. If the number is greater than 7, then we have truncated all the values from the number and added a number '99999999' after 7th digit.
[ { "code": null, "e": 1251, "s": 1062, "text": "You can truncate the text with ellipsis using LENGTH() with CASE statement. If your length is greater than 7 then truncate the text and add some number otherwise print the number as it is." }, { "code": null, "e": 1349, "s": 1251, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows:" }, { "code": null, "e": 1519, "s": 1349, "text": "mysql> create table TruncateText\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Number longtext,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1599, "s": 1519, "text": "Insert some records in the table using insert command. The query is as follows:" }, { "code": null, "e": 2316, "s": 1599, "text": "mysql> insert into TruncateText(Number) values('64575868667687');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into TruncateText(Number) values('7654332');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into TruncateText(Number) values('25434656');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into TruncateText(Number) values('6457586');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into TruncateText(Number) values('958567686868675757574');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into TruncateText(Number) values('374785868968787');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into TruncateText(Number) values('58969678685858585858585858585');\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 2400, "s": 2316, "text": "Display all records from the table using select statement. The query is as follows:" }, { "code": null, "e": 2434, "s": 2400, "text": "mysql> select *from TruncateText;" }, { "code": null, "e": 2463, "s": 2434, "text": "The following is the output:" }, { "code": null, "e": 2917, "s": 2463, "text": "+----+-------------------------------+\n| Id | Number |\n+----+-------------------------------+\n| 1 | 64575868667687 |\n| 2 | 7654332 |\n| 3 | 25434656 |\n| 4 | 6457586 |\n| 5 | 958567686868675757574 |\n| 6 | 374785868968787 |\n| 7 | 58969678685858585858585858585 |\n+----+-------------------------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3172, "s": 2917, "text": "In the above sample output, we have some numbers whose length is greater than 7. If the length is greater than 7 then we need to append a numeric number after 7th digit. If the length is 7 or equal to 7 then there is no need to append the numeric number." }, { "code": null, "e": 3197, "s": 3172, "text": "The query is as follows:" }, { "code": null, "e": 3358, "s": 3197, "text": "mysql> SELECT *, CASE WHEN LENGTH(Number) > 7\n -> THEN CONCAT(SUBSTRING(Number, 1, 7), '99999999')\n -> ELSE Number END AS AddNumber\n -> FROM TruncateText;" }, { "code": null, "e": 3387, "s": 3358, "text": "The following is the output:" }, { "code": null, "e": 4039, "s": 3387, "text": "+----+-------------------------------+-----------------+\n| Id | Number | AddNumber |\n+----+-------------------------------+-----------------+\n| 1 | 64575868667687 | 645758699999999 |\n| 2 | 7654332 | 7654332 |\n| 3 | 25434656 | 254346599999999 |\n| 4 | 6457586 | 6457586 |\n| 5 | 958567686868675757574 | 958567699999999 |\n| 6 | 374785868968787 | 374785899999999 |\n| 7 | 58969678685858585858585858585 | 589696799999999 |\n+----+-------------------------------+-----------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 4206, "s": 4039, "text": "Look at the above sample output. If the number is greater than 7, then we have truncated all the values from the number and added a number '99999999' after 7th digit." } ]
Divide array in two Subsets such that sum of square of sum of both subsets is maximum - GeeksforGeeks
21 Apr, 2021 Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.Examples: Input: arr[] = {1, 2, 3} Output: 26 Explanation: Sum of Subset Pairs are as follows (1)2 + (2 + 3)2 = 26 (2)2 + (1 + 3)2 = 20 (3)2 + (1 + 2)2 = 18 Maximum among these is 26, Therefore the required sum is 26Input: arr[] = {7, 2, 13, 4, 25, 8} Output: 2845 Approach: The task is to maximize the sum of a2 + b2 where a and b are the sum of the two subsets and a + b = C (constant), i.e., the sum of the entire array. The maximum sum can be achieved by sorting the array and dividing the first N/2 – 1 smaller elements in one subset and the rest N/2 + 1 elements in the other subset. In this way, the sum can be maximized while keeping the difference in size at most 1.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the maximum sum of the// square of the sum of two subsets of an arrayint maxSquareSubsetSum(int* A, int N){ // Initialize variables to store // the sum of subsets int sub1 = 0, sub2 = 0; // Sorting the array sort(A, A + N); // Loop through the array for (int i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2;} // Driver codeint main(){ int arr[] = { 7, 2, 13, 4, 25, 8 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxSquareSubsetSum(arr, N); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum sum of the // square of the sum of two subsets of an array static int maxSquareSubsetSum(int []A, int N) { // Initialize variables to store // the sum of subsets int sub1 = 0, sub2 = 0; // Sorting the array Arrays.sort(A); // Loop through the array for (int i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; } // Driver code public static void main (String[] args) { int arr[] = { 7, 2, 13, 4, 25, 8 }; int N = arr.length; System.out.println(maxSquareSubsetSum(arr, N)); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to return the maximum sum of the# square of the sum of two subsets of an arraydef maxSquareSubsetSum(A, N) : # Initialize variables to store # the sum of subsets sub1 = 0; sub2 = 0; # Sorting the array A.sort(); # Loop through the array for i in range(N) : # Sum of the first subset if (i < (N // 2) - 1) : sub1 += A[i]; # Sum of the second subset else : sub2 += A[i]; # Return the maximum sum of # the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; # Driver codeif __name__ == "__main__" : arr = [ 7, 2, 13, 4, 25, 8 ]; N = len(arr); print(maxSquareSubsetSum(arr, N)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the maximum sum of the // square of the sum of two subsets of an array static int maxSquareSubsetSum(int []A, int N) { // Initialize variables to store // the sum of subsets int sub1 = 0, sub2 = 0; // Sorting the array Array.Sort(A); // Loop through the array for (int i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; } // Driver code public static void Main() { int []arr = { 7, 2, 13, 4, 25, 8 }; int N = arr.Length; Console.WriteLine(maxSquareSubsetSum(arr, N)); }} // This code is contributed by AnkitRai01 <script>// javascript implementation of the approach// Creating the bblSort function function bblSort(arr){ for(var i = 0; i < arr.length; i++){ // Last i elements are already in place for(var j = 0; j < ( arr.length - i -1 ); j++){ // Checking if the item at present iteration // is greater than the next iteration if(arr[j] > arr[j+1]){ // If the condition is true then swap them var temp = arr[j] arr[j] = arr[j + 1] arr[j+1] = temp } } } // return the sorted array return arr;} // Function to return the maximum sum of the // square of the sum of two subsets of an array function maxSquareSubsetSum(A , N) { // Initialize variables to store // the sum of subsets var sub1 = 0, sub2 = 0; // Sorting the array A = bblSort(A); // Loop through the array for (i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; } // Driver code var arr = [ 7, 2, 13, 4, 25, 8 ]; var N = arr.length; document.write(maxSquareSubsetSum(arr, N)); // This code is contributed by todaysgaurav</script> 2845 Time Complexity: O(N*log(N)) ankthon todaysgaurav subset Technical Scripter 2019 Arrays Mathematical Arrays Mathematical subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Window Sliding Technique Trapping Rain Water Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space 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": "\n21 Apr, 2021" }, { "code": null, "e": 25033, "s": 24796, "text": "Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.Examples: " }, { "code": null, "e": 25290, "s": 25033, "text": "Input: arr[] = {1, 2, 3} Output: 26 Explanation: Sum of Subset Pairs are as follows (1)2 + (2 + 3)2 = 26 (2)2 + (1 + 3)2 = 20 (3)2 + (1 + 2)2 = 18 Maximum among these is 26, Therefore the required sum is 26Input: arr[] = {7, 2, 13, 4, 25, 8} Output: 2845 " }, { "code": null, "e": 25755, "s": 25292, "text": "Approach: The task is to maximize the sum of a2 + b2 where a and b are the sum of the two subsets and a + b = C (constant), i.e., the sum of the entire array. The maximum sum can be achieved by sorting the array and dividing the first N/2 – 1 smaller elements in one subset and the rest N/2 + 1 elements in the other subset. In this way, the sum can be maximized while keeping the difference in size at most 1.Below is the implementation of the above approach: " }, { "code": null, "e": 25759, "s": 25755, "text": "C++" }, { "code": null, "e": 25764, "s": 25759, "text": "Java" }, { "code": null, "e": 25772, "s": 25764, "text": "Python3" }, { "code": null, "e": 25775, "s": 25772, "text": "C#" }, { "code": null, "e": 25786, "s": 25775, "text": "Javascript" }, { "code": "// C++ implementation of the approach #include <bits/stdc++.h>using namespace std; // Function to return the maximum sum of the// square of the sum of two subsets of an arrayint maxSquareSubsetSum(int* A, int N){ // Initialize variables to store // the sum of subsets int sub1 = 0, sub2 = 0; // Sorting the array sort(A, A + N); // Loop through the array for (int i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2;} // Driver codeint main(){ int arr[] = { 7, 2, 13, 4, 25, 8 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxSquareSubsetSum(arr, N); return 0;}", "e": 26631, "s": 25786, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the maximum sum of the // square of the sum of two subsets of an array static int maxSquareSubsetSum(int []A, int N) { // Initialize variables to store // the sum of subsets int sub1 = 0, sub2 = 0; // Sorting the array Arrays.sort(A); // Loop through the array for (int i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; } // Driver code public static void main (String[] args) { int arr[] = { 7, 2, 13, 4, 25, 8 }; int N = arr.length; System.out.println(maxSquareSubsetSum(arr, N)); }} // This code is contributed by AnkitRai01", "e": 27677, "s": 26631, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum sum of the# square of the sum of two subsets of an arraydef maxSquareSubsetSum(A, N) : # Initialize variables to store # the sum of subsets sub1 = 0; sub2 = 0; # Sorting the array A.sort(); # Loop through the array for i in range(N) : # Sum of the first subset if (i < (N // 2) - 1) : sub1 += A[i]; # Sum of the second subset else : sub2 += A[i]; # Return the maximum sum of # the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; # Driver codeif __name__ == \"__main__\" : arr = [ 7, 2, 13, 4, 25, 8 ]; N = len(arr); print(maxSquareSubsetSum(arr, N)); # This code is contributed by AnkitRai01", "e": 28457, "s": 27677, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum sum of the // square of the sum of two subsets of an array static int maxSquareSubsetSum(int []A, int N) { // Initialize variables to store // the sum of subsets int sub1 = 0, sub2 = 0; // Sorting the array Array.Sort(A); // Loop through the array for (int i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; } // Driver code public static void Main() { int []arr = { 7, 2, 13, 4, 25, 8 }; int N = arr.Length; Console.WriteLine(maxSquareSubsetSum(arr, N)); }} // This code is contributed by AnkitRai01", "e": 29479, "s": 28457, "text": null }, { "code": "<script>// javascript implementation of the approach// Creating the bblSort function function bblSort(arr){ for(var i = 0; i < arr.length; i++){ // Last i elements are already in place for(var j = 0; j < ( arr.length - i -1 ); j++){ // Checking if the item at present iteration // is greater than the next iteration if(arr[j] > arr[j+1]){ // If the condition is true then swap them var temp = arr[j] arr[j] = arr[j + 1] arr[j+1] = temp } } } // return the sorted array return arr;} // Function to return the maximum sum of the // square of the sum of two subsets of an array function maxSquareSubsetSum(A , N) { // Initialize variables to store // the sum of subsets var sub1 = 0, sub2 = 0; // Sorting the array A = bblSort(A); // Loop through the array for (i = 0; i < N; i++) { // Sum of the first subset if (i < (N / 2) - 1) sub1 += A[i]; // Sum of the second subset else sub2 += A[i]; } // Return the maximum sum of // the square of the sum of subsets return sub1 * sub1 + sub2 * sub2; } // Driver code var arr = [ 7, 2, 13, 4, 25, 8 ]; var N = arr.length; document.write(maxSquareSubsetSum(arr, N)); // This code is contributed by todaysgaurav</script>", "e": 30913, "s": 29479, "text": null }, { "code": null, "e": 30918, "s": 30913, "text": "2845" }, { "code": null, "e": 30950, "s": 30920, "text": "Time Complexity: O(N*log(N)) " }, { "code": null, "e": 30958, "s": 30950, "text": "ankthon" }, { "code": null, "e": 30971, "s": 30958, "text": "todaysgaurav" }, { "code": null, "e": 30978, "s": 30971, "text": "subset" }, { "code": null, "e": 31002, "s": 30978, "text": "Technical Scripter 2019" }, { "code": null, "e": 31009, "s": 31002, "text": "Arrays" }, { "code": null, "e": 31022, "s": 31009, "text": "Mathematical" }, { "code": null, "e": 31029, "s": 31022, "text": "Arrays" }, { "code": null, "e": 31042, "s": 31029, "text": "Mathematical" }, { "code": null, "e": 31049, "s": 31042, "text": "subset" }, { "code": null, "e": 31147, "s": 31049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31172, "s": 31147, "text": "Window Sliding Technique" }, { "code": null, "e": 31192, "s": 31172, "text": "Trapping Rain Water" }, { "code": null, "e": 31230, "s": 31192, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31315, "s": 31230, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 31364, "s": 31315, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31394, "s": 31364, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31454, "s": 31394, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31469, "s": 31454, "text": "C++ Data Types" }, { "code": null, "e": 31512, "s": 31469, "text": "Set in C++ Standard Template Library (STL)" } ]
BCD addition of given Decimal numbers - GeeksforGeeks
26 Mar, 2021 Given two numbers A and B, the task is to perform BCD Addition of the given numbers. Examples: Input: A = 12, B = 20 Output: 110010 Explanation: The summation of A and B is 12 + 20 = 32. The binary representation of 3 = 0011 The binary representation of 2 = 0010 Therefore, the BCD Addition is “0011” + “0010” = “110010” Input: A = 10, B = 10 Output:100000 Explanation: The summation of A and B is 10 + 10 = 20. The binary representation of 2 = 0010 The binary representation of 0 = 0000 Therefore, the BCD Addition is “0010” + “0000” = “100000” Approach: The idea is to convert the summation of given two numbers A and B to BCD Number. Below are the steps: Find the summation(say num) of the two given numbers A and B.For each digit in the number num, convert it into binary representation up to 4 bits.Concatenate the binary representation of each digit above and print the result. Find the summation(say num) of the two given numbers A and B. For each digit in the number num, convert it into binary representation up to 4 bits. Concatenate the binary representation of each digit above and print the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to perform BCD Additionstring BCDAddition(int A, int B){ // Store the summation of A and B // in form of string string s = to_string(A + B); int l = s.length(); // To store the final result string ans; string str; // Forming BCD using Bitset for (int i = 0; i < l; i++) { // Find the binary representation // of the current characters str = bitset<4>(s[i]).to_string(); ans.append(str); } // Stripping off leading zeroes. const auto loc1 = ans.find('1'); // Return string ans if (loc1 != string::npos) { return ans.substr(loc1); } return "0";} // Driver Codeint main(){ // Given Numbers int A = 12, B = 20; // Function Call cout << BCDAddition(A, B); return 0;} // Java program for the above approachclass GFG{ // Function to perform BCD Additionstatic String BCDAddition(int A, int B){ // Store the summation of A and B // in form of string String s = String.valueOf(A + B); int l = s.length(); // Forming BCD using Bitset String temp[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001" }; String ans = ""; for(int i = 0; i < l; i++) { // Find the binary representation // of the current characters String t = temp[s.charAt(i) - '0']; ans = ans + String.valueOf(t); } // Stripping off leading zeroes. int loc1 = 0; while (loc1 < l && ans.charAt(loc1) != '1') { loc1++; } // Return string ans return ans.substring(loc1);} // Driver code public static void main(String[] args){ // Given Numbers int A = 12; int B = 20; // Function Call System.out.println(BCDAddition(A, B));}} // This code is contributed by divyesh072019 # Python3 program for the above approach # Function to perform BCD Additiondef BCDAddition(A, B): # Store the summation of A and B # in form of string s = str(A + B) l = len(s) # Forming BCD using Bitset temp = [ "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001" ] ans = "" for i in range(l): # Find the binary representation # of the current characters t = temp[ord(s[i]) - ord('0')] ans = ans + str(t) # Stripping off leading zeroes. loc1 = ans.find('1') # Return string ans return ans[loc1:] # Driver Code # Given NumbersA = 12B = 20 # Function Callprint(BCDAddition(A, B)) # This code is contributed by grand_master // C# program for the above approachusing System;class GFG{ // Function to perform BCD Addition static String BCDAddition(int A, int B) { // Store the summation of A and B // in form of string string s = (A + B).ToString(); int l = s.Length; // Forming BCD using Bitset string[] temp = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001" }; string ans = ""; for(int i = 0; i < l; i++) { // Find the binary representation // of the current characters string t = temp[s[i] - '0']; ans = ans + t.ToString(); } // Stripping off leading zeroes. int loc1 = 0; while (loc1 < l && ans[loc1] != '1') { loc1++; } // Return string ans return ans.Substring(loc1); } // Driver code static void Main() { // Given Numbers int A = 12; int B = 20; // Function Call Console.Write(BCDAddition(A, B)); }} // This code is contributed by divyeshrbadiya07. <script>// Javascript program for the above approach// Function to perform BCD Additionfunction BCDAddition(A, B){ // Store the summation of A and B // in form of string var s = (A + B).toString(); var l = s.length; // Forming BCD using Bitset temp = [ "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001" ] var ans = ""; for(var i = 0; i < l; i++) { // Find the binary representation // of the current characters var t = temp[s[i] - '0']; ans = ans + t.toString(); } // Stripping off leading zeroes. var loc1 = 0; while (loc1 < l && ans[loc1] != '1') { loc1++; } // Return string ans return ans.substring(loc1);} // Driver code // Given Numbersvar A = 12;var B = 20; // Function Calldocument.write(BCDAddition(A, B)); // This code is contributed by rutvik_56.</script> 110010 Time Complexity: O(log10(A+B)) yashbeersingh42 grand_master khushboogoyal499 divyesh072019 divyeshrabadiya07 rutvik_56 base-conversion Bit Magic Mathematical Strings Strings Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set, Clear and Toggle a given bit of a number in C Check whether K-th bit is set or not Program to find parity Write an Efficient Method to Check if a Number is Multiple of 3 Hamming code Implementation in C/C++ Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25012, "s": 24984, "text": "\n26 Mar, 2021" }, { "code": null, "e": 25097, "s": 25012, "text": "Given two numbers A and B, the task is to perform BCD Addition of the given numbers." }, { "code": null, "e": 25108, "s": 25097, "text": "Examples: " }, { "code": null, "e": 25334, "s": 25108, "text": "Input: A = 12, B = 20 Output: 110010 Explanation: The summation of A and B is 12 + 20 = 32. The binary representation of 3 = 0011 The binary representation of 2 = 0010 Therefore, the BCD Addition is “0011” + “0010” = “110010”" }, { "code": null, "e": 25559, "s": 25334, "text": "Input: A = 10, B = 10 Output:100000 Explanation: The summation of A and B is 10 + 10 = 20. The binary representation of 2 = 0010 The binary representation of 0 = 0000 Therefore, the BCD Addition is “0010” + “0000” = “100000”" }, { "code": null, "e": 25672, "s": 25559, "text": "Approach: The idea is to convert the summation of given two numbers A and B to BCD Number. Below are the steps: " }, { "code": null, "e": 25898, "s": 25672, "text": "Find the summation(say num) of the two given numbers A and B.For each digit in the number num, convert it into binary representation up to 4 bits.Concatenate the binary representation of each digit above and print the result." }, { "code": null, "e": 25960, "s": 25898, "text": "Find the summation(say num) of the two given numbers A and B." }, { "code": null, "e": 26046, "s": 25960, "text": "For each digit in the number num, convert it into binary representation up to 4 bits." }, { "code": null, "e": 26126, "s": 26046, "text": "Concatenate the binary representation of each digit above and print the result." }, { "code": null, "e": 26177, "s": 26126, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26181, "s": 26177, "text": "C++" }, { "code": null, "e": 26186, "s": 26181, "text": "Java" }, { "code": null, "e": 26194, "s": 26186, "text": "Python3" }, { "code": null, "e": 26197, "s": 26194, "text": "C#" }, { "code": null, "e": 26208, "s": 26197, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to perform BCD Additionstring BCDAddition(int A, int B){ // Store the summation of A and B // in form of string string s = to_string(A + B); int l = s.length(); // To store the final result string ans; string str; // Forming BCD using Bitset for (int i = 0; i < l; i++) { // Find the binary representation // of the current characters str = bitset<4>(s[i]).to_string(); ans.append(str); } // Stripping off leading zeroes. const auto loc1 = ans.find('1'); // Return string ans if (loc1 != string::npos) { return ans.substr(loc1); } return \"0\";} // Driver Codeint main(){ // Given Numbers int A = 12, B = 20; // Function Call cout << BCDAddition(A, B); return 0;}", "e": 27070, "s": 26208, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to perform BCD Additionstatic String BCDAddition(int A, int B){ // Store the summation of A and B // in form of string String s = String.valueOf(A + B); int l = s.length(); // Forming BCD using Bitset String temp[] = { \"0000\", \"0001\", \"0010\", \"0011\", \"0100\", \"0101\", \"0110\", \"0111\", \"1000\", \"1001\" }; String ans = \"\"; for(int i = 0; i < l; i++) { // Find the binary representation // of the current characters String t = temp[s.charAt(i) - '0']; ans = ans + String.valueOf(t); } // Stripping off leading zeroes. int loc1 = 0; while (loc1 < l && ans.charAt(loc1) != '1') { loc1++; } // Return string ans return ans.substring(loc1);} // Driver code public static void main(String[] args){ // Given Numbers int A = 12; int B = 20; // Function Call System.out.println(BCDAddition(A, B));}} // This code is contributed by divyesh072019", "e": 28199, "s": 27070, "text": null }, { "code": "# Python3 program for the above approach # Function to perform BCD Additiondef BCDAddition(A, B): # Store the summation of A and B # in form of string s = str(A + B) l = len(s) # Forming BCD using Bitset temp = [ \"0000\", \"0001\", \"0010\", \"0011\", \"0100\", \"0101\", \"0110\", \"0111\", \"1000\", \"1001\" ] ans = \"\" for i in range(l): # Find the binary representation # of the current characters t = temp[ord(s[i]) - ord('0')] ans = ans + str(t) # Stripping off leading zeroes. loc1 = ans.find('1') # Return string ans return ans[loc1:] # Driver Code # Given NumbersA = 12B = 20 # Function Callprint(BCDAddition(A, B)) # This code is contributed by grand_master", "e": 28942, "s": 28199, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to perform BCD Addition static String BCDAddition(int A, int B) { // Store the summation of A and B // in form of string string s = (A + B).ToString(); int l = s.Length; // Forming BCD using Bitset string[] temp = { \"0000\", \"0001\", \"0010\", \"0011\", \"0100\", \"0101\", \"0110\", \"0111\", \"1000\", \"1001\" }; string ans = \"\"; for(int i = 0; i < l; i++) { // Find the binary representation // of the current characters string t = temp[s[i] - '0']; ans = ans + t.ToString(); } // Stripping off leading zeroes. int loc1 = 0; while (loc1 < l && ans[loc1] != '1') { loc1++; } // Return string ans return ans.Substring(loc1); } // Driver code static void Main() { // Given Numbers int A = 12; int B = 20; // Function Call Console.Write(BCDAddition(A, B)); }} // This code is contributed by divyeshrbadiya07.", "e": 30190, "s": 28942, "text": null }, { "code": "<script>// Javascript program for the above approach// Function to perform BCD Additionfunction BCDAddition(A, B){ // Store the summation of A and B // in form of string var s = (A + B).toString(); var l = s.length; // Forming BCD using Bitset temp = [ \"0000\", \"0001\", \"0010\", \"0011\", \"0100\", \"0101\", \"0110\", \"0111\", \"1000\", \"1001\" ] var ans = \"\"; for(var i = 0; i < l; i++) { // Find the binary representation // of the current characters var t = temp[s[i] - '0']; ans = ans + t.toString(); } // Stripping off leading zeroes. var loc1 = 0; while (loc1 < l && ans[loc1] != '1') { loc1++; } // Return string ans return ans.substring(loc1);} // Driver code // Given Numbersvar A = 12;var B = 20; // Function Calldocument.write(BCDAddition(A, B)); // This code is contributed by rutvik_56.</script>", "e": 31185, "s": 30190, "text": null }, { "code": null, "e": 31192, "s": 31185, "text": "110010" }, { "code": null, "e": 31226, "s": 31194, "text": "Time Complexity: O(log10(A+B)) " }, { "code": null, "e": 31242, "s": 31226, "text": "yashbeersingh42" }, { "code": null, "e": 31255, "s": 31242, "text": "grand_master" }, { "code": null, "e": 31272, "s": 31255, "text": "khushboogoyal499" }, { "code": null, "e": 31286, "s": 31272, "text": "divyesh072019" }, { "code": null, "e": 31304, "s": 31286, "text": "divyeshrabadiya07" }, { "code": null, "e": 31314, "s": 31304, "text": "rutvik_56" }, { "code": null, "e": 31330, "s": 31314, "text": "base-conversion" }, { "code": null, "e": 31340, "s": 31330, "text": "Bit Magic" }, { "code": null, "e": 31353, "s": 31340, "text": "Mathematical" }, { "code": null, "e": 31361, "s": 31353, "text": "Strings" }, { "code": null, "e": 31369, "s": 31361, "text": "Strings" }, { "code": null, "e": 31382, "s": 31369, "text": "Mathematical" }, { "code": null, "e": 31392, "s": 31382, "text": "Bit Magic" }, { "code": null, "e": 31490, "s": 31392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31541, "s": 31490, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 31578, "s": 31541, "text": "Check whether K-th bit is set or not" }, { "code": null, "e": 31601, "s": 31578, "text": "Program to find parity" }, { "code": null, "e": 31665, "s": 31601, "text": "Write an Efficient Method to Check if a Number is Multiple of 3" }, { "code": null, "e": 31702, "s": 31665, "text": "Hamming code Implementation in C/C++" }, { "code": null, "e": 31732, "s": 31702, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31792, "s": 31732, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31807, "s": 31792, "text": "C++ Data Types" }, { "code": null, "e": 31850, "s": 31807, "text": "Set in C++ Standard Template Library (STL)" } ]
How to remove arrows/spinners from input type number with CSS?
Following is the code to remove arrows/spinners from input type using CSS − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } input[type="number"] { -moz-appearance: textfield; } </style> </head> <body> <h1>Input Numbers Hide Arrows</h1> <input type="number" value="10"> <h2>Only numbers can be entered in the above field</h2> </body> </html> his will produce the following output −
[ { "code": null, "e": 1138, "s": 1062, "text": "Following is the code to remove arrows/spinners from input type using CSS −" }, { "code": null, "e": 1149, "s": 1138, "text": " Live Demo" }, { "code": null, "e": 1592, "s": 1149, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\ninput::-webkit-outer-spin-button,\ninput::-webkit-inner-spin-button {\n -webkit-appearance: none;\n margin: 0;\n}\ninput[type=\"number\"] {\n -moz-appearance: textfield;\n}\n</style>\n</head>\n<body>\n<h1>Input Numbers Hide Arrows</h1>\n<input type=\"number\" value=\"10\">\n<h2>Only numbers can be entered in the above field</h2>\n</body>\n</html>" }, { "code": null, "e": 1632, "s": 1592, "text": "his will produce the following output −" } ]
What is the use of FileInputStream and FileOutputStream in classes in Java?
Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc. There are two types of streams available − InputStream − This is used to read (sequential) data from a source. OutputStream − This is used to write data to a destination. This class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images. To read the contents of a file using this class − First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read. FileInputStream inputStream = new FileInputStream("file_path"); or, File file = new File("file_path"); FileInputStream inputStream = new FileInputStream(file); Then read the contents of the specified file using either of the variants of read() method −int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached.int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given arrayThis method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached. int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format). This method returns -1 if the end of the file is reached. int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given arrayThis method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array. int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array. This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached. Assume we have the following image in the directory D:/images Following program reads contents of the above image using the FileInputStream. import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FileInputStreamExample { public static void main(String args[]) throws IOException { //Creating a File object File file = new File("D:/images/javafx.jpg"); //Creating a FileInputStream object FileInputStream inputStream = new FileInputStream(file); //Creating a byte array byte bytes[] = new byte[(int) file.length()]; //Reading data into the byte array int numOfBytes = inputStream.read(bytes); System.out.println("Data copied successfully..."); } } Data copied successfully... This writes data into a specific file or, file descriptor (byte by byte). It is usually used to write the contents of a file with raw bytes, such as images. To write the contents of a file using this class − First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read. FileOutputStream outputStream = new FileOutputStream("file_path"); or, File file = new File("file_path"); FileOutputStream outputStream = new FileOutputStream (file); You can also instantiate a FileOutputStream class by passing a FileDescriptor object. FileDescriptor descriptor = new FileDescriptor(); FileOutputStream outputStream = new FileOutputStream(descriptor); Then write the data to a specified file using either of the variants of write() method −int write(int b) − This method accepts a single byte and writes it to the current OutputStream.int write(byte[] b) − This method accepts a byte array as parameter and writes data from it to the current OutputStream.int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream. int write(int b) − This method accepts a single byte and writes it to the current OutputStream. int write(byte[] b) − This method accepts a byte array as parameter and writes data from it to the current OutputStream. int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream. Assume we have the following image in the directory D:/images Following program reads contents of the above image and writes it back to another file using the FileOutputStream class. import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileInputStreamExample { public static void main(String args[]) throws IOException { //Creating a File object File file = new File("D:/images/javafx.jpg"); //Creating a FileInputStream object FileInputStream inputStream = new FileInputStream(file); //Creating a byte array byte bytes[] = new byte[(int) file.length()]; //Reading data into the byte array int numOfBytes = inputStream.read(bytes); System.out.println("Data copied successfully..."); //Creating a FileInputStream object FileOutputStream outputStream = new FileOutputStream("D:/images/output.jpg"); //Writing the contents of the Output Stream to a file outputStream.write(bytes); System.out.println("Data written successfully..."); } } Data copied successfully... Data written successfully... If you verify the given path you can observe the generated image as −
[ { "code": null, "e": 1233, "s": 1062, "text": "Java provides I/O Streams to read and write data where, a Stream represents an input source or an output destination which could be a file, i/o devise, other program etc." }, { "code": null, "e": 1276, "s": 1233, "text": "There are two types of streams available −" }, { "code": null, "e": 1344, "s": 1276, "text": "InputStream − This is used to read (sequential) data from a source." }, { "code": null, "e": 1404, "s": 1344, "text": "OutputStream − This is used to write data to a destination." }, { "code": null, "e": 1549, "s": 1404, "text": "This class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images." }, { "code": null, "e": 1599, "s": 1549, "text": "To read the contents of a file using this class −" }, { "code": null, "e": 1741, "s": 1599, "text": "First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read." }, { "code": null, "e": 1901, "s": 1741, "text": "FileInputStream inputStream = new FileInputStream(\"file_path\");\nor,\nFile file = new File(\"file_path\");\nFileInputStream inputStream = new FileInputStream(file);" }, { "code": null, "e": 2729, "s": 1901, "text": "Then read the contents of the specified file using either of the variants of read() method −int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached.int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given arrayThis method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array.This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 2911, "s": 2729, "text": "int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).This method returns -1 if the end of the file is reached." }, { "code": null, "e": 3036, "s": 2911, "text": "int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format)." }, { "code": null, "e": 3094, "s": 3036, "text": "This method returns -1 if the end of the file is reached." }, { "code": null, "e": 3342, "s": 3094, "text": "int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given arrayThis method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 3479, "s": 3342, "text": "int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array" }, { "code": null, "e": 3591, "s": 3479, "text": "This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 3788, "s": 3591, "text": "int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array." }, { "code": null, "e": 3985, "s": 3788, "text": "int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array." }, { "code": null, "e": 4097, "s": 3985, "text": "This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 4209, "s": 4097, "text": "This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached." }, { "code": null, "e": 4271, "s": 4209, "text": "Assume we have the following image in the directory D:/images" }, { "code": null, "e": 4350, "s": 4271, "text": "Following program reads contents of the above image using the FileInputStream." }, { "code": null, "e": 4955, "s": 4350, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\npublic class FileInputStreamExample {\n public static void main(String args[]) throws IOException {\n //Creating a File object\n File file = new File(\"D:/images/javafx.jpg\");\n //Creating a FileInputStream object\n FileInputStream inputStream = new FileInputStream(file);\n //Creating a byte array\n byte bytes[] = new byte[(int) file.length()];\n //Reading data into the byte array\n int numOfBytes = inputStream.read(bytes);\n System.out.println(\"Data copied successfully...\");\n }\n}" }, { "code": null, "e": 4983, "s": 4955, "text": "Data copied successfully..." }, { "code": null, "e": 5140, "s": 4983, "text": "This writes data into a specific file or, file descriptor (byte by byte). It is usually used to write the contents of a file with raw bytes, such as images." }, { "code": null, "e": 5191, "s": 5140, "text": "To write the contents of a file using this class −" }, { "code": null, "e": 5333, "s": 5191, "text": "First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read." }, { "code": null, "e": 5500, "s": 5333, "text": "FileOutputStream outputStream = new FileOutputStream(\"file_path\");\nor,\nFile file = new File(\"file_path\");\nFileOutputStream outputStream = new FileOutputStream (file);" }, { "code": null, "e": 5586, "s": 5500, "text": "You can also instantiate a FileOutputStream class by passing a FileDescriptor object." }, { "code": null, "e": 5702, "s": 5586, "text": "FileDescriptor descriptor = new FileDescriptor();\nFileOutputStream outputStream = new FileOutputStream(descriptor);" }, { "code": null, "e": 6185, "s": 5702, "text": "Then write the data to a specified file using either of the variants of write() method −int write(int b) − This method accepts a single byte and writes it to the current OutputStream.int write(byte[] b) − This method accepts a byte array as parameter and writes data from it to the current OutputStream.int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream." }, { "code": null, "e": 6281, "s": 6185, "text": "int write(int b) − This method accepts a single byte and writes it to the current OutputStream." }, { "code": null, "e": 6402, "s": 6281, "text": "int write(byte[] b) − This method accepts a byte array as parameter and writes data from it to the current OutputStream." }, { "code": null, "e": 6582, "s": 6402, "text": "int write(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and writes its contents to the current OutputStream." }, { "code": null, "e": 6644, "s": 6582, "text": "Assume we have the following image in the directory D:/images" }, { "code": null, "e": 6765, "s": 6644, "text": "Following program reads contents of the above image and writes it back to another file using the FileOutputStream class." }, { "code": null, "e": 7680, "s": 6765, "text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\npublic class FileInputStreamExample {\n public static void main(String args[]) throws IOException {\n //Creating a File object\n File file = new File(\"D:/images/javafx.jpg\");\n //Creating a FileInputStream object\n FileInputStream inputStream = new FileInputStream(file);\n //Creating a byte array\n byte bytes[] = new byte[(int) file.length()];\n //Reading data into the byte array\n int numOfBytes = inputStream.read(bytes);\n System.out.println(\"Data copied successfully...\");\n //Creating a FileInputStream object\n FileOutputStream outputStream = new FileOutputStream(\"D:/images/output.jpg\");\n //Writing the contents of the Output Stream to a file\n outputStream.write(bytes);\n System.out.println(\"Data written successfully...\");\n }\n}" }, { "code": null, "e": 7737, "s": 7680, "text": "Data copied successfully...\nData written successfully..." }, { "code": null, "e": 7807, "s": 7737, "text": "If you verify the given path you can observe the generated image as −" } ]
Why we can't initialize static final variable in try/catch block in java?
In Java you can declare three types of variables namely, instance variables, static variables and, local variables. Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword. In the same way, static variables belong to the class and can be accessed anywhere within the class, which contradicts with the definition of the local variable. Therefore, declaring a static variable inside a method, block or, constructor is not allowed. Still, if you try to declare a static variable within a block a compile time error will be generated. In the following Java example we are trying to declare a String variable path in the try block. import java.io.File; import java.io.FileInputStream; public class Example { public static void main(String args[]){ System.out.println("Hello"); try{ static String path = "my_file"; File file =new File(path); FileInputStream fis = new FileInputStream(file); }catch(Exception e){ System.out.println("Given file path is not found"); } } } on compiling, the above program generates the following error. Example.java:7: error: illegal start of expression static String path = "my_file"; ^ 1 error If you compile the same program in eclipse it generates the following message.
[ { "code": null, "e": 1178, "s": 1062, "text": "In Java you can declare three types of variables namely, instance variables, static variables and, local variables." }, { "code": null, "e": 1411, "s": 1178, "text": "Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed." }, { "code": null, "e": 1538, "s": 1411, "text": "Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword." }, { "code": null, "e": 1896, "s": 1538, "text": "In the same way, static variables belong to the class and can be accessed anywhere within the class, which contradicts with the definition of the local variable. Therefore, declaring a static variable inside a method, block or, constructor is not allowed. Still, if you try to declare a static variable within a block a compile time error will be generated." }, { "code": null, "e": 1992, "s": 1896, "text": "In the following Java example we are trying to declare a String variable path in the try block." }, { "code": null, "e": 2395, "s": 1992, "text": "import java.io.File;\nimport java.io.FileInputStream;\npublic class Example {\n public static void main(String args[]){\n System.out.println(\"Hello\");\n try{\n static String path = \"my_file\";\n File file =new File(path);\n FileInputStream fis = new FileInputStream(file);\n }catch(Exception e){\n System.out.println(\"Given file path is not found\");\n }\n }\n}" }, { "code": null, "e": 2458, "s": 2395, "text": "on compiling, the above program generates the following error." }, { "code": null, "e": 2557, "s": 2458, "text": "Example.java:7: error: illegal start of expression\n static String path = \"my_file\";\n ^\n1 error" }, { "code": null, "e": 2636, "s": 2557, "text": "If you compile the same program in eclipse it generates the following message." } ]
Find the remainder when First digit of a number is divided by its Last digit - GeeksforGeeks
21 Apr, 2021 Given a number N, find the remainder when the first digit of N is divided by its last digit.Examples: Input: N = 1234 Output: 1 First digit = 1 Last digit = 4 Remainder = 1 % 4 = 1 Input: N = 5223 Output: 2 First digit = 5 Last digit = 3 Remainder = 5 % 3 = 2 Approach: Find the first digit and the last digit of the number. Find then the remainder when the first digit is divided by the last digit.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the remainder// when the First digit of a number// is divided by its Last digit #include <bits/stdc++.h>using namespace std; // Function to find the remaindervoid findRemainder(int n){ // Get the last digit int l = n % 10; // Get the first digit while (n >= 10) n /= 10; int f = n; // Compute the remainder int remainder = f % l; cout << remainder << endl;} // Driver codeint main(){ int n = 5223; findRemainder(n); return 0;} // Java program to find the remainder// when the First digit of a number// is divided by its Last digitclass GFG{ // Function to find the remainderstatic void findRemainder(int n){ // Get the last digit int l = n % 10; // Get the first digit while (n >= 10) n /= 10; int f = n; // Compute the remainder int remainder = f % l; System.out.println(remainder);} // Driver codepublic static void main(String[] args){ int n = 5223; findRemainder(n);}} // This code is contributed by Code_Mech # Python3 program to find the remainder# when the First digit of a number# is divided by its Last digit # Function to find the remainderdef findRemainder(n): # Get the last digit l = n % 10 # Get the first digit while (n >= 10): n //= 10 f = n # Compute the remainder remainder = f % l print(remainder) # Driver coden = 5223 findRemainder(n) # This code is contributed by Mohit Kumar // C# program to find the remainder// when the First digit of a number// is divided by its Last digitusing System; class GFG{ // Function to find the remainderstatic void findRemainder(int n){ // Get the last digit int l = n % 10; // Get the first digit while (n >= 10) n /= 10; int f = n; // Compute the remainder int remainder = f % l; Console.WriteLine(remainder);} // Driver codepublic static void Main(){ int n = 5223; findRemainder(n);}} // This code is contributed by Code_Mech <script> // Javascript program to find the remainder// when the First digit of a number// is divided by its Last digit // Function to find the remainderfunction findRemainder( n){ // Get the last digit let l = n % 10; // Get the first digit while (n >= 10) n /= 10; let f = n; // Compute the remainder let remainder = f % l; document.write(Math.floor(remainder));} // Driver code let n = 5223; findRemainder(n); // This code is contributed by mohan pavan </script> 2 Time Complexity: O(L ) where L is length of number in decimal representation Auxiliary Space: O(1) mohit kumar 29 Code_Mech ujjwalgoel1103 pulamolusaimohan number-digits school-programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Program for Decimal to Binary Conversion Find all factors of a natural number | Set 1 Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Program for factorial of a number Operators in C / C++
[ { "code": null, "e": 24751, "s": 24723, "text": "\n21 Apr, 2021" }, { "code": null, "e": 24854, "s": 24751, "text": "Given a number N, find the remainder when the first digit of N is divided by its last digit.Examples: " }, { "code": null, "e": 25013, "s": 24854, "text": "Input: N = 1234\nOutput: 1\nFirst digit = 1\nLast digit = 4\nRemainder = 1 % 4 = 1\n\nInput: N = 5223\nOutput: 2\nFirst digit = 5\nLast digit = 3\nRemainder = 5 % 3 = 2" }, { "code": null, "e": 25205, "s": 25013, "text": "Approach: Find the first digit and the last digit of the number. Find then the remainder when the first digit is divided by the last digit.Below is the implementation of the above approach: " }, { "code": null, "e": 25209, "s": 25205, "text": "C++" }, { "code": null, "e": 25214, "s": 25209, "text": "Java" }, { "code": null, "e": 25222, "s": 25214, "text": "Python3" }, { "code": null, "e": 25225, "s": 25222, "text": "C#" }, { "code": null, "e": 25236, "s": 25225, "text": "Javascript" }, { "code": "// C++ program to find the remainder// when the First digit of a number// is divided by its Last digit #include <bits/stdc++.h>using namespace std; // Function to find the remaindervoid findRemainder(int n){ // Get the last digit int l = n % 10; // Get the first digit while (n >= 10) n /= 10; int f = n; // Compute the remainder int remainder = f % l; cout << remainder << endl;} // Driver codeint main(){ int n = 5223; findRemainder(n); return 0;}", "e": 25732, "s": 25236, "text": null }, { "code": "// Java program to find the remainder// when the First digit of a number// is divided by its Last digitclass GFG{ // Function to find the remainderstatic void findRemainder(int n){ // Get the last digit int l = n % 10; // Get the first digit while (n >= 10) n /= 10; int f = n; // Compute the remainder int remainder = f % l; System.out.println(remainder);} // Driver codepublic static void main(String[] args){ int n = 5223; findRemainder(n);}} // This code is contributed by Code_Mech", "e": 26263, "s": 25732, "text": null }, { "code": "# Python3 program to find the remainder# when the First digit of a number# is divided by its Last digit # Function to find the remainderdef findRemainder(n): # Get the last digit l = n % 10 # Get the first digit while (n >= 10): n //= 10 f = n # Compute the remainder remainder = f % l print(remainder) # Driver coden = 5223 findRemainder(n) # This code is contributed by Mohit Kumar", "e": 26687, "s": 26263, "text": null }, { "code": "// C# program to find the remainder// when the First digit of a number// is divided by its Last digitusing System; class GFG{ // Function to find the remainderstatic void findRemainder(int n){ // Get the last digit int l = n % 10; // Get the first digit while (n >= 10) n /= 10; int f = n; // Compute the remainder int remainder = f % l; Console.WriteLine(remainder);} // Driver codepublic static void Main(){ int n = 5223; findRemainder(n);}} // This code is contributed by Code_Mech", "e": 27216, "s": 26687, "text": null }, { "code": "<script> // Javascript program to find the remainder// when the First digit of a number// is divided by its Last digit // Function to find the remainderfunction findRemainder( n){ // Get the last digit let l = n % 10; // Get the first digit while (n >= 10) n /= 10; let f = n; // Compute the remainder let remainder = f % l; document.write(Math.floor(remainder));} // Driver code let n = 5223; findRemainder(n); // This code is contributed by mohan pavan </script>", "e": 27724, "s": 27216, "text": null }, { "code": null, "e": 27726, "s": 27724, "text": "2" }, { "code": null, "e": 27805, "s": 27728, "text": "Time Complexity: O(L ) where L is length of number in decimal representation" }, { "code": null, "e": 27827, "s": 27805, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 27842, "s": 27827, "text": "mohit kumar 29" }, { "code": null, "e": 27852, "s": 27842, "text": "Code_Mech" }, { "code": null, "e": 27867, "s": 27852, "text": "ujjwalgoel1103" }, { "code": null, "e": 27884, "s": 27867, "text": "pulamolusaimohan" }, { "code": null, "e": 27898, "s": 27884, "text": "number-digits" }, { "code": null, "e": 27917, "s": 27898, "text": "school-programming" }, { "code": null, "e": 27930, "s": 27917, "text": "Mathematical" }, { "code": null, "e": 27943, "s": 27930, "text": "Mathematical" }, { "code": null, "e": 28041, "s": 27943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28050, "s": 28041, "text": "Comments" }, { "code": null, "e": 28063, "s": 28050, "text": "Old Comments" }, { "code": null, "e": 28087, "s": 28063, "text": "Merge two sorted arrays" }, { "code": null, "e": 28130, "s": 28087, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 28144, "s": 28130, "text": "Prime Numbers" }, { "code": null, "e": 28186, "s": 28144, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 28227, "s": 28186, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 28272, "s": 28227, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 28321, "s": 28272, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 28364, "s": 28321, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 28398, "s": 28364, "text": "Program for factorial of a number" } ]
Spring Boot - Securing Web Applications
If a Spring Boot Security dependency is added on the classpath, Spring Boot application automatically requires the Basic Authentication for all HTTP Endpoints. The Endpoint “/” and “/home” does not require any authentication. All other Endpoints require authentication. For adding a Spring Boot Security to your Spring Boot application, we need to add the Spring Boot Starter Security dependency in our build configuration file. Maven users can add the following dependency in the pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Gradle users can add the following dependency in the build.gradle file. compile("org.springframework.boot:spring-boot-starter-security") First, create an unsecure web application by using Thymeleaf templates. Then, create a home.html file under src/main/resources/templates directory. <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org" xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Example</title> </head> <body> <h1>Welcome!</h1> <p>Click <a th:href = "@{/hello}">here</a> to see a greeting.</p> </body> </html> The simple view /hello defined in the HTML file by using Thymeleaf templates. Now, create a hello.html under src/main/resources/templates directory. <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org" xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <h1>Hello world!</h1> </body> </html> Now, we need to setup the Spring MVC – View controller for home and hello views. For this, create a MVC configuration file that extends WebMvcConfigurerAdapter. package com.tutorialspoint.websecuritydemo; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); registry.addViewController("/").setViewName("home"); registry.addViewController("/hello").setViewName("hello"); registry.addViewController("/login").setViewName("login"); } } Now, add the Spring Boot Starter security dependency to your build configuration file. Maven users can add the following dependency in your pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Gradle users can add the following dependency in the build.gradle file. compile("org.springframework.boot:spring-boot-starter-security") Now, create a Web Security Configuration file, that is used to secure your application to access the HTTP Endpoints by using basic authentication. package com.tutorialspoint.websecuritydemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } } Now, create a login.html file under the src/main/resources directory to allow the user to access the HTTP Endpoint via login screen. <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org" xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Spring Security Example </title> </head> <body> <div th:if = "${param.error}"> Invalid username and password. </div> <div th:if = "${param.logout}"> You have been logged out. </div> <form th:action = "@{/login}" method = "post"> <div> <label> User Name : <input type = "text" name = "username"/> </label> </div> <div> <label> Password: <input type = "password" name = "password"/> </label> </div> <div> <input type = "submit" value = "Sign In"/> </div> </form> </body> </html> Finally, update the hello.html file – to allow the user to Sign-out from the application and display the current username as shown below − <!DOCTYPE html> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org" xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello World!</title> </head> <body> <h1 th:inline = "text">Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action = "@{/logout}" method = "post"> <input type = "submit" value = "Sign Out"/> </form> </body> </html> The code for main Spring Boot application is given below − package com.tutorialspoint.websecuritydemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class WebsecurityDemoApplication { public static void main(String[] args) { SpringApplication.run(WebsecurityDemoApplication.class, args); } } The complete code for build configuration file is given below. Maven – pom.xml <?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>websecurity-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>websecurity-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-security') compile('org.springframework.boot:spring-boot-starter-thymeleaf') compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') testCompile('org.springframework.security:spring-security-test') } Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. Maven users can use the command as given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under target directory. Gradle users can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command shown below − java –jar <JARFILE> Hit the URL http://localhost:8080/ in your web browser. You can see the output as shown. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 3295, "s": 3025, "text": "If a Spring Boot Security dependency is added on the classpath, Spring Boot application automatically requires the Basic Authentication for all HTTP Endpoints. The Endpoint “/” and “/home” does not require any authentication. All other Endpoints require authentication." }, { "code": null, "e": 3454, "s": 3295, "text": "For adding a Spring Boot Security to your Spring Boot application, we need to add the Spring Boot Starter Security dependency in our build configuration file." }, { "code": null, "e": 3520, "s": 3454, "text": "Maven users can add the following dependency in the pom.xml file." }, { "code": null, "e": 3651, "s": 3520, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-security</artifactId>\n</dependency>" }, { "code": null, "e": 3723, "s": 3651, "text": "Gradle users can add the following dependency in the build.gradle file." }, { "code": null, "e": 3789, "s": 3723, "text": "compile(\"org.springframework.boot:spring-boot-starter-security\")\n" }, { "code": null, "e": 3861, "s": 3789, "text": "First, create an unsecure web application by using Thymeleaf templates." }, { "code": null, "e": 3937, "s": 3861, "text": "Then, create a home.html file under src/main/resources/templates directory." }, { "code": null, "e": 4316, "s": 3937, "text": "<!DOCTYPE html>\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:th = \"http://www.thymeleaf.org\" \n xmlns:sec = \"http://www.thymeleaf.org/thymeleaf-extras-springsecurity3\">\n \n <head>\n <title>Spring Security Example</title>\n </head>\n <body>\n <h1>Welcome!</h1>\n <p>Click <a th:href = \"@{/hello}\">here</a> to see a greeting.</p>\n </body>\n \n</html>" }, { "code": null, "e": 4394, "s": 4316, "text": "The simple view /hello defined in the HTML file by using Thymeleaf templates." }, { "code": null, "e": 4465, "s": 4394, "text": "Now, create a hello.html under src/main/resources/templates directory." }, { "code": null, "e": 4765, "s": 4465, "text": "<!DOCTYPE html>\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:th = \"http://www.thymeleaf.org\" \n xmlns:sec = \"http://www.thymeleaf.org/thymeleaf-extras-springsecurity3\">\n \n <head>\n <title>Hello World!</title>\n </head>\n <body>\n <h1>Hello world!</h1>\n </body>\n \n</html>" }, { "code": null, "e": 4846, "s": 4765, "text": "Now, we need to setup the Spring MVC – View controller for home and hello views." }, { "code": null, "e": 4926, "s": 4846, "text": "For this, create a MVC configuration file that extends WebMvcConfigurerAdapter." }, { "code": null, "e": 5609, "s": 4926, "text": "package com.tutorialspoint.websecuritydemo;\n\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.config.annotation.ViewControllerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;\n\n@Configuration\npublic class MvcConfig extends WebMvcConfigurerAdapter {\n @Override\n public void addViewControllers(ViewControllerRegistry registry) {\n registry.addViewController(\"/home\").setViewName(\"home\");\n registry.addViewController(\"/\").setViewName(\"home\");\n registry.addViewController(\"/hello\").setViewName(\"hello\");\n registry.addViewController(\"/login\").setViewName(\"login\");\n }\n}" }, { "code": null, "e": 5696, "s": 5609, "text": "Now, add the Spring Boot Starter security dependency to your build configuration file." }, { "code": null, "e": 5763, "s": 5696, "text": "Maven users can add the following dependency in your pom.xml file." }, { "code": null, "e": 5894, "s": 5763, "text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-security</artifactId>\n</dependency>" }, { "code": null, "e": 5966, "s": 5894, "text": "Gradle users can add the following dependency in the build.gradle file." }, { "code": null, "e": 6032, "s": 5966, "text": "compile(\"org.springframework.boot:spring-boot-starter-security\")\n" }, { "code": null, "e": 6179, "s": 6032, "text": "Now, create a Web Security Configuration file, that is used to secure your application to access the HTTP Endpoints by using basic authentication." }, { "code": null, "e": 7434, "s": 6179, "text": "package com.tutorialspoint.websecuritydemo;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\n\n@Configuration\n@EnableWebSecurity\npublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {\n @Override\n protected void configure(HttpSecurity http) throws Exception {\n http\n .authorizeRequests()\n .antMatchers(\"/\", \"/home\").permitAll()\n .anyRequest().authenticated()\n .and()\n .formLogin()\n .loginPage(\"/login\")\n .permitAll()\n .and()\n .logout()\n .permitAll();\n }\n @Autowired\n public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {\n auth\n .inMemoryAuthentication()\n .withUser(\"user\").password(\"password\").roles(\"USER\");\n }\n}" }, { "code": null, "e": 7567, "s": 7434, "text": "Now, create a login.html file under the src/main/resources directory to allow the user to access the HTTP Endpoint via login screen." }, { "code": null, "e": 8413, "s": 7567, "text": "<!DOCTYPE html>\n<html xmlns = \"http://www.w3.org/1999/xhtml\" xmlns:th = \"http://www.thymeleaf.org\"\n xmlns:sec = \"http://www.thymeleaf.org/thymeleaf-extras-springsecurity3\">\n \n <head>\n <title>Spring Security Example </title>\n </head>\n <body>\n <div th:if = \"${param.error}\">\n Invalid username and password.\n </div>\n <div th:if = \"${param.logout}\">\n You have been logged out.\n </div>\n \n <form th:action = \"@{/login}\" method = \"post\">\n <div>\n <label> User Name : <input type = \"text\" name = \"username\"/> </label>\n </div>\n <div>\n <label> Password: <input type = \"password\" name = \"password\"/> </label>\n </div>\n <div>\n <input type = \"submit\" value = \"Sign In\"/>\n </div>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 8552, "s": 8413, "text": "Finally, update the hello.html file – to allow the user to Sign-out from the application and display the current username as shown below −" }, { "code": null, "e": 9020, "s": 8552, "text": "<!DOCTYPE html>\n<html xmlns = \"http://www.w3.org/1999/xhtml\" xmlns:th = \"http://www.thymeleaf.org\" \n xmlns:sec = \"http://www.thymeleaf.org/thymeleaf-extras-springsecurity3\">\n \n <head>\n <title>Hello World!</title>\n </head>\n <body>\n <h1 th:inline = \"text\">Hello [[${#httpServletRequest.remoteUser}]]!</h1>\n <form th:action = \"@{/logout}\" method = \"post\">\n <input type = \"submit\" value = \"Sign Out\"/>\n </form>\n </body>\n \n</html>" }, { "code": null, "e": 9079, "s": 9020, "text": "The code for main Spring Boot application is given below −" }, { "code": null, "e": 9430, "s": 9079, "text": "package com.tutorialspoint.websecuritydemo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class WebsecurityDemoApplication {\n public static void main(String[] args) {\n SpringApplication.run(WebsecurityDemoApplication.class, args);\n }\n}" }, { "code": null, "e": 9493, "s": 9430, "text": "The complete code for build configuration file is given below." }, { "code": null, "e": 9509, "s": 9493, "text": "Maven – pom.xml" }, { "code": null, "e": 11634, "s": 9509, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>websecurity-demo</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>websecurity-demo</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.9.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-security</artifactId>\n </dependency>\n \n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-thymeleaf</artifactId>\n </dependency>\n \n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n \n <dependency>\n <groupId>org.springframework.security</groupId>\n <artifactId>spring-security-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>" }, { "code": null, "e": 11656, "s": 11634, "text": "Gradle – build.gradle" }, { "code": null, "e": 12449, "s": 11656, "text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter-security')\n compile('org.springframework.boot:spring-boot-starter-thymeleaf')\n compile('org.springframework.boot:spring-boot-starter-web')\n \n testCompile('org.springframework.boot:spring-boot-starter-test')\n testCompile('org.springframework.security:spring-security-test')\n}" }, { "code": null, "e": 12570, "s": 12449, "text": "Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands." }, { "code": null, "e": 12619, "s": 12570, "text": "Maven users can use the command as given below −" }, { "code": null, "e": 12638, "s": 12619, "text": "mvn clean install\n" }, { "code": null, "e": 12711, "s": 12638, "text": "After “BUILD SUCCESS”, you can find the JAR file under target directory." }, { "code": null, "e": 12755, "s": 12711, "text": "Gradle users can use the command as shown −" }, { "code": null, "e": 12775, "s": 12755, "text": "gradle clean build\n" }, { "code": null, "e": 12859, "s": 12775, "text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory." }, { "code": null, "e": 12916, "s": 12859, "text": "Now, run the JAR file by using the command shown below −" }, { "code": null, "e": 12938, "s": 12916, "text": "java –jar <JARFILE> \n" }, { "code": null, "e": 13027, "s": 12938, "text": "Hit the URL http://localhost:8080/ in your web browser. You can see the output as shown." }, { "code": null, "e": 13061, "s": 13027, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 13075, "s": 13061, "text": " Karthikeya T" }, { "code": null, "e": 13108, "s": 13075, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 13123, "s": 13108, "text": " Chaand Sheikh" }, { "code": null, "e": 13158, "s": 13123, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 13170, "s": 13158, "text": " Senol Atac" }, { "code": null, "e": 13205, "s": 13170, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13217, "s": 13205, "text": " Senol Atac" }, { "code": null, "e": 13252, "s": 13217, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13264, "s": 13252, "text": " Senol Atac" }, { "code": null, "e": 13297, "s": 13264, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 13309, "s": 13297, "text": " Senol Atac" }, { "code": null, "e": 13316, "s": 13309, "text": " Print" }, { "code": null, "e": 13327, "s": 13316, "text": " Add Notes" } ]
Convert an Object into a Vector in R Programming - as.vector() Function - GeeksforGeeks
17 Jun, 2020 as.vector() function in R Language is used to convert an object into a vector. Syntax: as.vector(x) Parameters:x: Object to be converted Example 1: # R program to convert an object to vector # Creating an arrayx <- array(c(2, 3, 4, 7, 2, 5), c(3, 2))x # Calling as.vector() Functionas.vector(x) Output: [, 1] [, 2] [1, ] 2 7 [2, ] 3 2 [3, ] 4 5 [1] 2 3 4 7 2 5 Example 2: # R program to convert an object to vector # Creating a matrixx <- matrix(c(1:9), 3, 3)x # Calling as.vector() Functionas.vector(x) Output: [, 1] [, 2] [, 3] [1, ] 1 4 7 [2, ] 2 5 8 [3, ] 3 6 9 [1] 1 2 3 4 5 6 7 8 9 R Object-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n17 Jun, 2020" }, { "code": null, "e": 24930, "s": 24851, "text": "as.vector() function in R Language is used to convert an object into a vector." }, { "code": null, "e": 24951, "s": 24930, "text": "Syntax: as.vector(x)" }, { "code": null, "e": 24988, "s": 24951, "text": "Parameters:x: Object to be converted" }, { "code": null, "e": 24999, "s": 24988, "text": "Example 1:" }, { "code": "# R program to convert an object to vector # Creating an arrayx <- array(c(2, 3, 4, 7, 2, 5), c(3, 2))x # Calling as.vector() Functionas.vector(x)", "e": 25148, "s": 24999, "text": null }, { "code": null, "e": 25156, "s": 25148, "text": "Output:" }, { "code": null, "e": 25238, "s": 25156, "text": " [, 1] [, 2]\n[1, ] 2 7\n[2, ] 3 2\n[3, ] 4 5\n[1] 2 3 4 7 2 5\n" }, { "code": null, "e": 25249, "s": 25238, "text": "Example 2:" }, { "code": "# R program to convert an object to vector # Creating a matrixx <- matrix(c(1:9), 3, 3)x # Calling as.vector() Functionas.vector(x)", "e": 25383, "s": 25249, "text": null }, { "code": null, "e": 25391, "s": 25383, "text": "Output:" }, { "code": null, "e": 25500, "s": 25391, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n[1] 1 2 3 4 5 6 7 8 9\n" }, { "code": null, "e": 25518, "s": 25500, "text": "R Object-Function" }, { "code": null, "e": 25536, "s": 25518, "text": "R Vector-Function" }, { "code": null, "e": 25547, "s": 25536, "text": "R Language" }, { "code": null, "e": 25645, "s": 25547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25654, "s": 25645, "text": "Comments" }, { "code": null, "e": 25667, "s": 25654, "text": "Old Comments" }, { "code": null, "e": 25719, "s": 25667, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25757, "s": 25719, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25792, "s": 25757, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25850, "s": 25792, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 25899, "s": 25850, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 25942, "s": 25899, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 25992, "s": 25942, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26009, "s": 25992, "text": "R - if statement" }, { "code": null, "e": 26046, "s": 26009, "text": "How to import an Excel File into R ?" } ]
SQLite - AND & OR Operators
SQLite AND & OR operators are used to compile multiple conditions to narrow down the selected data in an SQLite statement. These two operators are called conjunctive operators. These operators provide a means to make multiple comparisons with different operators in the same SQLite statement. The AND operator allows the existence of multiple conditions in a SQLite statement's WHERE clause. While using AND operator, complete condition will be assumed true when all the conditions are true. For example, [condition1] AND [condition2] will be true only when both condition1 and condition2 are true. Following is the basic syntax of AND operator with WHERE clause. SELECT column1, column2, columnN FROM table_name WHERE [condition1] AND [condition2]...AND [conditionN]; You can combine N number of conditions using AND operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE. Consider COMPANY table with the following records − ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00. sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000; ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 The OR operator is also used to combine multiple conditions in a SQLite statement's WHERE clause. While using OR operator, complete condition will be assumed true when at least any of the conditions is true. For example, [condition1] OR [condition2] will be true if either condition1 or condition2 is true. Following is the basic syntax of OR operator with WHERE clause. SELECT column1, column2, columnN FROM table_name WHERE [condition1] OR [condition2]...OR [conditionN] You can combine N number of conditions using OR operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE. Consider COMPANY table with the following records. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00. sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000; ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2815, "s": 2638, "text": "SQLite AND & OR operators are used to compile multiple conditions to narrow down the selected data in an SQLite statement. These two operators are called conjunctive operators." }, { "code": null, "e": 2931, "s": 2815, "text": "These operators provide a means to make multiple comparisons with different operators in the same SQLite statement." }, { "code": null, "e": 3237, "s": 2931, "text": "The AND operator allows the existence of multiple conditions in a SQLite statement's WHERE clause. While using AND operator, complete condition will be assumed true when all the conditions are true. For example, [condition1] AND [condition2] will be true only when both condition1 and condition2 are true." }, { "code": null, "e": 3302, "s": 3237, "text": "Following is the basic syntax of AND operator with WHERE clause." }, { "code": null, "e": 3409, "s": 3302, "text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition1] AND [condition2]...AND [conditionN];\n" }, { "code": null, "e": 3607, "s": 3409, "text": "You can combine N number of conditions using AND operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, all conditions separated by the AND must be TRUE." }, { "code": null, "e": 3659, "s": 3607, "text": "Consider COMPANY table with the following records −" }, { "code": null, "e": 4165, "s": 3659, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 4309, "s": 4165, "text": "Following SELECT statement lists down all the records where AGE is greater than or equal to 25 AND salary is greater than or equal to 65000.00." }, { "code": null, "e": 4603, "s": 4309, "text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0" }, { "code": null, "e": 4910, "s": 4603, "text": "The OR operator is also used to combine multiple conditions in a SQLite statement's WHERE clause. While using OR operator, complete condition will be assumed true when at least any of the conditions is true. For example, [condition1] OR [condition2] will be true if either condition1 or condition2 is true." }, { "code": null, "e": 4974, "s": 4910, "text": "Following is the basic syntax of OR operator with WHERE clause." }, { "code": null, "e": 5078, "s": 4974, "text": "SELECT column1, column2, columnN \nFROM table_name\nWHERE [condition1] OR [condition2]...OR [conditionN]\n" }, { "code": null, "e": 5290, "s": 5078, "text": "You can combine N number of conditions using OR operator. For an action to be taken by the SQLite statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE." }, { "code": null, "e": 5341, "s": 5290, "text": "Consider COMPANY table with the following records." }, { "code": null, "e": 5847, "s": 5341, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 5990, "s": 5847, "text": "Following SELECT statement lists down all the records where AGE is greater than or equal to 25 OR salary is greater than or equal to 65000.00." }, { "code": null, "e": 6395, "s": 5990, "text": "sqlite> SELECT * FROM COMPANY WHERE AGE >= 25 OR SALARY >= 65000;\n\nID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0" }, { "code": null, "e": 6430, "s": 6395, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6451, "s": 6430, "text": " Sandip Bhattacharya" }, { "code": null, "e": 6484, "s": 6451, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 6501, "s": 6484, "text": " Laurence Svekis" }, { "code": null, "e": 6532, "s": 6501, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 6545, "s": 6532, "text": " Vinay Kumar" }, { "code": null, "e": 6552, "s": 6545, "text": " Print" }, { "code": null, "e": 6563, "s": 6552, "text": " Add Notes" } ]
C# | How to create a Stack - GeeksforGeeks
18 Feb, 2019 Stack() constructor is used to initialize a new instance of the Stack class which will be empty and will have the default initial capacity. Stack represents a last-in, first out collection of object. It is used when you need last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. This class comes under System.Collections namespace. Syntax: public Stack (); Important Points: The number of elements that a Stack can hold is known as the Capacity of the Stack. If the elements will be added to the Stack then capacity will be automatically increased by reallocating the internal array. Specifying the initial capacity will eliminate the requirement to perform a number of resizing operations while adding elements to the Stack if the size of the collection can be estimated. This constructor is an O(1) operation. Example 1: // C# Program to illustrate how// to create a Stackusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // st is the Stack object // Stack() is the constructor // used to initializes a new // instance of the Stack class Stack st = new Stack(); // Count property is used to get the // number of elements in Stack // It will give 0 as no elements // are present currently Console.WriteLine(st.Count); }} 0 Example 2: // C# Program to illustrate how// to create a Stackusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // st is the Stack object // Stack() is the constructor // used to initializes a new // instance of the Stack class Stack st = new Stack(); Console.Write("Before Push Method: "); // Count property is used to get the // number of elements in Stack // It will give 0 as no elements // are present currently Console.WriteLine(st.Count); // Inserting the elements // into the Stack st.Push("Chandigarh"); st.Push("Delhi"); st.Push("Noida"); st.Push("Himachal"); st.Push("Punjab"); st.Push("Jammu"); Console.Write("After Push Method: "); // Count property is used to get the // number of elements in st Console.WriteLine(st.Count); }} Before Push Method: 0 After Push Method: 6 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.-ctor?view=netframework-4.7.2#System_Collections_Stack__ctor CSharp-Collections-Namespace CSharp-Collections-Stack C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Abstract Class and Interface in C# C# | IsNullOrEmpty() Method C# | Class and Object C# Dictionary with examples C# | Method Overriding C# | Constructors String.Split() Method in C# with Examples C# | Arrays of Strings Difference between Ref and Out keywords in C# C# | How to check whether a List contains a specified element
[ { "code": null, "e": 23208, "s": 23180, "text": "\n18 Feb, 2019" }, { "code": null, "e": 23641, "s": 23208, "text": "Stack() constructor is used to initialize a new instance of the Stack class which will be empty and will have the default initial capacity. Stack represents a last-in, first out collection of object. It is used when you need last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. This class comes under System.Collections namespace." }, { "code": null, "e": 23649, "s": 23641, "text": "Syntax:" }, { "code": null, "e": 23666, "s": 23649, "text": "public Stack ();" }, { "code": null, "e": 23684, "s": 23666, "text": "Important Points:" }, { "code": null, "e": 23893, "s": 23684, "text": "The number of elements that a Stack can hold is known as the Capacity of the Stack. If the elements will be added to the Stack then capacity will be automatically increased by reallocating the internal array." }, { "code": null, "e": 24082, "s": 23893, "text": "Specifying the initial capacity will eliminate the requirement to perform a number of resizing operations while adding elements to the Stack if the size of the collection can be estimated." }, { "code": null, "e": 24121, "s": 24082, "text": "This constructor is an O(1) operation." }, { "code": null, "e": 24132, "s": 24121, "text": "Example 1:" }, { "code": "// C# Program to illustrate how// to create a Stackusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // st is the Stack object // Stack() is the constructor // used to initializes a new // instance of the Stack class Stack st = new Stack(); // Count property is used to get the // number of elements in Stack // It will give 0 as no elements // are present currently Console.WriteLine(st.Count); }}", "e": 24680, "s": 24132, "text": null }, { "code": null, "e": 24683, "s": 24680, "text": "0\n" }, { "code": null, "e": 24694, "s": 24683, "text": "Example 2:" }, { "code": "// C# Program to illustrate how// to create a Stackusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // st is the Stack object // Stack() is the constructor // used to initializes a new // instance of the Stack class Stack st = new Stack(); Console.Write(\"Before Push Method: \"); // Count property is used to get the // number of elements in Stack // It will give 0 as no elements // are present currently Console.WriteLine(st.Count); // Inserting the elements // into the Stack st.Push(\"Chandigarh\"); st.Push(\"Delhi\"); st.Push(\"Noida\"); st.Push(\"Himachal\"); st.Push(\"Punjab\"); st.Push(\"Jammu\"); Console.Write(\"After Push Method: \"); // Count property is used to get the // number of elements in st Console.WriteLine(st.Count); }}", "e": 25690, "s": 24694, "text": null }, { "code": null, "e": 25734, "s": 25690, "text": "Before Push Method: 0\nAfter Push Method: 6\n" }, { "code": null, "e": 25745, "s": 25734, "text": "Reference:" }, { "code": null, "e": 25875, "s": 25745, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.-ctor?view=netframework-4.7.2#System_Collections_Stack__ctor" }, { "code": null, "e": 25904, "s": 25875, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 25929, "s": 25904, "text": "CSharp-Collections-Stack" }, { "code": null, "e": 25932, "s": 25929, "text": "C#" }, { "code": null, "e": 26030, "s": 25932, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26039, "s": 26030, "text": "Comments" }, { "code": null, "e": 26052, "s": 26039, "text": "Old Comments" }, { "code": null, "e": 26106, "s": 26052, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 26134, "s": 26106, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 26156, "s": 26134, "text": "C# | Class and Object" }, { "code": null, "e": 26184, "s": 26156, "text": "C# Dictionary with examples" }, { "code": null, "e": 26207, "s": 26184, "text": "C# | Method Overriding" }, { "code": null, "e": 26225, "s": 26207, "text": "C# | Constructors" }, { "code": null, "e": 26267, "s": 26225, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 26290, "s": 26267, "text": "C# | Arrays of Strings" }, { "code": null, "e": 26336, "s": 26290, "text": "Difference between Ref and Out keywords in C#" } ]
Program to calculate Area Of Octagon
An octagon is a polygon with eight sides. To calculate the area of octagon the following formula is used, Area of octagon = ((a2*2) / *tan (22.5°)) = ((2*a*a)(1+√2)) Code Logic, The area of a polygon with eight side is calculated by using the above formula. The expression uses sqrt function to find the square root of 2. The value of expression is evaluated as a floating point value that is put into the float area variable. Live Demo #include <stdio.h> #include <math.h> int main(){ int a = 7; float area; float multiplier = 6.18; printf("Program to find area of octagon \n"); printf("The side of the octagon is %d \n", a); area = ((2*a*a)*(1 + sqrt(2))); printf("The area of Enneagon is %f \n", area); return 0; } Program to find area of octagon The side of the octagon is 7 The area of Enneagon is 236.592926
[ { "code": null, "e": 1168, "s": 1062, "text": "An octagon is a polygon with eight sides. To calculate the area of octagon the following formula is used," }, { "code": null, "e": 1228, "s": 1168, "text": "Area of octagon = ((a2*2) / *tan (22.5°)) = ((2*a*a)(1+√2))" }, { "code": null, "e": 1489, "s": 1228, "text": "Code Logic, The area of a polygon with eight side is calculated by using the above formula. The expression uses sqrt function to find the square root of 2. The value of expression is evaluated as a floating point value that is put into the float area variable." }, { "code": null, "e": 1500, "s": 1489, "text": " Live Demo" }, { "code": null, "e": 1805, "s": 1500, "text": "#include <stdio.h>\n#include <math.h>\nint main(){\n int a = 7;\n float area;\n float multiplier = 6.18;\n printf(\"Program to find area of octagon \\n\");\n printf(\"The side of the octagon is %d \\n\", a);\n area = ((2*a*a)*(1 + sqrt(2)));\n printf(\"The area of Enneagon is %f \\n\", area);\n return 0;\n}" }, { "code": null, "e": 1901, "s": 1805, "text": "Program to find area of octagon\nThe side of the octagon is 7\nThe area of Enneagon is 236.592926" } ]
Features of Cassandra - GeeksforGeeks
15 Nov, 2021 Apache Cassandra is an open source, user-available, distributed, NoSQL DBMS which is designed to handle large amounts of data across many servers. It provides zero point of failure. Cassandra offers massive support for clusters spanning multiple datacentres. There are some massive features of Cassandra. Here are some of the features described below: Distributed: Each node in the cluster has has same role. There’s no question of failure & the data set is distributed across the cluster but one issue is there that is the master isn’t present in each node to support request for service.Supports replication & Multi data center replication: Replication factor comes with best configurations in cassandra. Cassandra is designed to have a distributed system, for the deployment of large number of nodes for across multiple data centers and other key features too.Scalability: It is designed to r/w throughput, Increase gradually as new machines are added without interrupting other applications.Fault-tolerance: Data is automatically stored & replicated for fault-tolerance. If a node Fails, then it is replaced within no time.MapReduce Support: It supports Hadoop integration with MapReduce support.Apache Hive & Apache Pig is also supported.Query Language: Cassandra has introduced the CQL (Cassandra Query Language). Its a simple interface for accessing the Cassandra. Distributed: Each node in the cluster has has same role. There’s no question of failure & the data set is distributed across the cluster but one issue is there that is the master isn’t present in each node to support request for service. Supports replication & Multi data center replication: Replication factor comes with best configurations in cassandra. Cassandra is designed to have a distributed system, for the deployment of large number of nodes for across multiple data centers and other key features too. Scalability: It is designed to r/w throughput, Increase gradually as new machines are added without interrupting other applications. Fault-tolerance: Data is automatically stored & replicated for fault-tolerance. If a node Fails, then it is replaced within no time. MapReduce Support: It supports Hadoop integration with MapReduce support.Apache Hive & Apache Pig is also supported. Query Language: Cassandra has introduced the CQL (Cassandra Query Language). Its a simple interface for accessing the Cassandra. Cassandra Query Language (CQL) : CQL has simple interface for accessing the Cassandra, also an alternative for the traditional SQL. CQL adds an abstraction layer to hide the implementation of structure & also provides the native syntax for collections. For example please follow the given sample which shows how to create a keyspace including column family in CQL 3.0- CREATE KEYSPACE MyKeySpace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 3 }; USE MyKeySpace; CREATE COLUMNFAMILY MyColumns (id text, Last text, First text, PRIMARY KEY(id)); INSERT INTO MyColumns (id, Last, First) VALUES ('1', 'Doe', 'John'); Query: SELECT * FROM MyColumns; Which gives: id | First | Last ----+-------+------ 1 | Ratul | Sarkar (1 rows) Some facts regarding Cassandra are as follows: Before the updates of versions of Cassandra, upto Cassandra 1.0, Cassandra wasn’t row level consistent, which means inserting & updating the table. It may affect the same row that are processed at approximately the same time may affect the non-key columns in a inconsistent manner. Cassandra 1.1 solved this using row level isolation. Deletion of markers called the Tombstones (source Internet) are also known to causes performance degradation upto severe consequence levels. Cassandra, essentially a hybrid between a key-value & a organised tabular DBMS.Tables can be created, dropped and altered at run time without blocking updates & queries. A column family called table represents a RDBMS. Each row is specifically identified by a row & key, name, value, timestamp etc. A table in Cassandra is a disturbed multi dimensional map monitored by a key. Further more applications are specified by a super column family. sweetyty singghakshay Apache DBMS Technical Scripter DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Introduction of Relational Algebra in DBMS Two Phase Locking Protocol What is Temporary Table in SQL? KDD Process in Data Mining Conflict Serializability in DBMS MySQL | Regular expressions (Regexp) Nested Queries in SQL Difference between Star Schema and Snowflake Schema Difference between OLAP and OLTP in DBMS
[ { "code": null, "e": 24329, "s": 24301, "text": "\n15 Nov, 2021" }, { "code": null, "e": 24589, "s": 24329, "text": "Apache Cassandra is an open source, user-available, distributed, NoSQL DBMS which is designed to handle large amounts of data across many servers. It provides zero point of failure. Cassandra offers massive support for clusters spanning multiple datacentres. " }, { "code": null, "e": 24683, "s": 24589, "text": "There are some massive features of Cassandra. Here are some of the features described below: " }, { "code": null, "e": 25703, "s": 24683, "text": "Distributed: Each node in the cluster has has same role. There’s no question of failure & the data set is distributed across the cluster but one issue is there that is the master isn’t present in each node to support request for service.Supports replication & Multi data center replication: Replication factor comes with best configurations in cassandra. Cassandra is designed to have a distributed system, for the deployment of large number of nodes for across multiple data centers and other key features too.Scalability: It is designed to r/w throughput, Increase gradually as new machines are added without interrupting other applications.Fault-tolerance: Data is automatically stored & replicated for fault-tolerance. If a node Fails, then it is replaced within no time.MapReduce Support: It supports Hadoop integration with MapReduce support.Apache Hive & Apache Pig is also supported.Query Language: Cassandra has introduced the CQL (Cassandra Query Language). Its a simple interface for accessing the Cassandra." }, { "code": null, "e": 25941, "s": 25703, "text": "Distributed: Each node in the cluster has has same role. There’s no question of failure & the data set is distributed across the cluster but one issue is there that is the master isn’t present in each node to support request for service." }, { "code": null, "e": 26216, "s": 25941, "text": "Supports replication & Multi data center replication: Replication factor comes with best configurations in cassandra. Cassandra is designed to have a distributed system, for the deployment of large number of nodes for across multiple data centers and other key features too." }, { "code": null, "e": 26349, "s": 26216, "text": "Scalability: It is designed to r/w throughput, Increase gradually as new machines are added without interrupting other applications." }, { "code": null, "e": 26482, "s": 26349, "text": "Fault-tolerance: Data is automatically stored & replicated for fault-tolerance. If a node Fails, then it is replaced within no time." }, { "code": null, "e": 26599, "s": 26482, "text": "MapReduce Support: It supports Hadoop integration with MapReduce support.Apache Hive & Apache Pig is also supported." }, { "code": null, "e": 26728, "s": 26599, "text": "Query Language: Cassandra has introduced the CQL (Cassandra Query Language). Its a simple interface for accessing the Cassandra." }, { "code": null, "e": 26982, "s": 26728, "text": "Cassandra Query Language (CQL) : CQL has simple interface for accessing the Cassandra, also an alternative for the traditional SQL. CQL adds an abstraction layer to hide the implementation of structure & also provides the native syntax for collections. " }, { "code": null, "e": 27099, "s": 26982, "text": "For example please follow the given sample which shows how to create a keyspace including column family in CQL 3.0- " }, { "code": null, "e": 27428, "s": 27099, "text": "CREATE KEYSPACE MyKeySpace\nWITH REPLICATION = { 'class' : 'SimpleStrategy', \n 'replication_factor' : 3 };\n\nUSE MyKeySpace;\n\nCREATE COLUMNFAMILY MyColumns (id text, Last text, \n First text, PRIMARY KEY(id));\n\nINSERT INTO MyColumns (id, Last, First) \nVALUES ('1', 'Doe', 'John'); " }, { "code": null, "e": 27437, "s": 27428, "text": "Query: " }, { "code": null, "e": 27463, "s": 27437, "text": "SELECT * FROM MyColumns; " }, { "code": null, "e": 27478, "s": 27463, "text": "Which gives: " }, { "code": null, "e": 27536, "s": 27478, "text": "id | First | Last\n----+-------+------\n1 | Ratul | Sarkar " }, { "code": null, "e": 27546, "s": 27536, "text": "(1 rows) " }, { "code": null, "e": 27595, "s": 27546, "text": "Some facts regarding Cassandra are as follows: " }, { "code": null, "e": 27930, "s": 27595, "text": "Before the updates of versions of Cassandra, upto Cassandra 1.0, Cassandra wasn’t row level consistent, which means inserting & updating the table. It may affect the same row that are processed at approximately the same time may affect the non-key columns in a inconsistent manner. Cassandra 1.1 solved this using row level isolation." }, { "code": null, "e": 28071, "s": 27930, "text": "Deletion of markers called the Tombstones (source Internet) are also known to causes performance degradation upto severe consequence levels." }, { "code": null, "e": 28241, "s": 28071, "text": "Cassandra, essentially a hybrid between a key-value & a organised tabular DBMS.Tables can be created, dropped and altered at run time without blocking updates & queries." }, { "code": null, "e": 28515, "s": 28241, "text": "A column family called table represents a RDBMS. Each row is specifically identified by a row & key, name, value, timestamp etc. A table in Cassandra is a disturbed multi dimensional map monitored by a key. Further more applications are specified by a super column family. " }, { "code": null, "e": 28524, "s": 28515, "text": "sweetyty" }, { "code": null, "e": 28537, "s": 28524, "text": "singghakshay" }, { "code": null, "e": 28544, "s": 28537, "text": "Apache" }, { "code": null, "e": 28549, "s": 28544, "text": "DBMS" }, { "code": null, "e": 28568, "s": 28549, "text": "Technical Scripter" }, { "code": null, "e": 28573, "s": 28568, "text": "DBMS" }, { "code": null, "e": 28671, "s": 28573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28712, "s": 28671, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 28755, "s": 28712, "text": "Introduction of Relational Algebra in DBMS" }, { "code": null, "e": 28782, "s": 28755, "text": "Two Phase Locking Protocol" }, { "code": null, "e": 28814, "s": 28782, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 28841, "s": 28814, "text": "KDD Process in Data Mining" }, { "code": null, "e": 28874, "s": 28841, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 28911, "s": 28874, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 28933, "s": 28911, "text": "Nested Queries in SQL" }, { "code": null, "e": 28985, "s": 28933, "text": "Difference between Star Schema and Snowflake Schema" } ]
bc command in Linux with examples - GeeksforGeeks
21 Aug, 2021 bc command is used for command line calculator. It is similar to basic calculator by using which we can do basic mathematical calculations. Arithmetic operations are the most basic in any kind of programming language. Linux or Unix operating system provides the bc command and expr command for doing arithmetic calculations. You can use these commands in bash or shell script also for evaluating arithmetic expressions. Syntax: bc [ -hlwsqv ] [long-options] [ file ... ] Options: -h, {- -help } : Print the usage and exit -i, {- -interactive } : Force interactive mode -l, {- -mathlib } : Define the standard math library -w, {- -warn } : Give warnings for extensions to POSIX bc -s, {- -standard } : Process exactly the POSIX bc language -q, {- -quiet } : Do not print the normal GNU bc welcome -v, {- -version } : Print the version number and copyright and quit The bc command supports the following features: Arithmetic operators Increment or Decrement operators Assignment operators Comparison or Relational operators Logical or Boolean operators Math functions Conditional statements Iterative statements 1. Arithmetic Operators Examples: Input : $ echo "12+5" | bc Output : 17 Input : $ echo "10^2" | bc Output : 100 How to store the result of complete operation in variable? Example: Input: $ x=`echo "12+5" | bc` $ echo $x Output:17 Explanation: Stores the result of first line of input in variable x and then display variable x as $x. 2. Assignment Operators The list of assignments operators supported are: var = value : Assign the value to the variable var += value : similar to var = var + value var -= value : similar to var = var – value var *= value : similar to var = var * value var /= value : similar to var = var / value var ^= value : similar to var = var ^ value var %= value : similar to var = var % value Examples: Input: $ echo "var=10;var" | bc Output: 10 Explanation: Assign 10 to the variable and print the value on the terminal. Input: $ echo "var=10;var^=2;var" | bc Output: 100 Explanation: Squares the value of the variable and print the value on the terminal. How to store the result of complete operation in variable? Example: Input: $ x=`echo "var=500;var%=7;var" | bc` $ echo $x Output:3 Explanation: Stores the result of 500 modulo 7 i.e. remainder of 500/7 in variable x and then display variable x as $x. 3. Increment Operators There are 2 kinds of increment operators: ++var : Pre increment operator, variable is increased first and then result of variable is stored. var++ : Post increment operator, result of the variable is used first and then variable is incremented. Examples: Input: $ echo "var=10;++var" | bc Output: 11 Explanation: Variable is increased first and then result of variable is stored. Input: $ echo "var=10;var++" | bc Output: 10 Explanation: Result of the variable is used first and then variable is incremented. 4. Decrement Operators There are 2 kinds of decrement operators: – – var : Pre decrement operator, variable is decreased first and then result of variable is stored. var – – : Post decrement operator, result of the variable is used first and then variable is decremented. Examples: Input: $ echo "var=10;--var" | bc Output: 9 Explanation: Variable is decreased first and then result of variable is stored. Input: $ echo "var=10;var--" | bc Output: 10 Explanation: Result of the variable is used first and then variable is decremented. 5. Comparison or Relational Operators Relational operators are used to compare 2 numbers. If the comparison is true, then result is 1. Otherwise(false), returns 0. These operators are generally used in conditional statements like if. The list of relational operators supported in bc command are shown below: expr1<expr2 : Result is 1 if expr1 is strictly less than expr2. expr1<=expr2 : Result is 1 if expr1 is less than or equal to expr2. expr1>expr2 : Result is 1 if expr1 is strictly greater than expr2. expr1>=expr2 : Result is 1 if expr1 is greater than or equal to expr2. expr1==expr2 : Result is 1 if expr1 is equal to expr2. expr1!=expr2 : Result is 1 if expr1 is not equal to expr2. Examples: Input: $ echo "10>5" | bc Output: 1 Input: $ echo "1==2" | bc Output: 0 6. Logical or Boolean Operators Logical operators are mostly used in conditional statements. The result of the logical operators is either 1(TRUE) or 0(FALSE). expr1 && expr2 : Result is 1 if both expressions are non-zero. expr1 || expr2 : Result is 1 if either expression is non-zero. ! expr : Result is 1 if expr is 0. Examples: Input: $ echo "10 && 5" | bc Output: 1 Input: $ echo "0 || 0" | bc Output: 0 Input: $ echo "! 0" | bc Output: 1 7. Mathematical Functions The built-in math functions supported are : s (x): The sine of x, x is in radians. c (x) : The cosine of x, x is in radians. a (x) : The arctangent of x, arctangent returns radians. l (x) : The natural logarithm of x. e (x) : The exponential function of raising e to the value x. j (n,x) : The bessel function of integer order n of x. sqrt(x) : Square root of the number x. If the expression is negative, a run time error is generated. In addition to the math functions, the following functions are also supported : length(x) : returns the number of digits in x. read() : Reads the number from the standard input. scale(expression) : The value of the scale function is the number of digits after the decimal point in the expression. ibase and obase define the conversion base for input and output numbers. The default for both input and output is base 10. last (an extension) is a variable that has the value of the last printed number. Examples: Input: $ pi=`echo "h=10;4*a(1)" | bc -l` $ echo $pi Output: 3.14159265358979323844 Explanation: Assign the value of “pi” to the shell variable pi. Here, a refers to the arctangent function, which is part of the math library loaded with the -l option. Input: $ echo "scale($pi)" | bc -l Output: 20 Explanation: Gives the number of digits after decimal point in value of “pi” calculated in previous example. Input: $ echo "s($pi/3)" | bc -l Output: .86602540378443864675 Explanation: Gives sine values at “pi/3” angle. Angle must be in radians. Here, s refers to the sine function Input: $ echo "c($pi/3)" | bc -l Output: .50000000000000000001 Explanation: Gives cosine values at “pi/3” angle. Angle must be in radians. Here, c refers to the cosine function. Input: $ echo "e(3)" | bc -l Output:20.08553692318766774092 Explanation: Gives exponential^value as output. Input: $ echo "l(e(1))" | bc -l Output: .99999999999999999999 Explanation: Gives natural logarithm of the value i.e. w.r.t. base ‘e’. Input: $ echo "obase=2;15" | bc -l Output: 1111 Explanation: Convert Decimal to Binary. Input: $ echo "obase=8;9" | bc -l Output: 11 Explanation: Convert Decimal to Octal. Input: $ echo "ibase=2;1111" | bc -l Output: 15 Explanation: Convert Binary to Decimal. Input: $ echo "ibase=2;obase=8;10" | bc -l Output: 2 Explanation: Convert Binary to Octal. 8. Conditional Statements Conditional Statements are used to take decisions and execute statements based on these decisions. bc command supports the if condition. Syntax: if(condition) {statements} else {statements} Example: Input: $ echo 'n=8;m=10;if(n>m) print "n is greater" else print "m is greater" ' | bc -l Output: m is greater 9. Iterative statements bc command supports the for loop and while loop for doing iterations. Syntax: for(assignment; condition; updation) { statements..... ....... ........ } OR while(condition) { statements..... ....... ........ } Examples: Input: $ echo "for(i=1; i<=10; i++) {i;}" | bc Output: 1 2 3 4 5 6 7 8 9 10 Input: $ echo "i=1;while(i<=10) {i; i+=1}" | bc Output: 1 2 3 4 5 6 7 8 9 10 Explanation: Both examples prints numbers from 1 to 10 using the respective looping syntax. Some Pseudo Statements: break : This statement causes a forced exit of the most recent enclosing while statement or for statement. continue : The continue statement (an extension) causes the most recent enclosing for statement to start the next iteration. halt : The halt statement (an extension) is an executed statement that causes the bc processor to quit only when it is executed. For example, “if (0 == 1) halt” will not cause bc to terminate because the halt is not executed. return : Return the value 0 from a function. (See the section on functions). return(expression) : Return the value of the expression from a function. (See the section on functions). As an extension, the parenthesis are not required. limits : Print the local limits enforced by the local version of bc. (This is an extension). quit : When the quit statement is read, the bc processor is terminated, regardless of where the quit statement is found. For example, “if (0 == 1) quit” will cause bc to terminate. warranty : Print a warranty notice. (This is an extension). 10. Functions : Functions provide a method of defining a computation that can be executed later. Functions in bc always compute a value and return it to the caller. Function definitions are “dynamic” in the sense that a function is undefined until a definition is encountered in the input. That definition is then used until another definition function for the same name is encountered. The new definition then replaces the older definition. Syntax: define name (parameters) { statements....... ....... ........ return statement } 11. We can write our arithmetic expressions in a file and then execute those statements by providing the filename to the bc command. Example: Input : $ cat >> example.txt 2+5; var = 10*3 var print var quit Press ctrl+D $ bc example.txt Output : bc 1.06.95 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 7 30 TO AVOID SYSTEM GENERATED MESSAGE ON OUTPUT SCREEN, USE: $ bc -q example.txt Output : 7 30 12. Important Points: Bc command treats the semicolon (;) or newline as the statement separator.To group statements use the curly braces. Use with functions, if statement, for and while loops.If only an expression is specified as a statement, then bc command evaluates the expression and prints the result on the standard output.If an assignment operator is found. Bc command assigns the value to the variable and do not print the value on the terminal.A function should be defined before calling it. Always the function definition should appear first before the calling statements.If a standalone variable is found as a statement, bc command prints the value of the variable. You can also Use the print statement for displaying the list of values on the terminal. Bc command treats the semicolon (;) or newline as the statement separator. To group statements use the curly braces. Use with functions, if statement, for and while loops. If only an expression is specified as a statement, then bc command evaluates the expression and prints the result on the standard output. If an assignment operator is found. Bc command assigns the value to the variable and do not print the value on the terminal. A function should be defined before calling it. Always the function definition should appear first before the calling statements. If a standalone variable is found as a statement, bc command prints the value of the variable. You can also Use the print statement for displaying the list of values on the terminal. YouTubeGeeksforGeeks502K subscribersLinux Tutorials | bc - The Calculator | GeeksforGeeksWatch laterShareCopy link13/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_UwhS0IvwQk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Akansh Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. simmytarika5 varshagumber28 linux-command Linux-misc-commands 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 SORT command in Linux/Unix with examples curl command in Linux with Examples 'crontab' in Linux with Examples UDP Server-Client implementation in C diff command in Linux with examples Conditional Statements | Shell Script Cat command in Linux with examples Tail command in Linux with examples
[ { "code": null, "e": 24438, "s": 24410, "text": "\n21 Aug, 2021" }, { "code": null, "e": 24859, "s": 24438, "text": "bc command is used for command line calculator. It is similar to basic calculator by using which we can do basic mathematical calculations. Arithmetic operations are the most basic in any kind of programming language. Linux or Unix operating system provides the bc command and expr command for doing arithmetic calculations. You can use these commands in bash or shell script also for evaluating arithmetic expressions. " }, { "code": null, "e": 24868, "s": 24859, "text": "Syntax: " }, { "code": null, "e": 24912, "s": 24868, "text": "bc [ -hlwsqv ] [long-options] [ file ... ] " }, { "code": null, "e": 25306, "s": 24912, "text": "Options: -h, {- -help } : Print the usage and exit -i, {- -interactive } : Force interactive mode -l, {- -mathlib } : Define the standard math library -w, {- -warn } : Give warnings for extensions to POSIX bc -s, {- -standard } : Process exactly the POSIX bc language -q, {- -quiet } : Do not print the normal GNU bc welcome -v, {- -version } : Print the version number and copyright and quit " }, { "code": null, "e": 25355, "s": 25306, "text": "The bc command supports the following features: " }, { "code": null, "e": 25376, "s": 25355, "text": "Arithmetic operators" }, { "code": null, "e": 25409, "s": 25376, "text": "Increment or Decrement operators" }, { "code": null, "e": 25430, "s": 25409, "text": "Assignment operators" }, { "code": null, "e": 25465, "s": 25430, "text": "Comparison or Relational operators" }, { "code": null, "e": 25494, "s": 25465, "text": "Logical or Boolean operators" }, { "code": null, "e": 25509, "s": 25494, "text": "Math functions" }, { "code": null, "e": 25532, "s": 25509, "text": "Conditional statements" }, { "code": null, "e": 25554, "s": 25532, "text": "Iterative statements " }, { "code": null, "e": 25579, "s": 25554, "text": "1. Arithmetic Operators " }, { "code": null, "e": 25591, "s": 25579, "text": "Examples: " }, { "code": null, "e": 25671, "s": 25591, "text": "Input : $ echo \"12+5\" | bc\nOutput : 17\n\nInput : $ echo \"10^2\" | bc\nOutput : 100" }, { "code": null, "e": 25731, "s": 25671, "text": "How to store the result of complete operation in variable? " }, { "code": null, "e": 25742, "s": 25731, "text": "Example: " }, { "code": null, "e": 25782, "s": 25742, "text": "Input:\n$ x=`echo \"12+5\" | bc`\n$ echo $x" }, { "code": null, "e": 25792, "s": 25782, "text": "Output:17" }, { "code": null, "e": 25896, "s": 25792, "text": "Explanation: Stores the result of first line of input in variable x and then display variable x as $x. " }, { "code": null, "e": 25971, "s": 25896, "text": "2. Assignment Operators The list of assignments operators supported are: " }, { "code": null, "e": 26018, "s": 25971, "text": "var = value : Assign the value to the variable" }, { "code": null, "e": 26062, "s": 26018, "text": "var += value : similar to var = var + value" }, { "code": null, "e": 26106, "s": 26062, "text": "var -= value : similar to var = var – value" }, { "code": null, "e": 26150, "s": 26106, "text": "var *= value : similar to var = var * value" }, { "code": null, "e": 26194, "s": 26150, "text": "var /= value : similar to var = var / value" }, { "code": null, "e": 26238, "s": 26194, "text": "var ^= value : similar to var = var ^ value" }, { "code": null, "e": 26282, "s": 26238, "text": "var %= value : similar to var = var % value" }, { "code": null, "e": 26294, "s": 26282, "text": "Examples: " }, { "code": null, "e": 26337, "s": 26294, "text": "Input: $ echo \"var=10;var\" | bc\nOutput: 10" }, { "code": null, "e": 26415, "s": 26337, "text": "Explanation: Assign 10 to the variable and print the value on the terminal. " }, { "code": null, "e": 26466, "s": 26415, "text": "Input: $ echo \"var=10;var^=2;var\" | bc\nOutput: 100" }, { "code": null, "e": 26551, "s": 26466, "text": "Explanation: Squares the value of the variable and print the value on the terminal. " }, { "code": null, "e": 26611, "s": 26551, "text": "How to store the result of complete operation in variable? " }, { "code": null, "e": 26622, "s": 26611, "text": "Example: " }, { "code": null, "e": 26677, "s": 26622, "text": "Input:\n$ x=`echo \"var=500;var%=7;var\" | bc`\n$ echo $x " }, { "code": null, "e": 26686, "s": 26677, "text": "Output:3" }, { "code": null, "e": 26807, "s": 26686, "text": "Explanation: Stores the result of 500 modulo 7 i.e. remainder of 500/7 in variable x and then display variable x as $x. " }, { "code": null, "e": 26874, "s": 26807, "text": "3. Increment Operators There are 2 kinds of increment operators: " }, { "code": null, "e": 26973, "s": 26874, "text": "++var : Pre increment operator, variable is increased first and then result of variable is stored." }, { "code": null, "e": 27077, "s": 26973, "text": "var++ : Post increment operator, result of the variable is used first and then variable is incremented." }, { "code": null, "e": 27089, "s": 27077, "text": "Examples: " }, { "code": null, "e": 27134, "s": 27089, "text": "Input: $ echo \"var=10;++var\" | bc\nOutput: 11" }, { "code": null, "e": 27216, "s": 27134, "text": "Explanation: Variable is increased first and then result of variable is stored. " }, { "code": null, "e": 27261, "s": 27216, "text": "Input: $ echo \"var=10;var++\" | bc\nOutput: 10" }, { "code": null, "e": 27346, "s": 27261, "text": "Explanation: Result of the variable is used first and then variable is incremented. " }, { "code": null, "e": 27412, "s": 27346, "text": "4. Decrement Operators There are 2 kinds of decrement operators: " }, { "code": null, "e": 27513, "s": 27412, "text": "– – var : Pre decrement operator, variable is decreased first and then result of variable is stored." }, { "code": null, "e": 27619, "s": 27513, "text": "var – – : Post decrement operator, result of the variable is used first and then variable is decremented." }, { "code": null, "e": 27631, "s": 27619, "text": "Examples: " }, { "code": null, "e": 27675, "s": 27631, "text": "Input: $ echo \"var=10;--var\" | bc\nOutput: 9" }, { "code": null, "e": 27757, "s": 27675, "text": "Explanation: Variable is decreased first and then result of variable is stored. " }, { "code": null, "e": 27802, "s": 27757, "text": "Input: $ echo \"var=10;var--\" | bc\nOutput: 10" }, { "code": null, "e": 27887, "s": 27802, "text": "Explanation: Result of the variable is used first and then variable is decremented. " }, { "code": null, "e": 28122, "s": 27887, "text": "5. Comparison or Relational Operators Relational operators are used to compare 2 numbers. If the comparison is true, then result is 1. Otherwise(false), returns 0. These operators are generally used in conditional statements like if. " }, { "code": null, "e": 28197, "s": 28122, "text": "The list of relational operators supported in bc command are shown below: " }, { "code": null, "e": 28261, "s": 28197, "text": "expr1<expr2 : Result is 1 if expr1 is strictly less than expr2." }, { "code": null, "e": 28329, "s": 28261, "text": "expr1<=expr2 : Result is 1 if expr1 is less than or equal to expr2." }, { "code": null, "e": 28396, "s": 28329, "text": "expr1>expr2 : Result is 1 if expr1 is strictly greater than expr2." }, { "code": null, "e": 28467, "s": 28396, "text": "expr1>=expr2 : Result is 1 if expr1 is greater than or equal to expr2." }, { "code": null, "e": 28522, "s": 28467, "text": "expr1==expr2 : Result is 1 if expr1 is equal to expr2." }, { "code": null, "e": 28581, "s": 28522, "text": "expr1!=expr2 : Result is 1 if expr1 is not equal to expr2." }, { "code": null, "e": 28593, "s": 28581, "text": "Examples: " }, { "code": null, "e": 28666, "s": 28593, "text": "Input: $ echo \"10>5\" | bc\nOutput: 1\n\nInput: $ echo \"1==2\" | bc\nOutput: 0" }, { "code": null, "e": 28828, "s": 28666, "text": "6. Logical or Boolean Operators Logical operators are mostly used in conditional statements. The result of the logical operators is either 1(TRUE) or 0(FALSE). " }, { "code": null, "e": 28891, "s": 28828, "text": "expr1 && expr2 : Result is 1 if both expressions are non-zero." }, { "code": null, "e": 28954, "s": 28891, "text": "expr1 || expr2 : Result is 1 if either expression is non-zero." }, { "code": null, "e": 28989, "s": 28954, "text": "! expr : Result is 1 if expr is 0." }, { "code": null, "e": 29001, "s": 28989, "text": "Examples: " }, { "code": null, "e": 29115, "s": 29001, "text": "Input: $ echo \"10 && 5\" | bc\nOutput: 1\n\nInput: $ echo \"0 || 0\" | bc\nOutput: 0\n\nInput: $ echo \"! 0\" | bc\nOutput: 1" }, { "code": null, "e": 29187, "s": 29115, "text": "7. Mathematical Functions The built-in math functions supported are : " }, { "code": null, "e": 29226, "s": 29187, "text": "s (x): The sine of x, x is in radians." }, { "code": null, "e": 29268, "s": 29226, "text": "c (x) : The cosine of x, x is in radians." }, { "code": null, "e": 29325, "s": 29268, "text": "a (x) : The arctangent of x, arctangent returns radians." }, { "code": null, "e": 29361, "s": 29325, "text": "l (x) : The natural logarithm of x." }, { "code": null, "e": 29423, "s": 29361, "text": "e (x) : The exponential function of raising e to the value x." }, { "code": null, "e": 29478, "s": 29423, "text": "j (n,x) : The bessel function of integer order n of x." }, { "code": null, "e": 29580, "s": 29478, "text": "sqrt(x) : Square root of the number x. If the expression is negative, a run time error is generated. " }, { "code": null, "e": 29661, "s": 29580, "text": "In addition to the math functions, the following functions are also supported : " }, { "code": null, "e": 29708, "s": 29661, "text": "length(x) : returns the number of digits in x." }, { "code": null, "e": 29759, "s": 29708, "text": "read() : Reads the number from the standard input." }, { "code": null, "e": 29879, "s": 29759, "text": "scale(expression) : The value of the scale function is the number of digits after the decimal point in the expression. " }, { "code": null, "e": 30002, "s": 29879, "text": "ibase and obase define the conversion base for input and output numbers. The default for both input and output is base 10." }, { "code": null, "e": 30083, "s": 30002, "text": "last (an extension) is a variable that has the value of the last printed number." }, { "code": null, "e": 30095, "s": 30083, "text": "Examples: " }, { "code": null, "e": 30180, "s": 30095, "text": "Input: \n$ pi=`echo \"h=10;4*a(1)\" | bc -l`\n$ echo $pi\nOutput: 3.14159265358979323844" }, { "code": null, "e": 30350, "s": 30180, "text": "Explanation: Assign the value of “pi” to the shell variable pi. Here, a refers to the arctangent function, which is part of the math library loaded with the -l option. " }, { "code": null, "e": 30396, "s": 30350, "text": "Input: $ echo \"scale($pi)\" | bc -l\nOutput: 20" }, { "code": null, "e": 30507, "s": 30396, "text": "Explanation: Gives the number of digits after decimal point in value of “pi” calculated in previous example. " }, { "code": null, "e": 30570, "s": 30507, "text": "Input: $ echo \"s($pi/3)\" | bc -l\nOutput: .86602540378443864675" }, { "code": null, "e": 30682, "s": 30570, "text": "Explanation: Gives sine values at “pi/3” angle. Angle must be in radians. Here, s refers to the sine function " }, { "code": null, "e": 30745, "s": 30682, "text": "Input: $ echo \"c($pi/3)\" | bc -l\nOutput: .50000000000000000001" }, { "code": null, "e": 30862, "s": 30745, "text": "Explanation: Gives cosine values at “pi/3” angle. Angle must be in radians. Here, c refers to the cosine function. " }, { "code": null, "e": 30923, "s": 30862, "text": "Input: $ echo \"e(3)\" | bc -l\nOutput:20.08553692318766774092 " }, { "code": null, "e": 30973, "s": 30923, "text": "Explanation: Gives exponential^value as output. " }, { "code": null, "e": 31035, "s": 30973, "text": "Input: $ echo \"l(e(1))\" | bc -l\nOutput: .99999999999999999999" }, { "code": null, "e": 31109, "s": 31035, "text": "Explanation: Gives natural logarithm of the value i.e. w.r.t. base ‘e’. " }, { "code": null, "e": 31157, "s": 31109, "text": "Input: $ echo \"obase=2;15\" | bc -l\nOutput: 1111" }, { "code": null, "e": 31198, "s": 31157, "text": "Explanation: Convert Decimal to Binary. " }, { "code": null, "e": 31243, "s": 31198, "text": "Input: $ echo \"obase=8;9\" | bc -l\nOutput: 11" }, { "code": null, "e": 31283, "s": 31243, "text": "Explanation: Convert Decimal to Octal. " }, { "code": null, "e": 31331, "s": 31283, "text": "Input: $ echo \"ibase=2;1111\" | bc -l\nOutput: 15" }, { "code": null, "e": 31372, "s": 31331, "text": "Explanation: Convert Binary to Decimal. " }, { "code": null, "e": 31425, "s": 31372, "text": "Input: $ echo \"ibase=2;obase=8;10\" | bc -l\nOutput: 2" }, { "code": null, "e": 31464, "s": 31425, "text": "Explanation: Convert Binary to Octal. " }, { "code": null, "e": 31491, "s": 31464, "text": "8. Conditional Statements " }, { "code": null, "e": 31629, "s": 31491, "text": "Conditional Statements are used to take decisions and execute statements based on these decisions. bc command supports the if condition. " }, { "code": null, "e": 31639, "s": 31629, "text": "Syntax: " }, { "code": null, "e": 31684, "s": 31639, "text": "if(condition) {statements} else {statements}" }, { "code": null, "e": 31695, "s": 31684, "text": "Example: " }, { "code": null, "e": 31805, "s": 31695, "text": "Input: $ echo 'n=8;m=10;if(n>m) print \"n is greater\" else print \"m is greater\" ' | bc -l\nOutput: m is greater" }, { "code": null, "e": 31900, "s": 31805, "text": "9. Iterative statements bc command supports the for loop and while loop for doing iterations. " }, { "code": null, "e": 31909, "s": 31900, "text": "Syntax: " }, { "code": null, "e": 32078, "s": 31909, "text": "for(assignment; condition; updation)\n{\n statements.....\n .......\n ........\n}\n\nOR\n\nwhile(condition)\n{\n statements.....\n .......\n ........\n}" }, { "code": null, "e": 32090, "s": 32078, "text": "Examples: " }, { "code": null, "e": 32167, "s": 32090, "text": "Input: $ echo \"for(i=1; i<=10; i++) {i;}\" | bc\nOutput: \n1\n2\n3\n4\n5\n6\n7\n8\n9\n10" }, { "code": null, "e": 32245, "s": 32167, "text": "Input: $ echo \"i=1;while(i<=10) {i; i+=1}\" | bc\nOutput: \n1\n2\n3\n4\n5\n6\n7\n8\n9\n10" }, { "code": null, "e": 32363, "s": 32245, "text": "Explanation: Both examples prints numbers from 1 to 10 using the respective looping syntax. Some Pseudo Statements: " }, { "code": null, "e": 32470, "s": 32363, "text": "break : This statement causes a forced exit of the most recent enclosing while statement or for statement." }, { "code": null, "e": 32595, "s": 32470, "text": "continue : The continue statement (an extension) causes the most recent enclosing for statement to start the next iteration." }, { "code": null, "e": 32821, "s": 32595, "text": "halt : The halt statement (an extension) is an executed statement that causes the bc processor to quit only when it is executed. For example, “if (0 == 1) halt” will not cause bc to terminate because the halt is not executed." }, { "code": null, "e": 32898, "s": 32821, "text": "return : Return the value 0 from a function. (See the section on functions)." }, { "code": null, "e": 33054, "s": 32898, "text": "return(expression) : Return the value of the expression from a function. (See the section on functions). As an extension, the parenthesis are not required." }, { "code": null, "e": 33147, "s": 33054, "text": "limits : Print the local limits enforced by the local version of bc. (This is an extension)." }, { "code": null, "e": 33328, "s": 33147, "text": "quit : When the quit statement is read, the bc processor is terminated, regardless of where the quit statement is found. For example, “if (0 == 1) quit” will cause bc to terminate." }, { "code": null, "e": 33388, "s": 33328, "text": "warranty : Print a warranty notice. (This is an extension)." }, { "code": null, "e": 33831, "s": 33388, "text": "10. Functions : Functions provide a method of defining a computation that can be executed later. Functions in bc always compute a value and return it to the caller. Function definitions are “dynamic” in the sense that a function is undefined until a definition is encountered in the input. That definition is then used until another definition function for the same name is encountered. The new definition then replaces the older definition. " }, { "code": null, "e": 33841, "s": 33831, "text": "Syntax: " }, { "code": null, "e": 33957, "s": 33841, "text": "define name (parameters) \n{\n statements.......\n .......\n ........\n return statement\n\n} " }, { "code": null, "e": 34091, "s": 33957, "text": "11. We can write our arithmetic expressions in a file and then execute those statements by providing the filename to the bc command. " }, { "code": null, "e": 34102, "s": 34091, "text": "Example: " }, { "code": null, "e": 34199, "s": 34102, "text": "Input : \n$ cat >> example.txt\n2+5;\nvar = 10*3\nvar\nprint var\nquit\n\nPress ctrl+D\n\n$ bc example.txt" }, { "code": null, "e": 34386, "s": 34199, "text": "Output : \nbc 1.06.95\nCopyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.\nThis is free software with ABSOLUTELY NO WARRANTY.\nFor details type `warranty'.\n7\n30" }, { "code": null, "e": 34445, "s": 34386, "text": "TO AVOID SYSTEM GENERATED MESSAGE ON OUTPUT SCREEN, USE: " }, { "code": null, "e": 34465, "s": 34445, "text": "$ bc -q example.txt" }, { "code": null, "e": 34479, "s": 34465, "text": "Output :\n7\n30" }, { "code": null, "e": 34503, "s": 34479, "text": "12. Important Points: " }, { "code": null, "e": 35248, "s": 34503, "text": "Bc command treats the semicolon (;) or newline as the statement separator.To group statements use the curly braces. Use with functions, if statement, for and while loops.If only an expression is specified as a statement, then bc command evaluates the expression and prints the result on the standard output.If an assignment operator is found. Bc command assigns the value to the variable and do not print the value on the terminal.A function should be defined before calling it. Always the function definition should appear first before the calling statements.If a standalone variable is found as a statement, bc command prints the value of the variable. You can also Use the print statement for displaying the list of values on the terminal. " }, { "code": null, "e": 35323, "s": 35248, "text": "Bc command treats the semicolon (;) or newline as the statement separator." }, { "code": null, "e": 35420, "s": 35323, "text": "To group statements use the curly braces. Use with functions, if statement, for and while loops." }, { "code": null, "e": 35558, "s": 35420, "text": "If only an expression is specified as a statement, then bc command evaluates the expression and prints the result on the standard output." }, { "code": null, "e": 35683, "s": 35558, "text": "If an assignment operator is found. Bc command assigns the value to the variable and do not print the value on the terminal." }, { "code": null, "e": 35813, "s": 35683, "text": "A function should be defined before calling it. Always the function definition should appear first before the calling statements." }, { "code": null, "e": 35998, "s": 35813, "text": "If a standalone variable is found as a statement, bc command prints the value of the variable. You can also Use the print statement for displaying the list of values on the terminal. " }, { "code": null, "e": 36839, "s": 35998, "text": "YouTubeGeeksforGeeks502K subscribersLinux Tutorials | bc - The Calculator | GeeksforGeeksWatch laterShareCopy link13/36InfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_UwhS0IvwQk\" 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": 37136, "s": 36839, "text": "This article is contributed by Akansh Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 37262, "s": 37136, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37281, "s": 37268, "text": "simmytarika5" }, { "code": null, "e": 37296, "s": 37281, "text": "varshagumber28" }, { "code": null, "e": 37310, "s": 37296, "text": "linux-command" }, { "code": null, "e": 37330, "s": 37310, "text": "Linux-misc-commands" }, { "code": null, "e": 37341, "s": 37330, "text": "Linux-Unix" }, { "code": null, "e": 37439, "s": 37341, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37477, "s": 37439, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 37512, "s": 37477, "text": "tar command in Linux with examples" }, { "code": null, "e": 37553, "s": 37512, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 37589, "s": 37553, "text": "curl command in Linux with Examples" }, { "code": null, "e": 37622, "s": 37589, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 37660, "s": 37622, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 37696, "s": 37660, "text": "diff command in Linux with examples" }, { "code": null, "e": 37734, "s": 37696, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 37769, "s": 37734, "text": "Cat command in Linux with examples" } ]
Read last line from file in PHP
To read last line from file in PHP, the code is as follows − $line = ''; $f = fopen('data.txt', 'r'); $cursor = -1; fseek($f, $cursor, SEEK_END); $char = fgetc($f); //Trim trailing newline characters in the file while ($char === "\n" || $char === "\r") { fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } //Read until the next line of the file begins or the first newline char while ($char !== false && $char !== "\n" && $char !== "\r") { //Prepend the new character $line = $char . $line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } echo $line; Output will be the last line of the text file will be read and displayed. The text file is opened in read mode, and the cursor is set to point to -1, i.e. nothing initially. The ‘fseek’ function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed.
[ { "code": null, "e": 1123, "s": 1062, "text": "To read last line from file in PHP, the code is as follows −" }, { "code": null, "e": 1638, "s": 1123, "text": "$line = '';\n$f = fopen('data.txt', 'r');\n$cursor = -1;\nfseek($f, $cursor, SEEK_END);\n$char = fgetc($f);\n//Trim trailing newline characters in the file\nwhile ($char === \"\\n\" || $char === \"\\r\") {\n fseek($f, $cursor--, SEEK_END);\n $char = fgetc($f);\n}\n//Read until the next line of the file begins or the first newline char\nwhile ($char !== false && $char !== \"\\n\" && $char !== \"\\r\") {\n //Prepend the new character\n $line = $char . $line;\n fseek($f, $cursor--, SEEK_END);\n $char = fgetc($f);\n}\necho $line;" }, { "code": null, "e": 1712, "s": 1638, "text": "Output will be the last line of the text file will be read and displayed." }, { "code": null, "e": 1986, "s": 1712, "text": "The text file is opened in read mode, and the cursor is set to point to -1, i.e. nothing initially. The ‘fseek’ function is used to move to the end of the file or the last line. The line is read until a newline is encountered. After this, the read characters are displayed." } ]
How to Convert Decimal to Binary Using Recursion in Python?
Binary equivalent of a decimal number is obtained by printing in reverse order the remainder of successive division by 2. The recursive solution to this conversion is as follows: def tobin(x): strbin='' if x>1: tobin(x//2) print (x%2, end='') num=int(input('enter a number')) tobin(num) To test the output, run above code enter a number25 11001 enter a number16 10000
[ { "code": null, "e": 1241, "s": 1062, "text": "Binary equivalent of a decimal number is obtained by printing in reverse order the remainder of successive division by 2. The recursive solution to this conversion is as follows:" }, { "code": null, "e": 1406, "s": 1241, "text": "def tobin(x):\n strbin=''\n if x>1:\n tobin(x//2)\n print (x%2, end='')\n\nnum=int(input('enter a number'))\ntobin(num)\n\nTo test the output, run above code" }, { "code": null, "e": 1453, "s": 1406, "text": "enter a number25\n11001\nenter a number16\n10000\n" } ]
Quickly convert Decimal to other bases in Python - GeeksforGeeks
05 Jul, 2017 Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal. Examples: Input : 55 Output : 55 in Binary : 0b110111 55 in Octal : 0o67 55 in Hexadecimal : 0x37 Input : 282 Output : 282 in Binary : 0b100011010 282 in Octal : 0o432 282 in Hexadecimal : 0x11a One solution is to use the approach discussed in below post. Convert from any base to decimal and vice versa Python provides direct functions for standard base conversions like bin(), hex() and oct() # Python program to convert decimal to binary,# octal and hexadecimal # Function to convert decimal to binarydef decimal_to_binary(dec): decimal = int(dec) # Prints equivalent decimal print(decimal, " in Binary : ", bin(decimal)) # Function to convert decimal to octaldef decimal_to_octal(dec): decimal = int(dec) # Prints equivalent decimal print(decimal, "in Octal : ", oct(decimal)) # Function to convert decimal to hexadecimaldef decimal_to_hexadecimal(dec): decimal = int(dec) # Prints equivalent decimal print(decimal, " in Hexadecimal : ", hex(decimal)) # Driver programdec = 32decimal_to_binary(dec)decimal_to_octal(dec)decimal_to_hexadecimal(dec) Output: 32 in Binary : 0b100000 32 in Octal : 0o40 32 in Hexadecimal : 0x20 This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. base-conversion 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 ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe sum() function in Python Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 24504, "s": 24476, "text": "\n05 Jul, 2017" }, { "code": null, "e": 24683, "s": 24504, "text": "Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal." }, { "code": null, "e": 24693, "s": 24683, "text": "Examples:" }, { "code": null, "e": 24926, "s": 24693, "text": "Input : 55\nOutput : 55 in Binary : 0b110111\n 55 in Octal : 0o67\n 55 in Hexadecimal : 0x37\n\nInput : 282\nOutput : 282 in Binary : 0b100011010\n 282 in Octal : 0o432\n 282 in Hexadecimal : 0x11a\n" }, { "code": null, "e": 24987, "s": 24926, "text": "One solution is to use the approach discussed in below post." }, { "code": null, "e": 25035, "s": 24987, "text": "Convert from any base to decimal and vice versa" }, { "code": null, "e": 25126, "s": 25035, "text": "Python provides direct functions for standard base conversions like bin(), hex() and oct()" }, { "code": "# Python program to convert decimal to binary,# octal and hexadecimal # Function to convert decimal to binarydef decimal_to_binary(dec): decimal = int(dec) # Prints equivalent decimal print(decimal, \" in Binary : \", bin(decimal)) # Function to convert decimal to octaldef decimal_to_octal(dec): decimal = int(dec) # Prints equivalent decimal print(decimal, \"in Octal : \", oct(decimal)) # Function to convert decimal to hexadecimaldef decimal_to_hexadecimal(dec): decimal = int(dec) # Prints equivalent decimal print(decimal, \" in Hexadecimal : \", hex(decimal)) # Driver programdec = 32decimal_to_binary(dec)decimal_to_octal(dec)decimal_to_hexadecimal(dec)", "e": 25819, "s": 25126, "text": null }, { "code": null, "e": 25827, "s": 25819, "text": "Output:" }, { "code": null, "e": 25901, "s": 25827, "text": "32 in Binary : 0b100000\n32 in Octal : 0o40\n32 in Hexadecimal : 0x20\n" }, { "code": null, "e": 26201, "s": 25901, "text": "This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26326, "s": 26201, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26342, "s": 26326, "text": "base-conversion" }, { "code": null, "e": 26349, "s": 26342, "text": "Python" }, { "code": null, "e": 26447, "s": 26349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26456, "s": 26447, "text": "Comments" }, { "code": null, "e": 26469, "s": 26456, "text": "Old Comments" }, { "code": null, "e": 26501, "s": 26469, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26543, "s": 26501, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26580, "s": 26543, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26609, "s": 26580, "text": "*args and **kwargs in Python" }, { "code": null, "e": 26665, "s": 26609, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26690, "s": 26665, "text": "sum() function in Python" }, { "code": null, "e": 26711, "s": 26690, "text": "Python OOPs Concepts" }, { "code": null, "e": 26750, "s": 26711, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26792, "s": 26750, "text": "Check if element exists in list in Python" } ]
How to add drag behavior in kivy widget ? - GeeksforGeeks
30 Jun, 2021 In this article, we will develop a GUI window using kivy framework of python, and we will add a Label having drag behavior on this window Note: You can follow the same pattern for implementing drag events on other widgets also. Actually what we are doing is we are using are just using the concept of inheritance, and we are making a new widget(DraggableLabel) by combining the properties of Kivy Label widget and Kivy’s DragBehaviour class. And from the code, you can check that we have defined three properties drag_rectangle: it is the area in which we want to enable dragging you can see from the code the have used ourselves with the values of this property because we want to enable dragging in the whole Layout. drag_timeout: it specifies the time after which dragging will be disabled from the Label if Label is not dragged, but it will come into play again if we start dragging. drag_distance: Distance to move before dragging the DragBehavior, in pixels. As soon as the distance has been traveled, the DragBehavior will start to drag, and no touch event will be dispatched to the children. And after defining properties we are simply just using our newly created widget as we use others. Below is the Implementation: Python3 from kivy.app import Appfrom kivy.uix.label import Label # importing builder from kivyfrom kivy.lang import Builderfrom kivy.uix.behaviors import DragBehavior # using this class we will combine# the drag behaviour to our label widgetclass DraggableLabel(DragBehavior, Label): pass # this is the main class which# will render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string("""<DraggableLabel>: drag_rectangle: self.x, self.y, self.width, self.height drag_timeout: 10000 drag_distance: 0DraggableLabel: text:"[size=40]GeeksForGeeks[/size]" markup:True """) # running the applicationuiApp().run() Output: Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23927, "s": 23899, "text": "\n30 Jun, 2021" }, { "code": null, "e": 24065, "s": 23927, "text": "In this article, we will develop a GUI window using kivy framework of python, and we will add a Label having drag behavior on this window" }, { "code": null, "e": 24155, "s": 24065, "text": "Note: You can follow the same pattern for implementing drag events on other widgets also." }, { "code": null, "e": 24441, "s": 24155, "text": "Actually what we are doing is we are using are just using the concept of inheritance, and we are making a new widget(DraggableLabel) by combining the properties of Kivy Label widget and Kivy’s DragBehaviour class. And from the code, you can check that we have defined three properties " }, { "code": null, "e": 24647, "s": 24441, "text": "drag_rectangle: it is the area in which we want to enable dragging you can see from the code the have used ourselves with the values of this property because we want to enable dragging in the whole Layout." }, { "code": null, "e": 24816, "s": 24647, "text": "drag_timeout: it specifies the time after which dragging will be disabled from the Label if Label is not dragged, but it will come into play again if we start dragging." }, { "code": null, "e": 25028, "s": 24816, "text": "drag_distance: Distance to move before dragging the DragBehavior, in pixels. As soon as the distance has been traveled, the DragBehavior will start to drag, and no touch event will be dispatched to the children." }, { "code": null, "e": 25126, "s": 25028, "text": "And after defining properties we are simply just using our newly created widget as we use others." }, { "code": null, "e": 25155, "s": 25126, "text": "Below is the Implementation:" }, { "code": null, "e": 25163, "s": 25155, "text": "Python3" }, { "code": "from kivy.app import Appfrom kivy.uix.label import Label # importing builder from kivyfrom kivy.lang import Builderfrom kivy.uix.behaviors import DragBehavior # using this class we will combine# the drag behaviour to our label widgetclass DraggableLabel(DragBehavior, Label): pass # this is the main class which# will render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string(\"\"\"<DraggableLabel>: drag_rectangle: self.x, self.y, self.width, self.height drag_timeout: 10000 drag_distance: 0DraggableLabel: text:\"[size=40]GeeksForGeeks[/size]\" markup:True \"\"\") # running the applicationuiApp().run()", "e": 25907, "s": 25163, "text": null }, { "code": null, "e": 25915, "s": 25907, "text": "Output:" }, { "code": null, "e": 25927, "s": 25915, "text": "Python-kivy" }, { "code": null, "e": 25934, "s": 25927, "text": "Python" }, { "code": null, "e": 26032, "s": 25934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26041, "s": 26032, "text": "Comments" }, { "code": null, "e": 26054, "s": 26041, "text": "Old Comments" }, { "code": null, "e": 26075, "s": 26054, "text": "Python OOPs Concepts" }, { "code": null, "e": 26107, "s": 26075, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26130, "s": 26107, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 26152, "s": 26130, "text": "Defaultdict in Python" }, { "code": null, "e": 26179, "s": 26152, "text": "Python Classes and Objects" }, { "code": null, "e": 26195, "s": 26179, "text": "Deque in Python" }, { "code": null, "e": 26237, "s": 26195, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26293, "s": 26237, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26338, "s": 26293, "text": "Python - Ways to remove duplicates from list" } ]
F# - Variables
A variable is a name given to a storage area that our programs can manipulate. Each variable has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The let keyword is used for variable declaration − For example, let x = 10 It declares a variable x and assigns the value 10 to it. You can also assign an expression to a variable − let x = 10 let y = 20 let z = x + y The following example illustrates the concept − let x = 10 let y = 20 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z When you compile and execute the program, it yields the following output − x: 10 y: 20 z: 30 Variables in F# are immutable, which means once a variable is bound to a value, it can’t be changed. They are actually compiled as static read-only properties. The following example demonstrates this. let x = 10 let y = 20 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z let x = 15 let y = 20 let z = x + y printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z When you compile and execute the program, it shows the following error message − Duplicate definition of value 'x' Duplicate definition of value 'Y' Duplicate definition of value 'Z' A variable definition tells the compiler where and how much storage for the variable should be created. A variable definition may specify a data type and contains a list of one or more variables of that type as shown in the following example. let x:int32 = 10 let y:int32 = 20 let z:int32 = x + y printfn "x: %d" x printfn "y: %d" y printfn "z: %d" z let p:float = 15.99 let q:float = 20.78 let r:float = p + q printfn "p: %g" p printfn "q: %g" q printfn "r: %g" r When you compile and execute the program, it shows the following error message − x: 10 y: 20 z: 30 p: 15.99 q: 20.78 r: 36.77 At times you need to change the values stored in a variable. To specify that there could be a change in the value of a declared and assigned variable, in later part of a program, F# provides the mutable keyword. You can declare and assign mutable variables using this keyword, whose values you will change. The mutable keyword allows you to declare and assign values in a mutable variable. You can assign some initial value to a mutable variable using the let keyword. However, to assign new subsequent value to it, you need to use the ← operator. For example, let mutable x = 10 x ← 15 The following example will clear the concept − let mutable x = 10 let y = 20 let mutable z = x + y printfn "Original Values:" printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z printfn "Let us change the value of x" printfn "Value of z will change too." x <- 15 z <- x + y printfn "New Values:" printfn "x: %i" x printfn "y: %i" y printfn "z: %i" z When you compile and execute the program, it yields the following output − Original Values: x: 10 y: 20 z: 30 Let us change the value of x Value of z will change too. New Values: x: 15 y: 20 z: 35 Print Add Notes Bookmark this page
[ { "code": null, "e": 2460, "s": 2161, "text": "A variable is a name given to a storage area that our programs can manipulate. Each variable has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable." }, { "code": null, "e": 2511, "s": 2460, "text": "The let keyword is used for variable declaration −" }, { "code": null, "e": 2524, "s": 2511, "text": "For example," }, { "code": null, "e": 2536, "s": 2524, "text": "let x = 10\n" }, { "code": null, "e": 2593, "s": 2536, "text": "It declares a variable x and assigns the value 10 to it." }, { "code": null, "e": 2643, "s": 2593, "text": "You can also assign an expression to a variable −" }, { "code": null, "e": 2680, "s": 2643, "text": "let x = 10\nlet y = 20\nlet z = x + y\n" }, { "code": null, "e": 2728, "s": 2680, "text": "The following example illustrates the concept −" }, { "code": null, "e": 2819, "s": 2728, "text": "let x = 10\nlet y = 20\nlet z = x + y\n\nprintfn \"x: %i\" x\nprintfn \"y: %i\" y\nprintfn \"z: %i\" z" }, { "code": null, "e": 2894, "s": 2819, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 2913, "s": 2894, "text": "x: 10\ny: 20\nz: 30\n" }, { "code": null, "e": 3073, "s": 2913, "text": "Variables in F# are immutable, which means once a variable is bound to a value, it can’t be changed. They are actually compiled as static read-only properties." }, { "code": null, "e": 3114, "s": 3073, "text": "The following example demonstrates this." }, { "code": null, "e": 3297, "s": 3114, "text": "let x = 10\nlet y = 20\nlet z = x + y\n\nprintfn \"x: %i\" x\nprintfn \"y: %i\" y\nprintfn \"z: %i\" z\n\nlet x = 15\nlet y = 20\nlet z = x + y\n\nprintfn \"x: %i\" x\nprintfn \"y: %i\" y\nprintfn \"z: %i\" z" }, { "code": null, "e": 3378, "s": 3297, "text": "When you compile and execute the program, it shows the following error message −" }, { "code": null, "e": 3481, "s": 3378, "text": "Duplicate definition of value 'x'\nDuplicate definition of value 'Y'\nDuplicate definition of value 'Z'\n" }, { "code": null, "e": 3724, "s": 3481, "text": "A variable definition tells the compiler where and how much storage for the variable should be created. A variable definition may specify a data type and contains a list of one or more variables of that type as shown in the following example." }, { "code": null, "e": 3949, "s": 3724, "text": "let x:int32 = 10\nlet y:int32 = 20\nlet z:int32 = x + y\n\nprintfn \"x: %d\" x\nprintfn \"y: %d\" y\nprintfn \"z: %d\" z\n\nlet p:float = 15.99\nlet q:float = 20.78\nlet r:float = p + q\n\nprintfn \"p: %g\" p\nprintfn \"q: %g\" q\nprintfn \"r: %g\" r" }, { "code": null, "e": 4030, "s": 3949, "text": "When you compile and execute the program, it shows the following error message −" }, { "code": null, "e": 4076, "s": 4030, "text": "x: 10\ny: 20\nz: 30\np: 15.99\nq: 20.78\nr: 36.77\n" }, { "code": null, "e": 4383, "s": 4076, "text": "At times you need to change the values stored in a variable. To specify that there could be a change in the value of a declared and assigned variable, in later part of a program, F# provides the mutable keyword. You can declare and assign mutable variables using this keyword, whose values you will change." }, { "code": null, "e": 4466, "s": 4383, "text": "The mutable keyword allows you to declare and assign values in a mutable variable." }, { "code": null, "e": 4624, "s": 4466, "text": "You can assign some initial value to a mutable variable using the let keyword. However, to assign new subsequent value to it, you need to use the ← operator." }, { "code": null, "e": 4637, "s": 4624, "text": "For example," }, { "code": null, "e": 4664, "s": 4637, "text": "let mutable x = 10\nx ← 15\n" }, { "code": null, "e": 4711, "s": 4664, "text": "The following example will clear the concept −" }, { "code": null, "e": 5020, "s": 4711, "text": "let mutable x = 10\nlet y = 20\nlet mutable z = x + y\n\nprintfn \"Original Values:\"\nprintfn \"x: %i\" x\nprintfn \"y: %i\" y\nprintfn \"z: %i\" z\n\nprintfn \"Let us change the value of x\"\nprintfn \"Value of z will change too.\"\n\nx <- 15\nz <- x + y\n\nprintfn \"New Values:\"\nprintfn \"x: %i\" x\nprintfn \"y: %i\" y\nprintfn \"z: %i\" z" }, { "code": null, "e": 5095, "s": 5020, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 5218, "s": 5095, "text": "Original Values:\nx: 10\ny: 20\nz: 30\nLet us change the value of x\nValue of z will change too.\nNew Values:\nx: 15\ny: 20\nz: 35\n" }, { "code": null, "e": 5225, "s": 5218, "text": " Print" }, { "code": null, "e": 5236, "s": 5225, "text": " Add Notes" } ]
JavaFX | SplitPane Class - GeeksforGeeks
26 Sep, 2018 SplitPane class is a part of JavaFX. SplitPane class is a control which contains two or more sides separated by a divider. Sides can be dragged by the user to give more space to one of the sides which cause the other side to shrink by an equal amount. SplitPane class inherits Control class. Constructor of the Class: SplitPane(): Creates a new SplitPane. SplitPane(Node... n): Creates a SplitPane with specified nodes. Commonly Used Methods: Below programs illustrate the use of SplitPane Class: Java program to create a split pane and add labels to it:In this program, we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a split pane// and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Split Pane"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { split_pane.getItems().add(new Label("\tLabel no " + i + "\t")); } // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to create a split pane set its orientation and add labels to it:In this program we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Set the orientation of the split_pane using the setOrientation() function.Call the show() function to display the final results.// Java program to create a split pane, set// its orientation and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Split Pane"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { // create a label Label label = new Label("\tLabel no " + i + "\t"); // set preferred height label.setPrefHeight(50); split_pane.getItems().add(label); } // set Orientation of splitpane split_pane.setOrientation(Orientation.VERTICAL); // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: Java program to create a split pane and add labels to it:In this program, we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a split pane// and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Split Pane"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { split_pane.getItems().add(new Label("\tLabel no " + i + "\t")); } // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: In this program, we will create a SplitPane name split_pane. Create and add labels to the split pane using getItems().add() function. Add the split_pane to the scene and add the scene to the stage. Call the show() function to display the final results. // Java program to create a split pane// and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Split Pane"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { split_pane.getItems().add(new Label("\tLabel no " + i + "\t")); } // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Java program to create a split pane set its orientation and add labels to it:In this program we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Set the orientation of the split_pane using the setOrientation() function.Call the show() function to display the final results.// Java program to create a split pane, set// its orientation and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Split Pane"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { // create a label Label label = new Label("\tLabel no " + i + "\t"); // set preferred height label.setPrefHeight(50); split_pane.getItems().add(label); } // set Orientation of splitpane split_pane.setOrientation(Orientation.VERTICAL); // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output: In this program we will create a SplitPane name split_pane. Create and add labels to the split pane using getItems().add() function. Add the split_pane to the scene and add the scene to the stage. Set the orientation of the split_pane using the setOrientation() function. Call the show() function to display the final results. // Java program to create a split pane, set// its orientation and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("Split Pane"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { // create a label Label label = new Label("\tLabel no " + i + "\t"); // set preferred height label.setPrefHeight(50); split_pane.getItems().add(label); } // set Orientation of splitpane split_pane.setOrientation(Orientation.VERTICAL); // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Note: The above programs might not run in an online IDE please use an offline compiler. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/SplitPane.html JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Multithreading in Java Set in Java
[ { "code": null, "e": 23974, "s": 23946, "text": "\n26 Sep, 2018" }, { "code": null, "e": 24266, "s": 23974, "text": "SplitPane class is a part of JavaFX. SplitPane class is a control which contains two or more sides separated by a divider. Sides can be dragged by the user to give more space to one of the sides which cause the other side to shrink by an equal amount. SplitPane class inherits Control class." }, { "code": null, "e": 24292, "s": 24266, "text": "Constructor of the Class:" }, { "code": null, "e": 24330, "s": 24292, "text": "SplitPane(): Creates a new SplitPane." }, { "code": null, "e": 24394, "s": 24330, "text": "SplitPane(Node... n): Creates a SplitPane with specified nodes." }, { "code": null, "e": 24417, "s": 24394, "text": "Commonly Used Methods:" }, { "code": null, "e": 24471, "s": 24417, "text": "Below programs illustrate the use of SplitPane Class:" }, { "code": null, "e": 28265, "s": 24471, "text": "Java program to create a split pane and add labels to it:In this program, we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a split pane// and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Split Pane\"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { split_pane.getItems().add(new Label(\"\\tLabel no \" + i + \"\\t\")); } // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to create a split pane set its orientation and add labels to it:In this program we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Set the orientation of the split_pane using the setOrientation() function.Call the show() function to display the final results.// Java program to create a split pane, set// its orientation and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Split Pane\"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { // create a label Label label = new Label(\"\\tLabel no \" + i + \"\\t\"); // set preferred height label.setPrefHeight(50); split_pane.getItems().add(label); } // set Orientation of splitpane split_pane.setOrientation(Orientation.VERTICAL); // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": null, "e": 30003, "s": 28265, "text": "Java program to create a split pane and add labels to it:In this program, we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Call the show() function to display the final results.// Java program to create a split pane// and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Split Pane\"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { split_pane.getItems().add(new Label(\"\\tLabel no \" + i + \"\\t\")); } // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": null, "e": 30064, "s": 30003, "text": "In this program, we will create a SplitPane name split_pane." }, { "code": null, "e": 30137, "s": 30064, "text": "Create and add labels to the split pane using getItems().add() function." }, { "code": null, "e": 30201, "s": 30137, "text": "Add the split_pane to the scene and add the scene to the stage." }, { "code": null, "e": 30256, "s": 30201, "text": "Call the show() function to display the final results." }, { "code": "// Java program to create a split pane// and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Split Pane\"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { split_pane.getItems().add(new Label(\"\\tLabel no \" + i + \"\\t\")); } // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 31681, "s": 30256, "text": null }, { "code": null, "e": 31689, "s": 31681, "text": "Output:" }, { "code": null, "e": 33746, "s": 31689, "text": "Java program to create a split pane set its orientation and add labels to it:In this program we will create a SplitPane name split_pane.Create and add labels to the split pane using getItems().add() function.Add the split_pane to the scene and add the scene to the stage.Set the orientation of the split_pane using the setOrientation() function.Call the show() function to display the final results.// Java program to create a split pane, set// its orientation and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Split Pane\"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { // create a label Label label = new Label(\"\\tLabel no \" + i + \"\\t\"); // set preferred height label.setPrefHeight(50); split_pane.getItems().add(label); } // set Orientation of splitpane split_pane.setOrientation(Orientation.VERTICAL); // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": null, "e": 33806, "s": 33746, "text": "In this program we will create a SplitPane name split_pane." }, { "code": null, "e": 33879, "s": 33806, "text": "Create and add labels to the split pane using getItems().add() function." }, { "code": null, "e": 33943, "s": 33879, "text": "Add the split_pane to the scene and add the scene to the stage." }, { "code": null, "e": 34018, "s": 33943, "text": "Set the orientation of the split_pane using the setOrientation() function." }, { "code": null, "e": 34073, "s": 34018, "text": "Call the show() function to display the final results." }, { "code": "// Java program to create a split pane, set// its orientation and add labels to itimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.scene.text.*;import javafx.geometry.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.scene.paint.*;import javafx.scene.*;import java.io.*;import javafx.scene.image.*; public class SplitPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"Split Pane\"); // create a splitpane SplitPane split_pane = new SplitPane(); // create labels and add it to splitPane for (int i = 1; i < 5; i++) { // create a label Label label = new Label(\"\\tLabel no \" + i + \"\\t\"); // set preferred height label.setPrefHeight(50); split_pane.getItems().add(label); } // set Orientation of splitpane split_pane.setOrientation(Orientation.VERTICAL); // create a scene Scene scene = new Scene(split_pane, 500, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 35724, "s": 34073, "text": null }, { "code": null, "e": 35732, "s": 35724, "text": "Output:" }, { "code": null, "e": 35820, "s": 35732, "text": "Note: The above programs might not run in an online IDE please use an offline compiler." }, { "code": null, "e": 35911, "s": 35820, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/SplitPane.html" }, { "code": null, "e": 35918, "s": 35911, "text": "JavaFX" }, { "code": null, "e": 35923, "s": 35918, "text": "Java" }, { "code": null, "e": 35928, "s": 35923, "text": "Java" }, { "code": null, "e": 36026, "s": 35928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36035, "s": 36026, "text": "Comments" }, { "code": null, "e": 36048, "s": 36035, "text": "Old Comments" }, { "code": null, "e": 36078, "s": 36048, "text": "HashMap in Java with Examples" }, { "code": null, "e": 36097, "s": 36078, "text": "Interfaces in Java" }, { "code": null, "e": 36148, "s": 36097, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 36179, "s": 36148, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36211, "s": 36179, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 36235, "s": 36211, "text": "Singleton Class in Java" }, { "code": null, "e": 36254, "s": 36235, "text": "Overriding in Java" }, { "code": null, "e": 36274, "s": 36254, "text": "Collections in Java" }, { "code": null, "e": 36297, "s": 36274, "text": "Multithreading in Java" } ]
How to check whether a data frame exists or not in R?
Sometimes we keep writing codes in the programming console and suddenly we need to use something that was used in the upper side of programming console then recalling it becomes a little ambiguous if we forget about it. In this case, we might want to check whether something exists or not and that something could be a data frame in R programming. For this purpose, we can use the below syntax − exists("data_frame_name")&&is.data.frame(get("data_frame_name ")) Consider the below data frame − Live Demo set.seed(101) x1<-rnorm(20,1,0.5) x2<-rnorm(20,1,0.25) df1<-data.frame(x1,x2) df1 x1 x2 1 0.83698175 0.9590611 2 1.27623093 1.1771305 3 0.66252808 0.9330049 4 1.10717973 0.6340196 5 1.15538461 1.1861090 6 1.58698314 0.6474025 7 1.30939493 1.1167669 8 0.94363284 0.9701700 9 1.45851414 1.1168097 10 0.88837032 1.1245339 11 1.26322405 1.2237343 12 0.60257778 1.0697880 13 1.71387777 1.2519664 14 0.26659015 0.4817234 15 0.88165831 1.2974633 16 0.90333102 0.8189064 17 0.57512263 1.0419959 18 1.02923275 1.2300838 19 0.59116482 0.5820988 20 -0.02515391 1.1121173 exists("df1")&&is.data.frame(get("df1")) [1] TRUE Let’s have a look at another example − Live Demo y1<-rpois(20,1) y2<-rpois(20,5) y3<-rpois(20,2) y4<-rpois(20,8) df2<-data.frame(y1,y2,y3,y4) df2 y1 y2 y3 y4 1 2 2 2 11 2 0 4 1 8 3 1 1 1 9 4 0 2 2 4 5 2 8 0 8 6 2 6 3 4 7 0 5 2 11 8 0 5 3 11 9 0 5 5 9 10 2 5 1 7 11 3 4 2 9 12 0 5 0 8 13 0 6 4 13 14 2 5 2 8 15 1 3 1 9 16 0 3 1 10 17 0 6 1 7 18 1 3 3 9 19 0 8 0 5 20 1 4 2 9 exists("df2")&&is.data.frame(get("df2")) [1] TRUE
[ { "code": null, "e": 1458, "s": 1062, "text": "Sometimes we keep writing codes in the programming console and suddenly we need to use something that was used in the upper side of programming console then recalling it becomes a little ambiguous if we forget about it. In this case, we might want to check whether something exists or not and that something could be a data frame in R programming. For this purpose, we can use the below syntax −" }, { "code": null, "e": 1524, "s": 1458, "text": "exists(\"data_frame_name\")&&is.data.frame(get(\"data_frame_name \"))" }, { "code": null, "e": 1556, "s": 1524, "text": "Consider the below data frame −" }, { "code": null, "e": 1567, "s": 1556, "text": " Live Demo" }, { "code": null, "e": 1649, "s": 1567, "text": "set.seed(101)\nx1<-rnorm(20,1,0.5)\nx2<-rnorm(20,1,0.25)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 2127, "s": 1649, "text": "x1 x2\n1 0.83698175 0.9590611\n2 1.27623093 1.1771305\n3 0.66252808 0.9330049\n4 1.10717973 0.6340196\n5 1.15538461 1.1861090\n6 1.58698314 0.6474025\n7 1.30939493 1.1167669\n8 0.94363284 0.9701700\n9 1.45851414 1.1168097\n10 0.88837032 1.1245339\n11 1.26322405 1.2237343\n12 0.60257778 1.0697880\n13 1.71387777 1.2519664\n14 0.26659015 0.4817234\n15 0.88165831 1.2974633\n16 0.90333102 0.8189064\n17 0.57512263 1.0419959\n18 1.02923275 1.2300838\n19 0.59116482 0.5820988\n20 -0.02515391 1.1121173" }, { "code": null, "e": 2177, "s": 2127, "text": "exists(\"df1\")&&is.data.frame(get(\"df1\"))\n[1] TRUE" }, { "code": null, "e": 2216, "s": 2177, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2227, "s": 2216, "text": " Live Demo" }, { "code": null, "e": 2324, "s": 2227, "text": "y1<-rpois(20,1)\ny2<-rpois(20,5)\ny3<-rpois(20,2)\ny4<-rpois(20,8)\ndf2<-data.frame(y1,y2,y3,y4)\ndf2" }, { "code": null, "e": 2640, "s": 2324, "text": " y1 y2 y3 y4\n1 2 2 2 11\n2 0 4 1 8\n3 1 1 1 9\n4 0 2 2 4\n5 2 8 0 8\n6 2 6 3 4\n7 0 5 2 11\n8 0 5 3 11\n9 0 5 5 9\n10 2 5 1 7\n11 3 4 2 9\n12 0 5 0 8\n13 0 6 4 13\n14 2 5 2 8\n15 1 3 1 9\n16 0 3 1 10\n17 0 6 1 7\n18 1 3 3 9\n19 0 8 0 5\n20 1 4 2 9" }, { "code": null, "e": 2690, "s": 2640, "text": "exists(\"df2\")&&is.data.frame(get(\"df2\"))\n[1] TRUE" } ]
How to set NULL values in a table column and insert the same
To set NULL values, set the type as NULL as in the below syntax − yourColumnName dataType NULL; Let us first create a table − mysql> create table DemoTable759 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) NULL ); Query OK, 0 rows affected (0.72 sec) Insert some records in the table using insert command − mysql> insert into DemoTable759(FirstName) values('John'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable759(FirstName) values(NULL); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable759(FirstName) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable759(FirstName) values(NULL); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select *from DemoTable759; This will produce the following output. NULL values are also visible in the column − +----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | NULL | | 3 | Carol | | 4 | NULL | +----+-----------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1128, "s": 1062, "text": "To set NULL values, set the type as NULL as in the below syntax −" }, { "code": null, "e": 1158, "s": 1128, "text": "yourColumnName dataType NULL;" }, { "code": null, "e": 1188, "s": 1158, "text": "Let us first create a table −" }, { "code": null, "e": 1341, "s": 1188, "text": "mysql> create table DemoTable759 (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n FirstName varchar(100) NULL\n);\nQuery OK, 0 rows affected (0.72 sec)" }, { "code": null, "e": 1397, "s": 1341, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1774, "s": 1397, "text": "mysql> insert into DemoTable759(FirstName) values('John');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable759(FirstName) values(NULL);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable759(FirstName) values('Carol');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable759(FirstName) values(NULL);\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1834, "s": 1774, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1868, "s": 1834, "text": "mysql> select *from DemoTable759;" }, { "code": null, "e": 1953, "s": 1868, "text": "This will produce the following output. NULL values are also visible in the column −" }, { "code": null, "e": 2130, "s": 1953, "text": "+----+-----------+\n| Id | FirstName |\n+----+-----------+\n| 1 | John |\n| 2 | NULL |\n| 3 | Carol |\n| 4 | NULL |\n+----+-----------+\n4 rows in set (0.00 sec)" } ]
Explore and get value out of your raw data: An Introduction to Splunk | by Bruno Amaro Almeida | Towards Data Science
You just got your hands into some raw data files (json, csv, etc). What happens now? How do you make sense of it? You open a console and start using less, grep, jq and other tools. It’s great at start but... complex and hard to do something more than just the basic. Does this sounds familiar? Great! Keep reading and learn how Splunk can help you out. Let’s start by installing Splunk Enterprise in your machine. Installing Splunk is quite straightforward and the setup package is available to pretty much all platforms: OSX/Linux/Windows. Download the package here and follow the installation instructions. Splunk Enterprise? but... does it have a free license? Yes! “Index 500 MB/Day. (...) After 60 days you can convert to a perpetual free license or purchase a Splunk Enterprise license to continue using the expanded functionality designed for enterprise-scale deployments.” https://www.splunk.com/en_us/download/splunk-enterprise.html While in the scope of an introduction and personal usage a local installation in your machine is quite ok, I would highly recommend you to quickly shift to a proper Splunk deployment (on-premise or in the cloud) as soon as you start using it more extensively. If your local installation went well, you will be greeted with a web interface similar as the screenshot above. Yay! This article applies to any type of raw data - Splunk is well known for being able to ingest raw data without prior knowledge of it’s schema — but to be able to demonstrate this I need a raw dataset. Instead of generating some meaningless dummy test dataset, I decided to search for an interesting real world dataset available as Open Data. Helsinki Public Transportation (HSL) — Passenger Volume per Station during October 2016 I found an interesting dataset from the Helsinki Region Transport (HSL) containing the volume of Passengers per Station in the Helsinki area. The dataset (available here ) contains the average number of passengers per day during November 2016 and was collected from the passenger travel card system. While I was a bit disappointed that this particular dataset only has available old data (November 2016), I was positively surprised to discover that HSL (and the Finnish public authorities in general) have quite a big catalog of data openly available (https://www.opendata.fi/en). Nice! By downloading this particular HSL dataset — I choosed the GeoJSON APIJSON data format — you will get a raw data file named: HSL%3An_nousijamäärät.geojson As you are able to see, at the top level we have a single FeatureCollection that contains all the Feature events within. Since we only care about the events (the high level FeatureCollection array part is not needed) we can clean the data a bit by dropping the JSON array and pipe all the Feature events to a new file (HSLvolumes.json). It is quite straight forward to add new data into Splunk from a file in the local hard disk. Let’s head to Splunk and use the UI options to do so. Click on the Add Data option and select Upload (from files in my computer) A step by step guide will appear. Let’s start by selecting our raw data file. In my case, I will be using the HSLvolumes.json file that contain the Feature events. After getting your data in, Splunk will try to “understand” your data automatically and allow you to tweak and provide more details about the data format. In this particular case, you can see that it automatically recognized my data as JSON (Source type: _json) and overall the events look good. However, there are some warnings that it failed to parse a timestamp for each event. Why? Splunk is all about event processing and time is essential. Based on the events you are indexing, Splunk will automatically try to find a timestamp. Since our data doesn’t have a timestamp field, Splunk will be using the current time on when each event was indexed as the event timestamp. For an in-depth explanation on how Splunk timestamp assignments works, please check this Splunk documentation page. So, in the Timestamp section we will enforce this by choosing Current and since we modified the _json Source type, let’s hit Save As and name this according with our data source (e.g hslvolumesjson). In this section, we need to select in which Splunk index we want to store this data. It is a good practice to create separate indexes for different types of data, so let’s create a new index. Choose your index name and click Save. We can leave the other fields with their default values. Double check that the new index is selected. Click Review, Submit & Start Searching and you are ready to go. For a more in-depth explanation about getting data in Splunk, please check the Splunk documentation: http://dev.splunk.com/view/dev-guide/SP-CAAAE3A After you clicked the Start Searching button you will be directed to the Splunk Search panel. There are a lot of interesting things in this view. If you never used Splunk before you might actually feel a bit overwhelmed. Allow me to highlight some of areas and break the view apart for you. In the upper left corner, you will find in which Splunk app (default: Search & Reporting) and panel (default: Search) you currently are. Right below that, you will find the Splunk search bar with a query that (at first glance) might look a bit complex. Given our simple use case, the exact same search results would have appeared with the query: index=”hslnov2016". We will explore the query language below. In the upper right corner, you will find the Time picker (default: All time). This allows you to select the time range of your search. Since our timestamp was set to be the indexing current time, this will not be useful here. In the lower left corner, you find the Interesting Fields. These are fields from your data that Splunk was able to extract automatically. At last, the remaining lower part is where your search query result events are going to be displayed. In this case, all the index results are appearing. Cool, What now? One of my favorite options to use first to explore data in Splunk is the “Interesting Fields” panel. By clicking in any field you can really quickly gain valuable insights. In this case, by selecting the field properties.nimi_s we are able to quickly understand what are the field top values, ie, what HSL Station Names appear in the majority of the events. [ Without much surprise for any Helsinki area resident, Rautatientori (Central Railway Station) and Kamppi are on the top :) ] The Splunk search and query language is both powerful and vast, but with some simple commands and little experience you can quickly get some valuable answers. If you start from: index=yourindex | command , Splunk will provide you autocomplete, guidance and explanation about each command. Since each event contains the daily average of passengers in a single station, let’s say we want to now what is the total Volume of Passengers per Station. How can we do this? Easy! We can quickly use the stats command and sum all the daily averages (properties.nousijat) and aggregate those results by station name (properties.nimi_s). Side bonus: By getting 5071 results we also got to know the total number of stations in our dataset. Nice! What if I want to know the top or bottom X Stations? By appending to our previous query: | sort -volume | head 20 we immediately get the answer to that question. We use sort to get the higher volume results ie, descending (for lower, ie, ascending, it would be sort +volume) and head to filter out only the first X results Explore your data and get valuable answers with the different Splunk queries. Once you start to get the hang of the Splunk search and saved a couple of the most interesting queries, you can create your first Dashboard and visualize your data in different ways. Head to the Dashboards section and click Create New Dashboard. Give a name to your dashboard and add your first panel. With the same query as before, I added a simple Column chart panel. Quite quickly it becomes evident that our top 20 stations are very very very different in terms of volume of passengers. Both Kamppi and Rautatientori were handling 2x the passenger volume compared with the other 3 stations in the top 5. When we look at the remaining 15 stations (in the top 20!) we get 3x that volume. At this point I decided to add two additional new panels... On the left, the Passenger Volume per Station top 50 (same query but with |head 50) and a simple table visualization. On the right, the Passenger Volume per Station (bottom ranks , less than 30 passengers). With a pie chart and the query: index=”hslnov2016" | stats sum(properties.nousijat) as volume by “properties.nimi_s”| sort +volume | search volume < 30 | stats count by volume I decided to include only the stations with less than 30 passengers in volume. And I was surprised to see that there are so many stations (1827) with 0 passengers. One last Panel... Since my dataset included the geo coordinates (latitude and longitude) of each station, I decided to add one more panel (type Map). To do so, I extended my Splunk and installed a 3rd party visualization called Maps+ for Splunk. You can do the same, by exploring the existing visualization types and go to “Find more visualizations” Splunk has a built-in Map visualization. Why not to use it? I did use the built in Map at first, but I found some limitations: you can’t zoom at a city level and my Splunk query was more complex. The Maps+ for Splunk was a clear winner to me. The panel Splunk search query is: index=”hslnov2016" | spath path=”geometry.coordinates{0}” output=longitude | spath path=”geometry.coordinates{1}” output=latitude | stats first(latitude) as latitude , first(longitude) as longitude, first(properties.nimi_s) as description, sum(properties.nousijat) as title by “properties.nimi_s” | sort -title | search title > 0 The initial transformations using spath was needed because both the latitude and longitude were in the same field (multi value json type), therefore I had to “split” them into different fields. This visualization (Maps+ for Splunk) only requires that you have the fields in a table with some particular labeled names. Check the project documentation at: https://github.com/sghaskell/maps-plus for more details. base_search | table latitude, longitude [ description| title | (...) I found the map really nice and helpful. I was able to quickly see the volume of passengers at any given station by hovering over it. I hope you found this article useful ! Please share your feedback and thoughts. Reach out and follow on Twitter and Instagram
[ { "code": null, "e": 286, "s": 172, "text": "You just got your hands into some raw data files (json, csv, etc). What happens now? How do you make sense of it?" }, { "code": null, "e": 439, "s": 286, "text": "You open a console and start using less, grep, jq and other tools. It’s great at start but... complex and hard to do something more than just the basic." }, { "code": null, "e": 525, "s": 439, "text": "Does this sounds familiar? Great! Keep reading and learn how Splunk can help you out." }, { "code": null, "e": 781, "s": 525, "text": "Let’s start by installing Splunk Enterprise in your machine. Installing Splunk is quite straightforward and the setup package is available to pretty much all platforms: OSX/Linux/Windows. Download the package here and follow the installation instructions." }, { "code": null, "e": 841, "s": 781, "text": "Splunk Enterprise? but... does it have a free license? Yes!" }, { "code": null, "e": 1053, "s": 841, "text": "“Index 500 MB/Day. (...) After 60 days you can convert to a perpetual free license or purchase a Splunk Enterprise license to continue using the expanded functionality designed for enterprise-scale deployments.”" }, { "code": null, "e": 1114, "s": 1053, "text": "https://www.splunk.com/en_us/download/splunk-enterprise.html" }, { "code": null, "e": 1374, "s": 1114, "text": "While in the scope of an introduction and personal usage a local installation in your machine is quite ok, I would highly recommend you to quickly shift to a proper Splunk deployment (on-premise or in the cloud) as soon as you start using it more extensively." }, { "code": null, "e": 1491, "s": 1374, "text": "If your local installation went well, you will be greeted with a web interface similar as the screenshot above. Yay!" }, { "code": null, "e": 1832, "s": 1491, "text": "This article applies to any type of raw data - Splunk is well known for being able to ingest raw data without prior knowledge of it’s schema — but to be able to demonstrate this I need a raw dataset. Instead of generating some meaningless dummy test dataset, I decided to search for an interesting real world dataset available as Open Data." }, { "code": null, "e": 1920, "s": 1832, "text": "Helsinki Public Transportation (HSL) — Passenger Volume per Station during October 2016" }, { "code": null, "e": 2507, "s": 1920, "text": "I found an interesting dataset from the Helsinki Region Transport (HSL) containing the volume of Passengers per Station in the Helsinki area. The dataset (available here ) contains the average number of passengers per day during November 2016 and was collected from the passenger travel card system. While I was a bit disappointed that this particular dataset only has available old data (November 2016), I was positively surprised to discover that HSL (and the Finnish public authorities in general) have quite a big catalog of data openly available (https://www.opendata.fi/en). Nice!" }, { "code": null, "e": 2665, "s": 2507, "text": "By downloading this particular HSL dataset — I choosed the GeoJSON APIJSON data format — you will get a raw data file named: HSL%3An_nousijamäärät.geojson" }, { "code": null, "e": 2786, "s": 2665, "text": "As you are able to see, at the top level we have a single FeatureCollection that contains all the Feature events within." }, { "code": null, "e": 3002, "s": 2786, "text": "Since we only care about the events (the high level FeatureCollection array part is not needed) we can clean the data a bit by dropping the JSON array and pipe all the Feature events to a new file (HSLvolumes.json)." }, { "code": null, "e": 3149, "s": 3002, "text": "It is quite straight forward to add new data into Splunk from a file in the local hard disk. Let’s head to Splunk and use the UI options to do so." }, { "code": null, "e": 3224, "s": 3149, "text": "Click on the Add Data option and select Upload (from files in my computer)" }, { "code": null, "e": 3388, "s": 3224, "text": "A step by step guide will appear. Let’s start by selecting our raw data file. In my case, I will be using the HSLvolumes.json file that contain the Feature events." }, { "code": null, "e": 3543, "s": 3388, "text": "After getting your data in, Splunk will try to “understand” your data automatically and allow you to tweak and provide more details about the data format." }, { "code": null, "e": 3769, "s": 3543, "text": "In this particular case, you can see that it automatically recognized my data as JSON (Source type: _json) and overall the events look good. However, there are some warnings that it failed to parse a timestamp for each event." }, { "code": null, "e": 4063, "s": 3769, "text": "Why? Splunk is all about event processing and time is essential. Based on the events you are indexing, Splunk will automatically try to find a timestamp. Since our data doesn’t have a timestamp field, Splunk will be using the current time on when each event was indexed as the event timestamp." }, { "code": null, "e": 4179, "s": 4063, "text": "For an in-depth explanation on how Splunk timestamp assignments works, please check this Splunk documentation page." }, { "code": null, "e": 4379, "s": 4179, "text": "So, in the Timestamp section we will enforce this by choosing Current and since we modified the _json Source type, let’s hit Save As and name this according with our data source (e.g hslvolumesjson)." }, { "code": null, "e": 4571, "s": 4379, "text": "In this section, we need to select in which Splunk index we want to store this data. It is a good practice to create separate indexes for different types of data, so let’s create a new index." }, { "code": null, "e": 4667, "s": 4571, "text": "Choose your index name and click Save. We can leave the other fields with their default values." }, { "code": null, "e": 4776, "s": 4667, "text": "Double check that the new index is selected. Click Review, Submit & Start Searching and you are ready to go." }, { "code": null, "e": 4925, "s": 4776, "text": "For a more in-depth explanation about getting data in Splunk, please check the Splunk documentation: http://dev.splunk.com/view/dev-guide/SP-CAAAE3A" }, { "code": null, "e": 5019, "s": 4925, "text": "After you clicked the Start Searching button you will be directed to the Splunk Search panel." }, { "code": null, "e": 5216, "s": 5019, "text": "There are a lot of interesting things in this view. If you never used Splunk before you might actually feel a bit overwhelmed. Allow me to highlight some of areas and break the view apart for you." }, { "code": null, "e": 5353, "s": 5216, "text": "In the upper left corner, you will find in which Splunk app (default: Search & Reporting) and panel (default: Search) you currently are." }, { "code": null, "e": 5624, "s": 5353, "text": "Right below that, you will find the Splunk search bar with a query that (at first glance) might look a bit complex. Given our simple use case, the exact same search results would have appeared with the query: index=”hslnov2016\". We will explore the query language below." }, { "code": null, "e": 5850, "s": 5624, "text": "In the upper right corner, you will find the Time picker (default: All time). This allows you to select the time range of your search. Since our timestamp was set to be the indexing current time, this will not be useful here." }, { "code": null, "e": 5988, "s": 5850, "text": "In the lower left corner, you find the Interesting Fields. These are fields from your data that Splunk was able to extract automatically." }, { "code": null, "e": 6141, "s": 5988, "text": "At last, the remaining lower part is where your search query result events are going to be displayed. In this case, all the index results are appearing." }, { "code": null, "e": 6157, "s": 6141, "text": "Cool, What now?" }, { "code": null, "e": 6330, "s": 6157, "text": "One of my favorite options to use first to explore data in Splunk is the “Interesting Fields” panel. By clicking in any field you can really quickly gain valuable insights." }, { "code": null, "e": 6642, "s": 6330, "text": "In this case, by selecting the field properties.nimi_s we are able to quickly understand what are the field top values, ie, what HSL Station Names appear in the majority of the events. [ Without much surprise for any Helsinki area resident, Rautatientori (Central Railway Station) and Kamppi are on the top :) ]" }, { "code": null, "e": 6801, "s": 6642, "text": "The Splunk search and query language is both powerful and vast, but with some simple commands and little experience you can quickly get some valuable answers." }, { "code": null, "e": 6931, "s": 6801, "text": "If you start from: index=yourindex | command , Splunk will provide you autocomplete, guidance and explanation about each command." }, { "code": null, "e": 7107, "s": 6931, "text": "Since each event contains the daily average of passengers in a single station, let’s say we want to now what is the total Volume of Passengers per Station. How can we do this?" }, { "code": null, "e": 7268, "s": 7107, "text": "Easy! We can quickly use the stats command and sum all the daily averages (properties.nousijat) and aggregate those results by station name (properties.nimi_s)." }, { "code": null, "e": 7375, "s": 7268, "text": "Side bonus: By getting 5071 results we also got to know the total number of stations in our dataset. Nice!" }, { "code": null, "e": 7428, "s": 7375, "text": "What if I want to know the top or bottom X Stations?" }, { "code": null, "e": 7537, "s": 7428, "text": "By appending to our previous query: | sort -volume | head 20 we immediately get the answer to that question." }, { "code": null, "e": 7698, "s": 7537, "text": "We use sort to get the higher volume results ie, descending (for lower, ie, ascending, it would be sort +volume) and head to filter out only the first X results" }, { "code": null, "e": 7776, "s": 7698, "text": "Explore your data and get valuable answers with the different Splunk queries." }, { "code": null, "e": 7959, "s": 7776, "text": "Once you start to get the hang of the Splunk search and saved a couple of the most interesting queries, you can create your first Dashboard and visualize your data in different ways." }, { "code": null, "e": 8078, "s": 7959, "text": "Head to the Dashboards section and click Create New Dashboard. Give a name to your dashboard and add your first panel." }, { "code": null, "e": 8146, "s": 8078, "text": "With the same query as before, I added a simple Column chart panel." }, { "code": null, "e": 8466, "s": 8146, "text": "Quite quickly it becomes evident that our top 20 stations are very very very different in terms of volume of passengers. Both Kamppi and Rautatientori were handling 2x the passenger volume compared with the other 3 stations in the top 5. When we look at the remaining 15 stations (in the top 20!) we get 3x that volume." }, { "code": null, "e": 8526, "s": 8466, "text": "At this point I decided to add two additional new panels..." }, { "code": null, "e": 8644, "s": 8526, "text": "On the left, the Passenger Volume per Station top 50 (same query but with |head 50) and a simple table visualization." }, { "code": null, "e": 8909, "s": 8644, "text": "On the right, the Passenger Volume per Station (bottom ranks , less than 30 passengers). With a pie chart and the query: index=”hslnov2016\" | stats sum(properties.nousijat) as volume by “properties.nimi_s”| sort +volume | search volume < 30 | stats count by volume" }, { "code": null, "e": 9073, "s": 8909, "text": "I decided to include only the stations with less than 30 passengers in volume. And I was surprised to see that there are so many stations (1827) with 0 passengers." }, { "code": null, "e": 9091, "s": 9073, "text": "One last Panel..." }, { "code": null, "e": 9319, "s": 9091, "text": "Since my dataset included the geo coordinates (latitude and longitude) of each station, I decided to add one more panel (type Map). To do so, I extended my Splunk and installed a 3rd party visualization called Maps+ for Splunk." }, { "code": null, "e": 9423, "s": 9319, "text": "You can do the same, by exploring the existing visualization types and go to “Find more visualizations”" }, { "code": null, "e": 9483, "s": 9423, "text": "Splunk has a built-in Map visualization. Why not to use it?" }, { "code": null, "e": 9666, "s": 9483, "text": "I did use the built in Map at first, but I found some limitations: you can’t zoom at a city level and my Splunk query was more complex. The Maps+ for Splunk was a clear winner to me." }, { "code": null, "e": 10030, "s": 9666, "text": "The panel Splunk search query is: index=”hslnov2016\" | spath path=”geometry.coordinates{0}” output=longitude | spath path=”geometry.coordinates{1}” output=latitude | stats first(latitude) as latitude , first(longitude) as longitude, first(properties.nimi_s) as description, sum(properties.nousijat) as title by “properties.nimi_s” | sort -title | search title > 0" }, { "code": null, "e": 10224, "s": 10030, "text": "The initial transformations using spath was needed because both the latitude and longitude were in the same field (multi value json type), therefore I had to “split” them into different fields." }, { "code": null, "e": 10441, "s": 10224, "text": "This visualization (Maps+ for Splunk) only requires that you have the fields in a table with some particular labeled names. Check the project documentation at: https://github.com/sghaskell/maps-plus for more details." }, { "code": null, "e": 10510, "s": 10441, "text": "base_search | table latitude, longitude [ description| title | (...)" }, { "code": null, "e": 10644, "s": 10510, "text": "I found the map really nice and helpful. I was able to quickly see the volume of passengers at any given station by hovering over it." }, { "code": null, "e": 10724, "s": 10644, "text": "I hope you found this article useful ! Please share your feedback and thoughts." } ]
Maximum distance between two occurrences of same element in array in C
We are given with an array of integers. The array has multiple occurrences of the same elements. The task here is to find the maximum distance between any two same elements of the array. We will pick each element from the array starting from the left. Then we will find the last occurrence of that same number and store the difference between indexes. Now if this difference is maximum then return it. Input Arr[] = { 1,2,4,1,3,4,2,5,6,5 } Output −Maximum distance between two occurrences of same element in array − 4 Explanation − The repeating numbers with indexes − 1. 1, first index 0, last index 3 distance=3-0-1=2 2. 2, first index 1, last index 6 distance=6-1-1=4 3. 5, first index 7, last index 9 distance=9-7-1=1 Maximum distance between two occurrences of same element : 4 Input Arr[] = { 10,20,1,10,10,21,12,0 } Output −Maximum distance between two occurrences of same element in array − 3 Explanation − The repeating numbers with indexes − 1. 10 first index 0, last index 4 distance=4-0-1=3 Maximum distance between two occurrences of same element : 3 Note − if the input array has no repeating number, then return -1 We take an integer array having repeating numbers as Arr[] We take an integer array having repeating numbers as Arr[] The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element. The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element. We initialize the variable maxD with -1. We initialize the variable maxD with -1. Inside the for loop traverse the array of integers from the beginning. Inside the for loop traverse the array of integers from the beginning. In nested for loop traverse the remaining elements and search for repetitions if any. ( if ( arr[i] == arr[j] ). In nested for loop traverse the remaining elements and search for repetitions if any. ( if ( arr[i] == arr[j] ). If it is true then calculate the difference between numbers by subtracting the indexes. ( temp=j-i-1) If it is true then calculate the difference between numbers by subtracting the indexes. ( temp=j-i-1) If this value is maximum found so far, then store it in maxD If this value is maximum found so far, then store it in maxD Return maxD after traversing the whole array. Return maxD after traversing the whole array. Live Demo #include <stdio.h> #include <math.h> int maxDistance(int arr[],int n){ int size = n; int maxD = -1; for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] == arr[j]){ int temp=abs(j-i-1); maxD = maxD>temp?maxD:temp; } return maxD; } // Driver code int main(){ int Arr[] = {1,2,4,1,3,4,2,5,6,5}; printf("Maximum distance between two occurrences of same element in array:%d", maxDistance(Arr,10) ); return 0; } If we run the above code it will generate the following output − Maximum distance between two occurrences of same element in array − 4
[ { "code": null, "e": 1464, "s": 1062, "text": "We are given with an array of integers. The array has multiple occurrences of the same elements. The task here is to find the maximum distance between any two same elements of the array. We will pick each element from the array starting from the left. Then we will find the last occurrence of that same number and store the difference between indexes. Now if this difference is maximum then return it." }, { "code": null, "e": 1471, "s": 1464, "text": "Input " }, { "code": null, "e": 1503, "s": 1471, "text": "Arr[] = { 1,2,4,1,3,4,2,5,6,5 }" }, { "code": null, "e": 1581, "s": 1503, "text": "Output −Maximum distance between two occurrences of same element in array − 4" }, { "code": null, "e": 1632, "s": 1581, "text": "Explanation − The repeating numbers with indexes −" }, { "code": null, "e": 1846, "s": 1632, "text": "1. 1, first index 0, last index 3 distance=3-0-1=2\n2. 2, first index 1, last index 6 distance=6-1-1=4\n3. 5, first index 7, last index 9 distance=9-7-1=1\nMaximum distance between two occurrences of same element : 4" }, { "code": null, "e": 1853, "s": 1846, "text": "Input " }, { "code": null, "e": 1887, "s": 1853, "text": "Arr[] = { 10,20,1,10,10,21,12,0 }" }, { "code": null, "e": 1965, "s": 1887, "text": "Output −Maximum distance between two occurrences of same element in array − 3" }, { "code": null, "e": 2016, "s": 1965, "text": "Explanation − The repeating numbers with indexes −" }, { "code": null, "e": 2128, "s": 2016, "text": "1. 10 first index 0, last index 4 distance=4-0-1=3\nMaximum distance between two occurrences of same element : 3" }, { "code": null, "e": 2194, "s": 2128, "text": "Note − if the input array has no repeating number, then return -1" }, { "code": null, "e": 2253, "s": 2194, "text": "We take an integer array having repeating numbers as Arr[]" }, { "code": null, "e": 2312, "s": 2253, "text": "We take an integer array having repeating numbers as Arr[]" }, { "code": null, "e": 2442, "s": 2312, "text": "The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element." }, { "code": null, "e": 2572, "s": 2442, "text": "The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element." }, { "code": null, "e": 2613, "s": 2572, "text": "We initialize the variable maxD with -1." }, { "code": null, "e": 2654, "s": 2613, "text": "We initialize the variable maxD with -1." }, { "code": null, "e": 2725, "s": 2654, "text": "Inside the for loop traverse the array of integers from the beginning." }, { "code": null, "e": 2796, "s": 2725, "text": "Inside the for loop traverse the array of integers from the beginning." }, { "code": null, "e": 2909, "s": 2796, "text": "In nested for loop traverse the remaining elements and search for repetitions if any. ( if ( arr[i] == arr[j] )." }, { "code": null, "e": 3022, "s": 2909, "text": "In nested for loop traverse the remaining elements and search for repetitions if any. ( if ( arr[i] == arr[j] )." }, { "code": null, "e": 3124, "s": 3022, "text": "If it is true then calculate the difference between numbers by subtracting the indexes. ( temp=j-i-1)" }, { "code": null, "e": 3226, "s": 3124, "text": "If it is true then calculate the difference between numbers by subtracting the indexes. ( temp=j-i-1)" }, { "code": null, "e": 3287, "s": 3226, "text": "If this value is maximum found so far, then store it in maxD" }, { "code": null, "e": 3348, "s": 3287, "text": "If this value is maximum found so far, then store it in maxD" }, { "code": null, "e": 3394, "s": 3348, "text": "Return maxD after traversing the whole array." }, { "code": null, "e": 3440, "s": 3394, "text": "Return maxD after traversing the whole array." }, { "code": null, "e": 3451, "s": 3440, "text": " Live Demo" }, { "code": null, "e": 3949, "s": 3451, "text": "#include <stdio.h>\n#include <math.h>\nint maxDistance(int arr[],int n){\n int size = n;\n int maxD = -1;\n for (int i = 0; i < n - 1; i++)\n for (int j = i + 1; j < n; j++)\n if (arr[i] == arr[j]){\n int temp=abs(j-i-1);\n maxD = maxD>temp?maxD:temp;\n }\n return maxD;\n}\n// Driver code\nint main(){\n int Arr[] = {1,2,4,1,3,4,2,5,6,5};\n printf(\"Maximum distance between two occurrences of same element in array:%d\", maxDistance(Arr,10) );\n return 0;\n}" }, { "code": null, "e": 4014, "s": 3949, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 4084, "s": 4014, "text": "Maximum distance between two occurrences of same element in array − 4" } ]
Python - Find the Levenshtein distance using Enchant - GeeksforGeeks
26 May, 2020 Levenshtein distance between two strings is defined as the minimum number of characters needed to insert, delete or replace in a given string string1 to transform it to another string string2. Examples : Input : string1 = “geek”, string2 = “gesek”Output : 1Explanation : We can convert string1 into str2 by inserting a ‘s’. Input : str1 = “cat”, string2 = “cut”Output : 1Explanation : We can convert string1 into str2 by replacing ‘a’ with ‘u’. Input : string1 = “sunday”, string2 = “saturday”Output : 3Explanation : Last three and first characters are same. We basically need to convert “un” to “atur”. This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a The Levenshtein distance between two strings can be found using the enchant.utils.levenshtein() method of the enchant module. Syntax : enchant.utils.levenshtein(string1, string2) Parameters :string1 : the first string to be comparedstring2 : the second string to be compared Returns : an integer denoting the Levenshtein distance # import the enchant moduleimport enchant # determining the values of the parametersstring1 = "abc"string2 = "aef" # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2)) Output : 2 Example 2: # import the enchant moduleimport enchant # determining the values of the parametersstring1 = "Hello World"string2 = "Hello d" # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2)) Output : 4 Example 3: # import the enchant moduleimport enchant # determining the values of the parametersstring1 = "Computer Science Portal"string2 = "Computer Portal" # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2)) Output : 8 Python Enchant-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Selecting rows in pandas DataFrame based on conditions Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24389, "s": 24361, "text": "\n26 May, 2020" }, { "code": null, "e": 24582, "s": 24389, "text": "Levenshtein distance between two strings is defined as the minimum number of characters needed to insert, delete or replace in a given string string1 to transform it to another string string2." }, { "code": null, "e": 24593, "s": 24582, "text": "Examples :" }, { "code": null, "e": 24713, "s": 24593, "text": "Input : string1 = “geek”, string2 = “gesek”Output : 1Explanation : We can convert string1 into str2 by inserting a ‘s’." }, { "code": null, "e": 24834, "s": 24713, "text": "Input : str1 = “cat”, string2 = “cut”Output : 1Explanation : We can convert string1 into str2 by replacing ‘a’ with ‘u’." }, { "code": null, "e": 25081, "s": 24834, "text": "Input : string1 = “sunday”, string2 = “saturday”Output : 3Explanation : Last three and first characters are same. We basically need to convert “un” to “atur”. This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a" }, { "code": null, "e": 25207, "s": 25081, "text": "The Levenshtein distance between two strings can be found using the enchant.utils.levenshtein() method of the enchant module." }, { "code": null, "e": 25260, "s": 25207, "text": "Syntax : enchant.utils.levenshtein(string1, string2)" }, { "code": null, "e": 25356, "s": 25260, "text": "Parameters :string1 : the first string to be comparedstring2 : the second string to be compared" }, { "code": null, "e": 25411, "s": 25356, "text": "Returns : an integer denoting the Levenshtein distance" }, { "code": "# import the enchant moduleimport enchant # determining the values of the parametersstring1 = \"abc\"string2 = \"aef\" # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2))", "e": 25634, "s": 25411, "text": null }, { "code": null, "e": 25643, "s": 25634, "text": "Output :" }, { "code": null, "e": 25645, "s": 25643, "text": "2" }, { "code": null, "e": 25656, "s": 25645, "text": "Example 2:" }, { "code": "# import the enchant moduleimport enchant # determining the values of the parametersstring1 = \"Hello World\"string2 = \"Hello d\" # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2))", "e": 25891, "s": 25656, "text": null }, { "code": null, "e": 25900, "s": 25891, "text": "Output :" }, { "code": null, "e": 25902, "s": 25900, "text": "4" }, { "code": null, "e": 25913, "s": 25902, "text": "Example 3:" }, { "code": "# import the enchant moduleimport enchant # determining the values of the parametersstring1 = \"Computer Science Portal\"string2 = \"Computer Portal\" # the Levenshtein distance between# string1 and string2print(enchant.utils.levenshtein(string1, string2))", "e": 26168, "s": 25913, "text": null }, { "code": null, "e": 26177, "s": 26168, "text": "Output :" }, { "code": null, "e": 26179, "s": 26177, "text": "8" }, { "code": null, "e": 26201, "s": 26179, "text": "Python Enchant-module" }, { "code": null, "e": 26208, "s": 26201, "text": "Python" }, { "code": null, "e": 26306, "s": 26208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26315, "s": 26306, "text": "Comments" }, { "code": null, "e": 26328, "s": 26315, "text": "Old Comments" }, { "code": null, "e": 26346, "s": 26328, "text": "Python Dictionary" }, { "code": null, "e": 26381, "s": 26346, "text": "Read a file line by line in Python" }, { "code": null, "e": 26413, "s": 26381, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26455, "s": 26413, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26481, "s": 26455, "text": "Python String | replace()" }, { "code": null, "e": 26518, "s": 26481, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 26561, "s": 26518, "text": "Python program to convert a list to string" }, { "code": null, "e": 26616, "s": 26561, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26660, "s": 26616, "text": "Reading and Writing to text files in Python" } ]
Search for partial value match in an Array in PHP
The array_filter function can be used to match a partial value in an array. A callback can be provided, that helps in deciding which elements would remain in the array and which would be removed. When the callback returns false, it means the given element needs to be removed. Below is a code example demonstrating the same − $arr = array(0 => 'abc', 1 => 'def', 2 => 'ghijk', 3 => 'lmnxyz'); $results = array(); foreach ($arr as $value) { if (strpos($value, 'xyz') !== false) { $results[] = $value; } } if( empty($results) ) { echo 'No matches found.'; } else { echo "'xyz' was found in: " . implode('; ', $results); } Parsing JSON array with PHP foreach − 'xyz' was found in: lmnxyz
[ { "code": null, "e": 1258, "s": 1062, "text": "The array_filter function can be used to match a partial value in an array. A callback can be provided, that helps in deciding which elements would remain in the array and which would be removed." }, { "code": null, "e": 1388, "s": 1258, "text": "When the callback returns false, it means the given element needs to be removed. Below is a code example demonstrating the same −" }, { "code": null, "e": 1685, "s": 1388, "text": "$arr = array(0 => 'abc', 1 => 'def', 2 => 'ghijk', 3 => 'lmnxyz');\n$results = array();\nforeach ($arr as $value) {\n if (strpos($value, 'xyz') !== false) { $results[] = $value; }\n}\nif( empty($results) ) { echo 'No matches found.'; }\nelse { echo \"'xyz' was found in: \" . implode('; ', $results); }" }, { "code": null, "e": 1723, "s": 1685, "text": "Parsing JSON array with PHP foreach −" }, { "code": null, "e": 1750, "s": 1723, "text": "'xyz' was found in: lmnxyz" } ]
How to where Clause in Android sqlite?
Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc. This example demonstrate about How to where Clause in Android sqlite. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <EditText android:id = "@+id/name" android:layout_width = "match_parent" android:hint = "Enter Name" android:layout_height = "wrap_content" /> <EditText android:id = "@+id/salary" android:layout_width = "match_parent" android:inputType = "numberDecimal" android:hint = "Enter Salary" android:layout_height = "wrap_content" /> <LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content"><Button android:id = "@+id/save" android:text = "Save" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <Button android:id = "@+id/refresh" android:text = "Refresh" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> <ListView android:id = "@+id/listView" android:layout_width = "match_parent" android:layout_height = "wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button after insert values to update listview from cursor. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button save, refresh; EditText name, salary; private ListView listView; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); final DatabaseHelper helper = new DatabaseHelper(this); final ArrayList array_list = helper.getAllCotacts(); name = findViewById(R.id.name); salary = findViewById(R.id.salary); listView = findViewById(R.id.listView); final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { array_list.clear(); array_list.addAll(helper.getAllCotacts()); arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) { if (helper.insert(name.getText().toString(), salary.getText().toString())) { Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show(); } } else { name.setError("Enter NAME"); salary.setError("Enter Salary"); } } }); } } Step 4 − Add the following code to src/ DatabaseHelper.java package com.example.andy.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import java.io.IOException; import java.util.ArrayList; class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "salaryDatabase3"; public static final String CONTACTS_TABLE_NAME = "SalaryDetails"; public DatabaseHelper(Context context) { super(context,DATABASE_NAME,null,1); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL( "create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary text )" ); } catch (SQLiteException e) { try { throw new IOException(e); } catch (IOException e1) { e1.printStackTrace(); } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME); onCreate(db); } public boolean insert(String s, String s1) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", s); contentValues.put("salary", s1); db.insert(CONTACTS_TABLE_NAME, null, contentValues); return true; } public ArrayList getAllCotacts() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList<String> array_list = new ArrayList<String>(); Cursor res = db.rawQuery( "select * from "+CONTACTS_TABLE_NAME+" WHERE name = 'Me'", null ); res.moveToFirst(); while(res.isAfterLast() = = false) { array_list.add(res.getString(res.getColumnIndex("name"))); res.moveToNext(); } return array_list; } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – In the above result it is showing “Me” in listview because we have given where cause with select command so it is filtering name which is having “Me”. Click here to download the project code
[ { "code": null, "e": 1457, "s": 1062, "text": "Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc." }, { "code": null, "e": 1527, "s": 1457, "text": "This example demonstrate about How to where Clause in Android sqlite." }, { "code": null, "e": 1656, "s": 1527, "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": 1721, "s": 1656, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3034, "s": 1721, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <EditText\n android:id = \"@+id/name\"\n android:layout_width = \"match_parent\"\n android:hint = \"Enter Name\"\n android:layout_height = \"wrap_content\" />\n <EditText\n android:id = \"@+id/salary\"\n android:layout_width = \"match_parent\"\n android:inputType = \"numberDecimal\"\n android:hint = \"Enter Salary\"\n android:layout_height = \"wrap_content\" />\n <LinearLayout\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"><Button\n android:id = \"@+id/save\"\n android:text = \"Save\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <Button\n android:id = \"@+id/refresh\"\n android:text = \"Refresh\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\" />\n <ListView\n android:id = \"@+id/listView\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 3250, "s": 3034, "text": "In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button after insert values to update listview from cursor." }, { "code": null, "e": 3307, "s": 3250, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5436, "s": 3307, "text": "package com.example.andy.myapplication;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n Button save, refresh;\n EditText name, salary;\n private ListView listView;\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n final DatabaseHelper helper = new DatabaseHelper(this);\n final ArrayList array_list = helper.getAllCotacts();\n name = findViewById(R.id.name);\n salary = findViewById(R.id.salary);\n listView = findViewById(R.id.listView);\n final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n array_list.clear();\n array_list.addAll(helper.getAllCotacts());\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.insert(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Inserted\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 5496, "s": 5436, "text": "Step 4 − Add the following code to src/ DatabaseHelper.java" }, { "code": null, "e": 7451, "s": 5496, "text": "package com.example.andy.myapplication;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport java.io.IOException;\nimport java.util.ArrayList;\nclass DatabaseHelper extends SQLiteOpenHelper {\n public static final String DATABASE_NAME = \"salaryDatabase3\";\n public static final String CONTACTS_TABLE_NAME = \"SalaryDetails\";\n public DatabaseHelper(Context context) {\n super(context,DATABASE_NAME,null,1);\n }\n @Override\n public void onCreate(SQLiteDatabase db) {\n try {\n db.execSQL(\n \"create table \"+ CONTACTS_TABLE_NAME +\"(id INTEGER PRIMARY KEY, name text,salary text )\"\n );\n } catch (SQLiteException e) {\n try {\n throw new IOException(e);\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \"+CONTACTS_TABLE_NAME);\n onCreate(db);\n }\n public boolean insert(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", s);\n contentValues.put(\"salary\", s1);\n db.insert(CONTACTS_TABLE_NAME, null, contentValues);\n return true;\n }\n public ArrayList getAllCotacts() {\n SQLiteDatabase db = this.getReadableDatabase();\n ArrayList<String> array_list = new ArrayList<String>();\n Cursor res = db.rawQuery( \"select * from \"+CONTACTS_TABLE_NAME+\" WHERE name = 'Me'\", null );\n res.moveToFirst();\n while(res.isAfterLast() = = false) {\n array_list.add(res.getString(res.getColumnIndex(\"name\")));\n res.moveToNext();\n }\n return array_list;\n }\n}" }, { "code": null, "e": 7798, "s": 7451, "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": 7949, "s": 7798, "text": "In the above result it is showing “Me” in listview because we have given where cause with select command so it is filtering name which is having “Me”." }, { "code": null, "e": 7989, "s": 7949, "text": "Click here to download the project code" } ]
Multiplication Table Generator using Python - GeeksforGeeks
25 Feb, 2021 Prerequisites: Python GUI- Tkinter We all know that Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. In this article, we will learn How to create a Times-table using Tkinter. Approach: Import Tkinter Library Create Function of Multiplication Table Create the main window (container) Create Variabletext field that store value of Number Call the function By Generate Table Button Execute code Program: Python #import library import sys from tkinter import * def MultiTable(): print("\n:Multiplication Table:\n") print("\nTimes-Table of Number", (EnterTable.get()), '\n') for x in range(1, 13): number = int(EnterTable.get()) print('\t\t', (number), 'x', (x), '=', (x*number),) # Create Main window Table = Tk() Table.geometry('250x250+700+200') Table.title('Multiplication Table') # Variable Declaration EnterTable = StringVar() label1 = Label(Table, text='Enter Your Times-table Number:', font=30, fg='Black').grid(row=1, column=6) label1 = Label(Table, text=' ').grid(row=2, column=6) # Store Number in Textvariable entry = Entry(Table, textvariable=EnterTable, justify='center').grid(row=3, column=6) label1 = Label(Table, text=' ').grid(row=4, column=6) # Call the function button1 = Button(Table, text="Generate Table", fg="Blue", command=MultiTable).grid(row=5, column=6) label1 = Label(Table, text=' ').grid(row=6, column=6) # Exit EXIT = Button(Table, text="Quit", fg="red", command=Table.destroy).grid(row=7, column=6) Table.mainloop() Output: Python Tkinter-exercises Python-tkinter Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions 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 Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24392, "s": 24361, "text": " \n25 Feb, 2021\n" }, { "code": null, "e": 24427, "s": 24392, "text": "Prerequisites: Python GUI- Tkinter" }, { "code": null, "e": 24657, "s": 24427, "text": "We all know that Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. In this article, we will learn How to create a Times-table using Tkinter." }, { "code": null, "e": 24667, "s": 24657, "text": "Approach:" }, { "code": null, "e": 24690, "s": 24667, "text": "Import Tkinter Library" }, { "code": null, "e": 24730, "s": 24690, "text": "Create Function of Multiplication Table" }, { "code": null, "e": 24765, "s": 24730, "text": "Create the main window (container)" }, { "code": null, "e": 24818, "s": 24765, "text": "Create Variabletext field that store value of Number" }, { "code": null, "e": 24861, "s": 24818, "text": "Call the function By Generate Table Button" }, { "code": null, "e": 24874, "s": 24861, "text": "Execute code" }, { "code": null, "e": 24883, "s": 24874, "text": "Program:" }, { "code": null, "e": 24890, "s": 24883, "text": "Python" }, { "code": "\n\n\n\n\n\n\n#import library \nimport sys \nfrom tkinter import *\n \n \ndef MultiTable(): \n \n print(\"\\n:Multiplication Table:\\n\") \n print(\"\\nTimes-Table of Number\", (EnterTable.get()), '\\n') \n \n for x in range(1, 13): \n number = int(EnterTable.get()) \n print('\\t\\t', (number), 'x', (x), '=', (x*number),) \n \n \n# Create Main window \nTable = Tk() \nTable.geometry('250x250+700+200') \nTable.title('Multiplication Table') \n \n# Variable Declaration \nEnterTable = StringVar() \n \nlabel1 = Label(Table, text='Enter Your Times-table Number:', \n font=30, fg='Black').grid(row=1, column=6) \nlabel1 = Label(Table, text=' ').grid(row=2, column=6) \n \n# Store Number in Textvariable \nentry = Entry(Table, textvariable=EnterTable, \n justify='center').grid(row=3, column=6) \nlabel1 = Label(Table, text=' ').grid(row=4, column=6) \n \n# Call the function \nbutton1 = Button(Table, text=\"Generate Table\", fg=\"Blue\", \n command=MultiTable).grid(row=5, column=6) \nlabel1 = Label(Table, text=' ').grid(row=6, column=6) \n \n# Exit \nEXIT = Button(Table, text=\"Quit\", fg=\"red\", \n command=Table.destroy).grid(row=7, column=6) \n \nTable.mainloop() \n\n\n\n\n\n", "e": 26162, "s": 24900, "text": null }, { "code": null, "e": 26170, "s": 26162, "text": "Output:" }, { "code": null, "e": 26197, "s": 26170, "text": "\nPython Tkinter-exercises\n" }, { "code": null, "e": 26214, "s": 26197, "text": "\nPython-tkinter\n" }, { "code": null, "e": 26240, "s": 26214, "text": "\nTechnical Scripter 2020\n" }, { "code": null, "e": 26249, "s": 26240, "text": "\nPython\n" }, { "code": null, "e": 26270, "s": 26249, "text": "\nTechnical Scripter\n" }, { "code": null, "e": 26475, "s": 26270, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 26507, "s": 26475, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26562, "s": 26507, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26618, "s": 26562, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26660, "s": 26618, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26702, "s": 26660, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26741, "s": 26702, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26763, "s": 26741, "text": "Defaultdict in Python" }, { "code": null, "e": 26784, "s": 26763, "text": "Python OOPs Concepts" }, { "code": null, "e": 26815, "s": 26784, "text": "Python | os.path.join() method" } ]
DynamoDB - Query Table
Querying a table primarily requires selecting a table, specifying a partition key, and executing the query; with the options of using secondary indexes and performing deeper filtering through scan operations. Utilize the GUI Console, Java, or another option to perform the task. Perform some simple queries using the previously created tables. First, open the console at https://console.aws.amazon.com/dynamodb Choose Tables from the navigation pane and select Reply from the table list. Then select the Items tab to see the loaded data. Select the data filtering link (“Scan: [Table] Reply”) beneath the Create Item button. In the filtering screen, select Query for the operation. Enter the appropriate partition key value, and click Start. The Reply table then returns matching items. Use the query method in Java to perform data retrieval operations. It requires specifying the partition key value, with the sort key as optional. Code a Java query by first creating a querySpec object describing parameters. Then pass the object to the query method. We use the partition key from the previous examples. You can review the following example − import java.util.HashMap; import java.util.Iterator; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.ItemCollection; import com.amazonaws.services.dynamodbv2.document.QueryOutcome; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; import com.amazonaws.services.dynamodbv2.document.utils.NameMap; public class ProductsQuery { public static void main(String[] args) throws Exception { AmazonDynamoDBClient client = new AmazonDynamoDBClient() .withEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Products"); HashMap<String, String> nameMap = new HashMap<String, String>(); nameMap.put("#ID", "ID"); HashMap<String, Object> valueMap = new HashMap<String, Object>(); valueMap.put(":xxx", 122); QuerySpec querySpec = new QuerySpec() .withKeyConditionExpression("#ID = :xxx") .withNameMap(new NameMap().with("#ID", "ID")) .withValueMap(valueMap); ItemCollection<QueryOutcome> items = null; Iterator<Item> iterator = null; Item item = null; try { System.out.println("Product with the ID 122"); items = table.query(querySpec); iterator = items.iterator(); while (iterator.hasNext()) { item = iterator.next(); System.out.println(item.getNumber("ID") + ": " + item.getString("Nomenclature")); } } catch (Exception e) { System.err.println("Cannot find products with the ID number 122"); System.err.println(e.getMessage()); } } } Note that the query uses the partition key, however, secondary indexes provide another option for queries. Their flexibility allows querying of non-key attributes, a topic which will be discussed later in this tutorial. The scan method also supports retrieval operations by gathering all the table data. The optional .withFilterExpression prevents items outside of specified criteria from appearing in results. Later in this tutorial, we will discuss scanning in detail. Now, take a look at the following example − import java.util.Iterator; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.ItemCollection; import com.amazonaws.services.dynamodbv2.document.ScanOutcome; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.document.spec.ScanSpec; import com.amazonaws.services.dynamodbv2.document.utils.NameMap; import com.amazonaws.services.dynamodbv2.document.utils.ValueMap; public class ProductsScan { public static void main(String[] args) throws Exception { AmazonDynamoDBClient client = new AmazonDynamoDBClient() .withEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Products"); ScanSpec scanSpec = new ScanSpec() .withProjectionExpression("#ID, Nomenclature , stat.sales") .withFilterExpression("#ID between :start_id and :end_id") .withNameMap(new NameMap().with("#ID", "ID")) .withValueMap(new ValueMap().withNumber(":start_id", 120) .withNumber(":end_id", 129)); try { ItemCollection<ScanOutcome> items = table.scan(scanSpec); Iterator<Item> iter = items.iterator(); while (iter.hasNext()) { Item item = iter.next(); System.out.println(item.toString()); } } catch (Exception e) { System.err.println("Cannot perform a table scan:"); System.err.println(e.getMessage()); } } } 16 Lectures 1.5 hours Harshit Srivastava 49 Lectures 3.5 hours Niyazi Erdogan 48 Lectures 3 hours Niyazi Erdogan 13 Lectures 1 hours Harshit Srivastava 45 Lectures 4 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2600, "s": 2391, "text": "Querying a table primarily requires selecting a table, specifying a partition key, and executing the query; with the options of using secondary indexes and performing deeper filtering through scan operations." }, { "code": null, "e": 2670, "s": 2600, "text": "Utilize the GUI Console, Java, or another option to perform the task." }, { "code": null, "e": 2802, "s": 2670, "text": "Perform some simple queries using the previously created tables. First, open the console at https://console.aws.amazon.com/dynamodb" }, { "code": null, "e": 2929, "s": 2802, "text": "Choose Tables from the navigation pane and select Reply from the table list. Then select the Items tab to see the loaded data." }, { "code": null, "e": 3016, "s": 2929, "text": "Select the data filtering link (“Scan: [Table] Reply”) beneath the Create Item button." }, { "code": null, "e": 3133, "s": 3016, "text": "In the filtering screen, select Query for the operation. Enter the appropriate partition key value, and click Start." }, { "code": null, "e": 3178, "s": 3133, "text": "The Reply table then returns matching items." }, { "code": null, "e": 3324, "s": 3178, "text": "Use the query method in Java to perform data retrieval operations. It requires specifying the partition key value, with the sort key as optional." }, { "code": null, "e": 3497, "s": 3324, "text": "Code a Java query by first creating a querySpec object describing parameters. Then pass the object to the query method. We use the partition key from the previous examples." }, { "code": null, "e": 3536, "s": 3497, "text": "You can review the following example −" }, { "code": null, "e": 5462, "s": 3536, "text": "import java.util.HashMap;\nimport java.util.Iterator;\n\nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;\nimport com.amazonaws.services.dynamodbv2.document.DynamoDB;\nimport com.amazonaws.services.dynamodbv2.document.Item;\nimport com.amazonaws.services.dynamodbv2.document.ItemCollection;\nimport com.amazonaws.services.dynamodbv2.document.QueryOutcome;\nimport com.amazonaws.services.dynamodbv2.document.Table;\nimport com.amazonaws.services.dynamodbv2.document.spec.QuerySpec;\nimport com.amazonaws.services.dynamodbv2.document.utils.NameMap;\n\npublic class ProductsQuery { \n public static void main(String[] args) throws Exception { \n AmazonDynamoDBClient client = new AmazonDynamoDBClient() \n .withEndpoint(\"http://localhost:8000\"); \n \n DynamoDB dynamoDB = new DynamoDB(client); \n Table table = dynamoDB.getTable(\"Products\"); \n HashMap<String, String> nameMap = new HashMap<String, String>(); \n nameMap.put(\"#ID\", \"ID\"); \n HashMap<String, Object> valueMap = new HashMap<String, Object>(); \n valueMap.put(\":xxx\", 122);\n QuerySpec querySpec = new QuerySpec() \n .withKeyConditionExpression(\"#ID = :xxx\") \n .withNameMap(new NameMap().with(\"#ID\", \"ID\")) \n .withValueMap(valueMap); \n \n ItemCollection<QueryOutcome> items = null; \n Iterator<Item> iterator = null; \n Item item = null; \n try { \n System.out.println(\"Product with the ID 122\"); \n items = table.query(querySpec); \n iterator = items.iterator(); \n \n while (iterator.hasNext()) { \n item = iterator.next(); \n System.out.println(item.getNumber(\"ID\") + \": \" \n + item.getString(\"Nomenclature\")); \n } \n } catch (Exception e) { \n System.err.println(\"Cannot find products with the ID number 122\"); \n System.err.println(e.getMessage()); \n } \n } \n}" }, { "code": null, "e": 5682, "s": 5462, "text": "Note that the query uses the partition key, however, secondary indexes provide another option for queries. Their flexibility allows querying of non-key attributes, a topic which will be discussed later in this tutorial." }, { "code": null, "e": 5873, "s": 5682, "text": "The scan method also supports retrieval operations by gathering all the table data. The optional .withFilterExpression prevents items outside of specified criteria from appearing in results." }, { "code": null, "e": 5977, "s": 5873, "text": "Later in this tutorial, we will discuss scanning in detail. Now, take a look at the following example −" }, { "code": null, "e": 7670, "s": 5977, "text": "import java.util.Iterator;\n\nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;\nimport com.amazonaws.services.dynamodbv2.document.DynamoDB;\nimport com.amazonaws.services.dynamodbv2.document.Item;\nimport com.amazonaws.services.dynamodbv2.document.ItemCollection;\nimport com.amazonaws.services.dynamodbv2.document.ScanOutcome;\nimport com.amazonaws.services.dynamodbv2.document.Table;\nimport com.amazonaws.services.dynamodbv2.document.spec.ScanSpec;\nimport com.amazonaws.services.dynamodbv2.document.utils.NameMap;\nimport com.amazonaws.services.dynamodbv2.document.utils.ValueMap;\n\npublic class ProductsScan { \n public static void main(String[] args) throws Exception { \n AmazonDynamoDBClient client = new AmazonDynamoDBClient() \n .withEndpoint(\"http://localhost:8000\"); \n \n DynamoDB dynamoDB = new DynamoDB(client); \n Table table = dynamoDB.getTable(\"Products\"); \n ScanSpec scanSpec = new ScanSpec() \n .withProjectionExpression(\"#ID, Nomenclature , stat.sales\") \n .withFilterExpression(\"#ID between :start_id and :end_id\") \n .withNameMap(new NameMap().with(\"#ID\", \"ID\")) \n .withValueMap(new ValueMap().withNumber(\":start_id\", 120)\n .withNumber(\":end_id\", 129)); \n \n try { \n ItemCollection<ScanOutcome> items = table.scan(scanSpec); \n Iterator<Item> iter = items.iterator(); \n \n while (iter.hasNext()) {\n Item item = iter.next(); \n System.out.println(item.toString()); \n } \n } catch (Exception e) { \n System.err.println(\"Cannot perform a table scan:\"); \n System.err.println(e.getMessage()); \n } \n } \n} " }, { "code": null, "e": 7705, "s": 7670, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7725, "s": 7705, "text": " Harshit Srivastava" }, { "code": null, "e": 7760, "s": 7725, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7776, "s": 7760, "text": " Niyazi Erdogan" }, { "code": null, "e": 7809, "s": 7776, "text": "\n 48 Lectures \n 3 hours \n" }, { "code": null, "e": 7825, "s": 7809, "text": " Niyazi Erdogan" }, { "code": null, "e": 7858, "s": 7825, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 7878, "s": 7858, "text": " Harshit Srivastava" }, { "code": null, "e": 7911, "s": 7878, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 7951, "s": 7911, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 7958, "s": 7951, "text": " Print" }, { "code": null, "e": 7969, "s": 7958, "text": " Add Notes" } ]
Calculate the Manhattan Distance between two cells of given 2D array - GeeksforGeeks
06 Jan, 2022 Given a 2D array of size M * N and two points in the form (X1, Y1) and (X2 , Y2) where X1 and X2 represents the rows and Y1 and Y2 represents the column. The task is to calculate the Manhattan distance between the given points. Examples: Input: M = 5, N = 5, X1 = 1, Y1 = 2, X2 = 3, Y2 = 3Output: 3Explanation: As per the definition, the Manhattan the distance is same as sum of the absolute difference of the coordinates. Input: M = 5, N = 5, X1 = 4, Y1 = 2, X2 = 4, Y2 = 2Output: 0 Approach: The approach is based on mathematical observation. The Manhattan distance between two points is the sum of absolute difference of the coordinates. Manhattan distance = |X1 – X2| + |Y1 – Y2| Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Code to calculate Manhattan distanceint manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2){ int dist = abs(X2 - X1) + abs(Y2 - Y1); return dist;} // Driver codeint main(){ // Define size of 2-D array int M = 5, N = 5; // First point int X1 = 1, Y1 = 2; // Second point int X2 = 3, Y2 = 3; cout << manhattanDist(M, N, X1, Y1, X2, Y2); return 0;} // java code to implement above approach class GFG{ // Code to calculate Manhattan distance static int manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2) { int dist = Math.abs(X2 - X1) + Math.abs(Y2 - Y1); return dist; } // Driver code public static void main(String args[]) { // Define size of 2-D array int M = 5, N = 5; // First point int X1 = 1, Y1 = 2; // Second point int X2 = 3, Y2 = 3; System.out.println(manhattanDist(M, N, X1, Y1, X2, Y2)); }} // This code is contributed by gfgking. # Python code for the above approachimport math as Math # Code to calculate Manhattan distancedef manhattanDist(M, N, X1, Y1, X2, Y2): dist = Math.fabs(X2 - X1) + Math.fabs(Y2 - Y1) return (int)(dist) # Driver code # Define size of 2-D arrayM = 5N = 5 # First pointX1 = 1Y1 = 2 # Second pointX2 = 3Y2 = 3 print(manhattanDist(M, N, X1, Y1, X2, Y2)) # This code is contributed by Saurabh Jaiswal // C# code to implement above approachusing System;class GFG { // Code to calculate Manhattan distance static int manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2) { int dist = Math.Abs(X2 - X1) + Math.Abs(Y2 - Y1); return dist; } // Driver code public static void Main() { // Define size of 2-D array int M = 5, N = 5; // First point int X1 = 1, Y1 = 2; // Second point int X2 = 3, Y2 = 3; Console.WriteLine( manhattanDist(M, N, X1, Y1, X2, Y2)); }} // This code is contributed by ukasp. <script> // JavaScript code for the above approach // Code to calculate Manhattan distance function manhattanDist(M, N, X1, Y1, X2, Y2) { let dist = Math.abs(X2 - X1) + Math.abs(Y2 - Y1); return dist; } // Driver code // Define size of 2-D array let M = 5, N = 5; // First point let X1 = 1, Y1 = 2; // Second point let X2 = 3, Y2 = 3; document.write(manhattanDist(M, N, X1, Y1, X2, Y2)); // This code is contributed by Potta Lokesh </script> 3 Time Complexity: O(1)Auxiliary Space: O(1) lokeshpotta20 _saurabh_jaiswal gfgking ukasp Arrays Matrix Arrays Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Find duplicates in O(n) time and O(1) extra space | Set 1 Trapping Rain Water Matrix Chain Multiplication | DP-8 Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Rat in a Maze | Backtracking-2 Find the number of islands | Set 1 (Using DFS)
[ { "code": null, "e": 24716, "s": 24688, "text": "\n06 Jan, 2022" }, { "code": null, "e": 24945, "s": 24716, "text": "Given a 2D array of size M * N and two points in the form (X1, Y1) and (X2 , Y2) where X1 and X2 represents the rows and Y1 and Y2 represents the column. The task is to calculate the Manhattan distance between the given points. " }, { "code": null, "e": 24955, "s": 24945, "text": "Examples:" }, { "code": null, "e": 25140, "s": 24955, "text": "Input: M = 5, N = 5, X1 = 1, Y1 = 2, X2 = 3, Y2 = 3Output: 3Explanation: As per the definition, the Manhattan the distance is same as sum of the absolute difference of the coordinates." }, { "code": null, "e": 25201, "s": 25140, "text": "Input: M = 5, N = 5, X1 = 4, Y1 = 2, X2 = 4, Y2 = 2Output: 0" }, { "code": null, "e": 25358, "s": 25201, "text": "Approach: The approach is based on mathematical observation. The Manhattan distance between two points is the sum of absolute difference of the coordinates." }, { "code": null, "e": 25401, "s": 25358, "text": "Manhattan distance = |X1 – X2| + |Y1 – Y2|" }, { "code": null, "e": 25452, "s": 25401, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 25456, "s": 25452, "text": "C++" }, { "code": null, "e": 25461, "s": 25456, "text": "Java" }, { "code": null, "e": 25469, "s": 25461, "text": "Python3" }, { "code": null, "e": 25472, "s": 25469, "text": "C#" }, { "code": null, "e": 25483, "s": 25472, "text": "Javascript" }, { "code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Code to calculate Manhattan distanceint manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2){ int dist = abs(X2 - X1) + abs(Y2 - Y1); return dist;} // Driver codeint main(){ // Define size of 2-D array int M = 5, N = 5; // First point int X1 = 1, Y1 = 2; // Second point int X2 = 3, Y2 = 3; cout << manhattanDist(M, N, X1, Y1, X2, Y2); return 0;}", "e": 25974, "s": 25483, "text": null }, { "code": "// java code to implement above approach class GFG{ // Code to calculate Manhattan distance static int manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2) { int dist = Math.abs(X2 - X1) + Math.abs(Y2 - Y1); return dist; } // Driver code public static void main(String args[]) { // Define size of 2-D array int M = 5, N = 5; // First point int X1 = 1, Y1 = 2; // Second point int X2 = 3, Y2 = 3; System.out.println(manhattanDist(M, N, X1, Y1, X2, Y2)); }} // This code is contributed by gfgking.", "e": 26543, "s": 25974, "text": null }, { "code": "# Python code for the above approachimport math as Math # Code to calculate Manhattan distancedef manhattanDist(M, N, X1, Y1, X2, Y2): dist = Math.fabs(X2 - X1) + Math.fabs(Y2 - Y1) return (int)(dist) # Driver code # Define size of 2-D arrayM = 5N = 5 # First pointX1 = 1Y1 = 2 # Second pointX2 = 3Y2 = 3 print(manhattanDist(M, N, X1, Y1, X2, Y2)) # This code is contributed by Saurabh Jaiswal", "e": 26943, "s": 26543, "text": null }, { "code": "// C# code to implement above approachusing System;class GFG { // Code to calculate Manhattan distance static int manhattanDist(int M, int N, int X1, int Y1, int X2, int Y2) { int dist = Math.Abs(X2 - X1) + Math.Abs(Y2 - Y1); return dist; } // Driver code public static void Main() { // Define size of 2-D array int M = 5, N = 5; // First point int X1 = 1, Y1 = 2; // Second point int X2 = 3, Y2 = 3; Console.WriteLine( manhattanDist(M, N, X1, Y1, X2, Y2)); }} // This code is contributed by ukasp.", "e": 27514, "s": 26943, "text": null }, { "code": "<script> // JavaScript code for the above approach // Code to calculate Manhattan distance function manhattanDist(M, N, X1, Y1, X2, Y2) { let dist = Math.abs(X2 - X1) + Math.abs(Y2 - Y1); return dist; } // Driver code // Define size of 2-D array let M = 5, N = 5; // First point let X1 = 1, Y1 = 2; // Second point let X2 = 3, Y2 = 3; document.write(manhattanDist(M, N, X1, Y1, X2, Y2)); // This code is contributed by Potta Lokesh </script>", "e": 28067, "s": 27514, "text": null }, { "code": null, "e": 28072, "s": 28070, "text": "3" }, { "code": null, "e": 28115, "s": 28072, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 28131, "s": 28117, "text": "lokeshpotta20" }, { "code": null, "e": 28148, "s": 28131, "text": "_saurabh_jaiswal" }, { "code": null, "e": 28156, "s": 28148, "text": "gfgking" }, { "code": null, "e": 28162, "s": 28156, "text": "ukasp" }, { "code": null, "e": 28169, "s": 28162, "text": "Arrays" }, { "code": null, "e": 28176, "s": 28169, "text": "Matrix" }, { "code": null, "e": 28183, "s": 28176, "text": "Arrays" }, { "code": null, "e": 28190, "s": 28183, "text": "Matrix" }, { "code": null, "e": 28288, "s": 28190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28297, "s": 28288, "text": "Comments" }, { "code": null, "e": 28310, "s": 28297, "text": "Old Comments" }, { "code": null, "e": 28335, "s": 28310, "text": "Window Sliding Technique" }, { "code": null, "e": 28384, "s": 28335, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 28422, "s": 28384, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 28480, "s": 28422, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 28500, "s": 28480, "text": "Trapping Rain Water" }, { "code": null, "e": 28535, "s": 28500, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 28559, "s": 28535, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 28621, "s": 28559, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 28652, "s": 28621, "text": "Rat in a Maze | Backtracking-2" } ]
Properties of Asymptotic Notations - GeeksforGeeks
06 Sep, 2019 Prerequisite: Asymptotic NotationsAssuming f(n), g(n) and h(n) be asymptotic functions the mathematical definitions are: If f(n) = Θ(g(n)), then there exists positive constants c1, c2, n0 such that 0 ≤ c1.g(n) ≤ f(n) ≤ c2.g(n), for all n ≥ n0If f(n) = O(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) ≤ c.g(n), for all n ≥ n0If f(n) = Ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) ≤ f(n), for all n ≥ n0If f(n) = o(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) < c.g(n), for all n ≥ n0If f(n) = ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) < f(n), for all n ≥ n0 If f(n) = Θ(g(n)), then there exists positive constants c1, c2, n0 such that 0 ≤ c1.g(n) ≤ f(n) ≤ c2.g(n), for all n ≥ n0 If f(n) = O(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) ≤ c.g(n), for all n ≥ n0 If f(n) = Ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) ≤ f(n), for all n ≥ n0 If f(n) = o(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) < c.g(n), for all n ≥ n0 If f(n) = ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) < f(n), for all n ≥ n0 Properties: Reflexivity:If f(n) is given thenf(n) = O(f(n))Example:If f(n) = n3 ⇒ O(n3)Similarly,f(n) = Ω(f(n)) f(n) = Θ(f(n)) Symmetry:f(n) = Θ(g(n)) if and only if g(n) = Θ(f(n))Example:If f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2)Proof:Necessary part:f(n) = Θ(g(n)) ⇒ g(n) = Θ(f(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.g(n) ≤ f(n) ≤ c2.g(n) for all n ≥ no⇒ g(n) ≤ (1/c1).f(n) and g(n) ≥ (1/c2).f(n)⇒ (1/c2).f(n) ≤ g(n) ≤ (1/c1).f(n)Since c1 and c2 are positive constants, 1/c1 and 1/c2 are well defined. Therefore, by the definition of Θ, g(n) = Θ(f(n))Sufficiency part:g(n) = Θ(f(n)) ⇒ f(n) = Θ(g(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.f(n) ≤ g(n) ≤ c2.f(n) for all n ≥ no⇒ f(n) ≤ (1/c1).g(n) and f(n) ≥ (1/c2).g(n)⇒ (1/c2).g(n) ≤ f(n) ≤ (1/c1).g(n)By the definition of Theta(Θ), f(n) = Θ(g(n))Transistivity:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))Example:If f(n) = n, g(n) = n2 and h(n) = n3⇒ n is O(n2) and n2 is O(n3) then n is O(n3)Proof:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))By the definition of Big-Oh(O), there exists positive constants c, no such that f(n) ≤ c.g(n) for all n ≥ no⇒ f(n) ≤ c1.g(n)⇒ g(n) ≤ c2.h(n)⇒ f(n) ≤ c1.c2h(n)⇒ f(n) ≤ c.h(n), where, c = c1.c2 By the definition, f(n) = O(h(n))Similarly,f(n) = Θ(g(n)) and g(n) = Θ(h(n)) ⇒ f(n) = Θ(h(n)) f(n) = Ω(g(n)) and g(n) = Ω(h(n)) ⇒ f(n) = Ω(h(n)) f(n) = o(g(n)) and g(n) = o(h(n)) ⇒ f(n) = o(h(n)) f(n) = ω(g(n)) and g(n) = ω(h(n)) ⇒ f(n) = ω(h(n))Transpose Symmetry:f(n) = O(g(n)) if and only if g(n) = Ω(f(n))Example:If f(n) = n and g(n) = n2 then n is O(n2) and n2 is Ω(n)Proof:Necessary part:f(n) = O(g(n)) ⇒ g(n) = Ω(f(n))By the definition of Big-Oh (O) ⇒ f(n) ≤ c.g(n) for some positive constant c ⇒ g(n) ≥ (1/c).f(n)By the definition of Omega (Ω), g(n) = Ω(f(n))Sufficiency part:g(n) = Ω(f(n)) ⇒ f(n) = O(g(n))By the definition of Omega (Ω), for some positive constant c ⇒ g(n) ≥ c.f(n) ⇒ f(n) ≤ (1/c).g(n)By the definition of Big-Oh(O), f(n) = O(g(n))Similarly,f(n) = o(g(n)) if and only if g(n) = ω(f(n)) Since these properties hold for asymptotic notations, analogies can be drawn between functions f(n) and g(n) and two real numbers a and b.g(n) = O(f(n)) is similar to a ≤ bg(n) = Ω(f(n)) is similar to a ≥ bg(n) = Θ(f(n)) is similar to a = bg(n) = o(f(n)) is similar to a < bg(n) = ω(f(n)) is similar to a > bObservations:max(f(n), g(n)) = Θ(f(n) + g(n)) Proof:Without loss of generality, assume f(n) ≤ g(n), ⇒ max(f(n), g(n)) = g(n)Consider, g(n) ≤ max(f(n), g(n)) ≤ g(n)⇒ g(n) ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ g(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)From what we assumed, we can write⇒ f(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ (f(n) + g(n))/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)By the definition of Θ, max(f(n), g(n)) = Θ(f(n) + g(n))O(f(n)) + O(g(n)) = O(max(f(n), g(n)))Proof:Without loss of generality, assume f(n) ≤ g(n)⇒ O(f(n)) + O(g(n)) = c1.f(n) + c2.g(n)From what we assumed, we can writeO(f(n)) + O(g(n)) ≤ c1.g(n) + c2.g(n)≤ (c1 + c2) g(n)≤ c.g(n)≤ c.max(f(n), g(n))By the definition of Big-Oh(O),O(f(n)) + O(g(n)) = O(max(f(n), g(n))) Reflexivity:If f(n) is given thenf(n) = O(f(n))Example:If f(n) = n3 ⇒ O(n3)Similarly,f(n) = Ω(f(n)) f(n) = Θ(f(n)) f(n) = O(f(n)) Example:If f(n) = n3 ⇒ O(n3)Similarly, f(n) = Ω(f(n)) f(n) = Θ(f(n)) Symmetry:f(n) = Θ(g(n)) if and only if g(n) = Θ(f(n))Example:If f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2)Proof:Necessary part:f(n) = Θ(g(n)) ⇒ g(n) = Θ(f(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.g(n) ≤ f(n) ≤ c2.g(n) for all n ≥ no⇒ g(n) ≤ (1/c1).f(n) and g(n) ≥ (1/c2).f(n)⇒ (1/c2).f(n) ≤ g(n) ≤ (1/c1).f(n)Since c1 and c2 are positive constants, 1/c1 and 1/c2 are well defined. Therefore, by the definition of Θ, g(n) = Θ(f(n))Sufficiency part:g(n) = Θ(f(n)) ⇒ f(n) = Θ(g(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.f(n) ≤ g(n) ≤ c2.f(n) for all n ≥ no⇒ f(n) ≤ (1/c1).g(n) and f(n) ≥ (1/c2).g(n)⇒ (1/c2).g(n) ≤ f(n) ≤ (1/c1).g(n)By the definition of Theta(Θ), f(n) = Θ(g(n)) f(n) = Θ(g(n)) if and only if g(n) = Θ(f(n)) Example:If f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2)Proof: Necessary part:f(n) = Θ(g(n)) ⇒ g(n) = Θ(f(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.g(n) ≤ f(n) ≤ c2.g(n) for all n ≥ no⇒ g(n) ≤ (1/c1).f(n) and g(n) ≥ (1/c2).f(n)⇒ (1/c2).f(n) ≤ g(n) ≤ (1/c1).f(n)Since c1 and c2 are positive constants, 1/c1 and 1/c2 are well defined. Therefore, by the definition of Θ, g(n) = Θ(f(n)) Sufficiency part:g(n) = Θ(f(n)) ⇒ f(n) = Θ(g(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.f(n) ≤ g(n) ≤ c2.f(n) for all n ≥ no⇒ f(n) ≤ (1/c1).g(n) and f(n) ≥ (1/c2).g(n)⇒ (1/c2).g(n) ≤ f(n) ≤ (1/c1).g(n)By the definition of Theta(Θ), f(n) = Θ(g(n)) Transistivity:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))Example:If f(n) = n, g(n) = n2 and h(n) = n3⇒ n is O(n2) and n2 is O(n3) then n is O(n3)Proof:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))By the definition of Big-Oh(O), there exists positive constants c, no such that f(n) ≤ c.g(n) for all n ≥ no⇒ f(n) ≤ c1.g(n)⇒ g(n) ≤ c2.h(n)⇒ f(n) ≤ c1.c2h(n)⇒ f(n) ≤ c.h(n), where, c = c1.c2 By the definition, f(n) = O(h(n))Similarly,f(n) = Θ(g(n)) and g(n) = Θ(h(n)) ⇒ f(n) = Θ(h(n)) f(n) = Ω(g(n)) and g(n) = Ω(h(n)) ⇒ f(n) = Ω(h(n)) f(n) = o(g(n)) and g(n) = o(h(n)) ⇒ f(n) = o(h(n)) f(n) = ω(g(n)) and g(n) = ω(h(n)) ⇒ f(n) = ω(h(n)) f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n)) Example:If f(n) = n, g(n) = n2 and h(n) = n3⇒ n is O(n2) and n2 is O(n3) then n is O(n3)Proof:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))By the definition of Big-Oh(O), there exists positive constants c, no such that f(n) ≤ c.g(n) for all n ≥ no⇒ f(n) ≤ c1.g(n)⇒ g(n) ≤ c2.h(n)⇒ f(n) ≤ c1.c2h(n)⇒ f(n) ≤ c.h(n), where, c = c1.c2 By the definition, f(n) = O(h(n))Similarly, f(n) = Θ(g(n)) and g(n) = Θ(h(n)) ⇒ f(n) = Θ(h(n)) f(n) = Ω(g(n)) and g(n) = Ω(h(n)) ⇒ f(n) = Ω(h(n)) f(n) = o(g(n)) and g(n) = o(h(n)) ⇒ f(n) = o(h(n)) f(n) = ω(g(n)) and g(n) = ω(h(n)) ⇒ f(n) = ω(h(n)) Transpose Symmetry:f(n) = O(g(n)) if and only if g(n) = Ω(f(n))Example:If f(n) = n and g(n) = n2 then n is O(n2) and n2 is Ω(n)Proof:Necessary part:f(n) = O(g(n)) ⇒ g(n) = Ω(f(n))By the definition of Big-Oh (O) ⇒ f(n) ≤ c.g(n) for some positive constant c ⇒ g(n) ≥ (1/c).f(n)By the definition of Omega (Ω), g(n) = Ω(f(n))Sufficiency part:g(n) = Ω(f(n)) ⇒ f(n) = O(g(n))By the definition of Omega (Ω), for some positive constant c ⇒ g(n) ≥ c.f(n) ⇒ f(n) ≤ (1/c).g(n)By the definition of Big-Oh(O), f(n) = O(g(n))Similarly,f(n) = o(g(n)) if and only if g(n) = ω(f(n)) f(n) = O(g(n)) if and only if g(n) = Ω(f(n)) Example:If f(n) = n and g(n) = n2 then n is O(n2) and n2 is Ω(n)Proof: Necessary part:f(n) = O(g(n)) ⇒ g(n) = Ω(f(n))By the definition of Big-Oh (O) ⇒ f(n) ≤ c.g(n) for some positive constant c ⇒ g(n) ≥ (1/c).f(n)By the definition of Omega (Ω), g(n) = Ω(f(n)) Sufficiency part:g(n) = Ω(f(n)) ⇒ f(n) = O(g(n))By the definition of Omega (Ω), for some positive constant c ⇒ g(n) ≥ c.f(n) ⇒ f(n) ≤ (1/c).g(n)By the definition of Big-Oh(O), f(n) = O(g(n)) Similarly, f(n) = o(g(n)) if and only if g(n) = ω(f(n)) Since these properties hold for asymptotic notations, analogies can be drawn between functions f(n) and g(n) and two real numbers a and b.g(n) = O(f(n)) is similar to a ≤ bg(n) = Ω(f(n)) is similar to a ≥ bg(n) = Θ(f(n)) is similar to a = bg(n) = o(f(n)) is similar to a < bg(n) = ω(f(n)) is similar to a > b g(n) = O(f(n)) is similar to a ≤ b g(n) = Ω(f(n)) is similar to a ≥ b g(n) = Θ(f(n)) is similar to a = b g(n) = o(f(n)) is similar to a < b g(n) = ω(f(n)) is similar to a > b Observations:max(f(n), g(n)) = Θ(f(n) + g(n)) Proof:Without loss of generality, assume f(n) ≤ g(n), ⇒ max(f(n), g(n)) = g(n)Consider, g(n) ≤ max(f(n), g(n)) ≤ g(n)⇒ g(n) ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ g(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)From what we assumed, we can write⇒ f(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ (f(n) + g(n))/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)By the definition of Θ, max(f(n), g(n)) = Θ(f(n) + g(n)) max(f(n), g(n)) = Θ(f(n) + g(n)) Proof:Without loss of generality, assume f(n) ≤ g(n), ⇒ max(f(n), g(n)) = g(n)Consider, g(n) ≤ max(f(n), g(n)) ≤ g(n)⇒ g(n) ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ g(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)From what we assumed, we can write⇒ f(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ (f(n) + g(n))/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)By the definition of Θ, max(f(n), g(n)) = Θ(f(n) + g(n)) O(f(n)) + O(g(n)) = O(max(f(n), g(n)))Proof:Without loss of generality, assume f(n) ≤ g(n)⇒ O(f(n)) + O(g(n)) = c1.f(n) + c2.g(n)From what we assumed, we can writeO(f(n)) + O(g(n)) ≤ c1.g(n) + c2.g(n)≤ (c1 + c2) g(n)≤ c.g(n)≤ c.max(f(n), g(n))By the definition of Big-Oh(O),O(f(n)) + O(g(n)) = O(max(f(n), g(n))) O(f(n)) + O(g(n)) = O(max(f(n), g(n))) Proof:Without loss of generality, assume f(n) ≤ g(n)⇒ O(f(n)) + O(g(n)) = c1.f(n) + c2.g(n)From what we assumed, we can writeO(f(n)) + O(g(n)) ≤ c1.g(n) + c2.g(n)≤ (c1 + c2) g(n)≤ c.g(n)≤ c.max(f(n), g(n))By the definition of Big-Oh(O),O(f(n)) + O(g(n)) = O(max(f(n), g(n))) Note: If lim n→∞ f(n)/g(n) = c, c ∈ R+ then f(n) = Θ(g(n))If lim n→∞ f(n)/g(n) ≤ c, c ∈ R (c can be 0) then f(n) = O(g(n))If lim n→∞ f(n)/g(n) = 0, then f(n) = O(g(n)) and g(n) = O(f(n))If lim n→∞ f(n)/g(n) ≥ c, c ∈ R (c can be ∞) then f(n) = Ω(g(n))If lim n→∞ f(n)/g(n) = ∞, then f(n) = Ω(g(n))and g(n) = Ω(f(n)) If lim n→∞ f(n)/g(n) = c, c ∈ R+ then f(n) = Θ(g(n)) If lim n→∞ f(n)/g(n) ≤ c, c ∈ R (c can be 0) then f(n) = O(g(n)) If lim n→∞ f(n)/g(n) = 0, then f(n) = O(g(n)) and g(n) = O(f(n)) If lim n→∞ f(n)/g(n) ≥ c, c ∈ R (c can be ∞) then f(n) = Ω(g(n)) If lim n→∞ f(n)/g(n) = ∞, then f(n) = Ω(g(n))and g(n) = Ω(f(n)) Analysis GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Difference between Deterministic and Non-deterministic Algorithms Complexity analysis of various operations of Binary Min Heap Proof that Hamiltonian Cycle is NP-Complete Pseudo-polynomial Algorithms Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 26401, "s": 26373, "text": "\n06 Sep, 2019" }, { "code": null, "e": 26522, "s": 26401, "text": "Prerequisite: Asymptotic NotationsAssuming f(n), g(n) and h(n) be asymptotic functions the mathematical definitions are:" }, { "code": null, "e": 27064, "s": 26522, "text": "If f(n) = Θ(g(n)), then there exists positive constants c1, c2, n0 such that 0 ≤ c1.g(n) ≤ f(n) ≤ c2.g(n), for all n ≥ n0If f(n) = O(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) ≤ c.g(n), for all n ≥ n0If f(n) = Ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) ≤ f(n), for all n ≥ n0If f(n) = o(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) < c.g(n), for all n ≥ n0If f(n) = ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) < f(n), for all n ≥ n0" }, { "code": null, "e": 27186, "s": 27064, "text": "If f(n) = Θ(g(n)), then there exists positive constants c1, c2, n0 such that 0 ≤ c1.g(n) ≤ f(n) ≤ c2.g(n), for all n ≥ n0" }, { "code": null, "e": 27292, "s": 27186, "text": "If f(n) = O(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) ≤ c.g(n), for all n ≥ n0" }, { "code": null, "e": 27398, "s": 27292, "text": "If f(n) = Ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) ≤ f(n), for all n ≥ n0" }, { "code": null, "e": 27504, "s": 27398, "text": "If f(n) = o(g(n)), then there exists positive constants c, n0 such that 0 ≤ f(n) < c.g(n), for all n ≥ n0" }, { "code": null, "e": 27610, "s": 27504, "text": "If f(n) = ω(g(n)), then there exists positive constants c, n0 such that 0 ≤ c.g(n) < f(n), for all n ≥ n0" }, { "code": null, "e": 27622, "s": 27610, "text": "Properties:" }, { "code": null, "e": 30783, "s": 27622, "text": "Reflexivity:If f(n) is given thenf(n) = O(f(n))Example:If f(n) = n3 ⇒ O(n3)Similarly,f(n) = Ω(f(n)) \nf(n) = Θ(f(n)) Symmetry:f(n) = Θ(g(n)) if and only if g(n) = Θ(f(n))Example:If f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2)Proof:Necessary part:f(n) = Θ(g(n)) ⇒ g(n) = Θ(f(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.g(n) ≤ f(n) ≤ c2.g(n) for all n ≥ no⇒ g(n) ≤ (1/c1).f(n) and g(n) ≥ (1/c2).f(n)⇒ (1/c2).f(n) ≤ g(n) ≤ (1/c1).f(n)Since c1 and c2 are positive constants, 1/c1 and 1/c2 are well defined. Therefore, by the definition of Θ, g(n) = Θ(f(n))Sufficiency part:g(n) = Θ(f(n)) ⇒ f(n) = Θ(g(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.f(n) ≤ g(n) ≤ c2.f(n) for all n ≥ no⇒ f(n) ≤ (1/c1).g(n) and f(n) ≥ (1/c2).g(n)⇒ (1/c2).g(n) ≤ f(n) ≤ (1/c1).g(n)By the definition of Theta(Θ), f(n) = Θ(g(n))Transistivity:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))Example:If f(n) = n, g(n) = n2 and h(n) = n3⇒ n is O(n2) and n2 is O(n3) then n is O(n3)Proof:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))By the definition of Big-Oh(O), there exists positive constants c, no such that f(n) ≤ c.g(n) for all n ≥ no⇒ f(n) ≤ c1.g(n)⇒ g(n) ≤ c2.h(n)⇒ f(n) ≤ c1.c2h(n)⇒ f(n) ≤ c.h(n), where, c = c1.c2 By the definition, f(n) = O(h(n))Similarly,f(n) = Θ(g(n)) and g(n) = Θ(h(n)) ⇒ f(n) = Θ(h(n))\nf(n) = Ω(g(n)) and g(n) = Ω(h(n)) ⇒ f(n) = Ω(h(n))\nf(n) = o(g(n)) and g(n) = o(h(n)) ⇒ f(n) = o(h(n))\nf(n) = ω(g(n)) and g(n) = ω(h(n)) ⇒ f(n) = ω(h(n))Transpose Symmetry:f(n) = O(g(n)) if and only if g(n) = Ω(f(n))Example:If f(n) = n and g(n) = n2 then n is O(n2) and n2 is Ω(n)Proof:Necessary part:f(n) = O(g(n)) ⇒ g(n) = Ω(f(n))By the definition of Big-Oh (O) ⇒ f(n) ≤ c.g(n) for some positive constant c ⇒ g(n) ≥ (1/c).f(n)By the definition of Omega (Ω), g(n) = Ω(f(n))Sufficiency part:g(n) = Ω(f(n)) ⇒ f(n) = O(g(n))By the definition of Omega (Ω), for some positive constant c ⇒ g(n) ≥ c.f(n) ⇒ f(n) ≤ (1/c).g(n)By the definition of Big-Oh(O), f(n) = O(g(n))Similarly,f(n) = o(g(n)) if and only if g(n) = ω(f(n)) Since these properties hold for asymptotic notations, analogies can be drawn between functions f(n) and g(n) and two real numbers a and b.g(n) = O(f(n)) is similar to a ≤ bg(n) = Ω(f(n)) is similar to a ≥ bg(n) = Θ(f(n)) is similar to a = bg(n) = o(f(n)) is similar to a < bg(n) = ω(f(n)) is similar to a > bObservations:max(f(n), g(n)) = Θ(f(n) + g(n)) Proof:Without loss of generality, assume f(n) ≤ g(n), ⇒ max(f(n), g(n)) = g(n)Consider, g(n) ≤ max(f(n), g(n)) ≤ g(n)⇒ g(n) ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ g(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)From what we assumed, we can write⇒ f(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ (f(n) + g(n))/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)By the definition of Θ, max(f(n), g(n)) = Θ(f(n) + g(n))O(f(n)) + O(g(n)) = O(max(f(n), g(n)))Proof:Without loss of generality, assume f(n) ≤ g(n)⇒ O(f(n)) + O(g(n)) = c1.f(n) + c2.g(n)From what we assumed, we can writeO(f(n)) + O(g(n)) ≤ c1.g(n) + c2.g(n)≤ (c1 + c2) g(n)≤ c.g(n)≤ c.max(f(n), g(n))By the definition of Big-Oh(O),O(f(n)) + O(g(n)) = O(max(f(n), g(n)))" }, { "code": null, "e": 30900, "s": 30783, "text": "Reflexivity:If f(n) is given thenf(n) = O(f(n))Example:If f(n) = n3 ⇒ O(n3)Similarly,f(n) = Ω(f(n)) \nf(n) = Θ(f(n)) " }, { "code": null, "e": 30915, "s": 30900, "text": "f(n) = O(f(n))" }, { "code": null, "e": 30954, "s": 30915, "text": "Example:If f(n) = n3 ⇒ O(n3)Similarly," }, { "code": null, "e": 30986, "s": 30954, "text": "f(n) = Ω(f(n)) \nf(n) = Θ(f(n)) " }, { "code": null, "e": 31761, "s": 30986, "text": "Symmetry:f(n) = Θ(g(n)) if and only if g(n) = Θ(f(n))Example:If f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2)Proof:Necessary part:f(n) = Θ(g(n)) ⇒ g(n) = Θ(f(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.g(n) ≤ f(n) ≤ c2.g(n) for all n ≥ no⇒ g(n) ≤ (1/c1).f(n) and g(n) ≥ (1/c2).f(n)⇒ (1/c2).f(n) ≤ g(n) ≤ (1/c1).f(n)Since c1 and c2 are positive constants, 1/c1 and 1/c2 are well defined. Therefore, by the definition of Θ, g(n) = Θ(f(n))Sufficiency part:g(n) = Θ(f(n)) ⇒ f(n) = Θ(g(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.f(n) ≤ g(n) ≤ c2.f(n) for all n ≥ no⇒ f(n) ≤ (1/c1).g(n) and f(n) ≥ (1/c2).g(n)⇒ (1/c2).g(n) ≤ f(n) ≤ (1/c1).g(n)By the definition of Theta(Θ), f(n) = Θ(g(n))" }, { "code": null, "e": 31806, "s": 31761, "text": "f(n) = Θ(g(n)) if and only if g(n) = Θ(f(n))" }, { "code": null, "e": 31882, "s": 31806, "text": "Example:If f(n) = n2 and g(n) = n2 then f(n) = Θ(n2) and g(n) = Θ(n2)Proof:" }, { "code": null, "e": 32243, "s": 31882, "text": "Necessary part:f(n) = Θ(g(n)) ⇒ g(n) = Θ(f(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.g(n) ≤ f(n) ≤ c2.g(n) for all n ≥ no⇒ g(n) ≤ (1/c1).f(n) and g(n) ≥ (1/c2).f(n)⇒ (1/c2).f(n) ≤ g(n) ≤ (1/c1).f(n)Since c1 and c2 are positive constants, 1/c1 and 1/c2 are well defined. Therefore, by the definition of Θ, g(n) = Θ(f(n))" }, { "code": null, "e": 32530, "s": 32243, "text": "Sufficiency part:g(n) = Θ(f(n)) ⇒ f(n) = Θ(g(n))By the definition of Θ, there exists positive constants c1, c2, no such that c1.f(n) ≤ g(n) ≤ c2.f(n) for all n ≥ no⇒ f(n) ≤ (1/c1).g(n) and f(n) ≥ (1/c2).g(n)⇒ (1/c2).g(n) ≤ f(n) ≤ (1/c1).g(n)By the definition of Theta(Θ), f(n) = Θ(g(n))" }, { "code": null, "e": 33177, "s": 32530, "text": "Transistivity:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))Example:If f(n) = n, g(n) = n2 and h(n) = n3⇒ n is O(n2) and n2 is O(n3) then n is O(n3)Proof:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))By the definition of Big-Oh(O), there exists positive constants c, no such that f(n) ≤ c.g(n) for all n ≥ no⇒ f(n) ≤ c1.g(n)⇒ g(n) ≤ c2.h(n)⇒ f(n) ≤ c1.c2h(n)⇒ f(n) ≤ c.h(n), where, c = c1.c2 By the definition, f(n) = O(h(n))Similarly,f(n) = Θ(g(n)) and g(n) = Θ(h(n)) ⇒ f(n) = Θ(h(n))\nf(n) = Ω(g(n)) and g(n) = Ω(h(n)) ⇒ f(n) = Ω(h(n))\nf(n) = o(g(n)) and g(n) = o(h(n)) ⇒ f(n) = o(h(n))\nf(n) = ω(g(n)) and g(n) = ω(h(n)) ⇒ f(n) = ω(h(n))" }, { "code": null, "e": 33228, "s": 33177, "text": "f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))" }, { "code": null, "e": 33608, "s": 33228, "text": "Example:If f(n) = n, g(n) = n2 and h(n) = n3⇒ n is O(n2) and n2 is O(n3) then n is O(n3)Proof:f(n) = O(g(n)) and g(n) = O(h(n)) ⇒ f(n) = O(h(n))By the definition of Big-Oh(O), there exists positive constants c, no such that f(n) ≤ c.g(n) for all n ≥ no⇒ f(n) ≤ c1.g(n)⇒ g(n) ≤ c2.h(n)⇒ f(n) ≤ c1.c2h(n)⇒ f(n) ≤ c.h(n), where, c = c1.c2 By the definition, f(n) = O(h(n))Similarly," }, { "code": null, "e": 33812, "s": 33608, "text": "f(n) = Θ(g(n)) and g(n) = Θ(h(n)) ⇒ f(n) = Θ(h(n))\nf(n) = Ω(g(n)) and g(n) = Ω(h(n)) ⇒ f(n) = Ω(h(n))\nf(n) = o(g(n)) and g(n) = o(h(n)) ⇒ f(n) = o(h(n))\nf(n) = ω(g(n)) and g(n) = ω(h(n)) ⇒ f(n) = ω(h(n))" }, { "code": null, "e": 34379, "s": 33812, "text": "Transpose Symmetry:f(n) = O(g(n)) if and only if g(n) = Ω(f(n))Example:If f(n) = n and g(n) = n2 then n is O(n2) and n2 is Ω(n)Proof:Necessary part:f(n) = O(g(n)) ⇒ g(n) = Ω(f(n))By the definition of Big-Oh (O) ⇒ f(n) ≤ c.g(n) for some positive constant c ⇒ g(n) ≥ (1/c).f(n)By the definition of Omega (Ω), g(n) = Ω(f(n))Sufficiency part:g(n) = Ω(f(n)) ⇒ f(n) = O(g(n))By the definition of Omega (Ω), for some positive constant c ⇒ g(n) ≥ c.f(n) ⇒ f(n) ≤ (1/c).g(n)By the definition of Big-Oh(O), f(n) = O(g(n))Similarly,f(n) = o(g(n)) if and only if g(n) = ω(f(n)) " }, { "code": null, "e": 34424, "s": 34379, "text": "f(n) = O(g(n)) if and only if g(n) = Ω(f(n))" }, { "code": null, "e": 34495, "s": 34424, "text": "Example:If f(n) = n and g(n) = n2 then n is O(n2) and n2 is Ω(n)Proof:" }, { "code": null, "e": 34684, "s": 34495, "text": "Necessary part:f(n) = O(g(n)) ⇒ g(n) = Ω(f(n))By the definition of Big-Oh (O) ⇒ f(n) ≤ c.g(n) for some positive constant c ⇒ g(n) ≥ (1/c).f(n)By the definition of Omega (Ω), g(n) = Ω(f(n))" }, { "code": null, "e": 34875, "s": 34684, "text": "Sufficiency part:g(n) = Ω(f(n)) ⇒ f(n) = O(g(n))By the definition of Omega (Ω), for some positive constant c ⇒ g(n) ≥ c.f(n) ⇒ f(n) ≤ (1/c).g(n)By the definition of Big-Oh(O), f(n) = O(g(n))" }, { "code": null, "e": 34886, "s": 34875, "text": "Similarly," }, { "code": null, "e": 34932, "s": 34886, "text": "f(n) = o(g(n)) if and only if g(n) = ω(f(n)) " }, { "code": null, "e": 35241, "s": 34932, "text": "Since these properties hold for asymptotic notations, analogies can be drawn between functions f(n) and g(n) and two real numbers a and b.g(n) = O(f(n)) is similar to a ≤ bg(n) = Ω(f(n)) is similar to a ≥ bg(n) = Θ(f(n)) is similar to a = bg(n) = o(f(n)) is similar to a < bg(n) = ω(f(n)) is similar to a > b" }, { "code": null, "e": 35276, "s": 35241, "text": "g(n) = O(f(n)) is similar to a ≤ b" }, { "code": null, "e": 35311, "s": 35276, "text": "g(n) = Ω(f(n)) is similar to a ≥ b" }, { "code": null, "e": 35346, "s": 35311, "text": "g(n) = Θ(f(n)) is similar to a = b" }, { "code": null, "e": 35381, "s": 35346, "text": "g(n) = o(f(n)) is similar to a < b" }, { "code": null, "e": 35416, "s": 35381, "text": "g(n) = ω(f(n)) is similar to a > b" }, { "code": null, "e": 35855, "s": 35416, "text": "Observations:max(f(n), g(n)) = Θ(f(n) + g(n)) Proof:Without loss of generality, assume f(n) ≤ g(n), ⇒ max(f(n), g(n)) = g(n)Consider, g(n) ≤ max(f(n), g(n)) ≤ g(n)⇒ g(n) ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ g(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)From what we assumed, we can write⇒ f(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ (f(n) + g(n))/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)By the definition of Θ, max(f(n), g(n)) = Θ(f(n) + g(n))" }, { "code": null, "e": 35889, "s": 35855, "text": "max(f(n), g(n)) = Θ(f(n) + g(n)) " }, { "code": null, "e": 36282, "s": 35889, "text": "Proof:Without loss of generality, assume f(n) ≤ g(n), ⇒ max(f(n), g(n)) = g(n)Consider, g(n) ≤ max(f(n), g(n)) ≤ g(n)⇒ g(n) ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ g(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)From what we assumed, we can write⇒ f(n)/2 + g(n)/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)⇒ (f(n) + g(n))/2 ≤ max(f(n), g(n)) ≤ f(n) + g(n)By the definition of Θ, max(f(n), g(n)) = Θ(f(n) + g(n))" }, { "code": null, "e": 36595, "s": 36282, "text": "O(f(n)) + O(g(n)) = O(max(f(n), g(n)))Proof:Without loss of generality, assume f(n) ≤ g(n)⇒ O(f(n)) + O(g(n)) = c1.f(n) + c2.g(n)From what we assumed, we can writeO(f(n)) + O(g(n)) ≤ c1.g(n) + c2.g(n)≤ (c1 + c2) g(n)≤ c.g(n)≤ c.max(f(n), g(n))By the definition of Big-Oh(O),O(f(n)) + O(g(n)) = O(max(f(n), g(n)))" }, { "code": null, "e": 36634, "s": 36595, "text": "O(f(n)) + O(g(n)) = O(max(f(n), g(n)))" }, { "code": null, "e": 36909, "s": 36634, "text": "Proof:Without loss of generality, assume f(n) ≤ g(n)⇒ O(f(n)) + O(g(n)) = c1.f(n) + c2.g(n)From what we assumed, we can writeO(f(n)) + O(g(n)) ≤ c1.g(n) + c2.g(n)≤ (c1 + c2) g(n)≤ c.g(n)≤ c.max(f(n), g(n))By the definition of Big-Oh(O),O(f(n)) + O(g(n)) = O(max(f(n), g(n)))" }, { "code": null, "e": 36915, "s": 36909, "text": "Note:" }, { "code": null, "e": 37223, "s": 36915, "text": "If lim n→∞ f(n)/g(n) = c, c ∈ R+ then f(n) = Θ(g(n))If lim n→∞ f(n)/g(n) ≤ c, c ∈ R (c can be 0) then f(n) = O(g(n))If lim n→∞ f(n)/g(n) = 0, then f(n) = O(g(n)) and g(n) = O(f(n))If lim n→∞ f(n)/g(n) ≥ c, c ∈ R (c can be ∞) then f(n) = Ω(g(n))If lim n→∞ f(n)/g(n) = ∞, then f(n) = Ω(g(n))and g(n) = Ω(f(n))" }, { "code": null, "e": 37276, "s": 37223, "text": "If lim n→∞ f(n)/g(n) = c, c ∈ R+ then f(n) = Θ(g(n))" }, { "code": null, "e": 37341, "s": 37276, "text": "If lim n→∞ f(n)/g(n) ≤ c, c ∈ R (c can be 0) then f(n) = O(g(n))" }, { "code": null, "e": 37406, "s": 37341, "text": "If lim n→∞ f(n)/g(n) = 0, then f(n) = O(g(n)) and g(n) = O(f(n))" }, { "code": null, "e": 37471, "s": 37406, "text": "If lim n→∞ f(n)/g(n) ≥ c, c ∈ R (c can be ∞) then f(n) = Ω(g(n))" }, { "code": null, "e": 37535, "s": 37471, "text": "If lim n→∞ f(n)/g(n) = ∞, then f(n) = Ω(g(n))and g(n) = Ω(f(n))" }, { "code": null, "e": 37544, "s": 37535, "text": "Analysis" }, { "code": null, "e": 37552, "s": 37544, "text": "GATE CS" }, { "code": null, "e": 37650, "s": 37552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37717, "s": 37650, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 37783, "s": 37717, "text": "Difference between Deterministic and Non-deterministic Algorithms" }, { "code": null, "e": 37844, "s": 37783, "text": "Complexity analysis of various operations of Binary Min Heap" }, { "code": null, "e": 37888, "s": 37844, "text": "Proof that Hamiltonian Cycle is NP-Complete" }, { "code": null, "e": 37917, "s": 37888, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 37937, "s": 37917, "text": "Layers of OSI Model" }, { "code": null, "e": 37961, "s": 37937, "text": "ACID Properties in DBMS" }, { "code": null, "e": 37974, "s": 37961, "text": "TCP/IP Model" }, { "code": null, "e": 38001, "s": 37974, "text": "Types of Operating Systems" } ]
How to sort a matrix based on one column in R?
Since a matrix contain only numeric values, sorting can be also done for matrices. There might be multiple reasons to sort a matrix such as we want to convert the matrix to a data frame, the data stored in matrix needs to be sorted prior to matrix calculations so that the view of the result after calculations becomes clearer, etc. To sort a matrix based on one column, we can use order function. set.seed(123) M1 <-matrix(sample(1:100,20),ncol=2) M1 [,1] [,2] [1,] 31 90 [2,] 79 69 [3,] 51 57 [4,] 14 9 [5,] 67 72 [6,] 42 26 [7,] 50 7 [8,] 43 95 [9,] 97 87 [10,] 25 36 Sorting matrix M1 based on column 1 − M1[order(M1[,1],decreasing=FALSE),] [,1] [,2] [1,] 14 9 [2,] 25 36 [3,] 31 90 [4,] 42 26 [5,] 43 95 [6,] 50 7 [7,] 51 57 [8,] 67 72 [9,] 79 69 [10,] 97 87 M1[order(M1[,1],decreasing=TRUE),] [,1] [,2] [1,] 97 87 [2,] 79 69 [3,] 67 72 [4,] 51 57 [5,] 50 7 [6,] 43 95 [7,] 42 26 [8,] 31 90 [9,] 25 36 [10,] 14 9 M2 <-matrix(sample(1:10,20,replace=TRUE),ncol=2) M2 [,1] [,2] [1,] 1 7 [2,] 7 5 [3,] 5 6 [4,] 10 9 [5,] 7 2 [6,] 9 5 [7,] 9 8 [8,] 10 2 [9,] 7 1 [10,] 5 9 Sorting matrix M2 based on column 2 − M2[order(M2[,2],decreasing=TRUE),] [,1] [,2] [1,] 10 9 [2,] 5 9 [3,] 9 8 [4,] 1 7 [5,] 5 6 [6,] 7 5 [7,] 9 5 [8,] 7 2 [9,] 10 2 [10,] 7 1 M2[order(M2[,2],decreasing=FALSE),] [,1] [,2] [1,] 7 1 [2,] 7 2 [3,] 10 2 [4,] 7 5 [5,] 9 5 [6,] 5 6 [7,] 1 7 [8,] 9 8 [9,] 10 9 [10,] 5 9 M3 <-matrix(sample(1:50,20),ncol=2) M3 [,1] [,2] [1,] 27 6 [2,] 25 8 [3,] 38 22 [4,] 21 48 [5,] 15 43 [6,] 41 17 [7,] 26 34 [8,] 31 4 [9,] 16 13 [10,] 30 5 Sorting matrix M3 based on column 3 − M3[order(M3[,2],decreasing=FALSE),] [,1] [,2] [1,] 31 4 [2,] 30 5 [3,] 27 6 [4,] 25 8 [5,] 16 13 [6,] 41 17 [7,] 38 22 [8,] 26 34 [9,] 15 43 [10,] 21 48 M3[order(M3[,2],decreasing=TRUE),] [,1] [,2] [1,] 21 48 [2,] 15 43 [3,] 26 34 [4,] 38 22 [5,] 41 17 [6,] 16 13 [7,] 25 8 [8,] 27 6 [9,] 30 5 [10,] 31 4
[ { "code": null, "e": 1460, "s": 1062, "text": "Since a matrix contain only numeric values, sorting can be also done for matrices. There might be multiple reasons to sort a matrix such as we want to convert the matrix to a data frame, the data stored in matrix needs to be sorted prior to matrix calculations so that the view of the result after calculations becomes clearer, etc. To sort a matrix based on one column, we can use order function." }, { "code": null, "e": 1514, "s": 1460, "text": "set.seed(123)\nM1 <-matrix(sample(1:100,20),ncol=2)\nM1" }, { "code": null, "e": 1633, "s": 1514, "text": "[,1] [,2]\n[1,] 31 90\n[2,] 79 69\n[3,] 51 57\n[4,] 14 9\n[5,] 67 72\n[6,] 42 26\n[7,] 50 7\n[8,] 43 95\n[9,] 97 87\n[10,] 25 36" }, { "code": null, "e": 1671, "s": 1633, "text": "Sorting matrix M1 based on column 1 −" }, { "code": null, "e": 1707, "s": 1671, "text": "M1[order(M1[,1],decreasing=FALSE),]" }, { "code": null, "e": 1826, "s": 1707, "text": "[,1] [,2]\n[1,] 14 9\n[2,] 25 36\n[3,] 31 90\n[4,] 42 26\n[5,] 43 95\n[6,] 50 7\n[7,] 51 57\n[8,] 67 72\n[9,] 79 69\n[10,] 97 87" }, { "code": null, "e": 1861, "s": 1826, "text": "M1[order(M1[,1],decreasing=TRUE),]" }, { "code": null, "e": 1980, "s": 1861, "text": "[,1] [,2]\n[1,] 97 87\n[2,] 79 69\n[3,] 67 72\n[4,] 51 57\n[5,] 50 7\n[6,] 43 95\n[7,] 42 26\n[8,] 31 90\n[9,] 25 36\n[10,] 14 9" }, { "code": null, "e": 2032, "s": 1980, "text": "M2 <-matrix(sample(1:10,20,replace=TRUE),ncol=2)\nM2" }, { "code": null, "e": 2135, "s": 2032, "text": "[,1] [,2]\n[1,] 1 7\n[2,] 7 5\n[3,] 5 6\n[4,] 10 9\n[5,] 7 2\n[6,] 9 5\n[7,] 9 8\n[8,] 10 2\n[9,] 7 1\n[10,] 5 9" }, { "code": null, "e": 2173, "s": 2135, "text": "Sorting matrix M2 based on column 2 −" }, { "code": null, "e": 2208, "s": 2173, "text": "M2[order(M2[,2],decreasing=TRUE),]" }, { "code": null, "e": 2311, "s": 2208, "text": "[,1] [,2]\n[1,] 10 9\n[2,] 5 9\n[3,] 9 8\n[4,] 1 7\n[5,] 5 6\n[6,] 7 5\n[7,] 9 5\n[8,] 7 2\n[9,] 10 2\n[10,] 7 1" }, { "code": null, "e": 2347, "s": 2311, "text": "M2[order(M2[,2],decreasing=FALSE),]" }, { "code": null, "e": 2450, "s": 2347, "text": "[,1] [,2]\n[1,] 7 1\n[2,] 7 2\n[3,] 10 2\n[4,] 7 5\n[5,] 9 5\n[6,] 5 6\n[7,] 1 7\n[8,] 9 8\n[9,] 10 9\n[10,] 5 9" }, { "code": null, "e": 2489, "s": 2450, "text": "M3 <-matrix(sample(1:50,20),ncol=2)\nM3" }, { "code": null, "e": 2606, "s": 2489, "text": "[,1] [,2]\n[1,] 27 6\n[2,] 25 8\n[3,] 38 22\n[4,] 21 48\n[5,] 15 43\n[6,] 41 17\n[7,] 26 34\n[8,] 31 4\n[9,] 16 13\n[10,] 30 5" }, { "code": null, "e": 2644, "s": 2606, "text": "Sorting matrix M3 based on column 3 −" }, { "code": null, "e": 2680, "s": 2644, "text": "M3[order(M3[,2],decreasing=FALSE),]" }, { "code": null, "e": 2797, "s": 2680, "text": "[,1] [,2]\n[1,] 31 4\n[2,] 30 5\n[3,] 27 6\n[4,] 25 8\n[5,] 16 13\n[6,] 41 17\n[7,] 38 22\n[8,] 26 34\n[9,] 15 43\n[10,] 21 48" }, { "code": null, "e": 2832, "s": 2797, "text": "M3[order(M3[,2],decreasing=TRUE),]" }, { "code": null, "e": 2949, "s": 2832, "text": "[,1] [,2]\n[1,] 21 48\n[2,] 15 43\n[3,] 26 34\n[4,] 38 22\n[5,] 41 17\n[6,] 16 13\n[7,] 25 8\n[8,] 27 6\n[9,] 30 5\n[10,] 31 4" } ]
How to calculate elapsed/execution time in Java?
In general, the elapsed time or, execution is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java − The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The nanoTime() method returns the current time in nano seconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. The now() method of the Instant class returns the current time and the Duration.between() methods returns the difference between the given two time values you can find the time taken for the execution of a method using these. The Apache commons library provides a class known as Stopwatch to it provides the start() stop() and getTime() methods you can find the time taken for the execution of a method using these. The getTime() method of the java.util.Date class returns the current time. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method. You can also get the time in the current instance using the getInstance().getTime().getTime() after finding the elapsed time by getting the difference. Live Demo public class Example { public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String args[]){ //Start time long begin = System.currentTimeMillis(); //Starting the watch new Example().test(); //End time long end = System.currentTimeMillis(); long time = end-begin; System.out.println(); System.out.println("Elapsed Time: "+time +" milli seconds"); } } 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: 4 milli seconds Live Demo public class Example { public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String args[]){ //Start time long begin = System.nanoTime(); //Starting the watch new Example().test(); //End time long end = System.nanoTime(); long time = end-begin; System.out.println(); System.out.println("Elapsed Time: "+time); } } 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: 1530200 Live Demo import java.time.Duration; import java.time.Instant; public class Example { public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String args[]) { //Starting time Instant start = Instant.now(); new Example().test(); //End time Instant end = Instant.now(); long time = Duration.between(start, end).toMillis(); System.out.println(); System.out.println(time+" Milli seconds"); } } 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, 3 Milli seconds import org.apache.commons.lang3.time.StopWatch; public class Example { public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String args[]) { //Instantiating the StopWatch class StopWatch obj = new StopWatch(); //Starting the watch obj.start(); new Example().test(); //Stopping the watch obj.stop(); System.out.println(); System.out.println("Elapsed Time: "+obj.getTime() +" milli seconds"); } } 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: 1 milli seconds Live Demo import java.util.Date; public class Demo{ public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String[] args) { long startTime = new Date().getTime(); new Demo().test(); long endTime = new Date().getTime(); long time = endTime - startTime; System.out.println("Execution time: " + time); } } 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Execution time: 5 Live Demo import java.util.Calendar; public class Demo{ public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String[] args) throws InterruptedException { long startTime = Calendar.getInstance().getTime().getTime(); new Demo().test(); long endTime = Calendar.getInstance().getTime().getTime(); long time = endTime - startTime; System.out.println("Execution time: " + time); } } 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Execution time: 20 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Execution time: 20
[ { "code": null, "e": 1228, "s": 1062, "text": "In general, the elapsed time or, execution is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java −" }, { "code": null, "e": 1440, "s": 1228, "text": "The currentTimeMillis() method returns the current time in milliseconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method." }, { "code": null, "e": 1643, "s": 1440, "text": "The nanoTime() method returns the current time in nano seconds. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method." }, { "code": null, "e": 1869, "s": 1643, "text": "The now() method of the Instant class returns the current time and the Duration.between() methods returns the difference between the given two time values you can find the time taken for the execution of a method using these." }, { "code": null, "e": 2059, "s": 1869, "text": "The Apache commons library provides a class known as Stopwatch to it provides the start() stop() and getTime() methods you can find the time taken for the execution of a method using these." }, { "code": null, "e": 2273, "s": 2059, "text": "The getTime() method of the java.util.Date class returns the current time. To find the elapsed time for a method you can get the difference between time values before and after the execution of the desired method." }, { "code": null, "e": 2425, "s": 2273, "text": "You can also get the time in the current instance using the getInstance().getTime().getTime() after finding the elapsed time by getting the difference." }, { "code": null, "e": 2435, "s": 2425, "text": "Live Demo" }, { "code": null, "e": 2978, "s": 2435, "text": "public class Example {\n public void test(){\n int num = 0;\n for(int i=0; i<=50; i++){ \n num =num+i;\n System.out.print(num+\", \");\n } \n }\n public static void main(String args[]){ \n //Start time\n long begin = System.currentTimeMillis();\n //Starting the watch\n new Example().test();\n //End time\n long end = System.currentTimeMillis(); \n \n long time = end-begin;\n System.out.println();\n System.out.println(\"Elapsed Time: \"+time +\" milli seconds\");\n }\n}" }, { "code": null, "e": 3251, "s": 2978, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275,\nElapsed Time: 4 milli seconds" }, { "code": null, "e": 3261, "s": 3251, "text": "Live Demo" }, { "code": null, "e": 3768, "s": 3261, "text": "public class Example {\n public void test(){\n int num = 0;\n for(int i=0; i<=50; i++){ \n num =num+i;\n System.out.print(num+\", \");\n } \n }\n public static void main(String args[]){ \n //Start time\n long begin = System.nanoTime();\n //Starting the watch\n new Example().test();\n //End time\n long end = System.nanoTime(); \n \n long time = end-begin;\n System.out.println();\n System.out.println(\"Elapsed Time: \"+time);\n }\n}" }, { "code": null, "e": 4033, "s": 3768, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275,\nElapsed Time: 1530200" }, { "code": null, "e": 4043, "s": 4033, "text": "Live Demo" }, { "code": null, "e": 4597, "s": 4043, "text": "import java.time.Duration;\nimport java.time.Instant;\npublic class Example {\n public void test(){\n int num = 0;\n for(int i=0; i<=50; i++){ \n num =num+i;\n System.out.print(num+\", \");\n } \n }\n public static void main(String args[]) { \n //Starting time\n Instant start = Instant.now();\n new Example().test();\n //End time\n Instant end = Instant.now();\n long time = Duration.between(start, end).toMillis();\n System.out.println();\n System.out.println(time+\" Milli seconds\");\n\n }\n}" }, { "code": null, "e": 4856, "s": 4597, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275,\n3 Milli seconds" }, { "code": null, "e": 5433, "s": 4856, "text": "import org.apache.commons.lang3.time.StopWatch;\npublic class Example {\n public void test(){\n int num = 0;\n for(int i=0; i<=50; i++){ \n num =num+i;\n System.out.print(num+\", \");\n } \n }\n public static void main(String args[]) { \n //Instantiating the StopWatch class\n StopWatch obj = new StopWatch();\n //Starting the watch\n obj.start();\n new Example().test();\n //Stopping the watch\n obj.stop();\n System.out.println();\n System.out.println(\"Elapsed Time: \"+obj.getTime() +\" milli seconds\");\n }\n}" }, { "code": null, "e": 5706, "s": 5433, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275,\nElapsed Time: 1 milli seconds" }, { "code": null, "e": 5716, "s": 5706, "text": "Live Demo" }, { "code": null, "e": 6159, "s": 5716, "text": "import java.util.Date;\npublic class Demo{\n public void test(){\n int num = 0;\n for(int i=0; i<=50; i++){ \n num =num+i;\n System.out.print(num+\", \");\n } \n }\npublic static void main(String[] args) {\n long startTime = new Date().getTime();\n new Demo().test();\n long endTime = new Date().getTime();\n long time = endTime - startTime;\n System.out.println(\"Execution time: \" + time);\n }\n}" }, { "code": null, "e": 6420, "s": 6159, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Execution time: 5" }, { "code": null, "e": 6430, "s": 6420, "text": "Live Demo" }, { "code": null, "e": 6949, "s": 6430, "text": "import java.util.Calendar;\npublic class Demo{\n public void test(){\n int num = 0;\n for(int i=0; i<=50; i++){ \n num =num+i;\n System.out.print(num+\", \");\n } \n }\npublic static void main(String[] args) throws InterruptedException {\n long startTime = Calendar.getInstance().getTime().getTime();\n new Demo().test();\n long endTime = Calendar.getInstance().getTime().getTime();\n long time = endTime - startTime;\n System.out.println(\"Execution time: \" + time);\n }\n}" }, { "code": null, "e": 7211, "s": 6949, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Execution time: 20" }, { "code": null, "e": 7473, "s": 7211, "text": "0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Execution time: 20" } ]
How to Create an Animated Bar Chart in Jupyter | Towards Data Science
Table of ContentsIntroduction1. Data preparation2. Animated Bar Chart3. A line chartConclusion Every news outlet writes about economic hardships due to COVID-19. The fallout has disproportionally affected black communities. The Federal Reserve Bank of St. Louis (FRED) updated its unemployment rate data. The observation range varies by data sets, but the latest data is from May 2020. We’re going to visualize how the unemployment rate changed by race and gender over the year using a Plotly animated bar chart on Jupyter. This article assumes you are already familiar with the basic operation in JupyterLab/Jupyter Notebook. Plotly installation plotly.py may be installed using pip. $ pip install plotly==4.8.1 for Conda users: $ conda install -c plotly plotly=4.8.1 JupyterLab Support (Python 3.5+) Using pip: $ pip install jupyterlab "ipywidgets>=7.5" for Conda users: $ conda install jupyterlab "ipywidgets=7.5" Then run the following (you need node installed): # JupyterLab renderer support $ jupyter labextension install [email protected] # OPTIONAL: Jupyter widgets extension $ jupyter labextension install @jupyter-widgets/jupyterlab-manager [email protected] towardsdatascience.com towardsdatascience.com towardsdatascience.com The above data are 20 Yrs. & Over (LNS14000024), 20 Yrs. & Over, White Men (LNS14000028), 20 Yrs. Over, White Women (LNS14000029), 20 Yrs. & Over, Black or African American Men (LNS14000031), 20 Yrs. & Over, Black or African American Women (LNS14000032)), 20 Yrs. & Over, Hispanic or Latino Men (LNS14000034), 20 Yrs. & Over, Hispanic or Latino Women (LNS14000032). We’re going to concatenate all data sets, add a category column with appropriate names and filter by the date so that all data sets will have the same length as seen below. import pandas as pdimport plotly.express as px over20='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000024.csv'over20_white_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000028.csv'over20_white_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000029.csv'over20_black_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/7d63e7a7495dfb8578120016c7a7dd4edc04e20d/LNS14000031.csv'over20_black_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000032.csv'over20_hispanic_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/f693c9bdd76875b12a14033cc54931da894bd341/LNU04000034.csv'over20_hispanic_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/f693c9bdd76875b12a14033cc54931da894bd341/LNU04000035.csv' df_over20 = pd.read_csv(over20)df_over20_wm = pd.read_csv(over20_white_men)df_over20_ww = pd.read_csv(over20_white_women)df_over20_bm = pd.read_csv(over20_black_men)df_over20_bw = pd.read_csv(over20_black_women)df_over20_hm = pd.read_csv(over20_hispanic_men)df_over20_hw = pd.read_csv(over20_hispanic_women) def prepare(dfs, datefrom): result=[] for item in dfs: item.columns = ['date','rate','category'] item = item[item['date']>= datefrom] result.append(item) return result dfs = [df_over20, df_over20_wm, df_over20_ww, df_over20_bm, df_over20_bw, df_over20_hm, df_over20_hw]datefrom='2017-01-01'categories = ['Average', 'White men', 'White women', 'Black men', 'Black women','Hispanic men', 'Hispanic women'] i=0while i < len(categories): dfs[i].loc[:,'category'] = categories[i] i = i+1 df=prepare(dfs, datefrom) df = pd.concat(df, ignore_index=True)display(df) We import necessary libraries, Pandas and Plotly.express. We create variables for each data using Github URLs. We read all comma-separated values files (csv files) using read_csv. We create a function called prepare. This function takes two parameters, dfs a list of DataFrames and datefrom a string of a date. We create an empty list result. We iterate through the list of DataFrames to rename columns, filter date field using datefrom variable, and append each DataFrame to result. We define a variable dfs using all DataFrames, datefrom and categories. We add a new column using dfs and categories. We use prepare function dfs and datefrom as arguments. We combine all DataFrames using concat, with the ignore_index=True parameter. Each DataFrame has its own index and this allows us to ignore them and label index from 0, ..., n-1. The output of the df has the following structure. The plotly.express module is plotly’s high-level API for rapid figure generation. fig = px.bar(df, x="category", y="rate", color="category", animation_frame="date", animation_group="category", range_y=[0,20])fig.update_layout( height=600, title_text='Over 20 Unemployment Rate in USA from'+datefrom+' to May 2020')fig.show() Every Plotly Express function returns a graph_objects.Figure object, and we instantiate it using plotly.express.bar. We set parameter, x, y, color, etc. We use update_layout to set height and title, then display the animated bar chart. The unemployment of Black or African American Men and Women is consistently around double rate and during some periods they are more than twice than White Men and Women. We see the sudden spikes for all data sets at the end but the difference of rates becomes smaller. This chart below shows the unemployment rate from 1972–01–01 to 2020–05–01. We select five DataFrames and we change the datefrom value. If you want to create a line chart animation, please see this post. df = pd.concat([df_over20, df_over20_wm, df_over20_ww, df_over20_bm, df_over20_bw], ignore_index=True)datefrom='1972-01-01'fig = px.line(df, x="date", y="rate", color="category",range_x=[datefrom,'2020-07-30'])# fig.update_layout(hovermode='x unified')fig.update_layout( height=600, title_text='Over 20 Unemployment Rate in USA from'+datefrom+' to May 2020')fig.show() An animated bar chart is an excellent tool to show a dramatic unemployment rate change due to COVID-19. Pandas and Python make it easy to combine and modify the original data. In the near future, I’d like to review this post to see how the rate of unemployment changes for different groups. Get full access to every story on Medium by becoming a member.
[ { "code": null, "e": 142, "s": 47, "text": "Table of ContentsIntroduction1. Data preparation2. Animated Bar Chart3. A line chartConclusion" }, { "code": null, "e": 271, "s": 142, "text": "Every news outlet writes about economic hardships due to COVID-19. The fallout has disproportionally affected black communities." }, { "code": null, "e": 571, "s": 271, "text": "The Federal Reserve Bank of St. Louis (FRED) updated its unemployment rate data. The observation range varies by data sets, but the latest data is from May 2020. We’re going to visualize how the unemployment rate changed by race and gender over the year using a Plotly animated bar chart on Jupyter." }, { "code": null, "e": 674, "s": 571, "text": "This article assumes you are already familiar with the basic operation in JupyterLab/Jupyter Notebook." }, { "code": null, "e": 694, "s": 674, "text": "Plotly installation" }, { "code": null, "e": 732, "s": 694, "text": "plotly.py may be installed using pip." }, { "code": null, "e": 760, "s": 732, "text": "$ pip install plotly==4.8.1" }, { "code": null, "e": 777, "s": 760, "text": "for Conda users:" }, { "code": null, "e": 816, "s": 777, "text": "$ conda install -c plotly plotly=4.8.1" }, { "code": null, "e": 849, "s": 816, "text": "JupyterLab Support (Python 3.5+)" }, { "code": null, "e": 860, "s": 849, "text": "Using pip:" }, { "code": null, "e": 903, "s": 860, "text": "$ pip install jupyterlab \"ipywidgets>=7.5\"" }, { "code": null, "e": 920, "s": 903, "text": "for Conda users:" }, { "code": null, "e": 964, "s": 920, "text": "$ conda install jupyterlab \"ipywidgets=7.5\"" }, { "code": null, "e": 1014, "s": 964, "text": "Then run the following (you need node installed):" }, { "code": null, "e": 1224, "s": 1014, "text": "# JupyterLab renderer support $ jupyter labextension install [email protected] # OPTIONAL: Jupyter widgets extension $ jupyter labextension install @jupyter-widgets/jupyterlab-manager [email protected]" }, { "code": null, "e": 1247, "s": 1224, "text": "towardsdatascience.com" }, { "code": null, "e": 1270, "s": 1247, "text": "towardsdatascience.com" }, { "code": null, "e": 1293, "s": 1270, "text": "towardsdatascience.com" }, { "code": null, "e": 1659, "s": 1293, "text": "The above data are 20 Yrs. & Over (LNS14000024), 20 Yrs. & Over, White Men (LNS14000028), 20 Yrs. Over, White Women (LNS14000029), 20 Yrs. & Over, Black or African American Men (LNS14000031), 20 Yrs. & Over, Black or African American Women (LNS14000032)), 20 Yrs. & Over, Hispanic or Latino Men (LNS14000034), 20 Yrs. & Over, Hispanic or Latino Women (LNS14000032)." }, { "code": null, "e": 1832, "s": 1659, "text": "We’re going to concatenate all data sets, add a category column with appropriate names and filter by the date so that all data sets will have the same length as seen below." }, { "code": null, "e": 3890, "s": 1832, "text": "import pandas as pdimport plotly.express as px over20='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000024.csv'over20_white_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000028.csv'over20_white_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000029.csv'over20_black_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/7d63e7a7495dfb8578120016c7a7dd4edc04e20d/LNS14000031.csv'over20_black_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/d1db4261b76af67dd67c00a400e373c175eab428/LNS14000032.csv'over20_hispanic_men='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/f693c9bdd76875b12a14033cc54931da894bd341/LNU04000034.csv'over20_hispanic_women='https://gist.githubusercontent.com/shinokada/dfcdc538dedf136d4a58b9bcdcfc8f18/raw/f693c9bdd76875b12a14033cc54931da894bd341/LNU04000035.csv' df_over20 = pd.read_csv(over20)df_over20_wm = pd.read_csv(over20_white_men)df_over20_ww = pd.read_csv(over20_white_women)df_over20_bm = pd.read_csv(over20_black_men)df_over20_bw = pd.read_csv(over20_black_women)df_over20_hm = pd.read_csv(over20_hispanic_men)df_over20_hw = pd.read_csv(over20_hispanic_women) def prepare(dfs, datefrom): result=[] for item in dfs: item.columns = ['date','rate','category'] item = item[item['date']>= datefrom] result.append(item) return result dfs = [df_over20, df_over20_wm, df_over20_ww, df_over20_bm, df_over20_bw, df_over20_hm, df_over20_hw]datefrom='2017-01-01'categories = ['Average', 'White men', 'White women', 'Black men', 'Black women','Hispanic men', 'Hispanic women'] i=0while i < len(categories): dfs[i].loc[:,'category'] = categories[i] i = i+1 df=prepare(dfs, datefrom) df = pd.concat(df, ignore_index=True)display(df)" }, { "code": null, "e": 3948, "s": 3890, "text": "We import necessary libraries, Pandas and Plotly.express." }, { "code": null, "e": 4001, "s": 3948, "text": "We create variables for each data using Github URLs." }, { "code": null, "e": 4070, "s": 4001, "text": "We read all comma-separated values files (csv files) using read_csv." }, { "code": null, "e": 4201, "s": 4070, "text": "We create a function called prepare. This function takes two parameters, dfs a list of DataFrames and datefrom a string of a date." }, { "code": null, "e": 4374, "s": 4201, "text": "We create an empty list result. We iterate through the list of DataFrames to rename columns, filter date field using datefrom variable, and append each DataFrame to result." }, { "code": null, "e": 4446, "s": 4374, "text": "We define a variable dfs using all DataFrames, datefrom and categories." }, { "code": null, "e": 4492, "s": 4446, "text": "We add a new column using dfs and categories." }, { "code": null, "e": 4547, "s": 4492, "text": "We use prepare function dfs and datefrom as arguments." }, { "code": null, "e": 4776, "s": 4547, "text": "We combine all DataFrames using concat, with the ignore_index=True parameter. Each DataFrame has its own index and this allows us to ignore them and label index from 0, ..., n-1. The output of the df has the following structure." }, { "code": null, "e": 4858, "s": 4776, "text": "The plotly.express module is plotly’s high-level API for rapid figure generation." }, { "code": null, "e": 5112, "s": 4858, "text": "fig = px.bar(df, x=\"category\", y=\"rate\", color=\"category\", animation_frame=\"date\", animation_group=\"category\", range_y=[0,20])fig.update_layout( height=600, title_text='Over 20 Unemployment Rate in USA from'+datefrom+' to May 2020')fig.show()" }, { "code": null, "e": 5265, "s": 5112, "text": "Every Plotly Express function returns a graph_objects.Figure object, and we instantiate it using plotly.express.bar. We set parameter, x, y, color, etc." }, { "code": null, "e": 5348, "s": 5265, "text": "We use update_layout to set height and title, then display the animated bar chart." }, { "code": null, "e": 5617, "s": 5348, "text": "The unemployment of Black or African American Men and Women is consistently around double rate and during some periods they are more than twice than White Men and Women. We see the sudden spikes for all data sets at the end but the difference of rates becomes smaller." }, { "code": null, "e": 5821, "s": 5617, "text": "This chart below shows the unemployment rate from 1972–01–01 to 2020–05–01. We select five DataFrames and we change the datefrom value. If you want to create a line chart animation, please see this post." }, { "code": null, "e": 6196, "s": 5821, "text": "df = pd.concat([df_over20, df_over20_wm, df_over20_ww, df_over20_bm, df_over20_bw], ignore_index=True)datefrom='1972-01-01'fig = px.line(df, x=\"date\", y=\"rate\", color=\"category\",range_x=[datefrom,'2020-07-30'])# fig.update_layout(hovermode='x unified')fig.update_layout( height=600, title_text='Over 20 Unemployment Rate in USA from'+datefrom+' to May 2020')fig.show()" }, { "code": null, "e": 6372, "s": 6196, "text": "An animated bar chart is an excellent tool to show a dramatic unemployment rate change due to COVID-19. Pandas and Python make it easy to combine and modify the original data." }, { "code": null, "e": 6487, "s": 6372, "text": "In the near future, I’d like to review this post to see how the rate of unemployment changes for different groups." } ]
Pascal - Booleans
Pascal provides data type Boolean that enables the programmers to define, store and manipulate logical entities, such as constants, variables, functions and expressions, etc. Boolean values are basically integer type. Boolean type variables have two pre-defined possible values True and False. The expressions resolving to a Boolean value can also be assigned to a Boolean type. Free Pascal also supports the ByteBool, WordBool and LongBool types. These are of type Byte, Word or Longint, respectively. The value False is equivalent to 0 (zero) and any nonzero value is considered True when converting to a Boolean value. A Boolean value of True is converted to -1 in case it is assigned to a variable of type LongBool. It should be noted that logical operators and, or and not are defined for Boolean data types. A variable of Boolean type is declared using the var keyword. var boolean-identifier: boolean; for example, var choice: boolean; program exBoolean; var exit: boolean; choice: char; begin writeln('Do you want to continue? '); writeln('Enter Y/y for yes, and N/n for no'); readln(choice); if(choice = 'n') then exit := true else exit := false; if (exit) then writeln(' Good Bye!') else writeln('Please Continue'); readln; end. When the above code is compiled and executed, it produces the following result − Do you want to continue? Enter Y/y for yes, and N/n for no N Good Bye! Y Please Continue 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2258, "s": 2083, "text": "Pascal provides data type Boolean that enables the programmers to define, store and manipulate logical entities, such as constants, variables, functions and expressions, etc." }, { "code": null, "e": 2462, "s": 2258, "text": "Boolean values are basically integer type. Boolean type variables have two pre-defined possible values True and False. The expressions resolving to a Boolean value can also be assigned to a Boolean type." }, { "code": null, "e": 2586, "s": 2462, "text": "Free Pascal also supports the ByteBool, WordBool and LongBool types. These are of type Byte, Word or Longint, respectively." }, { "code": null, "e": 2804, "s": 2586, "text": "The value False is equivalent to 0 (zero) and any nonzero value is considered True when converting to a Boolean value. A Boolean value of True is converted to -1 in case it is assigned to a variable of type LongBool." }, { "code": null, "e": 2898, "s": 2804, "text": "It should be noted that logical operators and, or and not are defined for Boolean data types." }, { "code": null, "e": 2961, "s": 2898, "text": " A variable of Boolean type is declared using the var keyword." }, { "code": null, "e": 2994, "s": 2961, "text": "var\nboolean-identifier: boolean;" }, { "code": null, "e": 3007, "s": 2994, "text": "for example," }, { "code": null, "e": 3028, "s": 3007, "text": "var\nchoice: boolean;" }, { "code": null, "e": 3352, "s": 3028, "text": "program exBoolean;\nvar\nexit: boolean;\n\nchoice: char;\n begin\n writeln('Do you want to continue? ');\n writeln('Enter Y/y for yes, and N/n for no');\n readln(choice);\n\nif(choice = 'n') then\n exit := true\nelse\n exit := false;\n\nif (exit) then\n writeln(' Good Bye!')\nelse\n writeln('Please Continue');\n\nreadln;\nend." }, { "code": null, "e": 3433, "s": 3352, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3523, "s": 3433, "text": "Do you want to continue?\nEnter Y/y for yes, and N/n for no\nN\nGood Bye!\nY\nPlease Continue\n" }, { "code": null, "e": 3558, "s": 3523, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3581, "s": 3558, "text": " Stone River ELearning" }, { "code": null, "e": 3588, "s": 3581, "text": " Print" }, { "code": null, "e": 3599, "s": 3588, "text": " Add Notes" } ]
Ace the System Interview— Design a Chat Application | by Zixuan Zhang | Towards Data Science
Designing chat applications like Slack or Messenger has always been among the top questions asked by system design interviewers. Personally, I’ve run into this problem a few times by now. As new grads/junior SDEa, we are good at implementation, yet designing whole systems is a challenge of its own kind. In this article, I want to share with you my design of Slack, which is based on real-life interview feedbacks I received as well as discussions with senior engineers. First thing first, we must figure out the exact requirements of the target system. For Slack (or other apps you use), the following features can be expected: Direct messaging: two users can chat with each other Group chat: users can participate in group conversations Join/leave groups, (add/delete friends not important for Slack) Typing indicator: when typing, the recipient gets notified User status: whether you are online or offline When the user is offline, try send notifications to the user’s mobile device if a new message arrives. Besides the above features, the system should obviously be scalable and highly available. Some interviewers I talked to didn’t like upfront back-of-the-envelope estimation because the statistics are arbitrarily picked and the exact number doesn’t mean much. To some extent, they are right. However, we do need some rough numbers to help us make critical decisions: We expect millions of daily active users(DAU) from all over the world. On average each message is around a few hundred characters. Each person sends out a few hundred messages per day. Some groups have a handful of people, some others have hundreds of members Based on the numbers above, we can make the following conclusions: it is safe to say that we need a globally distributed system (to serve users in different regions). Users will be connected to different servers. The backend database should be horizontally scalable, as tons of messages (~100 GB) are saved each day. The system is write-heavy, as messages are written into DB but rarely read (most of them are delivered via the notification service and saved locally on the client. We shall see why later ) When it comes to database design, it is always a good idea to consider the access pattern of your application. Read Operations Given user A and user B, retrieve messages after a certain timestamp Given group G, retrieve all messages after a certain timestamp Given group G, find all member ID Given user A, find all groups he/she joined Write Operations Save a message between user A and user B Save a new message by user A in group G Add/delete user A to/from group G In our case, it is obvious that the database is used primarily as a key-value store. No complex relational ops such as join are needed. In addition to the access pattern, keep in mind that the database must be horizontally scalable and tuned for writes. In our case, we could use NoSQL databases such as Cassandra or sharded SQL such as Postgres (SQL is also very scalable if you don’t care about relations or foreign key constraints). In practice, many companies (e.g. Discord) use Cassandra because it scales up easily and is more suitable for write-heavy work (Cassandra uses LSTM rather than B+ Tree used by SQL). For a more detailed discussion, I refer you to this awesome post. Schema In Cassandra, records are sharded by the partition keys. On each node, records with the same partition key are sorted by the sort key. The chat tables are designed to best fit our access pattern. A key observation here is that the message ID is used to determine the ordering. The message Id is not globally unique, as its scope is determined by the partition key. The system will never retrieve an item by its message ID alone. However, auto-increment key generation is not well supported by distributed databases. We could use a dedicated key generation service such as Twitter’s Snowflake ID or simply use a precise timestamp as message ID (yes, clock skew can happen, but the message volume in a group/between two users may be small enough to ignore this with careful time synchronization) We need two tables to capture the relationship between users and groups. The Group Membership table is used for message broadcasting — we need to figure out who gets the message. The User Membership table is for listing all the groups a user has joined. We could use a single table with a secondary index, but the cardinality of group ID/user ID is too large for a secondary index. The two-table approach isn’t without problems either— if we mutate one, the other should be modified to maintain consistency, which requires distributed transactions. Finally, the user profile table. It keeps track of user-specific data such as profile picture location and other stuff. In a system design interview, it is always a good idea to lay down the API of the system upfront. It helps you formalize the features to implement and showcase your rigorous thinking. The requirements of our system can be broken down into the following RPC calls: send_message(user_id, receiver_id, channel_type, message)get_messages(user_id, user_id2, channel_type, earliest_message_id)join_group(user_id, group_id)leave_group(user_id, group_id)get_all_group(user_id)// ignore RPC for login/logout, ignore authentication token The channel_type field is used to distinguish private chats from group chats. The receiver_id /user_id2 can be a user ID or a group ID. The earliest_message_id is the latest message locally available on the client. It is used as the sort key to range query the chat tables. Finally, time for architecture design! By now we’ve laid down a solid foundation for the application — the database schema, the RPC calls. With all these in mind, we can proceed to write down the list of components in the system. Chat Service: each online user maintains a WebSocket connection with a WebSocket server in the Chat Service. Outgoing and incoming chat messages are exchanged here. Web Service: It handles all RPC calls except send_message(). Users talk to this service for authentication, join/leave groups, etc. No WebSocket is needed here since all calls are client-initiated and HTTP-based. Notification Service: When the user is offline, messages are pushed to external phone manufacturers’ notification servers (e.g. Apple’s ) Presence Service: When a user is typing or changes status, the Presence Service is responsible for figuring out who gets the push update. User Mapping Service: Our chat service is globally distributed. We need to keep track of the server ID of the user’s session host. Note that the ID generation service is left out in figure 5. Normal Message Delivery When the user sends out a message, it is delivered to a WebSocket server in the same region. The WebSocket server will write the message to the database and acknowledge the client. If the recipient is another user, her WebSocket service ID is obtained by calling the User Mapping Service. Once the message is forwarded to the appropriate server, the recipient will get the push message via WebSocket. Failed Message Delivery If for some reason the WebSocket is cut off and the user is unreachable, all messages will be redirected to the notification service for a best-effort delivery (no guarantee of delivery, since the user might not have an internet connection). History Catch-up Even with the duo message delivery system, it is possible that a message is never received by the client. Therefore, it is critical that all clients request the Gateway Service for the authoritative chat history upon reconnection/with fixed intervals. Group Chat When a user participates in a group chat, his message is broadcast to all group members. Given a group ID, the WebSocket server queries the database forward the messages to other servers. Presence Detection When a user is active in the app, applications like Slack will inform other users of your status. We can handle this signal as a special form of group chat. Instead of querying the database, the WebSocket server contacts the Presence Service who returns a list of contacts for broadcast. Since it is prohibitively expensive to inform everyone who has ever chatted with the user, the Presence Service runs some kind of algorithm (maybe based on chat frequency, latest exchange, ...) to keep the list short and precise. For less-frequent contacts, the status of a user can be obtained by polling the presence service instead of waiting for the push message. Typing Indication Logically there’s no difference between a typing indication message and a normal message. We can propagate the typing indication messages in the same way as private chat messages (figure 6). By now, we have established a clear architecture and concrete data flow that covers all functional requirements. However, there are so many things over which an interviewer can grill you. In this section, I want to talk about some interesting tradeoffs that interviewers might ask you. The first issue is how web socket servers communicate with each other (step 5 in figure 6). The easiest way is to use a separate, synchronous HTTP call for each message. However, two issues arise: No message ordering: If two messages are sent in sequence, it is possible that the first one arrives super late. It will seem to the user that an unread message pops out above the latest message you just read, which is very confusing.Large number of request per second: If each message is sent with a separate HTTP call, then the ingress traffic could overwhelm web socket Servers. No message ordering: If two messages are sent in sequence, it is possible that the first one arrives super late. It will seem to the user that an unread message pops out above the latest message you just read, which is very confusing. Large number of request per second: If each message is sent with a separate HTTP call, then the ingress traffic could overwhelm web socket Servers. One possible solution is using queues as middleware. Each server has a dedicated incoming queue, which serves as a buffer and imposes ordering on messages. Although it looks like that queue is a better solution, I would argue that it’s a devil of its own: For large-scale applications such as Slack, there are tens of thousands of web socket servers. Maintains and scales the middleware is expensive and a challenge itself. If the consumer (web socket server) is down, we don’t want the messages to accumulate in the queue since the users will reconnect to a different server and initiate history catch-up. Servers come and go all the time, it is laborous to create/purge queues with them. If the consumer rejoins, what should we do with the stale messages in the queue? What messages to discard and what to process? Here I propose a third approach that is based on synchronous HTTP calls: To solve the ordering issue, we can annotate every message with a prevMsgID field. The recipient checks his local log and initiates history catch-ups when an inconsistency is found. To reduce the number of messages exchanged between servers, we can implement some buffering algorithm on WebSocket servers — send accumulated messages, say, ~50 MS with randomized offsets (preventing everyone from sending messages at the same time). Right now the current design broadcasts all group messages regardless of group size. This approach does not work well if the group is very large. Theoretically, there are two ways to handle group chats — pushing and pulling: pushing: The message is broadcast to other web socket servers who then push it to the client pulling: the client sends a request to HTTP servers for the latest messages. The problem with pushing is that it converts one external request (one message) into many internal messages. This is called Write Amplification. If the group is large and active, pushing group messages will take up a tremendous amount of bandwidth. The problem with pulling is that one message is read over and over again by different clients (Read Amplification). Going along with this approach will surely overwhelm the database. My idea is that we can build a hybrid system with the above logic. For smaller groups or inactive groups, it is okay to do pushing since write amplification won’t stress out the servers. For very active and large groups, clients must query the HTTP server regularly for messages. When a message is received by a web socket server, it is persisted into the database. The simplest approach would be calling the database directly. With this implementation, the database is bombarded with ~100K RPS traffic, which demands tons of infrastructure. An alternative is using queues for batch insertion. When the queue service receives a write, the web socket server, in turn, acknowledges the client. At the other end of the queue, a dedicated batch writer can group hundreds of messages into a single request, thus reducing the RPS significantly. However, using queues such as Kafka does introduce delays between server ACK and the actual write. If a client queries the HTTP server immediately after receiving ACK from the web socket server, it is possible the message is not written yet. With middleware, it is hard to offer read-after-write consistency that might be important for certain applications. In this article, we came up with a high-level architecture for Slack, defined system APIs as well as database schema. In addition, we explored many important tradeoffs when the system is examined more closely. In a system design interview, there’s no such thing as a perfect answer. All solutions have flaws, our job is to evaluate each of them and pick the simplest one that meets all the requirements.
[ { "code": null, "e": 644, "s": 172, "text": "Designing chat applications like Slack or Messenger has always been among the top questions asked by system design interviewers. Personally, I’ve run into this problem a few times by now. As new grads/junior SDEa, we are good at implementation, yet designing whole systems is a challenge of its own kind. In this article, I want to share with you my design of Slack, which is based on real-life interview feedbacks I received as well as discussions with senior engineers." }, { "code": null, "e": 802, "s": 644, "text": "First thing first, we must figure out the exact requirements of the target system. For Slack (or other apps you use), the following features can be expected:" }, { "code": null, "e": 855, "s": 802, "text": "Direct messaging: two users can chat with each other" }, { "code": null, "e": 912, "s": 855, "text": "Group chat: users can participate in group conversations" }, { "code": null, "e": 976, "s": 912, "text": "Join/leave groups, (add/delete friends not important for Slack)" }, { "code": null, "e": 1035, "s": 976, "text": "Typing indicator: when typing, the recipient gets notified" }, { "code": null, "e": 1082, "s": 1035, "text": "User status: whether you are online or offline" }, { "code": null, "e": 1185, "s": 1082, "text": "When the user is offline, try send notifications to the user’s mobile device if a new message arrives." }, { "code": null, "e": 1275, "s": 1185, "text": "Besides the above features, the system should obviously be scalable and highly available." }, { "code": null, "e": 1550, "s": 1275, "text": "Some interviewers I talked to didn’t like upfront back-of-the-envelope estimation because the statistics are arbitrarily picked and the exact number doesn’t mean much. To some extent, they are right. However, we do need some rough numbers to help us make critical decisions:" }, { "code": null, "e": 1621, "s": 1550, "text": "We expect millions of daily active users(DAU) from all over the world." }, { "code": null, "e": 1735, "s": 1621, "text": "On average each message is around a few hundred characters. Each person sends out a few hundred messages per day." }, { "code": null, "e": 1810, "s": 1735, "text": "Some groups have a handful of people, some others have hundreds of members" }, { "code": null, "e": 1877, "s": 1810, "text": "Based on the numbers above, we can make the following conclusions:" }, { "code": null, "e": 2023, "s": 1877, "text": "it is safe to say that we need a globally distributed system (to serve users in different regions). Users will be connected to different servers." }, { "code": null, "e": 2127, "s": 2023, "text": "The backend database should be horizontally scalable, as tons of messages (~100 GB) are saved each day." }, { "code": null, "e": 2317, "s": 2127, "text": "The system is write-heavy, as messages are written into DB but rarely read (most of them are delivered via the notification service and saved locally on the client. We shall see why later )" }, { "code": null, "e": 2428, "s": 2317, "text": "When it comes to database design, it is always a good idea to consider the access pattern of your application." }, { "code": null, "e": 2444, "s": 2428, "text": "Read Operations" }, { "code": null, "e": 2513, "s": 2444, "text": "Given user A and user B, retrieve messages after a certain timestamp" }, { "code": null, "e": 2576, "s": 2513, "text": "Given group G, retrieve all messages after a certain timestamp" }, { "code": null, "e": 2610, "s": 2576, "text": "Given group G, find all member ID" }, { "code": null, "e": 2654, "s": 2610, "text": "Given user A, find all groups he/she joined" }, { "code": null, "e": 2671, "s": 2654, "text": "Write Operations" }, { "code": null, "e": 2712, "s": 2671, "text": "Save a message between user A and user B" }, { "code": null, "e": 2752, "s": 2712, "text": "Save a new message by user A in group G" }, { "code": null, "e": 2786, "s": 2752, "text": "Add/delete user A to/from group G" }, { "code": null, "e": 3040, "s": 2786, "text": "In our case, it is obvious that the database is used primarily as a key-value store. No complex relational ops such as join are needed. In addition to the access pattern, keep in mind that the database must be horizontally scalable and tuned for writes." }, { "code": null, "e": 3470, "s": 3040, "text": "In our case, we could use NoSQL databases such as Cassandra or sharded SQL such as Postgres (SQL is also very scalable if you don’t care about relations or foreign key constraints). In practice, many companies (e.g. Discord) use Cassandra because it scales up easily and is more suitable for write-heavy work (Cassandra uses LSTM rather than B+ Tree used by SQL). For a more detailed discussion, I refer you to this awesome post." }, { "code": null, "e": 3477, "s": 3470, "text": "Schema" }, { "code": null, "e": 3673, "s": 3477, "text": "In Cassandra, records are sharded by the partition keys. On each node, records with the same partition key are sorted by the sort key. The chat tables are designed to best fit our access pattern." }, { "code": null, "e": 3906, "s": 3673, "text": "A key observation here is that the message ID is used to determine the ordering. The message Id is not globally unique, as its scope is determined by the partition key. The system will never retrieve an item by its message ID alone." }, { "code": null, "e": 4271, "s": 3906, "text": "However, auto-increment key generation is not well supported by distributed databases. We could use a dedicated key generation service such as Twitter’s Snowflake ID or simply use a precise timestamp as message ID (yes, clock skew can happen, but the message volume in a group/between two users may be small enough to ignore this with careful time synchronization)" }, { "code": null, "e": 4820, "s": 4271, "text": "We need two tables to capture the relationship between users and groups. The Group Membership table is used for message broadcasting — we need to figure out who gets the message. The User Membership table is for listing all the groups a user has joined. We could use a single table with a secondary index, but the cardinality of group ID/user ID is too large for a secondary index. The two-table approach isn’t without problems either— if we mutate one, the other should be modified to maintain consistency, which requires distributed transactions." }, { "code": null, "e": 4940, "s": 4820, "text": "Finally, the user profile table. It keeps track of user-specific data such as profile picture location and other stuff." }, { "code": null, "e": 5124, "s": 4940, "text": "In a system design interview, it is always a good idea to lay down the API of the system upfront. It helps you formalize the features to implement and showcase your rigorous thinking." }, { "code": null, "e": 5204, "s": 5124, "text": "The requirements of our system can be broken down into the following RPC calls:" }, { "code": null, "e": 5469, "s": 5204, "text": "send_message(user_id, receiver_id, channel_type, message)get_messages(user_id, user_id2, channel_type, earliest_message_id)join_group(user_id, group_id)leave_group(user_id, group_id)get_all_group(user_id)// ignore RPC for login/logout, ignore authentication token " }, { "code": null, "e": 5547, "s": 5469, "text": "The channel_type field is used to distinguish private chats from group chats." }, { "code": null, "e": 5605, "s": 5547, "text": "The receiver_id /user_id2 can be a user ID or a group ID." }, { "code": null, "e": 5743, "s": 5605, "text": "The earliest_message_id is the latest message locally available on the client. It is used as the sort key to range query the chat tables." }, { "code": null, "e": 5973, "s": 5743, "text": "Finally, time for architecture design! By now we’ve laid down a solid foundation for the application — the database schema, the RPC calls. With all these in mind, we can proceed to write down the list of components in the system." }, { "code": null, "e": 6138, "s": 5973, "text": "Chat Service: each online user maintains a WebSocket connection with a WebSocket server in the Chat Service. Outgoing and incoming chat messages are exchanged here." }, { "code": null, "e": 6351, "s": 6138, "text": "Web Service: It handles all RPC calls except send_message(). Users talk to this service for authentication, join/leave groups, etc. No WebSocket is needed here since all calls are client-initiated and HTTP-based." }, { "code": null, "e": 6489, "s": 6351, "text": "Notification Service: When the user is offline, messages are pushed to external phone manufacturers’ notification servers (e.g. Apple’s )" }, { "code": null, "e": 6627, "s": 6489, "text": "Presence Service: When a user is typing or changes status, the Presence Service is responsible for figuring out who gets the push update." }, { "code": null, "e": 6758, "s": 6627, "text": "User Mapping Service: Our chat service is globally distributed. We need to keep track of the server ID of the user’s session host." }, { "code": null, "e": 6819, "s": 6758, "text": "Note that the ID generation service is left out in figure 5." }, { "code": null, "e": 6843, "s": 6819, "text": "Normal Message Delivery" }, { "code": null, "e": 7244, "s": 6843, "text": "When the user sends out a message, it is delivered to a WebSocket server in the same region. The WebSocket server will write the message to the database and acknowledge the client. If the recipient is another user, her WebSocket service ID is obtained by calling the User Mapping Service. Once the message is forwarded to the appropriate server, the recipient will get the push message via WebSocket." }, { "code": null, "e": 7268, "s": 7244, "text": "Failed Message Delivery" }, { "code": null, "e": 7510, "s": 7268, "text": "If for some reason the WebSocket is cut off and the user is unreachable, all messages will be redirected to the notification service for a best-effort delivery (no guarantee of delivery, since the user might not have an internet connection)." }, { "code": null, "e": 7527, "s": 7510, "text": "History Catch-up" }, { "code": null, "e": 7779, "s": 7527, "text": "Even with the duo message delivery system, it is possible that a message is never received by the client. Therefore, it is critical that all clients request the Gateway Service for the authoritative chat history upon reconnection/with fixed intervals." }, { "code": null, "e": 7790, "s": 7779, "text": "Group Chat" }, { "code": null, "e": 7978, "s": 7790, "text": "When a user participates in a group chat, his message is broadcast to all group members. Given a group ID, the WebSocket server queries the database forward the messages to other servers." }, { "code": null, "e": 7997, "s": 7978, "text": "Presence Detection" }, { "code": null, "e": 8515, "s": 7997, "text": "When a user is active in the app, applications like Slack will inform other users of your status. We can handle this signal as a special form of group chat. Instead of querying the database, the WebSocket server contacts the Presence Service who returns a list of contacts for broadcast. Since it is prohibitively expensive to inform everyone who has ever chatted with the user, the Presence Service runs some kind of algorithm (maybe based on chat frequency, latest exchange, ...) to keep the list short and precise." }, { "code": null, "e": 8653, "s": 8515, "text": "For less-frequent contacts, the status of a user can be obtained by polling the presence service instead of waiting for the push message." }, { "code": null, "e": 8671, "s": 8653, "text": "Typing Indication" }, { "code": null, "e": 8862, "s": 8671, "text": "Logically there’s no difference between a typing indication message and a normal message. We can propagate the typing indication messages in the same way as private chat messages (figure 6)." }, { "code": null, "e": 9148, "s": 8862, "text": "By now, we have established a clear architecture and concrete data flow that covers all functional requirements. However, there are so many things over which an interviewer can grill you. In this section, I want to talk about some interesting tradeoffs that interviewers might ask you." }, { "code": null, "e": 9345, "s": 9148, "text": "The first issue is how web socket servers communicate with each other (step 5 in figure 6). The easiest way is to use a separate, synchronous HTTP call for each message. However, two issues arise:" }, { "code": null, "e": 9727, "s": 9345, "text": "No message ordering: If two messages are sent in sequence, it is possible that the first one arrives super late. It will seem to the user that an unread message pops out above the latest message you just read, which is very confusing.Large number of request per second: If each message is sent with a separate HTTP call, then the ingress traffic could overwhelm web socket Servers." }, { "code": null, "e": 9962, "s": 9727, "text": "No message ordering: If two messages are sent in sequence, it is possible that the first one arrives super late. It will seem to the user that an unread message pops out above the latest message you just read, which is very confusing." }, { "code": null, "e": 10110, "s": 9962, "text": "Large number of request per second: If each message is sent with a separate HTTP call, then the ingress traffic could overwhelm web socket Servers." }, { "code": null, "e": 10266, "s": 10110, "text": "One possible solution is using queues as middleware. Each server has a dedicated incoming queue, which serves as a buffer and imposes ordering on messages." }, { "code": null, "e": 10366, "s": 10266, "text": "Although it looks like that queue is a better solution, I would argue that it’s a devil of its own:" }, { "code": null, "e": 10534, "s": 10366, "text": "For large-scale applications such as Slack, there are tens of thousands of web socket servers. Maintains and scales the middleware is expensive and a challenge itself." }, { "code": null, "e": 10800, "s": 10534, "text": "If the consumer (web socket server) is down, we don’t want the messages to accumulate in the queue since the users will reconnect to a different server and initiate history catch-up. Servers come and go all the time, it is laborous to create/purge queues with them." }, { "code": null, "e": 10927, "s": 10800, "text": "If the consumer rejoins, what should we do with the stale messages in the queue? What messages to discard and what to process?" }, { "code": null, "e": 11000, "s": 10927, "text": "Here I propose a third approach that is based on synchronous HTTP calls:" }, { "code": null, "e": 11182, "s": 11000, "text": "To solve the ordering issue, we can annotate every message with a prevMsgID field. The recipient checks his local log and initiates history catch-ups when an inconsistency is found." }, { "code": null, "e": 11432, "s": 11182, "text": "To reduce the number of messages exchanged between servers, we can implement some buffering algorithm on WebSocket servers — send accumulated messages, say, ~50 MS with randomized offsets (preventing everyone from sending messages at the same time)." }, { "code": null, "e": 11657, "s": 11432, "text": "Right now the current design broadcasts all group messages regardless of group size. This approach does not work well if the group is very large. Theoretically, there are two ways to handle group chats — pushing and pulling:" }, { "code": null, "e": 11750, "s": 11657, "text": "pushing: The message is broadcast to other web socket servers who then push it to the client" }, { "code": null, "e": 11827, "s": 11750, "text": "pulling: the client sends a request to HTTP servers for the latest messages." }, { "code": null, "e": 12076, "s": 11827, "text": "The problem with pushing is that it converts one external request (one message) into many internal messages. This is called Write Amplification. If the group is large and active, pushing group messages will take up a tremendous amount of bandwidth." }, { "code": null, "e": 12259, "s": 12076, "text": "The problem with pulling is that one message is read over and over again by different clients (Read Amplification). Going along with this approach will surely overwhelm the database." }, { "code": null, "e": 12539, "s": 12259, "text": "My idea is that we can build a hybrid system with the above logic. For smaller groups or inactive groups, it is okay to do pushing since write amplification won’t stress out the servers. For very active and large groups, clients must query the HTTP server regularly for messages." }, { "code": null, "e": 12801, "s": 12539, "text": "When a message is received by a web socket server, it is persisted into the database. The simplest approach would be calling the database directly. With this implementation, the database is bombarded with ~100K RPS traffic, which demands tons of infrastructure." }, { "code": null, "e": 13098, "s": 12801, "text": "An alternative is using queues for batch insertion. When the queue service receives a write, the web socket server, in turn, acknowledges the client. At the other end of the queue, a dedicated batch writer can group hundreds of messages into a single request, thus reducing the RPS significantly." }, { "code": null, "e": 13456, "s": 13098, "text": "However, using queues such as Kafka does introduce delays between server ACK and the actual write. If a client queries the HTTP server immediately after receiving ACK from the web socket server, it is possible the message is not written yet. With middleware, it is hard to offer read-after-write consistency that might be important for certain applications." } ]
How to convert XML file into array in PHP?
To convert the XML document into PHP array, we have to utilize some PHP functions. The procedure is explained underneath with an example. We have to create an XML file that needs to convert into the array. abc.xml <?xml version='1.0'?> <userdb> <firstname name='Alex'> <symbol>AL</symbol> <code>A</code> </firstname> <firstname name='Sandra'> <symbol>SA</symbol> <code>S</code> </firstname> </userdb> The above XML file will import into PHP using file_get_contents() function which read the entire file as a string and stores into a variable. After the above step, we can easily convert the string into an object through the inbuilt functions simplexml_load_string() of PHP. After the above step, we can use json_encode() function to present the object in the json encoded string. The json_decode() function decode a JSON string. It converts a JSON encoded string into a PHP array. <?php // xml file path $path = "abc.xml"; $xmlfile = file_get_contents($path); $new = simplexml_load_string($xmlfile); $jsonfile = json_encode($new); $myarray = json_decode($jsonfile, true); print_r($myarray); ?>
[ { "code": null, "e": 1200, "s": 1062, "text": "To convert the XML document into PHP array, we have to utilize some PHP functions. The procedure is explained underneath with an example." }, { "code": null, "e": 1268, "s": 1200, "text": "We have to create an XML file that needs to convert into the array." }, { "code": null, "e": 1510, "s": 1268, "text": "abc.xml\n<?xml version='1.0'?>\n<userdb>\n <firstname name='Alex'>\n <symbol>AL</symbol>\n <code>A</code>\n </firstname>\n <firstname name='Sandra'>\n <symbol>SA</symbol>\n <code>S</code>\n </firstname>\n</userdb>\n\n" }, { "code": null, "e": 1652, "s": 1510, "text": "The above XML file will import into PHP using file_get_contents() function which read the entire file as a string and stores into a variable." }, { "code": null, "e": 1784, "s": 1652, "text": "After the above step, we can easily convert the string into an object through the inbuilt functions simplexml_load_string() of PHP." }, { "code": null, "e": 1890, "s": 1784, "text": "After the above step, we can use json_encode() function to present the object in the json encoded string." }, { "code": null, "e": 1991, "s": 1890, "text": "The json_decode() function decode a JSON string. It converts a JSON encoded string into a PHP array." }, { "code": null, "e": 2222, "s": 1991, "text": "<?php\n// xml file path\n $path = \"abc.xml\";\n $xmlfile = file_get_contents($path);\n $new = simplexml_load_string($xmlfile);\n $jsonfile = json_encode($new);\n $myarray = json_decode($jsonfile, true);\n print_r($myarray);\n?>" } ]
VB.Net - ProgressBar Control
It represents a Windows progress bar control. It is used to provide visual feedback to your users about the status of some task. It shows a bar that fills in from left to right as the operation progresses. Let's click on a ProgressBar control from the Toolbox and place it on the form. The main properties of a progress bar are Value, Maximum and Minimum. The Minimum and Maximum properties are used to set the minimum and maximum values that the progress bar can display. The Value property specifies the current position of the progress bar. The ProgressBar control is typically used when an application performs tasks such as copying files or printing documents. To a user the application might look unresponsive if there is no visual cue. In such cases, using the ProgressBar allows the programmer to provide a visual status of progress. The following are some of the commonly used properties of the ProgressBar control − AllowDrop Overrides Control.AllowDrop. BackgroundImage Gets or sets the background image for the ProgressBar control. BackgroundImageLayout Gets or sets the layout of the background image of the progress bar. CausesValidation Gets or sets a value indicating whether the control, when it receives focus, causes validation to be performed on any controls that require validation. Font Gets or sets the font of text in the ProgressBar. ImeMode Gets or sets the input method editor (IME) for the ProgressBar. ImeModeBase Gets or sets the IME mode of a control. MarqueeAnimationSpeed Gets or sets the time period, in milliseconds, that it takes the progress block to scroll across the progress bar. Maximum Gets or sets the maximum value of the range of the control.v Minimum Gets or sets the minimum value of the range of the control. Padding Gets or sets the space between the edges of a ProgressBar control and its contents. RightToLeftLayout Gets or sets a value indicating whether the ProgressBar and any text it contains is displayed from right to left. Step Gets or sets the amount by which a call to the PerformStep method increases the current position of the progress bar. Style Gets or sets the manner in which progress should be indicated on the progress bar. Value Gets or sets the current position of the progress bar.v The following are some of the commonly used methods of the ProgressBar control − Increment Increments the current position of the ProgressBar control by specified amount. PerformStep Increments the value by the specified step. ResetText Resets the Text property to its default value. ToString Returns a string that represents the progress bar control. The following are some of the commonly used events of the ProgressBar control − BackgroundImageChanged Occurs when the value of the BackgroundImage property changes. BackgroundImageLayoutChanged Occurs when the value of the BackgroundImageLayout property changes. CausesValidationChanged Occurs when the value of the CausesValidation property changes. Click Occurs when the control is clicked. DoubleClick Occurs when the user double-clicks the control. Enter Occurs when focus enters the control. FontChanged Occurs when the value of the Font property changes. ImeModeChanged Occurs when the value of the ImeMode property changes. KeyDown Occurs when the user presses a key while the control has focus. KeyPress Occurs when the user presses a key while the control has focus. KeyUp Occurs when the user releases a key while the control has focus. Leave Occurs when focus leaves the ProgressBar control. MouseClick Occurs when the control is clicked by the mouse. MouseDoubleClick Occurs when the user double-clicks the control. PaddingChanged Occurs when the value of the Padding property changes. Paint Occurs when the ProgressBar is drawn. RightToLeftLayoutChanged Occurs when the RightToLeftLayout property changes. TabStopChanged Occurs when the TabStop property changes. TextChanged Occurs when the Text property changes. In this example, let us create a progress bar at runtime. Let's double click on the Form and put the follow code in the opened window. Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) _ Handles MyBase.Load 'create two progress bars Dim ProgressBar1 As ProgressBar Dim ProgressBar2 As ProgressBar ProgressBar1 = New ProgressBar() ProgressBar2 = New ProgressBar() 'set position ProgressBar1.Location = New Point(10, 10) ProgressBar2.Location = New Point(10, 50) 'set values ProgressBar1.Minimum = 0 ProgressBar1.Maximum = 200 ProgressBar1.Value = 130 ProgressBar2.Minimum = 0 ProgressBar2.Maximum = 100 ProgressBar2.Value = 40 'add the progress bar to the form Me.Controls.Add(ProgressBar1) Me.Controls.Add(ProgressBar2) ' Set the caption bar text of the form. Me.Text = "tutorialspoint.com" End Sub End Class When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window − 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2506, "s": 2300, "text": "It represents a Windows progress bar control. It is used to provide visual feedback to your users about the status of some task. It shows a bar that fills in from left to right as the operation progresses." }, { "code": null, "e": 2586, "s": 2506, "text": "Let's click on a ProgressBar control from the Toolbox and place it on the form." }, { "code": null, "e": 2844, "s": 2586, "text": "The main properties of a progress bar are Value, Maximum and Minimum. The Minimum and Maximum properties are used to set the minimum and maximum values that the progress bar can display. The Value property specifies the current position of the progress bar." }, { "code": null, "e": 3142, "s": 2844, "text": "The ProgressBar control is typically used when an application performs tasks such as copying files or printing documents. To a user the application might look unresponsive if there is no visual cue. In such cases, using the ProgressBar allows the programmer to provide a visual status of progress." }, { "code": null, "e": 3226, "s": 3142, "text": "The following are some of the commonly used properties of the ProgressBar control −" }, { "code": null, "e": 3236, "s": 3226, "text": "AllowDrop" }, { "code": null, "e": 3265, "s": 3236, "text": "Overrides Control.AllowDrop." }, { "code": null, "e": 3281, "s": 3265, "text": "BackgroundImage" }, { "code": null, "e": 3344, "s": 3281, "text": "Gets or sets the background image for the ProgressBar control." }, { "code": null, "e": 3366, "s": 3344, "text": "BackgroundImageLayout" }, { "code": null, "e": 3435, "s": 3366, "text": "Gets or sets the layout of the background image of the progress bar." }, { "code": null, "e": 3452, "s": 3435, "text": "CausesValidation" }, { "code": null, "e": 3604, "s": 3452, "text": "Gets or sets a value indicating whether the control, when it receives focus, causes validation to be performed on any controls that require validation." }, { "code": null, "e": 3609, "s": 3604, "text": "Font" }, { "code": null, "e": 3659, "s": 3609, "text": "Gets or sets the font of text in the ProgressBar." }, { "code": null, "e": 3667, "s": 3659, "text": "ImeMode" }, { "code": null, "e": 3731, "s": 3667, "text": "Gets or sets the input method editor (IME) for the ProgressBar." }, { "code": null, "e": 3743, "s": 3731, "text": "ImeModeBase" }, { "code": null, "e": 3783, "s": 3743, "text": "Gets or sets the IME mode of a control." }, { "code": null, "e": 3805, "s": 3783, "text": "MarqueeAnimationSpeed" }, { "code": null, "e": 3920, "s": 3805, "text": "Gets or sets the time period, in milliseconds, that it takes the progress block to scroll across the progress bar." }, { "code": null, "e": 3928, "s": 3920, "text": "Maximum" }, { "code": null, "e": 3989, "s": 3928, "text": "Gets or sets the maximum value of the range of the control.v" }, { "code": null, "e": 3997, "s": 3989, "text": "Minimum" }, { "code": null, "e": 4057, "s": 3997, "text": "Gets or sets the minimum value of the range of the control." }, { "code": null, "e": 4066, "s": 4057, "text": "Padding " }, { "code": null, "e": 4151, "s": 4066, "text": "Gets or sets the space between the edges of a ProgressBar control and its contents. " }, { "code": null, "e": 4170, "s": 4151, "text": "RightToLeftLayout " }, { "code": null, "e": 4284, "s": 4170, "text": "Gets or sets a value indicating whether the ProgressBar and any text it contains is displayed from right to left." }, { "code": null, "e": 4290, "s": 4284, "text": "Step " }, { "code": null, "e": 4408, "s": 4290, "text": "Gets or sets the amount by which a call to the PerformStep method increases the current position of the progress bar." }, { "code": null, "e": 4415, "s": 4408, "text": "Style " }, { "code": null, "e": 4498, "s": 4415, "text": "Gets or sets the manner in which progress should be indicated on the progress bar." }, { "code": null, "e": 4504, "s": 4498, "text": "Value" }, { "code": null, "e": 4560, "s": 4504, "text": "Gets or sets the current position of the progress bar.v" }, { "code": null, "e": 4641, "s": 4560, "text": "The following are some of the commonly used methods of the ProgressBar control −" }, { "code": null, "e": 4652, "s": 4641, "text": "Increment " }, { "code": null, "e": 4733, "s": 4652, "text": "Increments the current position of the ProgressBar control by specified amount." }, { "code": null, "e": 4745, "s": 4733, "text": "PerformStep" }, { "code": null, "e": 4789, "s": 4745, "text": "Increments the value by the specified step." }, { "code": null, "e": 4799, "s": 4789, "text": "ResetText" }, { "code": null, "e": 4846, "s": 4799, "text": "Resets the Text property to its default value." }, { "code": null, "e": 4855, "s": 4846, "text": "ToString" }, { "code": null, "e": 4914, "s": 4855, "text": "Returns a string that represents the progress bar control." }, { "code": null, "e": 4994, "s": 4914, "text": "The following are some of the commonly used events of the ProgressBar control −" }, { "code": null, "e": 5017, "s": 4994, "text": "BackgroundImageChanged" }, { "code": null, "e": 5080, "s": 5017, "text": "Occurs when the value of the BackgroundImage property changes." }, { "code": null, "e": 5109, "s": 5080, "text": "BackgroundImageLayoutChanged" }, { "code": null, "e": 5178, "s": 5109, "text": "Occurs when the value of the BackgroundImageLayout property changes." }, { "code": null, "e": 5202, "s": 5178, "text": "CausesValidationChanged" }, { "code": null, "e": 5266, "s": 5202, "text": "Occurs when the value of the CausesValidation property changes." }, { "code": null, "e": 5272, "s": 5266, "text": "Click" }, { "code": null, "e": 5308, "s": 5272, "text": "Occurs when the control is clicked." }, { "code": null, "e": 5320, "s": 5308, "text": "DoubleClick" }, { "code": null, "e": 5368, "s": 5320, "text": "Occurs when the user double-clicks the control." }, { "code": null, "e": 5374, "s": 5368, "text": "Enter" }, { "code": null, "e": 5412, "s": 5374, "text": "Occurs when focus enters the control." }, { "code": null, "e": 5424, "s": 5412, "text": "FontChanged" }, { "code": null, "e": 5476, "s": 5424, "text": "Occurs when the value of the Font property changes." }, { "code": null, "e": 5491, "s": 5476, "text": "ImeModeChanged" }, { "code": null, "e": 5546, "s": 5491, "text": "Occurs when the value of the ImeMode property changes." }, { "code": null, "e": 5554, "s": 5546, "text": "KeyDown" }, { "code": null, "e": 5618, "s": 5554, "text": "Occurs when the user presses a key while the control has focus." }, { "code": null, "e": 5627, "s": 5618, "text": "KeyPress" }, { "code": null, "e": 5691, "s": 5627, "text": "Occurs when the user presses a key while the control has focus." }, { "code": null, "e": 5697, "s": 5691, "text": "KeyUp" }, { "code": null, "e": 5762, "s": 5697, "text": "Occurs when the user releases a key while the control has focus." }, { "code": null, "e": 5768, "s": 5762, "text": "Leave" }, { "code": null, "e": 5818, "s": 5768, "text": "Occurs when focus leaves the ProgressBar control." }, { "code": null, "e": 5829, "s": 5818, "text": "MouseClick" }, { "code": null, "e": 5878, "s": 5829, "text": "Occurs when the control is clicked by the mouse." }, { "code": null, "e": 5895, "s": 5878, "text": "MouseDoubleClick" }, { "code": null, "e": 5943, "s": 5895, "text": "Occurs when the user double-clicks the control." }, { "code": null, "e": 5958, "s": 5943, "text": "PaddingChanged" }, { "code": null, "e": 6013, "s": 5958, "text": "Occurs when the value of the Padding property changes." }, { "code": null, "e": 6019, "s": 6013, "text": "Paint" }, { "code": null, "e": 6057, "s": 6019, "text": "Occurs when the ProgressBar is drawn." }, { "code": null, "e": 6082, "s": 6057, "text": "RightToLeftLayoutChanged" }, { "code": null, "e": 6134, "s": 6082, "text": "Occurs when the RightToLeftLayout property changes." }, { "code": null, "e": 6149, "s": 6134, "text": "TabStopChanged" }, { "code": null, "e": 6191, "s": 6149, "text": "Occurs when the TabStop property changes." }, { "code": null, "e": 6203, "s": 6191, "text": "TextChanged" }, { "code": null, "e": 6242, "s": 6203, "text": "Occurs when the Text property changes." }, { "code": null, "e": 6377, "s": 6242, "text": "In this example, let us create a progress bar at runtime. Let's double click on the Form and put the follow code in the opened window." }, { "code": null, "e": 7211, "s": 6377, "text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) _\n Handles MyBase.Load\n 'create two progress bars\n Dim ProgressBar1 As ProgressBar\n Dim ProgressBar2 As ProgressBar\n ProgressBar1 = New ProgressBar()\n ProgressBar2 = New ProgressBar()\n 'set position\n ProgressBar1.Location = New Point(10, 10)\n ProgressBar2.Location = New Point(10, 50)\n 'set values\n ProgressBar1.Minimum = 0\n ProgressBar1.Maximum = 200\n ProgressBar1.Value = 130\n ProgressBar2.Minimum = 0\n ProgressBar2.Maximum = 100\n ProgressBar2.Value = 40\n 'add the progress bar to the form\n Me.Controls.Add(ProgressBar1)\n Me.Controls.Add(ProgressBar2)\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspoint.com\"\n End Sub\nEnd Class" }, { "code": null, "e": 7357, "s": 7211, "text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −" }, { "code": null, "e": 7390, "s": 7357, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 7407, "s": 7390, "text": " Frahaan Hussain" }, { "code": null, "e": 7442, "s": 7407, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 7457, "s": 7442, "text": " Arnold Higuit" }, { "code": null, "e": 7492, "s": 7457, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 7507, "s": 7492, "text": " Arnold Higuit" }, { "code": null, "e": 7540, "s": 7507, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 7555, "s": 7540, "text": " Arnold Higuit" }, { "code": null, "e": 7562, "s": 7555, "text": " Print" }, { "code": null, "e": 7573, "s": 7562, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML attribute quotes
[]
Find the length of a set in Python - GeeksforGeeks
07 Jan, 2022 In Python, a Set is a collection data type that is unordered and mutable. A set cannot have duplicate elements. Here, the task is to find out the number of elements present in a set. See the below examples. Examples: Input: a = {1, 2, 3, 4, 5, 6} Output: 6 Input: a = {'Geeks', 'For'} Output: 2 The idea is use len() in Python Example 1: Python3 # Python program to find the length# of set set1 = set() # Adding element and tuple to the Set set1.add(8) set1.add(9) set1.add((6, 7)) print("The length of set is:", len(set1)) Output: The length of set is: 3 Example 2: Python3 n = len({1, 2, 3, 4, 5}) print("The length of set is:", n) Output: The length of set is: 5 How does len() work?len() works in O(1) time as the set is an object and has a member to store its size. Below is description of len() from Python docs. Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). sumitgumber28 python-set Python Python Programs python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24176, "s": 24148, "text": "\n07 Jan, 2022" }, { "code": null, "e": 24383, "s": 24176, "text": "In Python, a Set is a collection data type that is unordered and mutable. A set cannot have duplicate elements. Here, the task is to find out the number of elements present in a set. See the below examples." }, { "code": null, "e": 24393, "s": 24383, "text": "Examples:" }, { "code": null, "e": 24473, "s": 24393, "text": "Input: a = {1, 2, 3, 4, 5, 6}\nOutput: 6\n\nInput: a = {'Geeks', 'For'}\nOutput: 2\n" }, { "code": null, "e": 24505, "s": 24473, "text": "The idea is use len() in Python" }, { "code": null, "e": 24516, "s": 24505, "text": "Example 1:" }, { "code": null, "e": 24524, "s": 24516, "text": "Python3" }, { "code": "# Python program to find the length# of set set1 = set() # Adding element and tuple to the Set set1.add(8) set1.add(9) set1.add((6, 7)) print(\"The length of set is:\", len(set1))", "e": 24710, "s": 24524, "text": null }, { "code": null, "e": 24718, "s": 24710, "text": "Output:" }, { "code": null, "e": 24743, "s": 24718, "text": "The length of set is: 3\n" }, { "code": null, "e": 24754, "s": 24743, "text": "Example 2:" }, { "code": null, "e": 24762, "s": 24754, "text": "Python3" }, { "code": "n = len({1, 2, 3, 4, 5}) print(\"The length of set is:\", n)", "e": 24822, "s": 24762, "text": null }, { "code": null, "e": 24830, "s": 24822, "text": "Output:" }, { "code": null, "e": 24855, "s": 24830, "text": "The length of set is: 5\n" }, { "code": null, "e": 25008, "s": 24855, "text": "How does len() work?len() works in O(1) time as the set is an object and has a member to store its size. Below is description of len() from Python docs." }, { "code": null, "e": 25202, "s": 25008, "text": "Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set)." }, { "code": null, "e": 25216, "s": 25202, "text": "sumitgumber28" }, { "code": null, "e": 25227, "s": 25216, "text": "python-set" }, { "code": null, "e": 25234, "s": 25227, "text": "Python" }, { "code": null, "e": 25250, "s": 25234, "text": "Python Programs" }, { "code": null, "e": 25261, "s": 25250, "text": "python-set" }, { "code": null, "e": 25359, "s": 25261, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25381, "s": 25359, "text": "Enumerate() in Python" }, { "code": null, "e": 25413, "s": 25381, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25443, "s": 25413, "text": "Iterate over a list in Python" }, { "code": null, "e": 25485, "s": 25443, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25511, "s": 25485, "text": "Python String | replace()" }, { "code": null, "e": 25533, "s": 25511, "text": "Defaultdict in Python" }, { "code": null, "e": 25579, "s": 25533, "text": "Python | Split string into list of characters" }, { "code": null, "e": 25618, "s": 25579, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25656, "s": 25618, "text": "Python | Convert a list to dictionary" } ]
Limitations of ARIMA: Dealing with Outliers | by Michael Grogan | Towards Data Science
ARIMA models can be quite adept when it comes to modelling the overall trend of a series along with seasonal patterns. In a previous article titled SARIMA: Forecasting Seasonal Data with Python and R, the use of an ARIMA model for forecasting maximum air temperature values for Dublin, Ireland was used. The results showed significant accuracy, with 70% of the predictions ranging within 10% of the actual temperature values. That said, the data that was being used for the previous example took temperature values that did not particularly show extreme values. For instance, the minimum temperature value was 4.8°C while the maximum temperature value was 28.7°C. Neither of these values lie outside the norm for typical yearly Irish weather. However, let’s consider a more extreme example. Braemar is a village located in the Scottish highlands in Aberdeenshire, and is known as one of the coldest places in the United Kingdom in winter. In January 1982, a low of -27.2°C was recorded at this location according to the UK Met Office — which deviates strongly from the average minimum temperature of -1.5°C that was recorded between 1981–2010. How would an ARIMA model perform when forecasting an abnormally cold winter for Braemar? An ARIMA model is built using monthly Met Office data from January 1959 — July 2020 (contains public sector information licensed under the Open Government Licence v1.0). The time series is defined: weatherarima <- ts(mydata$tmin[1:591], start = c(1959,1), frequency = 12)plot(weatherarima,type="l",ylab="Temperature")title("Minimum Recorded Monthly Temperature: Braemar, Scotland") Here is a plot of the monthly data: Here is an overview of the individual time series components: 80% of the dataset (the first 591 months of data) are used to build the ARIMA model. The latter 20% of time series data is then used as validation data to compare the accuracy of the predictions to the actual values. Using auto.arima, the p, d, and q coordinates of best fit are selected: # ARIMAfitweatherarima<-auto.arima(weatherarima, trace=TRUE, test="kpss", ic="bic")fitweatherarimaconfint(fitweatherarima)plot(weatherarima,type='l')title('Minimum Recorded Monthly Temperature: Braemar, Scotland') The best configuration is selected as follows: > # ARIMA> fitweatherarima<-auto.arima(weatherarima, trace=TRUE, test="kpss", ic="bic")Fitting models using approximations to speed things up...ARIMA(2,0,2)(1,1,1)[12] with drift : 2257.369 ARIMA(0,0,0)(0,1,0)[12] with drift : 2565.334 ARIMA(1,0,0)(1,1,0)[12] with drift : 2425.901 ARIMA(0,0,1)(0,1,1)[12] with drift : 2246.551 ARIMA(0,0,0)(0,1,0)[12] : 2558.978 ARIMA(0,0,1)(0,1,0)[12] with drift : 2558.621 ARIMA(0,0,1)(1,1,1)[12] with drift : 2242.724 ARIMA(0,0,1)(1,1,0)[12] with drift : 2427.871 ARIMA(0,0,1)(2,1,1)[12] with drift : 2259.357 ARIMA(0,0,1)(1,1,2)[12] with drift : Inf ARIMA(0,0,1)(0,1,2)[12] with drift : 2252.908 ARIMA(0,0,1)(2,1,0)[12] with drift : 2341.9 ARIMA(0,0,1)(2,1,2)[12] with drift : 2249.612 ARIMA(0,0,0)(1,1,1)[12] with drift : 2264.59 ARIMA(1,0,1)(1,1,1)[12] with drift : 2248.085 ARIMA(0,0,2)(1,1,1)[12] with drift : 2246.688 ARIMA(1,0,0)(1,1,1)[12] with drift : 2241.727 ARIMA(1,0,0)(0,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,1)[12] with drift : 2261.885 ARIMA(1,0,0)(1,1,2)[12] with drift : Inf ARIMA(1,0,0)(0,1,0)[12] with drift : 2556.722 ARIMA(1,0,0)(0,1,2)[12] with drift : Inf ARIMA(1,0,0)(2,1,0)[12] with drift : 2338.482 ARIMA(1,0,0)(2,1,2)[12] with drift : 2248.515 ARIMA(2,0,0)(1,1,1)[12] with drift : 2250.884 ARIMA(2,0,1)(1,1,1)[12] with drift : 2254.411 ARIMA(1,0,0)(1,1,1)[12] : 2237.953 ARIMA(1,0,0)(0,1,1)[12] : Inf ARIMA(1,0,0)(1,1,0)[12] : 2419.587 ARIMA(1,0,0)(2,1,1)[12] : 2256.396 ARIMA(1,0,0)(1,1,2)[12] : Inf ARIMA(1,0,0)(0,1,0)[12] : 2550.361 ARIMA(1,0,0)(0,1,2)[12] : Inf ARIMA(1,0,0)(2,1,0)[12] : 2332.136 ARIMA(1,0,0)(2,1,2)[12] : 2243.701 ARIMA(0,0,0)(1,1,1)[12] : 2262.382 ARIMA(2,0,0)(1,1,1)[12] : 2245.429 ARIMA(1,0,1)(1,1,1)[12] : 2244.31 ARIMA(0,0,1)(1,1,1)[12] : 2239.268 ARIMA(2,0,1)(1,1,1)[12] : 2249.168Now re-fitting the best model(s) without approximations...ARIMA(1,0,0)(1,1,1)[12] : Inf ARIMA(0,0,1)(1,1,1)[12] : Inf ARIMA(1,0,0)(1,1,1)[12] with drift : Inf ARIMA(0,0,1)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,2)[12] : Inf ARIMA(1,0,1)(1,1,1)[12] : Inf ARIMA(2,0,0)(1,1,1)[12] : Inf ARIMA(0,0,1)(0,1,1)[12] with drift : Inf ARIMA(0,0,2)(1,1,1)[12] with drift : Inf ARIMA(1,0,1)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,2)[12] with drift : Inf ARIMA(2,0,1)(1,1,1)[12] : Inf ARIMA(0,0,1)(2,1,2)[12] with drift : Inf ARIMA(2,0,0)(1,1,1)[12] with drift : Inf ARIMA(0,0,1)(0,1,2)[12] with drift : Inf ARIMA(2,0,1)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,1)[12] : Inf ARIMA(2,0,2)(1,1,1)[12] with drift : Inf ARIMA(0,0,1)(2,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,1)[12] with drift : Inf ARIMA(0,0,0)(1,1,1)[12] : Inf ARIMA(0,0,0)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,0)[12] : 2355.279Best model: ARIMA(1,0,0)(2,1,0)[12] The parameters of the model are as follows: > fitweatherarimaSeries: weatherarima ARIMA(1,0,0)(2,1,0)[12]Coefficients: ar1 sar1 sar2 0.2372 -0.6523 -0.3915s.e. 0.0411 0.0392 0.0393 Using the configured model ARIMA(1,0,0)(2,1,0)[12], the forecasted values are generated: forecastedvalues=forecast(fitweatherarima,h=148)forecastedvaluesplot(forecastedvalues) Here is a plot of the forecasts: Now, a data frame can be generated to compare the forecasted with actual values: df<-data.frame(mydata$tmin[592:739],forecastedvalues$mean)col_headings<-c("Actual Weather","Forecasted Weather")names(df)<-col_headingsattach(df) Additionally, using the Metrics library in R, the RMSE (root mean squared error) value can be calculated. > library(Metrics)> rmse(df$`Actual Weather`,df$`Forecasted Weather`)[1] 1.780472> mean(df$`Actual Weather`)[1] 2.876351> var(df$`Actual Weather`)[1] 17.15774 It is observed that with a mean temperature of 2.87°C, the recorded RMSE of 1.78 is significantly large when compared to the mean. Let’s investigate the more extreme values in the data further. We can see that when it comes to forecasting particularly extreme minimum temperatures (below -4°C for the sake of argument), we see that the ARIMA model significantly overestimates the value of the minimum temperature. In this regard, the size of the RMSE is just over 60% relative to the mean temperature of 2.87°C in the test set — for the reason that RMSE penalises larger errors more heavily. In this regard, it would seem that the ARIMA model is effective at capturing temperatures that are more in the normal range of values. However, the model falls short in predicting values at the more extreme ends of the scales — particularly for the winter months. That said, what if the lower end of the ARIMA forecast was used? df<-data.frame(mydata$tmin[592:739],forecastedvalues$lower)col_headings<-c("Actual Weather","Forecasted Weather")names(df)<-col_headingsattach(df) We see that while the model is performing better in forecasting the minimum values, the actual minimums still exceed that of the forecast. Moreover, this does not solve the problem as it means that the model will now significantly underestimate temperature values above the mean. As a result, the RMSE increases significantly: > library(Metrics)> rmse(df$`Actual Weather`,df$`Forecasted Weather`)[1] 3.907014> mean(df$`Actual Weather`)[1] 2.876351 In this regard, ARIMA models should be interpreted with caution. While they can be effective in capturing seasonality and the overall trend, they can fall short in forecasting values that fall significantly outside the norm. When it comes to forecasting such values, statistical tools such as Monte Carlo simulations can be more effective in modelling a potential range of more extreme values. Here is a follow-up article that discusses how extreme weather events can potentially be modelled using this method. In this example, we have seen that ARIMA can be limited in forecasting extreme values. While the model is adept at modelling seasonality and trends, outliers are difficult to forecast for ARIMA for the very reason that they lie outside of the general trend as captured by the model. Many thanks for reading, and you can find more of my data science content at michael-grogan.com. Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way. The findings and interpretations in this article are those of the author and are not endorsed by or affiliated with the UK Met Office in any way.
[ { "code": null, "e": 290, "s": 171, "text": "ARIMA models can be quite adept when it comes to modelling the overall trend of a series along with seasonal patterns." }, { "code": null, "e": 475, "s": 290, "text": "In a previous article titled SARIMA: Forecasting Seasonal Data with Python and R, the use of an ARIMA model for forecasting maximum air temperature values for Dublin, Ireland was used." }, { "code": null, "e": 597, "s": 475, "text": "The results showed significant accuracy, with 70% of the predictions ranging within 10% of the actual temperature values." }, { "code": null, "e": 914, "s": 597, "text": "That said, the data that was being used for the previous example took temperature values that did not particularly show extreme values. For instance, the minimum temperature value was 4.8°C while the maximum temperature value was 28.7°C. Neither of these values lie outside the norm for typical yearly Irish weather." }, { "code": null, "e": 962, "s": 914, "text": "However, let’s consider a more extreme example." }, { "code": null, "e": 1315, "s": 962, "text": "Braemar is a village located in the Scottish highlands in Aberdeenshire, and is known as one of the coldest places in the United Kingdom in winter. In January 1982, a low of -27.2°C was recorded at this location according to the UK Met Office — which deviates strongly from the average minimum temperature of -1.5°C that was recorded between 1981–2010." }, { "code": null, "e": 1404, "s": 1315, "text": "How would an ARIMA model perform when forecasting an abnormally cold winter for Braemar?" }, { "code": null, "e": 1574, "s": 1404, "text": "An ARIMA model is built using monthly Met Office data from January 1959 — July 2020 (contains public sector information licensed under the Open Government Licence v1.0)." }, { "code": null, "e": 1602, "s": 1574, "text": "The time series is defined:" }, { "code": null, "e": 1786, "s": 1602, "text": "weatherarima <- ts(mydata$tmin[1:591], start = c(1959,1), frequency = 12)plot(weatherarima,type=\"l\",ylab=\"Temperature\")title(\"Minimum Recorded Monthly Temperature: Braemar, Scotland\")" }, { "code": null, "e": 1822, "s": 1786, "text": "Here is a plot of the monthly data:" }, { "code": null, "e": 1884, "s": 1822, "text": "Here is an overview of the individual time series components:" }, { "code": null, "e": 2101, "s": 1884, "text": "80% of the dataset (the first 591 months of data) are used to build the ARIMA model. The latter 20% of time series data is then used as validation data to compare the accuracy of the predictions to the actual values." }, { "code": null, "e": 2173, "s": 2101, "text": "Using auto.arima, the p, d, and q coordinates of best fit are selected:" }, { "code": null, "e": 2387, "s": 2173, "text": "# ARIMAfitweatherarima<-auto.arima(weatherarima, trace=TRUE, test=\"kpss\", ic=\"bic\")fitweatherarimaconfint(fitweatherarima)plot(weatherarima,type='l')title('Minimum Recorded Monthly Temperature: Braemar, Scotland')" }, { "code": null, "e": 2434, "s": 2387, "text": "The best configuration is selected as follows:" }, { "code": null, "e": 5923, "s": 2434, "text": "> # ARIMA> fitweatherarima<-auto.arima(weatherarima, trace=TRUE, test=\"kpss\", ic=\"bic\")Fitting models using approximations to speed things up...ARIMA(2,0,2)(1,1,1)[12] with drift : 2257.369 ARIMA(0,0,0)(0,1,0)[12] with drift : 2565.334 ARIMA(1,0,0)(1,1,0)[12] with drift : 2425.901 ARIMA(0,0,1)(0,1,1)[12] with drift : 2246.551 ARIMA(0,0,0)(0,1,0)[12] : 2558.978 ARIMA(0,0,1)(0,1,0)[12] with drift : 2558.621 ARIMA(0,0,1)(1,1,1)[12] with drift : 2242.724 ARIMA(0,0,1)(1,1,0)[12] with drift : 2427.871 ARIMA(0,0,1)(2,1,1)[12] with drift : 2259.357 ARIMA(0,0,1)(1,1,2)[12] with drift : Inf ARIMA(0,0,1)(0,1,2)[12] with drift : 2252.908 ARIMA(0,0,1)(2,1,0)[12] with drift : 2341.9 ARIMA(0,0,1)(2,1,2)[12] with drift : 2249.612 ARIMA(0,0,0)(1,1,1)[12] with drift : 2264.59 ARIMA(1,0,1)(1,1,1)[12] with drift : 2248.085 ARIMA(0,0,2)(1,1,1)[12] with drift : 2246.688 ARIMA(1,0,0)(1,1,1)[12] with drift : 2241.727 ARIMA(1,0,0)(0,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,1)[12] with drift : 2261.885 ARIMA(1,0,0)(1,1,2)[12] with drift : Inf ARIMA(1,0,0)(0,1,0)[12] with drift : 2556.722 ARIMA(1,0,0)(0,1,2)[12] with drift : Inf ARIMA(1,0,0)(2,1,0)[12] with drift : 2338.482 ARIMA(1,0,0)(2,1,2)[12] with drift : 2248.515 ARIMA(2,0,0)(1,1,1)[12] with drift : 2250.884 ARIMA(2,0,1)(1,1,1)[12] with drift : 2254.411 ARIMA(1,0,0)(1,1,1)[12] : 2237.953 ARIMA(1,0,0)(0,1,1)[12] : Inf ARIMA(1,0,0)(1,1,0)[12] : 2419.587 ARIMA(1,0,0)(2,1,1)[12] : 2256.396 ARIMA(1,0,0)(1,1,2)[12] : Inf ARIMA(1,0,0)(0,1,0)[12] : 2550.361 ARIMA(1,0,0)(0,1,2)[12] : Inf ARIMA(1,0,0)(2,1,0)[12] : 2332.136 ARIMA(1,0,0)(2,1,2)[12] : 2243.701 ARIMA(0,0,0)(1,1,1)[12] : 2262.382 ARIMA(2,0,0)(1,1,1)[12] : 2245.429 ARIMA(1,0,1)(1,1,1)[12] : 2244.31 ARIMA(0,0,1)(1,1,1)[12] : 2239.268 ARIMA(2,0,1)(1,1,1)[12] : 2249.168Now re-fitting the best model(s) without approximations...ARIMA(1,0,0)(1,1,1)[12] : Inf ARIMA(0,0,1)(1,1,1)[12] : Inf ARIMA(1,0,0)(1,1,1)[12] with drift : Inf ARIMA(0,0,1)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,2)[12] : Inf ARIMA(1,0,1)(1,1,1)[12] : Inf ARIMA(2,0,0)(1,1,1)[12] : Inf ARIMA(0,0,1)(0,1,1)[12] with drift : Inf ARIMA(0,0,2)(1,1,1)[12] with drift : Inf ARIMA(1,0,1)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,2)[12] with drift : Inf ARIMA(2,0,1)(1,1,1)[12] : Inf ARIMA(0,0,1)(2,1,2)[12] with drift : Inf ARIMA(2,0,0)(1,1,1)[12] with drift : Inf ARIMA(0,0,1)(0,1,2)[12] with drift : Inf ARIMA(2,0,1)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,1)[12] : Inf ARIMA(2,0,2)(1,1,1)[12] with drift : Inf ARIMA(0,0,1)(2,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,1)[12] with drift : Inf ARIMA(0,0,0)(1,1,1)[12] : Inf ARIMA(0,0,0)(1,1,1)[12] with drift : Inf ARIMA(1,0,0)(2,1,0)[12] : 2355.279Best model: ARIMA(1,0,0)(2,1,0)[12]" }, { "code": null, "e": 5967, "s": 5923, "text": "The parameters of the model are as follows:" }, { "code": null, "e": 6132, "s": 5967, "text": "> fitweatherarimaSeries: weatherarima ARIMA(1,0,0)(2,1,0)[12]Coefficients: ar1 sar1 sar2 0.2372 -0.6523 -0.3915s.e. 0.0411 0.0392 0.0393" }, { "code": null, "e": 6221, "s": 6132, "text": "Using the configured model ARIMA(1,0,0)(2,1,0)[12], the forecasted values are generated:" }, { "code": null, "e": 6308, "s": 6221, "text": "forecastedvalues=forecast(fitweatherarima,h=148)forecastedvaluesplot(forecastedvalues)" }, { "code": null, "e": 6341, "s": 6308, "text": "Here is a plot of the forecasts:" }, { "code": null, "e": 6422, "s": 6341, "text": "Now, a data frame can be generated to compare the forecasted with actual values:" }, { "code": null, "e": 6568, "s": 6422, "text": "df<-data.frame(mydata$tmin[592:739],forecastedvalues$mean)col_headings<-c(\"Actual Weather\",\"Forecasted Weather\")names(df)<-col_headingsattach(df)" }, { "code": null, "e": 6674, "s": 6568, "text": "Additionally, using the Metrics library in R, the RMSE (root mean squared error) value can be calculated." }, { "code": null, "e": 6833, "s": 6674, "text": "> library(Metrics)> rmse(df$`Actual Weather`,df$`Forecasted Weather`)[1] 1.780472> mean(df$`Actual Weather`)[1] 2.876351> var(df$`Actual Weather`)[1] 17.15774" }, { "code": null, "e": 6964, "s": 6833, "text": "It is observed that with a mean temperature of 2.87°C, the recorded RMSE of 1.78 is significantly large when compared to the mean." }, { "code": null, "e": 7027, "s": 6964, "text": "Let’s investigate the more extreme values in the data further." }, { "code": null, "e": 7247, "s": 7027, "text": "We can see that when it comes to forecasting particularly extreme minimum temperatures (below -4°C for the sake of argument), we see that the ARIMA model significantly overestimates the value of the minimum temperature." }, { "code": null, "e": 7425, "s": 7247, "text": "In this regard, the size of the RMSE is just over 60% relative to the mean temperature of 2.87°C in the test set — for the reason that RMSE penalises larger errors more heavily." }, { "code": null, "e": 7560, "s": 7425, "text": "In this regard, it would seem that the ARIMA model is effective at capturing temperatures that are more in the normal range of values." }, { "code": null, "e": 7689, "s": 7560, "text": "However, the model falls short in predicting values at the more extreme ends of the scales — particularly for the winter months." }, { "code": null, "e": 7754, "s": 7689, "text": "That said, what if the lower end of the ARIMA forecast was used?" }, { "code": null, "e": 7901, "s": 7754, "text": "df<-data.frame(mydata$tmin[592:739],forecastedvalues$lower)col_headings<-c(\"Actual Weather\",\"Forecasted Weather\")names(df)<-col_headingsattach(df)" }, { "code": null, "e": 8040, "s": 7901, "text": "We see that while the model is performing better in forecasting the minimum values, the actual minimums still exceed that of the forecast." }, { "code": null, "e": 8181, "s": 8040, "text": "Moreover, this does not solve the problem as it means that the model will now significantly underestimate temperature values above the mean." }, { "code": null, "e": 8228, "s": 8181, "text": "As a result, the RMSE increases significantly:" }, { "code": null, "e": 8349, "s": 8228, "text": "> library(Metrics)> rmse(df$`Actual Weather`,df$`Forecasted Weather`)[1] 3.907014> mean(df$`Actual Weather`)[1] 2.876351" }, { "code": null, "e": 8574, "s": 8349, "text": "In this regard, ARIMA models should be interpreted with caution. While they can be effective in capturing seasonality and the overall trend, they can fall short in forecasting values that fall significantly outside the norm." }, { "code": null, "e": 8860, "s": 8574, "text": "When it comes to forecasting such values, statistical tools such as Monte Carlo simulations can be more effective in modelling a potential range of more extreme values. Here is a follow-up article that discusses how extreme weather events can potentially be modelled using this method." }, { "code": null, "e": 9143, "s": 8860, "text": "In this example, we have seen that ARIMA can be limited in forecasting extreme values. While the model is adept at modelling seasonality and trends, outliers are difficult to forecast for ARIMA for the very reason that they lie outside of the general trend as captured by the model." }, { "code": null, "e": 9240, "s": 9143, "text": "Many thanks for reading, and you can find more of my data science content at michael-grogan.com." } ]
Largest lexicographical string with at most K consecutive elements - GeeksforGeeks
24 Feb, 2022 Given a string S, the task is to find the largest lexicographical string with no more than K consecutive occurrence of an element by either re-arranging or deleting the elements.Examples: Input: S = “baccc” K = 2 Output: Result = “ccbca” Explanation: Since K=2, a maximum of 2 same characters can be placed consecutively. No. of ‘c’ = 3. No. of ‘b’ = 1. No. of ‘a’ = 1. Since the largest lexicographical string has to be printed, therefore, the answer is “ccbca”. Input: S = “xxxxzaz” K = 3 Output: result = “zzxxxax” Approach: Form a frequency array of size 26, where index i is chosen using (a character in a string – ‘a’).Initialize an empty string to store corresponding changes.For i=25 to 0, do:If frequency at index i is greater than k, then append (i + ‘a’) K-times. Decrease frequency by K at index i.find the next greatest priority element and append to answer and decrease the frequency at the respective index by 1.If frequency at index i is greater than 0 but less than k, then append (i + ‘a’) times its frequency.If frequency at index i is 0, then that index cannot be used to form an element and therefore check for the next possible highest priority element. Form a frequency array of size 26, where index i is chosen using (a character in a string – ‘a’). Initialize an empty string to store corresponding changes. For i=25 to 0, do:If frequency at index i is greater than k, then append (i + ‘a’) K-times. Decrease frequency by K at index i.find the next greatest priority element and append to answer and decrease the frequency at the respective index by 1.If frequency at index i is greater than 0 but less than k, then append (i + ‘a’) times its frequency.If frequency at index i is 0, then that index cannot be used to form an element and therefore check for the next possible highest priority element. If frequency at index i is greater than k, then append (i + ‘a’) K-times. Decrease frequency by K at index i.find the next greatest priority element and append to answer and decrease the frequency at the respective index by 1. If frequency at index i is greater than 0 but less than k, then append (i + ‘a’) times its frequency. If frequency at index i is 0, then that index cannot be used to form an element and therefore check for the next possible highest priority element. C++ Java Python3 C# Javascript // C++ code for the above approach #include <bits/stdc++.h>using namespace std;#define ll long long int // Function to find the// largest lexicographical// string with given constraints.string getLargestString(string s, ll k){ // vector containing frequency // of each character. vector<int> frequency_array(26, 0); // assigning frequency to for (int i = 0; i < s.length(); i++) { frequency_array[s[i] - 'a']++; } // empty string of string class type string ans = ""; // loop to iterate over // maximum priority first. for (int i = 25; i >= 0;) { // if frequency is greater than // or equal to k. if (frequency_array[i] > k) { // temporary variable to operate // in-place of k. int temp = k; string st(1, i + 'a'); while (temp > 0) { // concatenating with the // resultant string ans. ans += st; temp--; } frequency_array[i] -= k; // handling k case by adjusting // with just smaller priority // element. int j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { string str(1, j + 'a'); ans += str; frequency_array[j] -= 1; } else { // if no such element is found // than string can not be // processed further. break; } } // if frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // here we don't need to fix K // consecutive element criteria. int temp = frequency_array[i]; frequency_array[i] -= temp; string st(1, i + 'a'); while (temp > 0) { ans += st; temp--; } } // otherwise check for next // possible element. else { i--; } } return ans;} // Driver programint main(){ string S = "xxxxzza"; int k = 3; cout << getLargestString(S, k) << endl; return 0;} // Java code for// the above approachimport java.util.*;class GFG{ // Function to find the// largest lexicographical// String with given constraints.static String getLargestString(String s, int k){ // Vector containing frequency // of each character. int []frequency_array = new int[26]; // Assigning frequency for (int i = 0; i < s.length(); i++) { frequency_array[s.charAt(i) - 'a']++; } // Empty String of // String class type String ans = ""; // Loop to iterate over // maximum priority first. for (int i = 25; i >= 0 { // If frequency is greater than // or equal to k. if (frequency_array[i] > k) { // Temporary variable to // operate in-place of k. int temp = k; String st = String.valueOf((char)(i + 'a')); while (temp > 0) { // Concatenating with the // resultant String ans. ans += st; temp--; } frequency_array[i] -= k; // Handling k case by adjusting // with just smaller priority // element. int j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // Condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { String str = String.valueOf((char)(j + 'a')); ans += str; frequency_array[j] -= 1; } else { // If no such element is found // than String can not be // processed further. break; } } // If frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // Here we don't need to fix K // consecutive element criteria. int temp = frequency_array[i]; frequency_array[i] -= temp; String st = String.valueOf((char)(i + 'a')); while (temp > 0) { ans += st; temp--; } } // Otherwise check for next // possible element. else { i--; } } return ans;} // Driver codepublic static void main(String[] args){ String S = "xxxxzza"; int k = 3; System.out.print(getLargestString(S, k));}} // This code is contributed by shikhasingrajput # Python3 code for the above approach # Function to find the# largest lexicographical# string with given constraints.def getLargestString(s, k): # Vector containing frequency # of each character. frequency_array = [0] * 26 # Assigning frequency to for i in range(len(s)): frequency_array[ord(s[i]) - ord('a')] += 1 # Empty string of # string class type ans = "" # Loop to iterate over # maximum priority first. i = 25 while i >= 0: # If frequency is greater than # or equal to k. if (frequency_array[i] > k): # Temporary variable to # operate in-place of k. temp = k st = chr( i + ord('a')) while (temp > 0): # concatenating with the # resultant string ans. ans += st temp -= 1 frequency_array[i] -= k # Handling k case by adjusting # with just smaller priority # element. j = i - 1 while (frequency_array[j] <= 0 and j >= 0): j -= 1 # Condition to verify if index # j does have frequency # greater than 0; if (frequency_array[j] > 0 and j >= 0): str1 = chr(j + ord( 'a')) ans += str1 frequency_array[j] -= 1 else: # if no such element is found # than string can not be # processed further. break # If frequency is greater than 0 #and less than k. elif (frequency_array[i] > 0): # Here we don't need to fix K # consecutive element criteria. temp = frequency_array[i] frequency_array[i] -= temp st = chr(i + ord('a')) while (temp > 0): ans += st temp -= 1 # Otherwise check for next # possible element. else: i -= 1 return ans # Driver codeif __name__ == "__main__": S = "xxxxzza" k = 3 print (getLargestString(S, k)) # This code is contributed by Chitranayal // C# code for// the above approachusing System;class GFG{ // Function to find the// largest lexicographical// String with given constraints.static String getLargestString(String s, int k){ // List containing frequency // of each character. int []frequency_array = new int[26]; // Assigning frequency for (int i = 0; i < s.Length; i++) { frequency_array[s[i] - 'a']++; } // Empty String of // String class type String ans = ""; // Loop to iterate over // maximum priority first. for (int i = 25; i >= 0;) { // If frequency is greater than // or equal to k. if (frequency_array[i] > k) { // Temporary variable to // operate in-place of k. int temp = k; String st = String.Join("", (char)(i + 'a')); while (temp > 0) { // Concatenating with the // resultant String ans. ans += st; temp--; } frequency_array[i] -= k; // Handling k case by adjusting // with just smaller priority // element. int j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // Condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { String str = String.Join("", (char)(j + 'a')); ans += str; frequency_array[j] -= 1; } else { // If no such element is found // than String can not be // processed further. break; } } // If frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // Here we don't need to fix K // consecutive element criteria. int temp = frequency_array[i]; frequency_array[i] -= temp; String st = String.Join("", (char)(i + 'a')); while (temp > 0) { ans += st; temp--; } } // Otherwise check for next // possible element. else { i--; } } return ans;} // Driver codepublic static void Main(String[] args){ String S = "xxxxzza"; int k = 3; Console.Write(getLargestString(S, k));}} // This code is contributed by Princi Singh <script>// Javascript code for// the above approach // Function to find the// largest lexicographical// String with given constraints.function getLargestString(s,k){ // Vector containing frequency // of each character. let frequency_array = new Array(26); for(let i=0;i<26;i++) { frequency_array[i]=0; } // Assigning frequency for (let i = 0; i < s.length; i++) { frequency_array[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Empty String of // String class type let ans = ""; // Loop to iterate over // maximum priority first. for (let i = 25; i >= 0;) { // If frequency is greater than // or equal to k. if (frequency_array[i] > k) { // Temporary variable to // operate in-place of k. let temp = k; let st = String.fromCharCode(i + 'a'.charCodeAt(0)); while (temp > 0) { // Concatenating with the // resultant String ans. ans += st; temp--; } frequency_array[i] -= k; // Handling k case by adjusting // with just smaller priority // element. let j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // Condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { let str = String.fromCharCode(j + 'a'.charCodeAt(0)); ans += str; frequency_array[j] -= 1; } else { // If no such element is found // than String can not be // processed further. break; } } // If frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // Here we don't need to fix K // consecutive element criteria. let temp = frequency_array[i]; frequency_array[i] -= temp; let st = String.fromCharCode(i + 'a'.charCodeAt(0)); while (temp > 0) { ans += st; temp--; } } // Otherwise check for next // possible element. else { i--; } } return ans;} // Driver codelet S = "xxxxzza";let k = 3;document.write(getLargestString(S, k)); // This code is contributed by avanitrachhadiya2155</script> zzxxxax Time Complexity: O(N) shikhasingrajput princi singh ukasp avanitrachhadiya2155 nidhi_ranjan lexicographic-ordering Algorithms Arrays Greedy Hash Strings Arrays Hash Strings Greedy Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24299, "s": 24271, "text": "\n24 Feb, 2022" }, { "code": null, "e": 24488, "s": 24299, "text": "Given a string S, the task is to find the largest lexicographical string with no more than K consecutive occurrence of an element by either re-arranging or deleting the elements.Examples: " }, { "code": null, "e": 24764, "s": 24488, "text": "Input: S = “baccc” K = 2 Output: Result = “ccbca” Explanation: Since K=2, a maximum of 2 same characters can be placed consecutively. No. of ‘c’ = 3. No. of ‘b’ = 1. No. of ‘a’ = 1. Since the largest lexicographical string has to be printed, therefore, the answer is “ccbca”." }, { "code": null, "e": 24819, "s": 24764, "text": "Input: S = “xxxxzaz” K = 3 Output: result = “zzxxxax” " }, { "code": null, "e": 24830, "s": 24819, "text": "Approach: " }, { "code": null, "e": 25479, "s": 24830, "text": "Form a frequency array of size 26, where index i is chosen using (a character in a string – ‘a’).Initialize an empty string to store corresponding changes.For i=25 to 0, do:If frequency at index i is greater than k, then append (i + ‘a’) K-times. Decrease frequency by K at index i.find the next greatest priority element and append to answer and decrease the frequency at the respective index by 1.If frequency at index i is greater than 0 but less than k, then append (i + ‘a’) times its frequency.If frequency at index i is 0, then that index cannot be used to form an element and therefore check for the next possible highest priority element. " }, { "code": null, "e": 25577, "s": 25479, "text": "Form a frequency array of size 26, where index i is chosen using (a character in a string – ‘a’)." }, { "code": null, "e": 25636, "s": 25577, "text": "Initialize an empty string to store corresponding changes." }, { "code": null, "e": 26130, "s": 25636, "text": "For i=25 to 0, do:If frequency at index i is greater than k, then append (i + ‘a’) K-times. Decrease frequency by K at index i.find the next greatest priority element and append to answer and decrease the frequency at the respective index by 1.If frequency at index i is greater than 0 but less than k, then append (i + ‘a’) times its frequency.If frequency at index i is 0, then that index cannot be used to form an element and therefore check for the next possible highest priority element. " }, { "code": null, "e": 26357, "s": 26130, "text": "If frequency at index i is greater than k, then append (i + ‘a’) K-times. Decrease frequency by K at index i.find the next greatest priority element and append to answer and decrease the frequency at the respective index by 1." }, { "code": null, "e": 26459, "s": 26357, "text": "If frequency at index i is greater than 0 but less than k, then append (i + ‘a’) times its frequency." }, { "code": null, "e": 26608, "s": 26459, "text": "If frequency at index i is 0, then that index cannot be used to form an element and therefore check for the next possible highest priority element. " }, { "code": null, "e": 26612, "s": 26608, "text": "C++" }, { "code": null, "e": 26617, "s": 26612, "text": "Java" }, { "code": null, "e": 26625, "s": 26617, "text": "Python3" }, { "code": null, "e": 26628, "s": 26625, "text": "C#" }, { "code": null, "e": 26639, "s": 26628, "text": "Javascript" }, { "code": "// C++ code for the above approach #include <bits/stdc++.h>using namespace std;#define ll long long int // Function to find the// largest lexicographical// string with given constraints.string getLargestString(string s, ll k){ // vector containing frequency // of each character. vector<int> frequency_array(26, 0); // assigning frequency to for (int i = 0; i < s.length(); i++) { frequency_array[s[i] - 'a']++; } // empty string of string class type string ans = \"\"; // loop to iterate over // maximum priority first. for (int i = 25; i >= 0;) { // if frequency is greater than // or equal to k. if (frequency_array[i] > k) { // temporary variable to operate // in-place of k. int temp = k; string st(1, i + 'a'); while (temp > 0) { // concatenating with the // resultant string ans. ans += st; temp--; } frequency_array[i] -= k; // handling k case by adjusting // with just smaller priority // element. int j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { string str(1, j + 'a'); ans += str; frequency_array[j] -= 1; } else { // if no such element is found // than string can not be // processed further. break; } } // if frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // here we don't need to fix K // consecutive element criteria. int temp = frequency_array[i]; frequency_array[i] -= temp; string st(1, i + 'a'); while (temp > 0) { ans += st; temp--; } } // otherwise check for next // possible element. else { i--; } } return ans;} // Driver programint main(){ string S = \"xxxxzza\"; int k = 3; cout << getLargestString(S, k) << endl; return 0;}", "e": 29123, "s": 26639, "text": null }, { "code": "// Java code for// the above approachimport java.util.*;class GFG{ // Function to find the// largest lexicographical// String with given constraints.static String getLargestString(String s, int k){ // Vector containing frequency // of each character. int []frequency_array = new int[26]; // Assigning frequency for (int i = 0; i < s.length(); i++) { frequency_array[s.charAt(i) - 'a']++; } // Empty String of // String class type String ans = \"\"; // Loop to iterate over // maximum priority first. for (int i = 25; i >= 0 { // If frequency is greater than // or equal to k. if (frequency_array[i] > k) { // Temporary variable to // operate in-place of k. int temp = k; String st = String.valueOf((char)(i + 'a')); while (temp > 0) { // Concatenating with the // resultant String ans. ans += st; temp--; } frequency_array[i] -= k; // Handling k case by adjusting // with just smaller priority // element. int j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // Condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { String str = String.valueOf((char)(j + 'a')); ans += str; frequency_array[j] -= 1; } else { // If no such element is found // than String can not be // processed further. break; } } // If frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // Here we don't need to fix K // consecutive element criteria. int temp = frequency_array[i]; frequency_array[i] -= temp; String st = String.valueOf((char)(i + 'a')); while (temp > 0) { ans += st; temp--; } } // Otherwise check for next // possible element. else { i--; } } return ans;} // Driver codepublic static void main(String[] args){ String S = \"xxxxzza\"; int k = 3; System.out.print(getLargestString(S, k));}} // This code is contributed by shikhasingrajput", "e": 31360, "s": 29123, "text": null }, { "code": "# Python3 code for the above approach # Function to find the# largest lexicographical# string with given constraints.def getLargestString(s, k): # Vector containing frequency # of each character. frequency_array = [0] * 26 # Assigning frequency to for i in range(len(s)): frequency_array[ord(s[i]) - ord('a')] += 1 # Empty string of # string class type ans = \"\" # Loop to iterate over # maximum priority first. i = 25 while i >= 0: # If frequency is greater than # or equal to k. if (frequency_array[i] > k): # Temporary variable to # operate in-place of k. temp = k st = chr( i + ord('a')) while (temp > 0): # concatenating with the # resultant string ans. ans += st temp -= 1 frequency_array[i] -= k # Handling k case by adjusting # with just smaller priority # element. j = i - 1 while (frequency_array[j] <= 0 and j >= 0): j -= 1 # Condition to verify if index # j does have frequency # greater than 0; if (frequency_array[j] > 0 and j >= 0): str1 = chr(j + ord( 'a')) ans += str1 frequency_array[j] -= 1 else: # if no such element is found # than string can not be # processed further. break # If frequency is greater than 0 #and less than k. elif (frequency_array[i] > 0): # Here we don't need to fix K # consecutive element criteria. temp = frequency_array[i] frequency_array[i] -= temp st = chr(i + ord('a')) while (temp > 0): ans += st temp -= 1 # Otherwise check for next # possible element. else: i -= 1 return ans # Driver codeif __name__ == \"__main__\": S = \"xxxxzza\" k = 3 print (getLargestString(S, k)) # This code is contributed by Chitranayal", "e": 33684, "s": 31360, "text": null }, { "code": "// C# code for// the above approachusing System;class GFG{ // Function to find the// largest lexicographical// String with given constraints.static String getLargestString(String s, int k){ // List containing frequency // of each character. int []frequency_array = new int[26]; // Assigning frequency for (int i = 0; i < s.Length; i++) { frequency_array[s[i] - 'a']++; } // Empty String of // String class type String ans = \"\"; // Loop to iterate over // maximum priority first. for (int i = 25; i >= 0;) { // If frequency is greater than // or equal to k. if (frequency_array[i] > k) { // Temporary variable to // operate in-place of k. int temp = k; String st = String.Join(\"\", (char)(i + 'a')); while (temp > 0) { // Concatenating with the // resultant String ans. ans += st; temp--; } frequency_array[i] -= k; // Handling k case by adjusting // with just smaller priority // element. int j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // Condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { String str = String.Join(\"\", (char)(j + 'a')); ans += str; frequency_array[j] -= 1; } else { // If no such element is found // than String can not be // processed further. break; } } // If frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // Here we don't need to fix K // consecutive element criteria. int temp = frequency_array[i]; frequency_array[i] -= temp; String st = String.Join(\"\", (char)(i + 'a')); while (temp > 0) { ans += st; temp--; } } // Otherwise check for next // possible element. else { i--; } } return ans;} // Driver codepublic static void Main(String[] args){ String S = \"xxxxzza\"; int k = 3; Console.Write(getLargestString(S, k));}} // This code is contributed by Princi Singh", "e": 35983, "s": 33684, "text": null }, { "code": "<script>// Javascript code for// the above approach // Function to find the// largest lexicographical// String with given constraints.function getLargestString(s,k){ // Vector containing frequency // of each character. let frequency_array = new Array(26); for(let i=0;i<26;i++) { frequency_array[i]=0; } // Assigning frequency for (let i = 0; i < s.length; i++) { frequency_array[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // Empty String of // String class type let ans = \"\"; // Loop to iterate over // maximum priority first. for (let i = 25; i >= 0;) { // If frequency is greater than // or equal to k. if (frequency_array[i] > k) { // Temporary variable to // operate in-place of k. let temp = k; let st = String.fromCharCode(i + 'a'.charCodeAt(0)); while (temp > 0) { // Concatenating with the // resultant String ans. ans += st; temp--; } frequency_array[i] -= k; // Handling k case by adjusting // with just smaller priority // element. let j = i - 1; while (frequency_array[j] <= 0 && j >= 0) { j--; } // Condition to verify if index // j does have frequency // greater than 0; if (frequency_array[j] > 0 && j >= 0) { let str = String.fromCharCode(j + 'a'.charCodeAt(0)); ans += str; frequency_array[j] -= 1; } else { // If no such element is found // than String can not be // processed further. break; } } // If frequency is greater than 0 // and less than k. else if (frequency_array[i] > 0) { // Here we don't need to fix K // consecutive element criteria. let temp = frequency_array[i]; frequency_array[i] -= temp; let st = String.fromCharCode(i + 'a'.charCodeAt(0)); while (temp > 0) { ans += st; temp--; } } // Otherwise check for next // possible element. else { i--; } } return ans;} // Driver codelet S = \"xxxxzza\";let k = 3;document.write(getLargestString(S, k)); // This code is contributed by avanitrachhadiya2155</script>", "e": 38228, "s": 35983, "text": null }, { "code": null, "e": 38236, "s": 38228, "text": "zzxxxax" }, { "code": null, "e": 38259, "s": 38236, "text": "Time Complexity: O(N) " }, { "code": null, "e": 38276, "s": 38259, "text": "shikhasingrajput" }, { "code": null, "e": 38289, "s": 38276, "text": "princi singh" }, { "code": null, "e": 38295, "s": 38289, "text": "ukasp" }, { "code": null, "e": 38316, "s": 38295, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38329, "s": 38316, "text": "nidhi_ranjan" }, { "code": null, "e": 38352, "s": 38329, "text": "lexicographic-ordering" }, { "code": null, "e": 38363, "s": 38352, "text": "Algorithms" }, { "code": null, "e": 38370, "s": 38363, "text": "Arrays" }, { "code": null, "e": 38377, "s": 38370, "text": "Greedy" }, { "code": null, "e": 38382, "s": 38377, "text": "Hash" }, { "code": null, "e": 38390, "s": 38382, "text": "Strings" }, { "code": null, "e": 38397, "s": 38390, "text": "Arrays" }, { "code": null, "e": 38402, "s": 38397, "text": "Hash" }, { "code": null, "e": 38410, "s": 38402, "text": "Strings" }, { "code": null, "e": 38417, "s": 38410, "text": "Greedy" }, { "code": null, "e": 38428, "s": 38417, "text": "Algorithms" }, { "code": null, "e": 38526, "s": 38428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38535, "s": 38526, "text": "Comments" }, { "code": null, "e": 38548, "s": 38535, "text": "Old Comments" }, { "code": null, "e": 38573, "s": 38548, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38629, "s": 38573, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 38672, "s": 38629, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 38701, "s": 38672, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 38735, "s": 38701, "text": "K means Clustering - Introduction" }, { "code": null, "e": 38750, "s": 38735, "text": "Arrays in Java" }, { "code": null, "e": 38766, "s": 38750, "text": "Arrays in C/C++" }, { "code": null, "e": 38793, "s": 38766, "text": "Program for array rotation" }, { "code": null, "e": 38841, "s": 38793, "text": "Stack Data Structure (Introduction and Program)" } ]
Capturing JavaScript error in Selenium.
We can capture Javascript error in Selenium. This type of error appears at the Console Tab on opening the Developer tools in the browser. This can occur due to some functional issue in the page or due to extra logs which may cause performance issues. We can handle the Javascript errors with the driver object and manage method. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; import java.util.ArrayList; import org.openqa.selenium.logging.LogEntries; import org.openqa.selenium.logging.LogEntry; import org.openqa.selenium.logging.LogType; import java.util.logging.Level; import java.util.Set; public class JavascrptLogErs{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String u = "https://the−internet.herokuapp.com/javascript_error"; driver.get(u); // maximize browser driver.manage().window().maximize(); // to obtain browser errors Set<String> logtyp = driver.manage().logs().getAvailableLogTypes(); for (String s : logtyp) { System.out.println(logtyp); } LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER); List<LogEntry> lg = logEntries.filter(Level.ALL); for(LogEntry logEntry : lg) { System.out.println(logEntry); } driver.quit(); } }
[ { "code": null, "e": 1313, "s": 1062, "text": "We can capture Javascript error in Selenium. This type of error appears at the Console Tab on opening the Developer tools in the browser. This can occur due to some functional issue in the page or due to extra logs which may cause performance issues." }, { "code": null, "e": 1391, "s": 1313, "text": "We can handle the Javascript errors with the driver object and manage method." }, { "code": null, "e": 2610, "s": 1391, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.List;\nimport java.util.ArrayList;\nimport org.openqa.selenium.logging.LogEntries;\nimport org.openqa.selenium.logging.LogEntry;\nimport org.openqa.selenium.logging.LogType;\nimport java.util.logging.Level;\nimport java.util.Set;\npublic class JavascrptLogErs{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String u = \"https://the−internet.herokuapp.com/javascript_error\";\n driver.get(u);\n // maximize browser\n driver.manage().window().maximize();\n // to obtain browser errors\n Set<String> logtyp = driver.manage().logs().getAvailableLogTypes();\n for (String s : logtyp) {\n System.out.println(logtyp);\n }\n LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);\n List<LogEntry> lg = logEntries.filter(Level.ALL);\n for(LogEntry logEntry : lg) {\n System.out.println(logEntry);\n }\n driver.quit();\n }\n}" } ]
Bootstrap 4 | Panels - GeeksforGeeks
01 Sep, 2021 When we have to quote some content on a webpage, we can use a panel. We place the content inbox with some padding around it. A bootstrap panel is indicated with a “panel” class. Example: This example describes the basic code to make a panel. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Panels</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <h2 style="text-align:center;"> Panel </h2> <div class="panel panel-default"> <div class="panel-body"> This is a body of bootstrap panel </div> </div></body> </html> Output: Different classes of panel: There are sections available in a Bootstrap panel like a Bootstrap Cards. All the body parts of Bootstrap Panel are described below: panel body It is used to define body of a panel. panel heading: It is used to give heading to a panel. panel footer: It is used to give footer class to panel. panel group: It is used to collect different panels together into a group. panel with contextual classes: Contextual classes are used to color the panel. panel-default panel-primary panel-success panel-info panel-warning panel-danger Panel Heading: It is used to create a panel with heading. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Panels</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <h2 style="text-align:center;"> Panel heading </h2> <div class="panel panel-default"> <div class="panel-heading"> This is a heading of bootstrap panel </div> <div class="panel-body"> This is a body of bootstrap panel </div> </div></body> </html> Output: Panel Footer: It is used to add footer into the panel. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Panels</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <h2 style="text-align:center;"> Panel footer </h2> <div class="panel panel-default"> <div class="panel-body"> This is a body of bootstrap panel </div> <div class="panel-footer"> This is a footer of bootstrap panel </div> </div></body> </html> Output: Panel Groups: It is used to collect panels together into a group. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Panels</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <div class="container"> <h2>Panel Group</h2> <p> The panel-group class clears the bottom-margin. Try to remove the class and see what happens. </p> <div class="panel-group"> <div class="panel panel-default"> <div class="panel-body"> This is bootstrap panel 1 </div> </div> <div class="panel panel-default"> <div class="panel-body"> This is bootstrap panel 2 </div> </div> <div class="panel panel-default"> <div class="panel-body"> This is bootstrap panel 3 </div> </div> <div class="panel panel-default"> <div class="panel-body"> This is bootstrap panel 4 </div> </div> </div> </div></body> </html> Output Panels with contextual classes: They are used to highlight the panel content as per different situations of use. Example: HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Panels</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <div class="container"> <h2>Panels with Contextual Classes</h2> <div class="panel-group"> <div class="panel panel-default"> <div class="panel-heading">panel-default</div> <div class="panel-body">Content</div> </div> <div class="panel panel-primary"> <div class="panel-heading">panel-primary</div> <div class="panel-body">Content</div> </div> <div class="panel panel-success"> <div class="panel-heading"> panel-success</div> <div class="panel-body">Content</div> </div> <div class="panel panel-info"> <div class="panel-heading"> panel-info</div> <div class="panel-body">Content</div> </div> <div class="panel panel-warning"> <div class="panel-heading">panel-warning</div> <div class="panel-body">Content</div> </div> <div class="panel panel-danger"> <div class="panel-heading">panel-danger</div> <div class="panel-body">Content</div> </div> </div></body> </html> Output: simmytarika5 Bootstrap-4 Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Form validation using jQuery How to change navigation bar color in Bootstrap ? How to align navbar items to the right in Bootstrap 4 ? How to set Bootstrap Timepicker using datetimepicker library ? How to pass data into a bootstrap modal? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28385, "s": 28357, "text": "\n01 Sep, 2021" }, { "code": null, "e": 28563, "s": 28385, "text": "When we have to quote some content on a webpage, we can use a panel. We place the content inbox with some padding around it. A bootstrap panel is indicated with a “panel” class." }, { "code": null, "e": 28627, "s": 28563, "text": "Example: This example describes the basic code to make a panel." }, { "code": null, "e": 28632, "s": 28627, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Panels</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <h2 style=\"text-align:center;\"> Panel </h2> <div class=\"panel panel-default\"> <div class=\"panel-body\"> This is a body of bootstrap panel </div> </div></body> </html>", "e": 29485, "s": 28632, "text": null }, { "code": null, "e": 29494, "s": 29485, "text": "Output: " }, { "code": null, "e": 29656, "s": 29494, "text": "Different classes of panel: There are sections available in a Bootstrap panel like a Bootstrap Cards. All the body parts of Bootstrap Panel are described below: " }, { "code": null, "e": 29705, "s": 29656, "text": "panel body It is used to define body of a panel." }, { "code": null, "e": 29759, "s": 29705, "text": "panel heading: It is used to give heading to a panel." }, { "code": null, "e": 29815, "s": 29759, "text": "panel footer: It is used to give footer class to panel." }, { "code": null, "e": 29890, "s": 29815, "text": "panel group: It is used to collect different panels together into a group." }, { "code": null, "e": 29971, "s": 29890, "text": "panel with contextual classes: Contextual classes are used to color the panel. " }, { "code": null, "e": 29985, "s": 29971, "text": "panel-default" }, { "code": null, "e": 29999, "s": 29985, "text": "panel-primary" }, { "code": null, "e": 30013, "s": 29999, "text": "panel-success" }, { "code": null, "e": 30024, "s": 30013, "text": "panel-info" }, { "code": null, "e": 30038, "s": 30024, "text": "panel-warning" }, { "code": null, "e": 30051, "s": 30038, "text": "panel-danger" }, { "code": null, "e": 30110, "s": 30051, "text": "Panel Heading: It is used to create a panel with heading. " }, { "code": null, "e": 30120, "s": 30110, "text": "Example: " }, { "code": null, "e": 30125, "s": 30120, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Panels</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <h2 style=\"text-align:center;\"> Panel heading </h2> <div class=\"panel panel-default\"> <div class=\"panel-heading\"> This is a heading of bootstrap panel </div> <div class=\"panel-body\"> This is a body of bootstrap panel </div> </div></body> </html>", "e": 31079, "s": 30125, "text": null }, { "code": null, "e": 31088, "s": 31079, "text": "Output: " }, { "code": null, "e": 31145, "s": 31088, "text": "Panel Footer: It is used to add footer into the panel. " }, { "code": null, "e": 31155, "s": 31145, "text": "Example: " }, { "code": null, "e": 31160, "s": 31155, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Panels</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <h2 style=\"text-align:center;\"> Panel footer </h2> <div class=\"panel panel-default\"> <div class=\"panel-body\"> This is a body of bootstrap panel </div> <div class=\"panel-footer\"> This is a footer of bootstrap panel </div> </div></body> </html>", "e": 32113, "s": 31160, "text": null }, { "code": null, "e": 32122, "s": 32113, "text": "Output: " }, { "code": null, "e": 32189, "s": 32122, "text": "Panel Groups: It is used to collect panels together into a group. " }, { "code": null, "e": 32199, "s": 32189, "text": "Example: " }, { "code": null, "e": 32204, "s": 32199, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Panels</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <h2>Panel Group</h2> <p> The panel-group class clears the bottom-margin. Try to remove the class and see what happens. </p> <div class=\"panel-group\"> <div class=\"panel panel-default\"> <div class=\"panel-body\"> This is bootstrap panel 1 </div> </div> <div class=\"panel panel-default\"> <div class=\"panel-body\"> This is bootstrap panel 2 </div> </div> <div class=\"panel panel-default\"> <div class=\"panel-body\"> This is bootstrap panel 3 </div> </div> <div class=\"panel panel-default\"> <div class=\"panel-body\"> This is bootstrap panel 4 </div> </div> </div> </div></body> </html>", "e": 33677, "s": 32204, "text": null }, { "code": null, "e": 33685, "s": 33677, "text": "Output " }, { "code": null, "e": 33799, "s": 33685, "text": "Panels with contextual classes: They are used to highlight the panel content as per different situations of use. " }, { "code": null, "e": 33809, "s": 33799, "text": "Example: " }, { "code": null, "e": 33814, "s": 33809, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Panels</title> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <style> .panel { margin: 5px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <div class=\"container\"> <h2>Panels with Contextual Classes</h2> <div class=\"panel-group\"> <div class=\"panel panel-default\"> <div class=\"panel-heading\">panel-default</div> <div class=\"panel-body\">Content</div> </div> <div class=\"panel panel-primary\"> <div class=\"panel-heading\">panel-primary</div> <div class=\"panel-body\">Content</div> </div> <div class=\"panel panel-success\"> <div class=\"panel-heading\"> panel-success</div> <div class=\"panel-body\">Content</div> </div> <div class=\"panel panel-info\"> <div class=\"panel-heading\"> panel-info</div> <div class=\"panel-body\">Content</div> </div> <div class=\"panel panel-warning\"> <div class=\"panel-heading\">panel-warning</div> <div class=\"panel-body\">Content</div> </div> <div class=\"panel panel-danger\"> <div class=\"panel-heading\">panel-danger</div> <div class=\"panel-body\">Content</div> </div> </div></body> </html> ", "e": 35550, "s": 33814, "text": null }, { "code": null, "e": 35559, "s": 35550, "text": "Output: " }, { "code": null, "e": 35574, "s": 35561, "text": "simmytarika5" }, { "code": null, "e": 35586, "s": 35574, "text": "Bootstrap-4" }, { "code": null, "e": 35601, "s": 35586, "text": "Bootstrap-Misc" }, { "code": null, "e": 35611, "s": 35601, "text": "Bootstrap" }, { "code": null, "e": 35628, "s": 35611, "text": "Web Technologies" }, { "code": null, "e": 35726, "s": 35628, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35735, "s": 35726, "text": "Comments" }, { "code": null, "e": 35748, "s": 35735, "text": "Old Comments" }, { "code": null, "e": 35777, "s": 35748, "text": "Form validation using jQuery" }, { "code": null, "e": 35827, "s": 35777, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 35883, "s": 35827, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 35946, "s": 35883, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 35987, "s": 35946, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 36029, "s": 35987, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 36062, "s": 36029, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36105, "s": 36062, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 36167, "s": 36105, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Sequence Unpacking in Python. Understanding Python Sequence Unpacking | by Sadrach Pierre, Ph.D. | Towards Data Science
Sequence unpacking in python allows you to take objects in a collection and store them in variables for later use. This is particularly useful when a function or method returns a sequence of objects. In this post, we will discuss sequence unpacking in python. Let’s get started! A key feature of python is that any sequence can be unpacked into variables by assignment. Consider a list of values corresponding to the attributes of a specific run on the Nike run application. This list will contain the date, pace (minutes), time (minutes), distance (miles) and elevation (feet) for a run: new_run = ['09/01/2020', '10:00', 60, 6, 100] We can unpack this list with appropriately named variables by assignment: date, pace, time, distance, elevation = new_run We can then print the values for these variables to validate that the assignments were correct: print("Date: ", date)print("Pace: ", pace, 'min')print("Time: ", time, 'min')print("Distance: ", distance, 'miles')print("Elevation: ", elevation, 'feet') The elements in the sequence we are unpacking can be sequences as well. For example, in addition to the average pace of the overall run, we can have a tuple of mile splits: new_run_with_splits = ['09/01/2020', '10:00', 60, 6, 100, ('12:00', '12:00', '10:00', '11;00', '8:00', '7:00')] Let’s now unpack our new sequence: date, pace, time, distance, elevation, splits = new_run_with_splits And we can print the mile splits: print("Mile splits: ", splits) We can even further unpack the splits list in the previous code. Let’s unpack the split lists with variables denoting the mile number: date, pace, time, distance, elevation, (mile_2, mile_2, mile3_, mile_4, mile_5, mile_6) = new_run_with_splits Let’s print the mile variables: print("Mile Two: ", mile_2)print("Mile Three: ", mile_3)print("Mile Four: ", mile_4)print("Mile Five: ", mile_5)print("Mile Six: ", mile_6) We can also use the ‘_’ character to leave out unwanted values. For example if we want to leave out date and elevation we do: _, pace, time, distance, _, (mile_2, mile_2, mile_3, mile_4, mile_5, mile_6) = new_run_with_splits We can also unpack an arbitrary number of elements using the python “star expression” (*). For example, if we want to store the first and last variables and store the middle values in a list we can do the following: date, pace, time, distance, elevation, (first, *middle, last) = new_run_with_splits Let’s print the first, middle and last variables: print("First: ", first)print("Middlle: ", middle)print("Last: ", last I’d like to emphasize that the objects in our sequence can be of any type. For example, we could have used a dictionary instead of a tuple for the mile splits: new_run_with_splits_dict = ['09/01/2020', '10:00', 60, 6, 100, {'mile_1': '12:00', 'mile_2':'12:00', 'mile3':'10:00', 'mile_4':'11;00', 'mile_5':'8:00', 'mile_6':'7:00'}] Let’s unpack our new list: date, pace, time, distance, elevation, splits_dict = new_run_with_splits_dict Now we can access the mile split values by key: print("Mile One: ", splits_dict['mile_1'])print("Mile Two: ", splits_dict['mile_2'])print("Mile Three: ", splits_dict['mile_3']) I’ll stop here but I encourage you to play around with the code yourself. In this post, we discussed how to unpack sequences in python. First, we showed how to unpack a list of values associated with a run published to the Nike Run application. We also showed that the values in the sequences can also be sequences, where the sequence or its elements can be stored in separate variables for later use. We then showed how we can leave values out using the underscore character. Next, we discussed how to unpack an arbitrary number of objects using the python “star expression”. Finally, we demonstrated how we can unpack a dictionary object from a list of objects and access the dictionary values by key. I hope you found this post interesting/useful. The code in this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 431, "s": 171, "text": "Sequence unpacking in python allows you to take objects in a collection and store them in variables for later use. This is particularly useful when a function or method returns a sequence of objects. In this post, we will discuss sequence unpacking in python." }, { "code": null, "e": 450, "s": 431, "text": "Let’s get started!" }, { "code": null, "e": 760, "s": 450, "text": "A key feature of python is that any sequence can be unpacked into variables by assignment. Consider a list of values corresponding to the attributes of a specific run on the Nike run application. This list will contain the date, pace (minutes), time (minutes), distance (miles) and elevation (feet) for a run:" }, { "code": null, "e": 806, "s": 760, "text": "new_run = ['09/01/2020', '10:00', 60, 6, 100]" }, { "code": null, "e": 880, "s": 806, "text": "We can unpack this list with appropriately named variables by assignment:" }, { "code": null, "e": 928, "s": 880, "text": "date, pace, time, distance, elevation = new_run" }, { "code": null, "e": 1024, "s": 928, "text": "We can then print the values for these variables to validate that the assignments were correct:" }, { "code": null, "e": 1179, "s": 1024, "text": "print(\"Date: \", date)print(\"Pace: \", pace, 'min')print(\"Time: \", time, 'min')print(\"Distance: \", distance, 'miles')print(\"Elevation: \", elevation, 'feet')" }, { "code": null, "e": 1352, "s": 1179, "text": "The elements in the sequence we are unpacking can be sequences as well. For example, in addition to the average pace of the overall run, we can have a tuple of mile splits:" }, { "code": null, "e": 1464, "s": 1352, "text": "new_run_with_splits = ['09/01/2020', '10:00', 60, 6, 100, ('12:00', '12:00', '10:00', '11;00', '8:00', '7:00')]" }, { "code": null, "e": 1499, "s": 1464, "text": "Let’s now unpack our new sequence:" }, { "code": null, "e": 1567, "s": 1499, "text": "date, pace, time, distance, elevation, splits = new_run_with_splits" }, { "code": null, "e": 1601, "s": 1567, "text": "And we can print the mile splits:" }, { "code": null, "e": 1632, "s": 1601, "text": "print(\"Mile splits: \", splits)" }, { "code": null, "e": 1767, "s": 1632, "text": "We can even further unpack the splits list in the previous code. Let’s unpack the split lists with variables denoting the mile number:" }, { "code": null, "e": 1877, "s": 1767, "text": "date, pace, time, distance, elevation, (mile_2, mile_2, mile3_, mile_4, mile_5, mile_6) = new_run_with_splits" }, { "code": null, "e": 1909, "s": 1877, "text": "Let’s print the mile variables:" }, { "code": null, "e": 2049, "s": 1909, "text": "print(\"Mile Two: \", mile_2)print(\"Mile Three: \", mile_3)print(\"Mile Four: \", mile_4)print(\"Mile Five: \", mile_5)print(\"Mile Six: \", mile_6)" }, { "code": null, "e": 2175, "s": 2049, "text": "We can also use the ‘_’ character to leave out unwanted values. For example if we want to leave out date and elevation we do:" }, { "code": null, "e": 2274, "s": 2175, "text": "_, pace, time, distance, _, (mile_2, mile_2, mile_3, mile_4, mile_5, mile_6) = new_run_with_splits" }, { "code": null, "e": 2490, "s": 2274, "text": "We can also unpack an arbitrary number of elements using the python “star expression” (*). For example, if we want to store the first and last variables and store the middle values in a list we can do the following:" }, { "code": null, "e": 2574, "s": 2490, "text": "date, pace, time, distance, elevation, (first, *middle, last) = new_run_with_splits" }, { "code": null, "e": 2624, "s": 2574, "text": "Let’s print the first, middle and last variables:" }, { "code": null, "e": 2694, "s": 2624, "text": "print(\"First: \", first)print(\"Middlle: \", middle)print(\"Last: \", last" }, { "code": null, "e": 2854, "s": 2694, "text": "I’d like to emphasize that the objects in our sequence can be of any type. For example, we could have used a dictionary instead of a tuple for the mile splits:" }, { "code": null, "e": 3025, "s": 2854, "text": "new_run_with_splits_dict = ['09/01/2020', '10:00', 60, 6, 100, {'mile_1': '12:00', 'mile_2':'12:00', 'mile3':'10:00', 'mile_4':'11;00', 'mile_5':'8:00', 'mile_6':'7:00'}]" }, { "code": null, "e": 3052, "s": 3025, "text": "Let’s unpack our new list:" }, { "code": null, "e": 3130, "s": 3052, "text": "date, pace, time, distance, elevation, splits_dict = new_run_with_splits_dict" }, { "code": null, "e": 3178, "s": 3130, "text": "Now we can access the mile split values by key:" }, { "code": null, "e": 3307, "s": 3178, "text": "print(\"Mile One: \", splits_dict['mile_1'])print(\"Mile Two: \", splits_dict['mile_2'])print(\"Mile Three: \", splits_dict['mile_3'])" }, { "code": null, "e": 3381, "s": 3307, "text": "I’ll stop here but I encourage you to play around with the code yourself." } ]
Identify and mark unmatched parenthesis in an expression - GeeksforGeeks
31 Aug, 2021 Given an expression, find and mark matched and unmatched parenthesis in it. We need to replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1, and all unbalanced with -1.Examples: Input : ((a) Output : -10a1 Input : (a)) Output : 0a1-1 Input : (((abc))((d))))) Output : 000abc1100d111-1-1 The idea is based on a stack. We run a loop from the start of the string Up to end and for every ‘(‘, we push it into a stack. If the stack is empty, and we encounter a closing bracket ‘)’ we replace -1 at that index of the string. Else we replace all opening brackets ‘(‘ with 0 and closing brackets with 1. Then pop from the stack. C++ Java Python3 C# Javascript // CPP program to mark balanced and unbalanced// parenthesis.#include <bits/stdc++.h>using namespace std; void identifyParenthesis(string a){ stack<int> st; // run the loop upto end of the string for (int i = 0; i < a.length(); i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.empty()) a.replace(i, 1, "-1"); else { // replace all opening brackets with 0 // and closing brackets with 1 a.replace(i, 1, "1"); a.replace(st.top(), 1, "0"); st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (!st.empty()) { a.replace(st.top(), 1, "-1"); st.pop(); } // print final string cout << a << endl;} // Driver codeint main(){ string str = "(a))"; identifyParenthesis(str); return 0;} // Java program to mark balanced and// unbalanced parenthesis.import java.util.*; class GFG{static void identifyParenthesis(StringBuffer a){ Stack<Integer> st = new Stack<Integer>(); // run the loop upto end of the string for (int i = 0; i < a.length(); i++) { // if a[i] is opening bracket then push // into stack if (a.charAt(i) == '(') st.push(i); // if a[i] is closing bracket ')' else if (a.charAt(i) == ')') { // If this closing bracket is unmatched if (st.empty()) a.replace(i, i + 1, "-1"); else { // replace all opening brackets with 0 // and closing brackets with 1 a.replace(i, i + 1, "1"); a.replace(st.peek(), st.peek() + 1, "0"); st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (!st.empty()) { a.replace(st.peek(), 1, "-1"); st.pop(); } // print final string System.out.println(a);} // Driver codepublic static void main(String[] args){ StringBuffer str = new StringBuffer("(a))"); identifyParenthesis(str);}} // This code is contributed by Princi Singh # Python3 program to# mark balanced and# unbalanced parenthesis.def identifyParenthesis(a): st = [] # run the loop upto # end of the string for i in range (len(a)): # if a[i] is opening # bracket then push # into stack if (a[i] == '('): st.append(a[i]) # if a[i] is closing bracket ')' elif (a[i] == ')'): # If this closing bracket # is unmatched if (len(st) == 0): a = a.replace(a[i], "-1", 1) else: # replace all opening brackets with 0 # and closing brackets with 1 a = a.replace(a[i], "1", 1) a = a.replace(st[-1], "0", 1) st.pop() # if stack is not empty # then pop out all # elements from it and # replace -1 at that # index of the string while (len(st) != 0): a = a.replace(st[-1], 1, "-1"); st.pop() # print final string print(a) # Driver codeif __name__ == "__main__": st = "(a))" identifyParenthesis(st) # This code is contributed by Chitranayal // C# program to mark balanced and// unbalanced parenthesis.using System;using System.Collections.Generic;class GFG { static void identifyParenthesis(string a) { Stack<int> st = new Stack<int>(); // run the loop upto end of the string for (int i = 0; i < a.Length; i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.Push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.Count == 0) { a = a.Substring(0, i) + "-1" + a.Substring(i + 1); } else { // replace all opening brackets with 0 // and closing brackets with 1 a = a.Substring(0, i) + "1" + a.Substring(i + 1); a = a.Substring(0, st.Peek()) + "0" + a.Substring(st.Peek() + 1); st.Pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (st.Count > 0) { a = a.Substring(0, st.Peek()) + "-1" + a.Substring(st.Peek() + 1); st.Pop(); } // print final string Console.Write(new string(a)); } static void Main() { string str = "(a))"; identifyParenthesis(str); }} // This code is contributed by divyesh072019. <script> // Javascript program to mark balanced and // unbalanced parenthesis. function identifyParenthesis(a) { let st = []; // run the loop upto end of the string for (let i = 0; i < a.length; i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.length == 0) { a[i] = "-1"; } else { // replace all opening brackets with 0 // and closing brackets with 1 a[i] = "1"; a[st[st.length - 1]] = "0"; st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (st.length > 0) { a[st[st.length - 1]] = "-1"; st.pop(); } // print final string document.write(a.join("")); } let str = "(a))"; identifyParenthesis(str.split('')); // This code is contributed by suresh07.</script> Output: 0a1-1 HARDY_123 princi singh ukasp suresh07 divyesh072019 cpp-stack Stack Strings Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Real-time application of Data Structures Sort a stack using a temporary stack Reverse individual words Iterative Tower of Hanoi ZigZag Tree Traversal Reverse a string in Java Write a program to reverse an array or string C++ Data Types Write a program to print all permutations of a given string Longest Common Subsequence | DP-4
[ { "code": null, "e": 24686, "s": 24658, "text": "\n31 Aug, 2021" }, { "code": null, "e": 24898, "s": 24686, "text": "Given an expression, find and mark matched and unmatched parenthesis in it. We need to replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1, and all unbalanced with -1.Examples: " }, { "code": null, "e": 25011, "s": 24898, "text": "Input : ((a) \nOutput : -10a1\n\nInput : (a))\nOutput : 0a1-1\n\nInput : (((abc))((d)))))\nOutput : 000abc1100d111-1-1" }, { "code": null, "e": 25347, "s": 25011, "text": "The idea is based on a stack. We run a loop from the start of the string Up to end and for every ‘(‘, we push it into a stack. If the stack is empty, and we encounter a closing bracket ‘)’ we replace -1 at that index of the string. Else we replace all opening brackets ‘(‘ with 0 and closing brackets with 1. Then pop from the stack. " }, { "code": null, "e": 25351, "s": 25347, "text": "C++" }, { "code": null, "e": 25356, "s": 25351, "text": "Java" }, { "code": null, "e": 25364, "s": 25356, "text": "Python3" }, { "code": null, "e": 25367, "s": 25364, "text": "C#" }, { "code": null, "e": 25378, "s": 25367, "text": "Javascript" }, { "code": "// CPP program to mark balanced and unbalanced// parenthesis.#include <bits/stdc++.h>using namespace std; void identifyParenthesis(string a){ stack<int> st; // run the loop upto end of the string for (int i = 0; i < a.length(); i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.empty()) a.replace(i, 1, \"-1\"); else { // replace all opening brackets with 0 // and closing brackets with 1 a.replace(i, 1, \"1\"); a.replace(st.top(), 1, \"0\"); st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (!st.empty()) { a.replace(st.top(), 1, \"-1\"); st.pop(); } // print final string cout << a << endl;} // Driver codeint main(){ string str = \"(a))\"; identifyParenthesis(str); return 0;}", "e": 26546, "s": 25378, "text": null }, { "code": "// Java program to mark balanced and// unbalanced parenthesis.import java.util.*; class GFG{static void identifyParenthesis(StringBuffer a){ Stack<Integer> st = new Stack<Integer>(); // run the loop upto end of the string for (int i = 0; i < a.length(); i++) { // if a[i] is opening bracket then push // into stack if (a.charAt(i) == '(') st.push(i); // if a[i] is closing bracket ')' else if (a.charAt(i) == ')') { // If this closing bracket is unmatched if (st.empty()) a.replace(i, i + 1, \"-1\"); else { // replace all opening brackets with 0 // and closing brackets with 1 a.replace(i, i + 1, \"1\"); a.replace(st.peek(), st.peek() + 1, \"0\"); st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (!st.empty()) { a.replace(st.peek(), 1, \"-1\"); st.pop(); } // print final string System.out.println(a);} // Driver codepublic static void main(String[] args){ StringBuffer str = new StringBuffer(\"(a))\"); identifyParenthesis(str);}} // This code is contributed by Princi Singh", "e": 27888, "s": 26546, "text": null }, { "code": "# Python3 program to# mark balanced and# unbalanced parenthesis.def identifyParenthesis(a): st = [] # run the loop upto # end of the string for i in range (len(a)): # if a[i] is opening # bracket then push # into stack if (a[i] == '('): st.append(a[i]) # if a[i] is closing bracket ')' elif (a[i] == ')'): # If this closing bracket # is unmatched if (len(st) == 0): a = a.replace(a[i], \"-1\", 1) else: # replace all opening brackets with 0 # and closing brackets with 1 a = a.replace(a[i], \"1\", 1) a = a.replace(st[-1], \"0\", 1) st.pop() # if stack is not empty # then pop out all # elements from it and # replace -1 at that # index of the string while (len(st) != 0): a = a.replace(st[-1], 1, \"-1\"); st.pop() # print final string print(a) # Driver codeif __name__ == \"__main__\": st = \"(a))\" identifyParenthesis(st) # This code is contributed by Chitranayal", "e": 29030, "s": 27888, "text": null }, { "code": "// C# program to mark balanced and// unbalanced parenthesis.using System;using System.Collections.Generic;class GFG { static void identifyParenthesis(string a) { Stack<int> st = new Stack<int>(); // run the loop upto end of the string for (int i = 0; i < a.Length; i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.Push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.Count == 0) { a = a.Substring(0, i) + \"-1\" + a.Substring(i + 1); } else { // replace all opening brackets with 0 // and closing brackets with 1 a = a.Substring(0, i) + \"1\" + a.Substring(i + 1); a = a.Substring(0, st.Peek()) + \"0\" + a.Substring(st.Peek() + 1); st.Pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (st.Count > 0) { a = a.Substring(0, st.Peek()) + \"-1\" + a.Substring(st.Peek() + 1); st.Pop(); } // print final string Console.Write(new string(a)); } static void Main() { string str = \"(a))\"; identifyParenthesis(str); }} // This code is contributed by divyesh072019.", "e": 30612, "s": 29030, "text": null }, { "code": "<script> // Javascript program to mark balanced and // unbalanced parenthesis. function identifyParenthesis(a) { let st = []; // run the loop upto end of the string for (let i = 0; i < a.length; i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.length == 0) { a[i] = \"-1\"; } else { // replace all opening brackets with 0 // and closing brackets with 1 a[i] = \"1\"; a[st[st.length - 1]] = \"0\"; st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (st.length > 0) { a[st[st.length - 1]] = \"-1\"; st.pop(); } // print final string document.write(a.join(\"\")); } let str = \"(a))\"; identifyParenthesis(str.split('')); // This code is contributed by suresh07.</script>", "e": 31956, "s": 30612, "text": null }, { "code": null, "e": 31966, "s": 31956, "text": "Output: " }, { "code": null, "e": 31972, "s": 31966, "text": "0a1-1" }, { "code": null, "e": 31984, "s": 31974, "text": "HARDY_123" }, { "code": null, "e": 31997, "s": 31984, "text": "princi singh" }, { "code": null, "e": 32003, "s": 31997, "text": "ukasp" }, { "code": null, "e": 32012, "s": 32003, "text": "suresh07" }, { "code": null, "e": 32026, "s": 32012, "text": "divyesh072019" }, { "code": null, "e": 32036, "s": 32026, "text": "cpp-stack" }, { "code": null, "e": 32042, "s": 32036, "text": "Stack" }, { "code": null, "e": 32050, "s": 32042, "text": "Strings" }, { "code": null, "e": 32058, "s": 32050, "text": "Strings" }, { "code": null, "e": 32064, "s": 32058, "text": "Stack" }, { "code": null, "e": 32162, "s": 32064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32171, "s": 32162, "text": "Comments" }, { "code": null, "e": 32184, "s": 32171, "text": "Old Comments" }, { "code": null, "e": 32225, "s": 32184, "text": "Real-time application of Data Structures" }, { "code": null, "e": 32262, "s": 32225, "text": "Sort a stack using a temporary stack" }, { "code": null, "e": 32287, "s": 32262, "text": "Reverse individual words" }, { "code": null, "e": 32312, "s": 32287, "text": "Iterative Tower of Hanoi" }, { "code": null, "e": 32334, "s": 32312, "text": "ZigZag Tree Traversal" }, { "code": null, "e": 32359, "s": 32334, "text": "Reverse a string in Java" }, { "code": null, "e": 32405, "s": 32359, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32420, "s": 32405, "text": "C++ Data Types" }, { "code": null, "e": 32480, "s": 32420, "text": "Write a program to print all permutations of a given string" } ]
D3.js zoom() Function - GeeksforGeeks
09 Sep, 2020 The d3.zoom() Function in D3.js is used to create a new zoom behaviour. It is used to apply the zoom transformation on a selected element. Syntax: d3.zoom(); Parameters: This function does not accept any parameter. Return Value: This function returns the zoom behaviour. Below programs illustrate the d3.zoom() function in D3.js Example 1: This example, Zooming and panning is done. Double click to zoom, the circle gets bigger. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"> </script> </head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | d3.zoom() Function</h3> <div id="GFG"></div> <script> var svg = d3.select("#GFG") .append("svg") .attr("width", 300) .attr("height", 300) .call(d3.zoom().on("zoom", function () { svg.attr("transform", d3.event.transform) })) .append("g") svg .append("circle") .attr("cx", 150) .attr("cy", 150) .attr("r", 40) .style("fill", "green") </script> </center></body> </html> Output: Example 2: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 20px sans-serif; text-anchor: center; } rect { pointer-events: all; } </style></head> <body> <center> <h1 style="color: green;"> Geeksforgeeks </h1> <h3>D3.js | d3.zoom() Function </h3> <svg></svg> <script> var width = 400; var height = 200; var svg = d3.select("svg") .attr("width", width) .attr("height", height); // The scale used to display the axis. var scale = d3.scaleLinear() .range([10, width-20]) .domain([0, 100]); var shadowScale = scale.copy(); var axis = d3.axisBottom() .scale(scale); var g = svg.append("g") .attr("transform", "translate(0, 50)") .call(axis); // Standard zoom behavior: var zoom = d3.zoom() .scaleExtent([1, 10]) .translateExtent([[0, 0], [width, height]]) .on("zoom", zoomed); // Call the Zoom. svg.call(zoom); </script> </center></body> </html> Output: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26012, "s": 25984, "text": "\n09 Sep, 2020" }, { "code": null, "e": 26151, "s": 26012, "text": "The d3.zoom() Function in D3.js is used to create a new zoom behaviour. It is used to apply the zoom transformation on a selected element." }, { "code": null, "e": 26159, "s": 26151, "text": "Syntax:" }, { "code": null, "e": 26170, "s": 26159, "text": "d3.zoom();" }, { "code": null, "e": 26227, "s": 26170, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 26283, "s": 26227, "text": "Return Value: This function returns the zoom behaviour." }, { "code": null, "e": 26341, "s": 26283, "text": "Below programs illustrate the d3.zoom() function in D3.js" }, { "code": null, "e": 26441, "s": 26341, "text": "Example 1: This example, Zooming and panning is done. Double click to zoom, the circle gets bigger." }, { "code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> </head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | d3.zoom() Function</h3> <div id=\"GFG\"></div> <script> var svg = d3.select(\"#GFG\") .append(\"svg\") .attr(\"width\", 300) .attr(\"height\", 300) .call(d3.zoom().on(\"zoom\", function () { svg.attr(\"transform\", d3.event.transform) })) .append(\"g\") svg .append(\"circle\") .attr(\"cx\", 150) .attr(\"cy\", 150) .attr(\"r\", 40) .style(\"fill\", \"green\") </script> </center></body> </html> ", "e": 27331, "s": 26441, "text": null }, { "code": null, "e": 27339, "s": 27331, "text": "Output:" }, { "code": null, "e": 27350, "s": 27339, "text": "Example 2:" }, { "code": "<!DOCTYPE html> <html> <head> <meta charset=\"utf-8\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 20px sans-serif; text-anchor: center; } rect { pointer-events: all; } </style></head> <body> <center> <h1 style=\"color: green;\"> Geeksforgeeks </h1> <h3>D3.js | d3.zoom() Function </h3> <svg></svg> <script> var width = 400; var height = 200; var svg = d3.select(\"svg\") .attr(\"width\", width) .attr(\"height\", height); // The scale used to display the axis. var scale = d3.scaleLinear() .range([10, width-20]) .domain([0, 100]); var shadowScale = scale.copy(); var axis = d3.axisBottom() .scale(scale); var g = svg.append(\"g\") .attr(\"transform\", \"translate(0, 50)\") .call(axis); // Standard zoom behavior: var zoom = d3.zoom() .scaleExtent([1, 10]) .translateExtent([[0, 0], [width, height]]) .on(\"zoom\", zoomed); // Call the Zoom. svg.call(zoom); </script> </center></body> </html>", "e": 28841, "s": 27350, "text": null }, { "code": null, "e": 28849, "s": 28841, "text": "Output:" }, { "code": null, "e": 28855, "s": 28849, "text": "D3.js" }, { "code": null, "e": 28866, "s": 28855, "text": "JavaScript" }, { "code": null, "e": 28883, "s": 28866, "text": "Web Technologies" }, { "code": null, "e": 28981, "s": 28883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29026, "s": 28981, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29087, "s": 29026, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29159, "s": 29087, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29205, "s": 29159, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 29246, "s": 29205, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29288, "s": 29246, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29321, "s": 29288, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29364, "s": 29321, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29426, "s": 29364, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Python – List product excluding duplicates
06 Oct, 2021 This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicated and finding its product. This operations has large no. of applications and hence it’s knowledge is good to have.Method 1 : Naive method In naive method, we simply traverse the list and append the first occurrence of the element in new list and ignore all the other occurrences of that particular element. The task of performing product is done using loop. Python3 # Python 3 code to demonstrate# Duplication Removal List Product# using naive methods # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print ("The original list is : " + str(test_list)) # using naive method# Duplication Removal List Productres = []for i in test_list: if i not in res: res.append(i)res = prod(res) # printing list after removalprint ("Duplication removal list product : " + str(res)) The original list is : [1, 3, 5, 6, 3, 5, 6, 1] Duplication removal list product : 90 Method 2 : Using list comprehension This method has working similar to the above method, but this is just a one-liner shorthand of longer method done with the help of list comprehension. Python3 # Python 3 code to demonstrate# Duplication Removal List Product# using list comprehension # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print ("The original list is : " + str(test_list)) # using list comprehension# Duplication Removal List Productres = [][res.append(x) for x in test_list if x not in res]res = prod(res) # printing list after removalprint ("Duplication removal list product : " + str(res)) The original list is : [1, 3, 5, 6, 3, 5, 6, 1] Duplication removal list product : 90 Method 3: Using set() and functools.reduce() [Intermediate] Checking for list membership is O(n) on average, so building up the list of non-duplicates becomes an O(n2) operation on average. One can transform a list into a set to remove the duplicates which is O(n) complexity. After this the product of the set elements can be calculated in the usual fashion by iterating over them or, to further reduce the code, the reduce() method from functools module can be used. As the documentation explains: Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. Here’s how the code can be reduced to a couple of lines Python3 import functools functools.reduce(lambda x, y: x*y, set([1, 3, 5, 6, 3, 5, 6, 1]), 1) What this does is applies a lambda to the set obtained from the list. The lambda takes in two arguments x, and y and returns the product of the two numbers. This lambda is applied to all the elements in the list cumulatively i.e. lambda(lambda(lambda(1, 3), 5), 6).... which yields the final product as 90. It’s always prudent to add in an initial argument to the reduce() function to handle empty sequences so that the default value can be returned. In this case, since it’s a product, that value should be 1. Thus something like functools.reduce(lambda x,y: x*y, set([]), 1) yields the output 1, despite the list being empty. This initial argument is added before the values in the sequence and the lambda is applied as usual. lambda(lambda(lambda(lambda(1,1 ), 3), 5), 6).... Zoso Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Oct, 2021" }, { "code": null, "e": 529, "s": 52, "text": "This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicated and finding its product. This operations has large no. of applications and hence it’s knowledge is good to have.Method 1 : Naive method In naive method, we simply traverse the list and append the first occurrence of the element in new list and ignore all the other occurrences of that particular element. The task of performing product is done using loop. " }, { "code": null, "e": 537, "s": 529, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# Duplication Removal List Product# using naive methods # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print (\"The original list is : \" + str(test_list)) # using naive method# Duplication Removal List Productres = []for i in test_list: if i not in res: res.append(i)res = prod(res) # printing list after removalprint (\"Duplication removal list product : \" + str(res))", "e": 1049, "s": 537, "text": null }, { "code": null, "e": 1135, "s": 1049, "text": "The original list is : [1, 3, 5, 6, 3, 5, 6, 1]\nDuplication removal list product : 90" }, { "code": null, "e": 1327, "s": 1137, "text": " Method 2 : Using list comprehension This method has working similar to the above method, but this is just a one-liner shorthand of longer method done with the help of list comprehension. " }, { "code": null, "e": 1335, "s": 1327, "text": "Python3" }, { "code": "# Python 3 code to demonstrate# Duplication Removal List Product# using list comprehension # getting Productdef prod(val) : res = 1 for ele in val: res *= ele return res # initializing listtest_list = [1, 3, 5, 6, 3, 5, 6, 1]print (\"The original list is : \" + str(test_list)) # using list comprehension# Duplication Removal List Productres = [][res.append(x) for x in test_list if x not in res]res = prod(res) # printing list after removalprint (\"Duplication removal list product : \" + str(res))", "e": 1848, "s": 1335, "text": null }, { "code": null, "e": 1934, "s": 1848, "text": "The original list is : [1, 3, 5, 6, 3, 5, 6, 1]\nDuplication removal list product : 90" }, { "code": null, "e": 1996, "s": 1936, "text": "Method 3: Using set() and functools.reduce() [Intermediate]" }, { "code": null, "e": 2437, "s": 1996, "text": "Checking for list membership is O(n) on average, so building up the list of non-duplicates becomes an O(n2) operation on average. One can transform a list into a set to remove the duplicates which is O(n) complexity. After this the product of the set elements can be calculated in the usual fashion by iterating over them or, to further reduce the code, the reduce() method from functools module can be used. As the documentation explains:" }, { "code": null, "e": 2576, "s": 2437, "text": "Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value." }, { "code": null, "e": 2632, "s": 2576, "text": "Here’s how the code can be reduced to a couple of lines" }, { "code": null, "e": 2640, "s": 2632, "text": "Python3" }, { "code": "import functools functools.reduce(lambda x, y: x*y, set([1, 3, 5, 6, 3, 5, 6, 1]), 1)", "e": 2726, "s": 2640, "text": null }, { "code": null, "e": 2956, "s": 2726, "text": "What this does is applies a lambda to the set obtained from the list. The lambda takes in two arguments x, and y and returns the product of the two numbers. This lambda is applied to all the elements in the list cumulatively i.e." }, { "code": null, "e": 2995, "s": 2956, "text": "lambda(lambda(lambda(1, 3), 5), 6)...." }, { "code": null, "e": 3257, "s": 2995, "text": "which yields the final product as 90. It’s always prudent to add in an initial argument to the reduce() function to handle empty sequences so that the default value can be returned. In this case, since it’s a product, that value should be 1. Thus something like" }, { "code": null, "e": 3303, "s": 3257, "text": "functools.reduce(lambda x,y: x*y, set([]), 1)" }, { "code": null, "e": 3455, "s": 3303, "text": "yields the output 1, despite the list being empty. This initial argument is added before the values in the sequence and the lambda is applied as usual." }, { "code": null, "e": 3505, "s": 3455, "text": "lambda(lambda(lambda(lambda(1,1 ), 3), 5), 6)...." }, { "code": null, "e": 3510, "s": 3505, "text": "Zoso" }, { "code": null, "e": 3531, "s": 3510, "text": "Python list-programs" }, { "code": null, "e": 3538, "s": 3531, "text": "Python" }, { "code": null, "e": 3554, "s": 3538, "text": "Python Programs" }, { "code": null, "e": 3652, "s": 3554, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3684, "s": 3652, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3711, "s": 3684, "text": "Python Classes and Objects" }, { "code": null, "e": 3732, "s": 3711, "text": "Python OOPs Concepts" }, { "code": null, "e": 3755, "s": 3732, "text": "Introduction To PYTHON" }, { "code": null, "e": 3786, "s": 3755, "text": "Python | os.path.join() method" }, { "code": null, "e": 3808, "s": 3786, "text": "Defaultdict in Python" }, { "code": null, "e": 3847, "s": 3808, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3885, "s": 3847, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3934, "s": 3885, "text": "Python | Convert string dictionary to dictionary" } ]
Affinity Propagation in ML | To find the number of clusters - GeeksforGeeks
14 May, 2019 Affinity Propagation creates clusters by sending messages between data points until convergence. Unlike clustering algorithms such as k-means or k-medoids, affinity propagation does not require the number of clusters to be determined or estimated before running the algorithm, for this purpose the two important parameters are the preference, which controls how many exemplars (or prototypes) are used, and the damping factor which damps the responsibility and availability of messages to avoid numerical oscillations when updating these messages. A dataset is described using a small number of exemplars, ‘exemplars’ are members of the input set that are representative of clusters. The messages sent between pairs represent the suitability for one sample to be the exemplar of the other, which is updated in response to the values from other pairs. This updating happens iteratively until convergence, at that point the final exemplars are chosen, and hence we obtain the final clustering. Algorithm for Affinity Propagation: Input: Given a dataset D = {d1, d2, d3, .....dn}s is a NxN matrix such that s(i, j) represents the similarity between di and dj. The negative squared distance of two data points was used as s i.e. for points xi and xj, s(i, j)= -||xi-xj||2 .The diagonal of s i.e. s(i, i) is particularly important, as it represents the input preference, meaning how likely a particular input is to become an exemplar. When it is set to the same value for all inputs, it controls how many classes the algorithm produces. A value close to the minimum possible similarity produces fewer classes, while a value close to or larger than the maximum possible similarity, produces many classes. It is typically initialized to the median similarity of all pairs of inputs. The algorithm proceeds by alternating two message passing steps, to update two matrices: The “responsibility” matrix R has values r(i, k) that quantify how well-suited xk is to serve as the exemplar for xi, relative to other candidate exemplars for xi. The “availability” matrix A contains values a(i, k) that represent how “appropriate” it would be for xi to pick xk as its exemplar, taking into account other points’ preference for xk as an exemplar. Both matrices are initialized to all zeroes. The algorithm then performs the following updates iteratively: First, responsibility updates are sent around Then, availability is updated per The iterations are performed until either the cluster boundaries remain unchanged over a number of iterations, or after some predetermined number of iterations. The exemplars are extracted from the final matrices as those whose ‘responsibility + availability’ for themselves is positive (i.e. (r(i, i) + a(i, i)) > 0). Below is the Python implementation of the Affinity Propagation clustering using scikit-learn library: from sklearn.cluster import AffinityPropagationfrom sklearn import metricsfrom sklearn.datasets.samples_generator import make_blobs # Generate sample datacenters = [[1, 1], [-1, -1], [1, -1], [-1, -1]]X, labels_true = make_blobs(n_samples = 400, centers = centers, cluster_std = 0.5, random_state = 0) # Compute Affinity Propagationaf = AffinityPropagation(preference =-50).fit(X)cluster_centers_indices = af.cluster_centers_indices_labels = af.labels_ n_clusters_ = len(cluster_centers_indices) # Plot resultimport matplotlib.pyplot as pltfrom itertools import cycle plt.close('all')plt.figure(1)plt.clf() colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): class_members = labels == k cluster_center = X[cluster_centers_indices[k]] plt.plot(X[class_members, 0], X[class_members, 1], col + '.') plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor = col, markeredgecolor ='k', markersize = 14) for x in X[class_members]: plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) plt.title('Estimated number of clusters: % d' % n_clusters_)plt.show() Output: Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Difference between Informed and Uninformed Search in AI Normalization vs Standardization Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24344, "s": 24316, "text": "\n14 May, 2019" }, { "code": null, "e": 24892, "s": 24344, "text": "Affinity Propagation creates clusters by sending messages between data points until convergence. Unlike clustering algorithms such as k-means or k-medoids, affinity propagation does not require the number of clusters to be determined or estimated before running the algorithm, for this purpose the two important parameters are the preference, which controls how many exemplars (or prototypes) are used, and the damping factor which damps the responsibility and availability of messages to avoid numerical oscillations when updating these messages." }, { "code": null, "e": 25372, "s": 24892, "text": "A dataset is described using a small number of exemplars, ‘exemplars’ are members of the input set that are representative of clusters. The messages sent between pairs represent the suitability for one sample to be the exemplar of the other, which is updated in response to the values from other pairs. This updating happens iteratively until convergence, at that point the final exemplars are chosen, and hence we obtain the final clustering. Algorithm for Affinity Propagation:" }, { "code": null, "e": 26120, "s": 25372, "text": "Input: Given a dataset D = {d1, d2, d3, .....dn}s is a NxN matrix such that s(i, j) represents the similarity between di and dj. The negative squared distance of two data points was used as s i.e. for points xi and xj, s(i, j)= -||xi-xj||2 .The diagonal of s i.e. s(i, i) is particularly important, as it represents the input preference, meaning how likely a particular input is to become an exemplar. When it is set to the same value for all inputs, it controls how many classes the algorithm produces. A value close to the minimum possible similarity produces fewer classes, while a value close to or larger than the maximum possible similarity, produces many classes. It is typically initialized to the median similarity of all pairs of inputs." }, { "code": null, "e": 26209, "s": 26120, "text": "The algorithm proceeds by alternating two message passing steps, to update two matrices:" }, { "code": null, "e": 26373, "s": 26209, "text": "The “responsibility” matrix R has values r(i, k) that quantify how well-suited xk is to serve as the exemplar for xi, relative to other candidate exemplars for xi." }, { "code": null, "e": 26573, "s": 26373, "text": "The “availability” matrix A contains values a(i, k) that represent how “appropriate” it would be for xi to pick xk as its exemplar, taking into account other points’ preference for xk as an exemplar." }, { "code": null, "e": 26681, "s": 26573, "text": "Both matrices are initialized to all zeroes. The algorithm then performs the following updates iteratively:" }, { "code": null, "e": 26727, "s": 26681, "text": "First, responsibility updates are sent around" }, { "code": null, "e": 26761, "s": 26727, "text": "Then, availability is updated per" }, { "code": null, "e": 27182, "s": 26761, "text": "The iterations are performed until either the cluster boundaries remain unchanged over a number of iterations, or after some predetermined number of iterations. The exemplars are extracted from the final matrices as those whose ‘responsibility + availability’ for themselves is positive (i.e. (r(i, i) + a(i, i)) > 0). Below is the Python implementation of the Affinity Propagation clustering using scikit-learn library:" }, { "code": "from sklearn.cluster import AffinityPropagationfrom sklearn import metricsfrom sklearn.datasets.samples_generator import make_blobs # Generate sample datacenters = [[1, 1], [-1, -1], [1, -1], [-1, -1]]X, labels_true = make_blobs(n_samples = 400, centers = centers, cluster_std = 0.5, random_state = 0) # Compute Affinity Propagationaf = AffinityPropagation(preference =-50).fit(X)cluster_centers_indices = af.cluster_centers_indices_labels = af.labels_ n_clusters_ = len(cluster_centers_indices)", "e": 27707, "s": 27182, "text": null }, { "code": "# Plot resultimport matplotlib.pyplot as pltfrom itertools import cycle plt.close('all')plt.figure(1)plt.clf() colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): class_members = labels == k cluster_center = X[cluster_centers_indices[k]] plt.plot(X[class_members, 0], X[class_members, 1], col + '.') plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor = col, markeredgecolor ='k', markersize = 14) for x in X[class_members]: plt.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) plt.title('Estimated number of clusters: % d' % n_clusters_)plt.show()", "e": 28398, "s": 27707, "text": null }, { "code": null, "e": 28406, "s": 28398, "text": "Output:" }, { "code": null, "e": 28423, "s": 28406, "text": "Machine Learning" }, { "code": null, "e": 28430, "s": 28423, "text": "Python" }, { "code": null, "e": 28447, "s": 28430, "text": "Machine Learning" }, { "code": null, "e": 28545, "s": 28447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28578, "s": 28545, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28617, "s": 28578, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 28652, "s": 28617, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 28708, "s": 28652, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 28741, "s": 28708, "text": "Normalization vs Standardization" }, { "code": null, "e": 28769, "s": 28741, "text": "Read JSON file using Python" }, { "code": null, "e": 28819, "s": 28769, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28841, "s": 28819, "text": "Python map() function" } ]
Python - Convert a list of lists into tree-like dict
Given a nested list we want to convert it to a dictionary whose elements can be considered as part of a tree data structure. In this article we will see the two approaches to convert a nested list into to add dictionary whose elements represent a tree like data structure. We reverse the items in the list aby slicing and then check if the item is present in the list. If it is not present we ignore it else we add it to the tree. def CreateTree(lst): new_tree = {} for list_item in lst: currTree = new_tree for key in list_item[::-1]: if key not in currTree: currTree[key] = {} currTree = currTree[key] return new_tree # Given list listA = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']] print(CreateTree(listA)) Running the above code gives us the following result − {'X': {'Y': {}, 'Z': {'P': {}}}} We use the functools and operator module to get the functions reduce and getitem. Using these functions we define two functions to get the items from the list and set the items into a tree structure. Here also we use the slicing approach to reverse the elements of the list and then apply the two created functions to create the dictionaries whose elements are in tree structure. from functools import reduce from operator import getitem def getTree(tree, mappings): return reduce(getitem, mappings, tree) def setTree(tree, mappings): getTree(tree, mappings[:-1])[mappings[-1]] = dict() # Given list lst = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']] tree = {} for i in lst: setTree(tree, i[::-1]) print(tree) Running the above code gives us the following result − {'X': {'Y': {}, 'Z': {'P': {}}}}
[ { "code": null, "e": 1335, "s": 1062, "text": "Given a nested list we want to convert it to a dictionary whose elements can be considered as part of a tree data structure. In this article we will see the two approaches to convert a nested list into to add dictionary whose elements represent a tree like data structure." }, { "code": null, "e": 1493, "s": 1335, "text": "We reverse the items in the list aby slicing and then check if the item is present in the list. If it is not present we ignore it else we add it to the tree." }, { "code": null, "e": 1832, "s": 1493, "text": "def CreateTree(lst):\n new_tree = {}\n for list_item in lst:\n currTree = new_tree\n\n for key in list_item[::-1]:\n if key not in currTree:\n currTree[key] = {}\n currTree = currTree[key]\n return new_tree\n# Given list\nlistA = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]\nprint(CreateTree(listA))" }, { "code": null, "e": 1887, "s": 1832, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1920, "s": 1887, "text": "{'X': {'Y': {}, 'Z': {'P': {}}}}" }, { "code": null, "e": 2300, "s": 1920, "text": "We use the functools and operator module to get the functions reduce and getitem. Using these functions we define two functions to get the items from the list and set the items into a tree structure. Here also we use the slicing approach to reverse the elements of the list and then apply the two created functions to create the dictionaries whose elements are in tree structure." }, { "code": null, "e": 2646, "s": 2300, "text": "from functools import reduce\nfrom operator import getitem\n\ndef getTree(tree, mappings):\n return reduce(getitem, mappings, tree)\n\ndef setTree(tree, mappings):\n getTree(tree, mappings[:-1])[mappings[-1]] = dict()\n\n# Given list\nlst = [['X'], ['Y', 'X'], ['Z', 'X'], ['P', 'Z', 'X']]\ntree = {}\nfor i in lst:\n setTree(tree, i[::-1])\nprint(tree)" }, { "code": null, "e": 2701, "s": 2646, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2734, "s": 2701, "text": "{'X': {'Y': {}, 'Z': {'P': {}}}}" } ]
GATE | GATE CS 2010 | Question 65 - GeeksforGeeks
28 Jun, 2021 A system has n resources R0,...,Rn-1,and k processes P0,....Pk-1.The implementation of the resource request logic of each process Pi is as follows: if (i % 2 == 0) { if (i < n) request Ri if (i+2 < n) request Ri+2 } else { if (i < n) request Rn-i if (i+2 < n) request Rn-i-2 } In which one of the following situations is a deadlock possible?(A) n=40, k=26(B) n=21, k=12(C) n=20, k=10(D) n=41, k=19Answer: (B)Explanation: Option B is answer No. of resources, n = 21 No. of processes, k = 12 Processes {P0, P1....P11} make the following Resource requests: {R0, R20, R2, R18, R4, R16, R6, R14, R8, R12, R10, R10} For example P0 will request R0 (0%2 is = 0 and 0< n=21). Similarly, P10 will request R10. P11 will request R10 as n - i = 21 - 11 = 10. As different processes are requesting the same resource, deadlock may occur. Quiz of this Question GATE-CS-2010 GATE-GATE CS 2010 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE CS 2019 | Question 27 GATE | GATE-IT-2004 | Question 66 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE-CS-2006 | Question 49 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2000 | Question 43 GATE | GATE-CS-2017 (Set 2) | Question 42 GATE | GATE CS 2010 | Question 24 GATE | Gate IT 2007 | Question 30
[ { "code": null, "e": 24540, "s": 24512, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24689, "s": 24540, "text": "A system has n resources R0,...,Rn-1,and k processes P0,....Pk-1.The implementation of the resource request logic of each process Pi is as follows: " }, { "code": null, "e": 24843, "s": 24689, "text": " if (i % 2 == 0) {\n if (i < n) request Ri\n if (i+2 < n) request Ri+2\n}\nelse {\n if (i < n) request Rn-i\n if (i+2 < n) request Rn-i-2\n}" }, { "code": null, "e": 24987, "s": 24843, "text": "In which one of the following situations is a deadlock possible?(A) n=40, k=26(B) n=21, k=12(C) n=20, k=10(D) n=41, k=19Answer: (B)Explanation:" }, { "code": null, "e": 25398, "s": 24987, "text": "Option B is answer\n\nNo. of resources, n = 21\nNo. of processes, k = 12\n\nProcesses {P0, P1....P11} make the following Resource requests:\n{R0, R20, R2, R18, R4, R16, R6, R14, R8, R12, R10, R10}\n\nFor example P0 will request R0 (0%2 is = 0 and 0< n=21). \n\nSimilarly, P10 will request R10.\n\nP11 will request R10 as n - i = 21 - 11 = 10.\n\nAs different processes are requesting the same resource, deadlock\nmay occur. " }, { "code": null, "e": 25420, "s": 25398, "text": "Quiz of this Question" }, { "code": null, "e": 25433, "s": 25420, "text": "GATE-CS-2010" }, { "code": null, "e": 25451, "s": 25433, "text": "GATE-GATE CS 2010" }, { "code": null, "e": 25456, "s": 25451, "text": "GATE" }, { "code": null, "e": 25554, "s": 25456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25588, "s": 25554, "text": "GATE | GATE CS 2019 | Question 27" }, { "code": null, "e": 25622, "s": 25588, "text": "GATE | GATE-IT-2004 | Question 66" }, { "code": null, "e": 25664, "s": 25622, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 25698, "s": 25664, "text": "GATE | GATE-CS-2006 | Question 49" }, { "code": null, "e": 25740, "s": 25698, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 25773, "s": 25740, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25807, "s": 25773, "text": "GATE | GATE-CS-2000 | Question 43" }, { "code": null, "e": 25849, "s": 25807, "text": "GATE | GATE-CS-2017 (Set 2) | Question 42" }, { "code": null, "e": 25883, "s": 25849, "text": "GATE | GATE CS 2010 | Question 24" } ]
Find a triplet that sum to a given value in C++
In this tutorial, we are going to write a program that finds the triplet in the array whose sum is equal to the given number. Let's see the steps to solve the problem. Create the array with dummy data. Create the array with dummy data. Write three inner loops for three elements which iterate until the end of the array.Add the three elements.Compare the sum with the given number.If both are equal, then print the elements and break the loops. Write three inner loops for three elements which iterate until the end of the array. Add the three elements. Add the three elements. Compare the sum with the given number. Compare the sum with the given number. If both are equal, then print the elements and break the loops. If both are equal, then print the elements and break the loops. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; bool findTriplet(int arr[], int arr_size, int sum) { for (int i = 0; i < arr_size - 2; i++) { for (int j = i + 1; j < arr_size - 1; j++) { for (int k = j + 1; k < arr_size; k++) { if (arr[i] + arr[j] + arr[k] == sum) { cout << arr[i] << " " << arr[j] << " " << arr[k] << endl; return true; } } } } return false; } int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; findTriplet(arr, 7, 12); return 0; } If you execute the above program, then you will get the following result. 1 4 7 If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1188, "s": 1062, "text": "In this tutorial, we are going to write a program that finds the triplet in the array whose sum is equal to the given number." }, { "code": null, "e": 1230, "s": 1188, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1264, "s": 1230, "text": "Create the array with dummy data." }, { "code": null, "e": 1298, "s": 1264, "text": "Create the array with dummy data." }, { "code": null, "e": 1507, "s": 1298, "text": "Write three inner loops for three elements which iterate until the end of the array.Add the three elements.Compare the sum with the given number.If both are equal, then print the elements and break the loops." }, { "code": null, "e": 1592, "s": 1507, "text": "Write three inner loops for three elements which iterate until the end of the array." }, { "code": null, "e": 1616, "s": 1592, "text": "Add the three elements." }, { "code": null, "e": 1640, "s": 1616, "text": "Add the three elements." }, { "code": null, "e": 1679, "s": 1640, "text": "Compare the sum with the given number." }, { "code": null, "e": 1718, "s": 1679, "text": "Compare the sum with the given number." }, { "code": null, "e": 1782, "s": 1718, "text": "If both are equal, then print the elements and break the loops." }, { "code": null, "e": 1846, "s": 1782, "text": "If both are equal, then print the elements and break the loops." }, { "code": null, "e": 1866, "s": 1846, "text": "Let's see the code." }, { "code": null, "e": 1877, "s": 1866, "text": " Live Demo" }, { "code": null, "e": 2426, "s": 1877, "text": "#include <bits/stdc++.h>\nusing namespace std;\nbool findTriplet(int arr[], int arr_size, int sum) {\n for (int i = 0; i < arr_size - 2; i++) {\n for (int j = i + 1; j < arr_size - 1; j++) {\n for (int k = j + 1; k < arr_size; k++) {\n if (arr[i] + arr[j] + arr[k] == sum) {\n cout << arr[i] << \" \" << arr[j] << \" \" << arr[k] << endl;\n return true;\n }\n }\n }\n }\n return false;\n}\nint main() {\n int arr[] = { 1, 2, 3, 4, 5, 6, 7 };\n findTriplet(arr, 7, 12);\n return 0;\n}" }, { "code": null, "e": 2500, "s": 2426, "text": "If you execute the above program, then you will get the following result." }, { "code": null, "e": 2506, "s": 2500, "text": "1 4 7" }, { "code": null, "e": 2584, "s": 2506, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Getting the Cursor position in Tkinter Entry widget
We are already familiar with input forms where various single Entry fields are created to capture the user input. With Tkinter, we can also create a single input field using the Entry widget. Each character in the Entry field that the user enters is indexed. Thus, you can retrieve this index to get the current position of the cursor by using the index() method. To retrieve the current location of the cursor, you can pass the INSERT argument in this function. # Import required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter window win = Tk() win.geometry("700x350") win.title("Get the Cursor Position") # Create an instance of style class style=ttk.Style(win) # Function to retrieve the current position of the cursor def get_current_info(): print ("The cursor is at: ", entry.index(INSERT)) # Create an entry widget entry=ttk.Entry(win, width=18) entry.pack(pady=30) # Create a button widget button=ttk.Button(win, text="Get Info", command=get_current_info) button.pack(pady=30) win.mainloop() Running the above code will display a window with an Entry widget and a button which can be used to get the current index of the cursor. Type some text in the Entry widget and click the "Get Info" button. It will print the current location of the cursor on the console. The cursor is at: 15
[ { "code": null, "e": 1525, "s": 1062, "text": "We are already familiar with input forms where various single Entry fields are created to capture the user input. With Tkinter, we can also create a single input field using the Entry widget. Each character in the Entry field that the user enters is indexed. Thus, you can retrieve this index to get the current position of the cursor by using the index() method. To retrieve the current location of the cursor, you can pass the INSERT argument in this function." }, { "code": null, "e": 2112, "s": 1525, "text": "# Import required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter window\nwin = Tk()\nwin.geometry(\"700x350\")\nwin.title(\"Get the Cursor Position\")\n\n# Create an instance of style class\nstyle=ttk.Style(win)\n\n# Function to retrieve the current position of the cursor\ndef get_current_info():\n print (\"The cursor is at: \", entry.index(INSERT))\n\n# Create an entry widget\nentry=ttk.Entry(win, width=18)\nentry.pack(pady=30)\n\n\n# Create a button widget\nbutton=ttk.Button(win, text=\"Get Info\", command=get_current_info)\nbutton.pack(pady=30)\n\nwin.mainloop()" }, { "code": null, "e": 2249, "s": 2112, "text": "Running the above code will display a window with an Entry widget and a button which can be used to get the current index of the cursor." }, { "code": null, "e": 2382, "s": 2249, "text": "Type some text in the Entry widget and click the \"Get Info\" button. It will print the current location of the cursor on the console." }, { "code": null, "e": 2403, "s": 2382, "text": "The cursor is at: 15" } ]
JavaScript JSON.stringify() with Example
The JavaScript JSON.stringify() is used for converting JavaScript object into a string. It is particularly useful when sending data to a web server. Following is the code for JSON stringify() method − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; color: red; } </style> </head> <body> <h1>JSON.stringify()</h1> <div class="sample"></div> <div style="font-weight: bold;" class="result"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to convert the above object into a JSON string </h3> <script> let sampleEle = document.querySelector(".sample"); let resultEle = document.querySelector(".result"); let obj = {name: "Rohan",sports: ["Cricket", "Football"],Country: "India",}; sampleEle.innerHTML ="Name = " +obj.name +"<br>" +" Country = " +obj.Country + " <br>" +"sports = " +obj.sports; document.querySelector(".Btn").addEventListener("click", () => { resultEle.innerHTML = JSON.stringify(obj); }); </script> </body> </html> On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1211, "s": 1062, "text": "The JavaScript JSON.stringify() is used for converting JavaScript object into a string. It is particularly useful when sending data to a web server." }, { "code": null, "e": 1263, "s": 1211, "text": "Following is the code for JSON stringify() method −" }, { "code": null, "e": 1274, "s": 1263, "text": " Live Demo" }, { "code": null, "e": 2334, "s": 1274, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample {\n font-size: 18px;\n font-weight: 500;\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>JSON.stringify()</h1>\n<div class=\"sample\"></div>\n<div style=\"font-weight: bold;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to convert the above object into a JSON string\n</h3>\n<script>\n let sampleEle = document.querySelector(\".sample\");\n let resultEle = document.querySelector(\".result\");\n let obj = {name: \"Rohan\",sports: [\"Cricket\", \"Football\"],Country: \"India\",};\n sampleEle.innerHTML =\"Name = \" +obj.name +\"<br>\" +\" Country = \" +obj.Country +\n \" <br>\" +\"sports = \" +obj.sports;\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n resultEle.innerHTML = JSON.stringify(obj);\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2372, "s": 2334, "text": "On clicking the ‘CLICK HERE’ button −" } ]
How to select last 10 rows from MySQL?
To select last 10 rows from MySQL, we can use a subquery with SELECT statement and Limit concept. The following is an example. Creating a table. mysql> create table Last10RecordsDemo -> ( -> id int, -> name varchar(100) -> ); Query OK, 0 rows affected (0.75 sec) Inserting records into the table. mysql> insert into Last10RecordsDemo values(1,'John'),(2,'Carol'),(3,'Bob'),(4,'Sam'),(5,'David'),(6,'Taylor'); Query OK, 6 rows affected (0.12 sec) Records: 6 Duplicates: 0 Warnings: 0 mysql> insert into Last10RecordsDemo values(7,'Sam'),(8,'Justin'),(9,'Ramit'),(10,'Smith'),(11,'Clark'),(12,'Johnson'); Query OK, 6 rows affected (0.14 sec) Records: 6 Duplicates: 0 Warnings: 0 To display all records. mysql> select *from Last10RecordsDemo; The following is the output. +------+---------+ | id | name | +------+---------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Sam | | 5 | David | | 6 | Taylor | | 7 | Sam | | 8 | Justin | | 9 | Ramit | | 10 | Smith | | 11 | Clark | | 12 | Johnson | +------+---------+ 12 rows in set (0.00 sec) The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query. mysql> SELECT * FROM ( -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10 -> )Var1 -> -> ORDER BY id ASC; The following is the output that displays the last 10 records. +------+---------+ | id | name | +------+---------+ | 3 | Bob | | 4 | Sam | | 5 | David | | 6 | Taylor | | 7 | Sam | | 8 | Justin | | 9 | Ramit | | 10 | Smith | | 11 | Clark | | 12 | Johnson | +------+---------+ 10 rows in set (0.00 sec) We can match both records with the help of the SELECT statement.
[ { "code": null, "e": 1189, "s": 1062, "text": "To select last 10 rows from MySQL, we can use a subquery with SELECT statement and Limit concept. The following is an example." }, { "code": null, "e": 1207, "s": 1189, "text": "Creating a table." }, { "code": null, "e": 1337, "s": 1207, "text": "mysql> create table Last10RecordsDemo\n -> (\n -> id int,\n -> name varchar(100)\n -> );\nQuery OK, 0 rows affected (0.75 sec)" }, { "code": null, "e": 1371, "s": 1337, "text": "Inserting records into the table." }, { "code": null, "e": 1756, "s": 1371, "text": "mysql> insert into Last10RecordsDemo values(1,'John'),(2,'Carol'),(3,'Bob'),(4,'Sam'),(5,'David'),(6,'Taylor');\nQuery OK, 6 rows affected (0.12 sec)\nRecords: 6 Duplicates: 0 Warnings: 0\n\nmysql> insert into Last10RecordsDemo values(7,'Sam'),(8,'Justin'),(9,'Ramit'),(10,'Smith'),(11,'Clark'),(12,'Johnson');\nQuery OK, 6 rows affected (0.14 sec)\nRecords: 6 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1780, "s": 1756, "text": "To display all records." }, { "code": null, "e": 1819, "s": 1780, "text": "mysql> select *from Last10RecordsDemo;" }, { "code": null, "e": 1848, "s": 1819, "text": "The following is the output." }, { "code": null, "e": 2179, "s": 1848, "text": "+------+---------+\n| id | name |\n+------+---------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Bob |\n| 4 | Sam |\n| 5 | David |\n| 6 | Taylor |\n| 7 | Sam |\n| 8 | Justin |\n| 9 | Ramit |\n| 10 | Smith |\n| 11 | Clark |\n| 12 | Johnson |\n+------+---------+\n12 rows in set (0.00 sec)\n" }, { "code": null, "e": 2283, "s": 2179, "text": "The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause." }, { "code": null, "e": 2382, "s": 2283, "text": "SELECT * FROM (\n SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10\n)Var1\n ORDER BY id ASC;" }, { "code": null, "e": 2420, "s": 2382, "text": "Let us now implement the above query." }, { "code": null, "e": 2552, "s": 2420, "text": "mysql> SELECT * FROM (\n -> SELECT * FROM Last10RecordsDemo ORDER BY id DESC LIMIT 10\n -> )Var1\n ->\n -> ORDER BY id ASC;" }, { "code": null, "e": 2615, "s": 2552, "text": "The following is the output that displays the last 10 records." }, { "code": null, "e": 2908, "s": 2615, "text": "+------+---------+\n| id | name |\n+------+---------+\n| 3 | Bob |\n| 4 | Sam |\n| 5 | David |\n| 6 | Taylor |\n| 7 | Sam |\n| 8 | Justin |\n| 9 | Ramit |\n| 10 | Smith |\n| 11 | Clark |\n| 12 | Johnson |\n+------+---------+\n10 rows in set (0.00 sec)\n" }, { "code": null, "e": 2973, "s": 2908, "text": "We can match both records with the help of the SELECT statement." } ]
What are the Selection Modes in a JTable with Java?
Selection modes sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals. Let us see the selection modes one by one − The following is an example of Single Selection mode for a JTable. It allows you to select one cell at a time − package my; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP)); String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); table.setShowHorizontalLines(true); table.setGridColor(Color.orange); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } } This will produce the following output − The following is an example of Single Interval Selection mode for a JTable. It allows you to select one contiguous range of indices at a time − package my; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP)); String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); table.setShowHorizontalLines(true); table.setGridColor(Color.orange); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } } This will produce the following output − The following is an example of Multiple Interval Selection mode for a JTable. It allows you to select one or more contiguous ranges of indices at a time − package my; import java.awt.Color; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP)); String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); table.setShowHorizontalLines(true); table.setGridColor(Color.orange); table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } } This will produce the following output −
[ { "code": null, "e": 1240, "s": 1062, "text": "Selection modes sets the table's selection mode to allow only single selections, a single contiguous interval, or multiple intervals. Let us see the selection modes one by one −" }, { "code": null, "e": 1352, "s": 1240, "text": "The following is an example of Single Selection mode for a JTable. It allows you to select one cell at a time −" }, { "code": null, "e": 2571, "s": 1352, "text": "package my;\nimport java.awt.Color;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.ListSelectionModel;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER, TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n table.setShowHorizontalLines(true);\n table.setGridColor(Color.orange);\n table.setCellSelectionEnabled(true);\n table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2612, "s": 2571, "text": "This will produce the following output −" }, { "code": null, "e": 2756, "s": 2612, "text": "The following is an example of Single Interval Selection mode for a JTable. It allows you to select one contiguous range of indices at a time −" }, { "code": null, "e": 3978, "s": 2756, "text": "package my;\nimport java.awt.Color;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.ListSelectionModel;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER, TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n table.setShowHorizontalLines(true);\n table.setGridColor(Color.orange);\n table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 4019, "s": 3978, "text": "This will produce the following output −" }, { "code": null, "e": 4174, "s": 4019, "text": "The following is an example of Multiple Interval Selection mode for a JTable. It allows you to select one or more contiguous ranges of indices at a time −" }, { "code": null, "e": 5464, "s": 4174, "text": "package my;\nimport java.awt.Color;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTable;\nimport javax.swing.ListSelectionModel;\nimport javax.swing.border.TitledBorder;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame();\n JPanel panel = new JPanel();\n panel.setBorder(BorderFactory.createTitledBorder(\n BorderFactory.createEtchedBorder(), \"ODI Rankings\", TitledBorder.CENTER, TitledBorder.TOP));\n String[][] rec = {\n { \"1\", \"Steve\", \"AUS\" },\n { \"2\", \"Virat\", \"IND\" },\n { \"3\", \"Kane\", \"NZ\" },\n { \"4\", \"David\", \"AUS\" },\n { \"5\", \"Ben\", \"ENG\" },\n { \"6\", \"Eion\", \"ENG\" },\n };\n String[] header = { \"Rank\", \"Player\", \"Country\" };\n JTable table = new JTable(rec, header);\n table.setShowHorizontalLines(true);\n table.setGridColor(Color.orange);\n table.setCellSelectionEnabled(true); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);\n panel.add(new JScrollPane(table));\n frame.add(panel);\n frame.setSize(550, 400);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 5505, "s": 5464, "text": "This will produce the following output −" } ]
A Keras-Based Autoencoder for Anomaly Detection in Sequences | by Alon Agmon | Towards Data Science
Suppose that you have a very long list of string sequences, such as a list of amino acid structures (‘PHE-SER-CYS’, ‘GLN-ARG-SER’,...), product serial numbers (‘AB121E’, ‘AB323’, ‘DN176’...), or users UIDs, and you are required to create a validation process of some kind that will detect anomalies in this sequence. An anomaly might be a string that follows a slightly different or unusual format than the others (whether it was created by mistake or on purpose) or just one that is extremely rare. To make things even more interesting, suppose that you don't know what is the correct format or structure that sequences suppose to follow. This is a relatively common problem (though with an uncommon twist) that many data scientists usually approach using one of the popular unsupervised ML algorithms, such as DBScan, Isolation Forest, etc. Many of these algorithms typically do a good job in finding anomalies or outliers by singling out data points that are relatively far from the others or from areas in which most data points lie. Although autoencoders are also well-known for their anomaly detection capabilities, they work quite differently and are less common when it comes to problems of this sort. I will leave the explanations of what is exactly an autoencoder to the many insightful and well-written posts, and articles that are freely available online. Very very briefly (and please just read on if this doesn't make sense to you), just like other kinds of ML algorithms, autoencoders learn by creating different representations of data and by measuring how well these representations do in generating an expected outcome; and just like other kinds of neural network, autoencoders learn by creating different layers of such representations that allow them to learn more complex and sophisticated representations of data (which on my view is exactly what makes them superior for a task like ours). Autoencoders are a special form of a neural network, however, because the output that they attempt to generate is a reconstruction of the input they receive. An autoencoder starts with input data (i.e., a set of numbers) and then transforms it in different ways using a set of mathematical operations until it learns the parameters that it ought to use in order to reconstruct the same data (or get very close to it). In this learning process, an autoencoder essentially learns the format rules of the input data. And, that's exactly what makes it perform well as an anomaly detection mechanism in settings like ours. Using autoencoders to detect anomalies usually involves two main steps: First, we feed our data to an autoencoder and tune it until it is well trained to reconstruct the expected output with minimum error. An autoencoder that receives an input like 10,5,100 and returns 11,5,99, for example, is well-trained if we consider the reconstructed output as sufficiently close to the input and if the autoencoder is able to successfully reconstruct most of the data in this way. Second, we feed all our data again to our trained autoencoder and measure the error term of each reconstructed data point. In other words, we measure how “far” is the reconstructed data point from the actual datapoint. A well-trained autoencoder essentially learns how to reconstruct an input that follows a certain format, so if we give a badly formatted data point to a well-trained autoencoder then we are likely to get something that is quite different from our input, and a large error term. Let's get into the details. I should emphasize, though, that this is just one way that one can go about such a task using an autoencoder. There are other ways and technics to build autoencoders and you should experiment until you find the architecture that suits your project. These are the steps that I'm going to follow: Generate a set of random string sequences that follow a specified format, and add a few anomalies.Encode the sequences into numbers and scale them.Design, fit, and tune an autoencoder.Feed the sequences to the trained autoencoder and calculate the error term of each data point.Find the anomalies by finding the data points with the highest error term.Generate a long sequence of strings. Generate a set of random string sequences that follow a specified format, and add a few anomalies. Encode the sequences into numbers and scale them. Design, fit, and tune an autoencoder. Feed the sequences to the trained autoencoder and calculate the error term of each data point. Find the anomalies by finding the data points with the highest error term. Generate a long sequence of strings. We're gonna start by writing a function that creates strings of the following format: CEBF0ZPQ ([4 letters A-F][1 digit 0–2][3 letters QWOPZXML]), and generate 25K sequences of this format. 2. Encode the string sequences into numbers and scale them Now we have an array of the following shape as every string sequence has 8 characters, each of which is encoded as a number which we will treat as a column. encoded_seqs.shape#(25005,8) Finally, before feeding the data to the autoencoder I'm going to scale the data using a MinMaxScaler, and split it into a training and test set. Proper scaling can often significantly improve the performance of NNs so it is important to experiment with more than one method. 3. Design, fit and tune the autoencoder. As mentioned earlier, there is more than one way to design an autoencoder. It is usually based on small hidden layers wrapped with larger layers (this is what creates the encoding-decoding effect). I have made a few tuning sessions in order to determine the best params to use here as different kinds of data usually lend themselves to very different best-performance parameters. And, indeed, our autoencoder seems to perform very well as it is able to minimize the error term (or loss function) quite impressively. 4. Calculate the Error and Find the Anomalies! Now, we feed the data again as a whole to the autoencoder and check the error term on each sample. Recall that seqs_ds is a pandas DataFrame that holds the actual string sequences. Line #2 encodes each string, and line #4 scales it. Then, I use the predict() method to get the reconstructed inputs of the strings stored in seqs_ds. Finally, I get the error term for each data point by calculating the “distance” between the input data point (or the actual data point) and the output that was reconstructed by the autoencoder: mse = np.mean(np.power(actual_data - reconstructed_data, 2), axis=1) After we store the error term in the data frame, we can see how well each input data was constructed by our autoencoder. How do we find the anomalies? Well, the first thing we need to do is decide what is our threshold, and that usually depends on our data and domain knowledge. Some will say that an anomaly is a data point that has an error term that is higher than 95% of our data, for example. That would be an appropriate threshold if we expect that 5% of our data will be anomalous. However, recall that we injected 5 anomalies to a list of 25,000 perfectly formatted sequences, which means that only 0.02% of our data is anomalous, so we want to set our threshold as higher than 99.98% of our data (or the 0.9998 percentile). So first let's find this threshold: Next, I will add an MSE_Outlier column to the data set and set it to 1 when the error term crosses this threshold. And now all we have to do is check how many outliers do we have and whether these outliers are the ones we injected and mixed in the data ['XYDC2DCA', 'TXSX1ABC','RNIU4XRE','AABDXUEI','SDRAC5RF'] So let's see how many outliers we have and whether they are the ones we injected. And.... Voila! We found 6 outliers while 5 of which are the “real” outliers. Looks like magic ha? Source code on git available here
[ { "code": null, "e": 812, "s": 172, "text": "Suppose that you have a very long list of string sequences, such as a list of amino acid structures (‘PHE-SER-CYS’, ‘GLN-ARG-SER’,...), product serial numbers (‘AB121E’, ‘AB323’, ‘DN176’...), or users UIDs, and you are required to create a validation process of some kind that will detect anomalies in this sequence. An anomaly might be a string that follows a slightly different or unusual format than the others (whether it was created by mistake or on purpose) or just one that is extremely rare. To make things even more interesting, suppose that you don't know what is the correct format or structure that sequences suppose to follow." }, { "code": null, "e": 1382, "s": 812, "text": "This is a relatively common problem (though with an uncommon twist) that many data scientists usually approach using one of the popular unsupervised ML algorithms, such as DBScan, Isolation Forest, etc. Many of these algorithms typically do a good job in finding anomalies or outliers by singling out data points that are relatively far from the others or from areas in which most data points lie. Although autoencoders are also well-known for their anomaly detection capabilities, they work quite differently and are less common when it comes to problems of this sort." }, { "code": null, "e": 2702, "s": 1382, "text": "I will leave the explanations of what is exactly an autoencoder to the many insightful and well-written posts, and articles that are freely available online. Very very briefly (and please just read on if this doesn't make sense to you), just like other kinds of ML algorithms, autoencoders learn by creating different representations of data and by measuring how well these representations do in generating an expected outcome; and just like other kinds of neural network, autoencoders learn by creating different layers of such representations that allow them to learn more complex and sophisticated representations of data (which on my view is exactly what makes them superior for a task like ours). Autoencoders are a special form of a neural network, however, because the output that they attempt to generate is a reconstruction of the input they receive. An autoencoder starts with input data (i.e., a set of numbers) and then transforms it in different ways using a set of mathematical operations until it learns the parameters that it ought to use in order to reconstruct the same data (or get very close to it). In this learning process, an autoencoder essentially learns the format rules of the input data. And, that's exactly what makes it perform well as an anomaly detection mechanism in settings like ours." }, { "code": null, "e": 2774, "s": 2702, "text": "Using autoencoders to detect anomalies usually involves two main steps:" }, { "code": null, "e": 3174, "s": 2774, "text": "First, we feed our data to an autoencoder and tune it until it is well trained to reconstruct the expected output with minimum error. An autoencoder that receives an input like 10,5,100 and returns 11,5,99, for example, is well-trained if we consider the reconstructed output as sufficiently close to the input and if the autoencoder is able to successfully reconstruct most of the data in this way." }, { "code": null, "e": 3671, "s": 3174, "text": "Second, we feed all our data again to our trained autoencoder and measure the error term of each reconstructed data point. In other words, we measure how “far” is the reconstructed data point from the actual datapoint. A well-trained autoencoder essentially learns how to reconstruct an input that follows a certain format, so if we give a badly formatted data point to a well-trained autoencoder then we are likely to get something that is quite different from our input, and a large error term." }, { "code": null, "e": 3948, "s": 3671, "text": "Let's get into the details. I should emphasize, though, that this is just one way that one can go about such a task using an autoencoder. There are other ways and technics to build autoencoders and you should experiment until you find the architecture that suits your project." }, { "code": null, "e": 3994, "s": 3948, "text": "These are the steps that I'm going to follow:" }, { "code": null, "e": 4383, "s": 3994, "text": "Generate a set of random string sequences that follow a specified format, and add a few anomalies.Encode the sequences into numbers and scale them.Design, fit, and tune an autoencoder.Feed the sequences to the trained autoencoder and calculate the error term of each data point.Find the anomalies by finding the data points with the highest error term.Generate a long sequence of strings." }, { "code": null, "e": 4482, "s": 4383, "text": "Generate a set of random string sequences that follow a specified format, and add a few anomalies." }, { "code": null, "e": 4532, "s": 4482, "text": "Encode the sequences into numbers and scale them." }, { "code": null, "e": 4570, "s": 4532, "text": "Design, fit, and tune an autoencoder." }, { "code": null, "e": 4665, "s": 4570, "text": "Feed the sequences to the trained autoencoder and calculate the error term of each data point." }, { "code": null, "e": 4740, "s": 4665, "text": "Find the anomalies by finding the data points with the highest error term." }, { "code": null, "e": 4777, "s": 4740, "text": "Generate a long sequence of strings." }, { "code": null, "e": 4967, "s": 4777, "text": "We're gonna start by writing a function that creates strings of the following format: CEBF0ZPQ ([4 letters A-F][1 digit 0–2][3 letters QWOPZXML]), and generate 25K sequences of this format." }, { "code": null, "e": 5026, "s": 4967, "text": "2. Encode the string sequences into numbers and scale them" }, { "code": null, "e": 5183, "s": 5026, "text": "Now we have an array of the following shape as every string sequence has 8 characters, each of which is encoded as a number which we will treat as a column." }, { "code": null, "e": 5212, "s": 5183, "text": "encoded_seqs.shape#(25005,8)" }, { "code": null, "e": 5487, "s": 5212, "text": "Finally, before feeding the data to the autoencoder I'm going to scale the data using a MinMaxScaler, and split it into a training and test set. Proper scaling can often significantly improve the performance of NNs so it is important to experiment with more than one method." }, { "code": null, "e": 5528, "s": 5487, "text": "3. Design, fit and tune the autoencoder." }, { "code": null, "e": 5908, "s": 5528, "text": "As mentioned earlier, there is more than one way to design an autoencoder. It is usually based on small hidden layers wrapped with larger layers (this is what creates the encoding-decoding effect). I have made a few tuning sessions in order to determine the best params to use here as different kinds of data usually lend themselves to very different best-performance parameters." }, { "code": null, "e": 6044, "s": 5908, "text": "And, indeed, our autoencoder seems to perform very well as it is able to minimize the error term (or loss function) quite impressively." }, { "code": null, "e": 6091, "s": 6044, "text": "4. Calculate the Error and Find the Anomalies!" }, { "code": null, "e": 6617, "s": 6091, "text": "Now, we feed the data again as a whole to the autoencoder and check the error term on each sample. Recall that seqs_ds is a pandas DataFrame that holds the actual string sequences. Line #2 encodes each string, and line #4 scales it. Then, I use the predict() method to get the reconstructed inputs of the strings stored in seqs_ds. Finally, I get the error term for each data point by calculating the “distance” between the input data point (or the actual data point) and the output that was reconstructed by the autoencoder:" }, { "code": null, "e": 6686, "s": 6617, "text": "mse = np.mean(np.power(actual_data - reconstructed_data, 2), axis=1)" }, { "code": null, "e": 6807, "s": 6686, "text": "After we store the error term in the data frame, we can see how well each input data was constructed by our autoencoder." }, { "code": null, "e": 6837, "s": 6807, "text": "How do we find the anomalies?" }, { "code": null, "e": 7455, "s": 6837, "text": "Well, the first thing we need to do is decide what is our threshold, and that usually depends on our data and domain knowledge. Some will say that an anomaly is a data point that has an error term that is higher than 95% of our data, for example. That would be an appropriate threshold if we expect that 5% of our data will be anomalous. However, recall that we injected 5 anomalies to a list of 25,000 perfectly formatted sequences, which means that only 0.02% of our data is anomalous, so we want to set our threshold as higher than 99.98% of our data (or the 0.9998 percentile). So first let's find this threshold:" }, { "code": null, "e": 7570, "s": 7455, "text": "Next, I will add an MSE_Outlier column to the data set and set it to 1 when the error term crosses this threshold." }, { "code": null, "e": 7708, "s": 7570, "text": "And now all we have to do is check how many outliers do we have and whether these outliers are the ones we injected and mixed in the data" }, { "code": null, "e": 7766, "s": 7708, "text": "['XYDC2DCA', 'TXSX1ABC','RNIU4XRE','AABDXUEI','SDRAC5RF']" }, { "code": null, "e": 7848, "s": 7766, "text": "So let's see how many outliers we have and whether they are the ones we injected." }, { "code": null, "e": 7925, "s": 7848, "text": "And.... Voila! We found 6 outliers while 5 of which are the “real” outliers." }, { "code": null, "e": 7946, "s": 7925, "text": "Looks like magic ha?" } ]
Console.Clear Method in C#
The Console.Clear method in C# is used to clear the console buffer and corresponding console window of display information. Following is the syntax − public static void Clear (); Let us now see an example before implementing the Console.Clear method − using System; public class Demo { public static void Main(){ Uri newURI1 = new Uri("https://www.tutorialspoint.com/"); Console.WriteLine("URI = "+newURI1); Console.WriteLine("String representation = "+newURI1.ToString()); Uri newURI2 = new Uri("https://www.tutorialspoint.com/jquery.htm#abcd"); Console.WriteLine("\nURI = "+newURI2); Console.WriteLine("String representation = "+newURI2.ToString()); if(newURI1.Equals(newURI2)) Console.WriteLine("\nBoth the URIs are equal!"); else Console.WriteLine("\nBoth the URIs aren't equal!"); Uri res = newURI1.MakeRelativeUri(newURI2); Console.WriteLine("Relative uri = "+res); } } This will produce the following output before using Console.Clear() − URI = https://www.tutorialspoint.com/ String representation = https://www.tutorialspoint.com/ URI = https://www.tutorialspoint.com/jquery.htm#abcd String representation = https://www.tutorialspoint.com/jquery.htm#abcd Both the URIs aren't equal! Relative uri = jquery.htm#abcd Let us now see the same example to implement the Console.Clear method − using System; public class Demo { public static void Main(){ Uri newURI1 = new Uri("https://www.tutorialspoint.com/"); Console.WriteLine("URI = "+newURI1); Console.WriteLine("String representation = "+newURI1.ToString()); Uri newURI2 = new Uri("https://www.tutorialspoint.com/jquery.htm#abcd"); Console.WriteLine("\nURI = "+newURI2); Console.WriteLine("String representation = "+newURI2.ToString()); if(newURI1.Equals(newURI2)) Console.WriteLine("\nBoth the URIs are equal!"); else Console.WriteLine("\nBoth the URIs aren't equal!"); Uri res = newURI1.MakeRelativeUri(newURI2); Console.WriteLine("Relative uri = "+res); Console.Clear(); Console.WriteLine("Console cleared now!"); } } This will produce the following output − Console cleared now!
[ { "code": null, "e": 1186, "s": 1062, "text": "The Console.Clear method in C# is used to clear the console buffer and corresponding console window of display information." }, { "code": null, "e": 1212, "s": 1186, "text": "Following is the syntax −" }, { "code": null, "e": 1241, "s": 1212, "text": "public static void Clear ();" }, { "code": null, "e": 1314, "s": 1241, "text": "Let us now see an example before implementing the Console.Clear method −" }, { "code": null, "e": 2019, "s": 1314, "text": "using System;\npublic class Demo {\n public static void Main(){\n Uri newURI1 = new Uri(\"https://www.tutorialspoint.com/\");\n Console.WriteLine(\"URI = \"+newURI1);\n Console.WriteLine(\"String representation = \"+newURI1.ToString());\n Uri newURI2 = new Uri(\"https://www.tutorialspoint.com/jquery.htm#abcd\");\n Console.WriteLine(\"\\nURI = \"+newURI2);\n Console.WriteLine(\"String representation = \"+newURI2.ToString());\n if(newURI1.Equals(newURI2))\n Console.WriteLine(\"\\nBoth the URIs are equal!\");\n else\n Console.WriteLine(\"\\nBoth the URIs aren't equal!\");\n Uri res = newURI1.MakeRelativeUri(newURI2);\n Console.WriteLine(\"Relative uri = \"+res);\n}\n}" }, { "code": null, "e": 2089, "s": 2019, "text": "This will produce the following output before using Console.Clear() −" }, { "code": null, "e": 2366, "s": 2089, "text": "URI = https://www.tutorialspoint.com/\nString representation = https://www.tutorialspoint.com/\nURI = https://www.tutorialspoint.com/jquery.htm#abcd\nString representation = https://www.tutorialspoint.com/jquery.htm#abcd\nBoth the URIs aren't equal!\nRelative uri = jquery.htm#abcd" }, { "code": null, "e": 2438, "s": 2366, "text": "Let us now see the same example to implement the Console.Clear method −" }, { "code": null, "e": 3218, "s": 2438, "text": "using System;\npublic class Demo {\n public static void Main(){\n Uri newURI1 = new Uri(\"https://www.tutorialspoint.com/\");\n Console.WriteLine(\"URI = \"+newURI1);\n Console.WriteLine(\"String representation = \"+newURI1.ToString());\n Uri newURI2 = new Uri(\"https://www.tutorialspoint.com/jquery.htm#abcd\");\n Console.WriteLine(\"\\nURI = \"+newURI2);\n Console.WriteLine(\"String representation = \"+newURI2.ToString());\n if(newURI1.Equals(newURI2))\n Console.WriteLine(\"\\nBoth the URIs are equal!\");\n else\n Console.WriteLine(\"\\nBoth the URIs aren't equal!\");\n Uri res = newURI1.MakeRelativeUri(newURI2);\n Console.WriteLine(\"Relative uri = \"+res);\n Console.Clear();\n Console.WriteLine(\"Console cleared now!\");\n }\n}" }, { "code": null, "e": 3259, "s": 3218, "text": "This will produce the following output −" }, { "code": null, "e": 3280, "s": 3259, "text": "Console cleared now!" } ]
How to multiply all values in a list by a number in R?
To multiply all values in a list by a number, we can use lapply function. Inside the lapply function we would need to supply multiplication sign that is * with the list name and the number by which we want to multiple all the list values. For example, if we have a list called LIST and we want to multiply each value in LIST by 2 then it can be done by using the command lapply(LIST,"*",2). Live Demo List1<−list(x1=rpois(100,5),x2=rpois(100,2),x3=rpois(100,2),x4=rpois(100,3)) List1 $x1 [1] 4 4 1 4 7 4 8 4 8 7 7 6 3 8 6 5 5 4 9 4 4 7 2 8 8 [26] 8 3 3 7 2 7 9 6 9 7 4 2 8 1 10 3 5 8 6 5 3 2 8 7 4 [51] 4 3 3 3 12 8 1 1 2 9 3 6 2 2 2 12 3 6 7 3 2 6 10 6 8 [76] 3 2 2 8 4 6 4 4 5 6 3 2 6 4 6 3 7 8 8 3 8 2 3 6 2 $x2 [1] 3 1 0 1 4 2 2 0 2 0 2 0 0 1 1 1 2 3 3 4 1 0 3 7 1 0 0 0 1 0 2 2 2 3 2 2 1 [38] 6 1 2 5 1 2 2 0 0 4 4 2 1 1 4 4 4 2 2 3 0 3 1 3 2 2 0 4 3 1 1 2 2 3 0 4 3 [75] 1 1 1 2 2 3 3 3 0 0 1 1 1 1 2 2 2 6 3 2 1 2 4 0 2 4 $x3 [1] 0 1 3 0 4 1 3 0 1 1 1 1 1 2 1 2 1 2 4 2 3 2 2 1 1 1 2 1 1 3 1 3 0 2 2 0 1 [38] 1 3 1 3 0 1 0 0 2 2 2 2 3 3 5 2 3 3 2 4 4 1 4 1 1 3 3 2 0 3 3 0 4 6 1 1 2 [75] 2 3 1 2 0 0 2 2 1 1 0 1 1 0 2 2 1 0 1 1 1 4 5 0 1 1 $x4 [1] 3 5 2 3 3 6 4 3 1 2 2 4 3 3 1 3 4 2 3 3 3 4 1 5 3 3 1 4 4 2 3 4 5 2 3 4 5 [38] 5 2 1 2 2 2 3 7 2 3 1 2 3 0 7 0 5 4 5 0 2 3 3 2 6 2 4 6 1 4 2 3 1 2 5 5 4 [75] 4 1 2 1 3 3 1 2 1 2 3 1 3 4 2 4 5 0 2 3 2 0 2 3 1 4 lapply(List1,"*",2) $x1 [1] 8 8 2 8 14 8 16 8 16 14 14 12 6 16 12 10 10 8 18 8 8 14 4 16 16 [26] 16 6 6 14 4 14 18 12 18 14 8 4 16 2 20 6 10 16 12 10 6 4 16 14 8 [51] 8 6 6 6 24 16 2 2 4 18 6 12 4 4 4 24 6 12 14 6 4 12 20 12 16 [76] 6 4 4 16 8 12 8 8 10 12 6 4 12 8 12 6 14 16 16 6 16 4 6 12 4 $x2 [1] 6 2 0 2 8 4 4 0 4 0 4 0 0 2 2 2 4 6 6 8 2 0 6 14 2 [26] 0 0 0 2 0 4 4 4 6 4 4 2 12 2 4 10 2 4 4 0 0 8 8 4 2 [51] 2 8 8 8 4 4 6 0 6 2 6 4 4 0 8 6 2 2 4 4 6 0 8 6 2 [76] 2 2 4 4 6 6 6 0 0 2 2 2 2 4 4 4 12 6 4 2 4 8 0 4 8 $x3 [1] 0 2 6 0 8 2 6 0 2 2 2 2 2 4 2 4 2 4 8 4 6 4 4 2 2 [26] 2 4 2 2 6 2 6 0 4 4 0 2 2 6 2 6 0 2 0 0 4 4 4 4 6 [51] 6 10 4 6 6 4 8 8 2 8 2 2 6 6 4 0 6 6 0 8 12 2 2 4 4 [76] 6 2 4 0 0 4 4 2 2 0 2 2 0 4 4 2 0 2 2 2 8 10 0 2 2 $x4 [1] 6 10 4 6 6 12 8 6 2 4 4 8 6 6 2 6 8 4 6 6 6 8 2 10 6 [26] 6 2 8 8 4 6 8 10 4 6 8 10 10 4 2 4 4 4 6 14 4 6 2 4 6 [51] 0 14 0 10 8 10 0 4 6 6 4 12 4 8 12 2 8 4 6 2 4 10 10 8 8 [76] 2 4 2 6 6 2 4 2 4 6 2 6 8 4 8 10 0 4 6 4 0 4 6 2 8 Live Demo List2<−list(y1=rnorm(60),y2=rnorm(60),y3=rnorm(60),y4=rnorm(60)) List2 $y1 [1] −0.31163597 1.31111498 −0.19732872 0.03670371 −1.74136270 −1.73202546 [7] −0.85604459 −1.08738522 0.04607248 0.23118367 −0.30069029 1.43418146 [13] 0.77450898 0.07784119 −0.43203884 0.13325803 −0.14362337 0.25831355 [19] 1.38866227 −1.09862061 0.64613438 −1.32020851 2.60029183 −0.39076198 [25] 1.95940690 −2.90627199 −0.85716448 −2.29113101 −0.36391797 0.27953465 [31] −0.55970366 1.66004351 0.37252545 −1.20711293 −0.97442206 −0.60294787 [37] 0.28482319 −0.47526746 −0.14472626 −0.34765058 −0.17956233 0.83179604 [43] −0.54103465 −0.59289760 −0.47182615 1.23503752 −1.55850727 −1.47658115 [49] 0.45597554 −1.88919278 −0.54725354 −0.12290071 −0.39011417 1.75596002 [55] 0.27345890 0.73473652 2.14774838 0.10433414 0.80609900 −0.82809754 $y2 [1] −1.623672143 0.003084120 −0.561001042 −0.178228838 −0.823175428 [6] 0.929877416 0.863926212 1.325543440 −0.541493024 −0.009362746 [11] −0.129437573 −1.585157629 0.877743659 −0.627391935 −0.654981581 [16] −0.306416266 0.558174323 −1.043557130 −2.573204941 −1.294325222 [21] −0.016823428 −1.368899397 −0.590039700 −2.202028385 −0.554894422 [26] 0.610074368 −0.819197524 −0.445224730 −1.900221008 0.601714463 [31] −0.079940702 0.694214712 1.316136858 0.037047671 −0.091877586 [36] −0.465346207 0.757206965 −0.378488738 0.122390473 −0.883163844 [41] −1.066922165 −0.270249611 −1.013880453 1.200566623 −0.339003531 [46] −0.047016170 −0.362101913 0.530307469 −0.130723097 0.007871984 [51] −0.349658650 −0.880650261 −0.908030270 −0.277984503 −0.493396224 [56] −0.426178105 −1.121039154 −0.315448483 −0.909254190 −1.603703109 $y3 [1] −0.88039331 0.76544832 1.22880981 0.16976841 1.12925426 0.53261916 [7] 0.28677249 1.70873367 −0.67911957 −1.19809637 0.69498197 1.19278318 [13] −0.05228474 −1.08885299 0.19005880 2.34425462 −1.57071722 0.72814587 [19] 2.11903192 0.65422408 −1.39110194 −1.14576983 0.27405209 −2.29361953 [25] −0.20552462 0.88146995 1.25313309 −0.20630170 0.73259536 −1.84433751 [31] −0.48475525 0.41909993 −0.07445892 −0.43277142 −1.64111889 −0.28010780 [37] 0.21812110 0.73271307 0.53579162 −2.33502312 0.23435896 −0.33286180 [43] −0.51595049 0.50167700 1.19512552 0.81918189 0.92670118 −1.14790393 [49] 0.52236941 0.43611326 −1.66171008 1.23703794 1.21188380 0.05098244 [55] −0.11015191 1.29874013 0.82369746 0.51228221 −0.82378145 −0.03410876 $y4 [1] −0.90671186 −1.62314816 0.53747830 −0.79900645 −0.48835823 1.30813592 [7] −3.00377348 1.08945104 −3.23377322 0.76212670 2.05818852 0.83020833 [13] −0.36424022 0.51441704 −1.19970463 −0.29484763 2.32675699 −0.38035400 [19] −0.14898653 0.05102723 1.62873977 0.56577113 0.58290260 −0.01132887 [25] −0.35880198 0.75001388 1.61442786 −1.19526377 −0.32975458 0.66136658 [31] −1.78432711 1.34315562 −0.49093017 1.15765222 0.70897553 −0.59435317 [37] −1.30037062 −0.32505505 1.24492762 0.38108942 1.80967268 −1.33037559 [43] 0.59490582 0.95420870 −0.85584273 0.67958732 0.46651930 0.15742018 [49] 1.05988736 0.64473740 −0.16923553 −1.59558728 0.17408084 −0.30705672 [55] 0.85890141 0.06370434 −1.33648832 −0.39414900 1.98460864 −0.77319788 lapply(List2,"*",2) $y1 [1] −0.62327194 2.62222997 −0.39465744 0.07340742 −3.48272540 −3.46405093 [7] −1.71208919 −2.17477044 0.09214496 0.46236734 −0.60138058 2.86836291 [13] 1.54901796 0.15568238 −0.86407768 0.26651607 −0.28724674 0.51662711 [19] 2.77732454 −2.19724123 1.29226875 −2.64041702 5.20058366 −0.78152396 [25] 3.91881381 −5.81254398 −1.71432897 −4.58226201 −0.72783594 0.55906930 [31] −1.11940731 3.32008702 0.74505091 −2.41422586 −1.94884412 −1.20589575 [37] 0.56964637 −0.95053491 −0.28945252 −0.69530117 −0.35912465 1.66359207 [43] −1.08206931 −1.18579520 −0.94365230 2.47007503 −3.11701454 −2.95316230 [49] 0.91195108 −3.77838556 −1.09450709 −0.24580141 −0.78022833 3.51192004 [55] 0.54691780 1.46947305 4.29549677 0.20866829 1.61219799 −1.65619509 $y2 [1] −3.24734429 0.00616824 −1.12200208 −0.35645768 −1.64635086 1.85975483 [7] 1.72785242 2.65108688 −1.08298605 −0.01872549 −0.25887515 −3.17031526 [13] 1.75548732 −1.25478387 −1.30996316 −0.61283253 1.11634865 −2.08711426 [19] −5.14640988 −2.58865044 −0.03364686 −2.73779879 −1.18007940 −4.40405677 [25] −1.10978884 1.22014874 −1.63839505 −0.89044946 −3.80044202 1.20342893 [31] −0.15988140 1.38842942 2.63227372 0.07409534 −0.18375517 −0.93069241 [37] 1.51441393 −0.75697748 0.24478095 −1.76632769 −2.13384433 −0.54049922 [43] −2.02776091 2.40113325 −0.67800706 −0.09403234 −0.72420383 1.06061494 [49] −0.26144619 0.01574397 −0.69931730 −1.76130052 −1.81606054 −0.55596901 [55] −0.98679245 −0.85235621 −2.24207831 −0.63089697 −1.81850838 −3.20740622 $y3 [1] −1.76078661 1.53089665 2.45761962 0.33953682 2.25850851 1.06523833 [7] 0.57354499 3.41746734 −1.35823913 −2.39619274 1.38996394 2.38556636 [13] −0.10456948 −2.17770598 0.38011761 4.68850923 −3.14143444 1.45629174 [19] 4.23806383 1.30844816 −2.78220389 −2.29153965 0.54810418 −4.58723906 [25] −0.41104924 1.76293990 2.50626617 −0.41260340 1.46519071 −3.68867502 [31] −0.96951051 0.83819985 −0.14891784 −0.86554284 −3.28223777 −0.56021560 [37] 0.43624221 1.46542613 1.07158323 −4.67004624 0.46871793 −0.66572360 [43] −1.03190098 1.00335400 2.39025103 1.63836378 1.85340236 −2.29580786 [49] 1.04473881 0.87222652 −3.32342016 2.47407589 2.42376760 0.10196487 [55] −0.22030383 2.59748026 1.64739492 1.02456441 −1.64756290 −0.06821753 $y4 [1] −1.81342372 −3.24629631 1.07495661 −1.59801291 −0.97671646 2.61627183 [7] −6.00754697 2.17890207 −6.46754644 1.52425341 4.11637703 1.66041665 [13] −0.72848044 1.02883408 −2.39940926 −0.58969527 4.65351399 −0.76070800 [19] −0.29797306 0.10205446 3.25747953 1.13154225 1.16580519 −0.02265774 [25] −0.71760396 1.50002776 3.22885572 −2.39052753 −0.65950916 1.32273316 [31] −3.56865422 2.68631125 −0.98186034 2.31530444 1.41795107 −1.18870635 [37] −2.60074124 −0.65011010 2.48985524 0.76217885 3.61934536 −2.66075118 [43] 1.18981164 1.90841740 −1.71168547 1.35917465 0.93303860 0.31484035 [49] 2.11977472 1.28947481 −0.33847105 −3.19117456 0.34816169 −0.61411343 [55] 1.71780283 0.12740868 −2.67297665 −0.78829801 3.96921727 −1.54639577
[ { "code": null, "e": 1453, "s": 1062, "text": "To multiply all values in a list by a number, we can use lapply function. Inside the lapply function we would need to supply multiplication sign that is * with the list name and the number by which we want to multiple all the list values. For example, if we have a list called LIST and we want to multiply each value in LIST by 2 then it can be done by using the command lapply(LIST,\"*\",2)." }, { "code": null, "e": 1464, "s": 1453, "text": " Live Demo" }, { "code": null, "e": 1547, "s": 1464, "text": "List1<−list(x1=rpois(100,5),x2=rpois(100,2),x3=rpois(100,2),x4=rpois(100,3))\nList1" }, { "code": null, "e": 2428, "s": 1547, "text": "$x1\n[1] 4 4 1 4 7 4 8 4 8 7 7 6 3 8 6 5 5 4 9 4 4 7 2 8 8\n[26] 8 3 3 7 2 7 9 6 9 7 4 2 8 1 10 3 5 8 6 5 3 2 8 7 4\n[51] 4 3 3 3 12 8 1 1 2 9 3 6 2 2 2 12 3 6 7 3 2 6 10 6 8\n[76] 3 2 2 8 4 6 4 4 5 6 3 2 6 4 6 3 7 8 8 3 8 2 3 6 2\n$x2\n[1] 3 1 0 1 4 2 2 0 2 0 2 0 0 1 1 1 2 3 3 4 1 0 3 7 1 0 0 0 1 0 2 2 2 3 2 2 1\n[38] 6 1 2 5 1 2 2 0 0 4 4 2 1 1 4 4 4 2 2 3 0 3 1 3 2 2 0 4 3 1 1 2 2 3 0 4 3\n[75] 1 1 1 2 2 3 3 3 0 0 1 1 1 1 2 2 2 6 3 2 1 2 4 0 2 4\n$x3\n[1] 0 1 3 0 4 1 3 0 1 1 1 1 1 2 1 2 1 2 4 2 3 2 2 1 1 1 2 1 1 3 1 3 0 2 2 0 1\n[38] 1 3 1 3 0 1 0 0 2 2 2 2 3 3 5 2 3 3 2 4 4 1 4 1 1 3 3 2 0 3 3 0 4 6 1 1 2\n[75] 2 3 1 2 0 0 2 2 1 1 0 1 1 0 2 2 1 0 1 1 1 4 5 0 1 1\n$x4\n[1] 3 5 2 3 3 6 4 3 1 2 2 4 3 3 1 3 4 2 3 3 3 4 1 5 3 3 1 4 4 2 3 4 5 2 3 4 5\n[38] 5 2 1 2 2 2 3 7 2 3 1 2 3 0 7 0 5 4 5 0 2 3 3 2 6 2 4 6 1 4 2 3 1 2 5 5 4\n[75] 4 1 2 1 3 3 1 2 1 2 3 1 3 4 2 4 5 0 2 3 2 0 2 3 1 4" }, { "code": null, "e": 2448, "s": 2428, "text": "lapply(List1,\"*\",2)" }, { "code": null, "e": 3413, "s": 2448, "text": "$x1\n[1] 8 8 2 8 14 8 16 8 16 14 14 12 6 16 12 10 10 8 18 8 8 14 4 16 16\n[26] 16 6 6 14 4 14 18 12 18 14 8 4 16 2 20 6 10 16 12 10 6 4 16 14 8\n[51] 8 6 6 6 24 16 2 2 4 18 6 12 4 4 4 24 6 12 14 6 4 12 20 12 16\n[76] 6 4 4 16 8 12 8 8 10 12 6 4 12 8 12 6 14 16 16 6 16 4 6 12 4\n$x2\n[1] 6 2 0 2 8 4 4 0 4 0 4 0 0 2 2 2 4 6 6 8 2 0 6 14 2\n[26] 0 0 0 2 0 4 4 4 6 4 4 2 12 2 4 10 2 4 4 0 0 8 8 4 2\n[51] 2 8 8 8 4 4 6 0 6 2 6 4 4 0 8 6 2 2 4 4 6 0 8 6 2\n[76] 2 2 4 4 6 6 6 0 0 2 2 2 2 4 4 4 12 6 4 2 4 8 0 4 8\n$x3\n[1] 0 2 6 0 8 2 6 0 2 2 2 2 2 4 2 4 2 4 8 4 6 4 4 2 2\n[26] 2 4 2 2 6 2 6 0 4 4 0 2 2 6 2 6 0 2 0 0 4 4 4 4 6\n[51] 6 10 4 6 6 4 8 8 2 8 2 2 6 6 4 0 6 6 0 8 12 2 2 4 4\n[76] 6 2 4 0 0 4 4 2 2 0 2 2 0 4 4 2 0 2 2 2 8 10 0 2 2\n$x4\n[1] 6 10 4 6 6 12 8 6 2 4 4 8 6 6 2 6 8 4 6 6 6 8 2 10 6\n[26] 6 2 8 8 4 6 8 10 4 6 8 10 10 4 2 4 4 4 6 14 4 6 2 4 6\n[51] 0 14 0 10 8 10 0 4 6 6 4 12 4 8 12 2 8 4 6 2 4 10 10 8 8\n[76] 2 4 2 6 6 2 4 2 4 6 2 6 8 4 8 10 0 4 6 4 0 4 6 2 8" }, { "code": null, "e": 3424, "s": 3413, "text": " Live Demo" }, { "code": null, "e": 3495, "s": 3424, "text": "List2<−list(y1=rnorm(60),y2=rnorm(60),y3=rnorm(60),y4=rnorm(60))\nList2" }, { "code": null, "e": 6544, "s": 3495, "text": "$y1\n[1] −0.31163597 1.31111498 −0.19732872 0.03670371 −1.74136270 −1.73202546\n[7] −0.85604459 −1.08738522 0.04607248 0.23118367 −0.30069029 1.43418146\n[13] 0.77450898 0.07784119 −0.43203884 0.13325803 −0.14362337 0.25831355\n[19] 1.38866227 −1.09862061 0.64613438 −1.32020851 2.60029183 −0.39076198\n[25] 1.95940690 −2.90627199 −0.85716448 −2.29113101 −0.36391797 0.27953465\n[31] −0.55970366 1.66004351 0.37252545 −1.20711293 −0.97442206 −0.60294787\n[37] 0.28482319 −0.47526746 −0.14472626 −0.34765058 −0.17956233 0.83179604\n[43] −0.54103465 −0.59289760 −0.47182615 1.23503752 −1.55850727 −1.47658115\n[49] 0.45597554 −1.88919278 −0.54725354 −0.12290071 −0.39011417 1.75596002\n[55] 0.27345890 0.73473652 2.14774838 0.10433414 0.80609900 −0.82809754\n$y2\n[1] −1.623672143 0.003084120 −0.561001042 −0.178228838 −0.823175428\n[6] 0.929877416 0.863926212 1.325543440 −0.541493024 −0.009362746\n[11] −0.129437573 −1.585157629 0.877743659 −0.627391935 −0.654981581\n[16] −0.306416266 0.558174323 −1.043557130 −2.573204941 −1.294325222\n[21] −0.016823428 −1.368899397 −0.590039700 −2.202028385 −0.554894422\n[26] 0.610074368 −0.819197524 −0.445224730 −1.900221008 0.601714463\n[31] −0.079940702 0.694214712 1.316136858 0.037047671 −0.091877586\n[36] −0.465346207 0.757206965 −0.378488738 0.122390473 −0.883163844\n[41] −1.066922165 −0.270249611 −1.013880453 1.200566623 −0.339003531\n[46] −0.047016170 −0.362101913 0.530307469 −0.130723097 0.007871984\n[51] −0.349658650 −0.880650261 −0.908030270 −0.277984503 −0.493396224\n[56] −0.426178105 −1.121039154 −0.315448483 −0.909254190 −1.603703109\n$y3\n[1] −0.88039331 0.76544832 1.22880981 0.16976841 1.12925426 0.53261916\n[7] 0.28677249 1.70873367 −0.67911957 −1.19809637 0.69498197 1.19278318\n[13] −0.05228474 −1.08885299 0.19005880 2.34425462 −1.57071722 0.72814587\n[19] 2.11903192 0.65422408 −1.39110194 −1.14576983 0.27405209 −2.29361953\n[25] −0.20552462 0.88146995 1.25313309 −0.20630170 0.73259536 −1.84433751\n[31] −0.48475525 0.41909993 −0.07445892 −0.43277142 −1.64111889 −0.28010780\n[37] 0.21812110 0.73271307 0.53579162 −2.33502312 0.23435896 −0.33286180\n[43] −0.51595049 0.50167700 1.19512552 0.81918189 0.92670118 −1.14790393\n[49] 0.52236941 0.43611326 −1.66171008 1.23703794 1.21188380 0.05098244\n[55] −0.11015191 1.29874013 0.82369746 0.51228221 −0.82378145 −0.03410876\n$y4\n[1] −0.90671186 −1.62314816 0.53747830 −0.79900645 −0.48835823 1.30813592\n[7] −3.00377348 1.08945104 −3.23377322 0.76212670 2.05818852 0.83020833\n[13] −0.36424022 0.51441704 −1.19970463 −0.29484763 2.32675699 −0.38035400\n[19] −0.14898653 0.05102723 1.62873977 0.56577113 0.58290260 −0.01132887\n[25] −0.35880198 0.75001388 1.61442786 −1.19526377 −0.32975458 0.66136658\n[31] −1.78432711 1.34315562 −0.49093017 1.15765222 0.70897553 −0.59435317\n[37] −1.30037062 −0.32505505 1.24492762 0.38108942 1.80967268 −1.33037559\n[43] 0.59490582 0.95420870 −0.85584273 0.67958732 0.46651930 0.15742018\n[49] 1.05988736 0.64473740 −0.16923553 −1.59558728 0.17408084 −0.30705672\n[55] 0.85890141 0.06370434 −1.33648832 −0.39414900 1.98460864 −0.77319788" }, { "code": null, "e": 6564, "s": 6544, "text": "lapply(List2,\"*\",2)" }, { "code": null, "e": 9543, "s": 6564, "text": "$y1\n[1] −0.62327194 2.62222997 −0.39465744 0.07340742 −3.48272540 −3.46405093\n[7] −1.71208919 −2.17477044 0.09214496 0.46236734 −0.60138058 2.86836291\n[13] 1.54901796 0.15568238 −0.86407768 0.26651607 −0.28724674 0.51662711\n[19] 2.77732454 −2.19724123 1.29226875 −2.64041702 5.20058366 −0.78152396\n[25] 3.91881381 −5.81254398 −1.71432897 −4.58226201 −0.72783594 0.55906930\n[31] −1.11940731 3.32008702 0.74505091 −2.41422586 −1.94884412 −1.20589575\n[37] 0.56964637 −0.95053491 −0.28945252 −0.69530117 −0.35912465 1.66359207\n[43] −1.08206931 −1.18579520 −0.94365230 2.47007503 −3.11701454 −2.95316230\n[49] 0.91195108 −3.77838556 −1.09450709 −0.24580141 −0.78022833 3.51192004\n[55] 0.54691780 1.46947305 4.29549677 0.20866829 1.61219799 −1.65619509\n$y2\n[1] −3.24734429 0.00616824 −1.12200208 −0.35645768 −1.64635086 1.85975483\n[7] 1.72785242 2.65108688 −1.08298605 −0.01872549 −0.25887515 −3.17031526\n[13] 1.75548732 −1.25478387 −1.30996316 −0.61283253 1.11634865 −2.08711426\n[19] −5.14640988 −2.58865044 −0.03364686 −2.73779879 −1.18007940 −4.40405677\n[25] −1.10978884 1.22014874 −1.63839505 −0.89044946 −3.80044202 1.20342893\n[31] −0.15988140 1.38842942 2.63227372 0.07409534 −0.18375517 −0.93069241\n[37] 1.51441393 −0.75697748 0.24478095 −1.76632769 −2.13384433 −0.54049922\n[43] −2.02776091 2.40113325 −0.67800706 −0.09403234 −0.72420383 1.06061494\n[49] −0.26144619 0.01574397 −0.69931730 −1.76130052 −1.81606054 −0.55596901\n[55] −0.98679245 −0.85235621 −2.24207831 −0.63089697 −1.81850838 −3.20740622\n$y3\n[1] −1.76078661 1.53089665 2.45761962 0.33953682 2.25850851 1.06523833\n[7] 0.57354499 3.41746734 −1.35823913 −2.39619274 1.38996394 2.38556636\n[13] −0.10456948 −2.17770598 0.38011761 4.68850923 −3.14143444 1.45629174\n[19] 4.23806383 1.30844816 −2.78220389 −2.29153965 0.54810418 −4.58723906\n[25] −0.41104924 1.76293990 2.50626617 −0.41260340 1.46519071 −3.68867502\n[31] −0.96951051 0.83819985 −0.14891784 −0.86554284 −3.28223777 −0.56021560\n[37] 0.43624221 1.46542613 1.07158323 −4.67004624 0.46871793 −0.66572360\n[43] −1.03190098 1.00335400 2.39025103 1.63836378 1.85340236 −2.29580786\n[49] 1.04473881 0.87222652 −3.32342016 2.47407589 2.42376760 0.10196487\n[55] −0.22030383 2.59748026 1.64739492 1.02456441 −1.64756290 −0.06821753\n$y4\n[1] −1.81342372 −3.24629631 1.07495661 −1.59801291 −0.97671646 2.61627183\n[7] −6.00754697 2.17890207 −6.46754644 1.52425341 4.11637703 1.66041665\n[13] −0.72848044 1.02883408 −2.39940926 −0.58969527 4.65351399 −0.76070800\n[19] −0.29797306 0.10205446 3.25747953 1.13154225 1.16580519 −0.02265774\n[25] −0.71760396 1.50002776 3.22885572 −2.39052753 −0.65950916 1.32273316\n[31] −3.56865422 2.68631125 −0.98186034 2.31530444 1.41795107 −1.18870635\n[37] −2.60074124 −0.65011010 2.48985524 0.76217885 3.61934536 −2.66075118\n[43] 1.18981164 1.90841740 −1.71168547 1.35917465 0.93303860 0.31484035\n[49] 2.11977472 1.28947481 −0.33847105 −3.19117456 0.34816169 −0.61411343\n[55] 1.71780283 0.12740868 −2.67297665 −0.78829801 3.96921727 −1.54639577" } ]
NumPy Array Processing With Cython: 5000x Faster | by Ahmed Gad | Towards Data Science
This tutorial will show you how to speed up the processing of NumPy arrays using Cython. By explicitly specifying the data types of variables in Python, Cython can give drastic speed increases at runtime. The sections covered in this tutorial are as follows: Looping through NumPy arrays The Cython type for NumPy arrays Data type of NumPy array elements NumPy array as a function argument Indexing, not iterating, over a NumPy Array Disabling bounds checking and negative indices Summary For an introduction to Cython and how to use it, check out my post on using Cython to boost Python scripts. Otherwise, let’s get started! blog.paperspace.com We’ll start with the same code as in the previous tutorial, except here we’ll iterate through a NumPy array rather than a list. The NumPy array is created in the arr variable using the arrange() function, which returns one billion numbers starting from 0 with a step of 1. import timeimport numpytotal = 0arr = numpy.arange(1000000000)t1 = time.time()for k in arr: total = total + kt2 = time.time()print("Total = ", total)t = t2 - t1print("%.20f" % t) I’m running this on a machine with Core i7–6500U CPU @ 2.5 GHz, and 16 GB DDR3 RAM. The Python code completed in 458 seconds (7.63 minutes). It’s too long. Let’s see how much time it takes to complete after editing the Cython script created in the previous tutorial, as given below. The only change is the inclusion of the NumPy array in the for loop. Note that you have to rebuild the Cython script using the command below before using it. python setup.py build_ext --inplace The Cython script in its current form completed in 128 seconds (2.13 minutes). Still long, but it’s a start. Let’s see how we can make it even faster. Previously we saw that Cython code runs very quickly after explicitly defining C types for the variables used. This is also the case for the NumPy array. If we leave the NumPy array in its current form, Cython works exactly as regular Python does by creating an object for each number in the array. To make things run faster we need to define a C data type for the NumPy array as well, just like for any other variable. The data type for NumPy arrays is ndarray, which stands for n-dimensional array. If you used the keyword int for creating a variable of type integer, then you can use ndarray for creating a variable for a NumPy array. Note that ndarray must be called using NumPy, because ndarray is inside NumPy. So, the syntax for creating a NumPy array variable is numpy.ndarray. The code listed below creates a variable named arr with data type NumPy ndarray. The first important thing to note is that NumPy is imported using the regular keyword import in the second line. In the third line, you may notice that NumPy is also imported using the keyword cimport. It’s time to see that a Cython file can be classified into two categories: Definition file (.pxd)Implementation file (.pyx) Definition file (.pxd) Implementation file (.pyx) The definition file has the extension .pxd and is used to hold C declarations, such as data types to be imported and used in other Cython files. The other file is the implementation file with extension .pyx, which we are currently using to write Cython code. Within this file, we can import a definition file to use what is declared within it. The code below is to be written inside an implementation file with extension .pyx. The cimport numpy statement imports a definition file in Cython named “numpy”. The is done because the Cython “numpy” file has the data types for handling NumPy arrays. The code below defines the variables discussed previously, which are maxval, total, k, t1, t2, and t. There is a new variable named arr which holds the array, with data type numpy.ndarray. Previously two import statements were used, namely import numpy and cimport numpy. Which one is relevant here? Here we'll use need cimport numpy, not regular import. This is what lets us access the numpy.ndarray type declared within the Cython numpy definition file, so we can define the type of the arr variable to numpy.ndarray. The maxval variable is set equal to the length of the NumPy array. We can start by creating an array of length 10,000 and increase this number later to compare how Cython improves compared to Python. import timeimport numpycimport numpycdef unsigned long long int maxvalcdef unsigned long long int totalcdef int kcdef double t1, t2, tcdef numpy.ndarray arrmaxval = 10000arr = numpy.arange(maxval)t1 = time.time()for k in arr: total = total + kprint "Total =", totalt2 = time.time()t = t2 - t1print("%.20f" % t) After creating a variable of type numpy.ndarray and defining its length, next is to create the array using the numpy.arange() function. Notice that here we're using the Python NumPy, imported using the import numpy statement. By running the above code, Cython took just 0.001 seconds to complete. For Python, the code took 0.003 seconds. Cython is nearly 3x faster than Python in this case. When the maxsize variable is set to 1 million, the Cython code runs in 0.096 seconds while Python takes 0.293 seconds (Cython is also 3x faster). When working with 100 million, Cython takes 10.220 seconds compared to 37.173 with Python. For 1 billion, Cython takes 120 seconds, whereas Python takes 458. Still, Cython can do better. Let's see how. The first improvement is related to the datatype of the array. The datatype of the NumPy array arr is defined according to the next line. Note that all we did is define the type of the array, but we can give more information to Cython to simplify things. Note that there is nothing that can warn you that there is a part of the code that needs to be optimized. Everything will work; you have to investigate your code to find the parts that could be optimized to run faster. cdef numpy.ndarray arr In addition to defining the datatype of the array, we can define two more pieces of information: Datatype for array elementsNumber of dimensions Datatype for array elements Number of dimensions The datatype of the array elements is int and defined according to the line below. The numpy imported using cimport has a type corresponding to each type in NumPy but with _t at the end. For example, int in regular NumPy corresponds to int_t in Cython. The argument is ndim, which specifies the number of dimensions in the array. It is set to 1 here. Note that its default value is also 1, and thus can be omitted from our example. If more dimensions are being used, we must specify it. cdef numpy.ndarray[numpy.int_t, ndim=1] arr Unfortunately, you are only permitted to define the type of the NumPy array this way when it is an argument inside a function, or a local variable in the function– not inside the script body. I hope Cython overcomes this issue soon. We now need to edit the previous code to add it within a function which will be created in the next section. For now, let’s create the array after defining it. Note that we defined the type of the variable arr to be numpy.ndarray, but do not forget that this is the type of the container. This container has elements and these elements are translated as objects if nothing else is specified. To force these elements to be integers, the dtype argument is set to numpy.int according to the next line. arr = numpy.arange(maxval, dtype=numpy.int) The numpy used here is the one imported using the cimport keyword. Generally, whenever you find the keyword numpy used to define a variable, then make sure it is the one imported from Cython using the cimport keyword. After preparing the array, next is to create a function that accepts a variable of type numpy.ndarray as listed below. The function is named do_calc(). import timeimport numpycimport numpyctypedef numpy.int_t DTYPE_tdef do_calc(numpy.ndarray[DTYPE_t, ndim=1] arr): cdef int maxval cdef unsigned long long int total cdef int k cdef double t1, t2, t t1 = time.time() for k in arr: total = total + k print "Total = ", total t2 = time.time() t = t2 - t1 print("%.20f" % t) After building the Cython script, next we call the function do_calc() according to the code below. import test_cythonimport numpyarr = numpy.arange(1000000000, dtype=numpy.int)test_cython.do_calc(arr) The computational time in this case is reduced from 120 seconds to 98 seconds. This makes Cython 5x faster than Python for summing 1 billion numbers. As you might expect by now, to me this is still not fast enough. We'll see another trick to speed up computation in the next section. Cython just reduced the computational time by 5x factor which is something not to encourage me using Cython. But it is not a problem of Cython but a problem of using it. The problem is exactly how the loop is created. Let’s have a closer look at the loop which is given below. In the previous tutorial, something very important is mentioned which is that Python is just an interface. An interface just makes things easier to the user. Note that the easy way is not always an efficient way to do something. Python has a special way of iterating over arrays which are implemented in the loop below. The loop variable k loops through the arr NumPy array where element by element is fetched from the array. The variable k is assigned to such the returned element. Looping through the array this way is a style introduced in Python but it is not the way that C uses for looping through an array. for k in arr: total = total + k The normal way for looping through an array for programming languages is to create indices starting from 0 (sometimes from 1) until reaching the last index in the array. Each index is used for indexing the array to return the corresponding element. This is the normal way for looping through an array. Because C does not know how to loop through the array in the Python style, then the above loop is executed in Python style and thus takes much time for being executed. In order to overcome this issue, we need to create a loop in the normal style that uses indices for accessing the array elements. The new loop is implemented as follows. At first, there is a new variable named arr_shape used to store the number of elements within the array. In our example, there is only a single dimension and its length is returned by indexing the result of arr.shape using index 0. The arr_shape variable is then fed to the range() function which returns the indices for accessing the array elements. In this case, the variable k represents an index, not an array value. Inside the loop, the elements are returned by indexing the variable arr by the index k. cdef int arr_shape = arr.shape[0]for k in range(arr_shape): total = total + arr[k] Let’s edit the Cython script to include the above loop. The new Script is listed below. The old loop is commented out. import timeimport numpycimport numpyctypedef numpy.int_t DTYPE_tdef do_calc(numpy.ndarray[DTYPE_t, ndim=1] arr): cdef int maxval cdef unsigned long long int total cdef int k cdef double t1, t2, t cdef int arr_shape = arr.shape[0] t1=time.time()# for k in arr:# total = total + k for k in range(arr_shape): total = total + arr[k] print "Total =", total t2=time.time() t = t2-t1 print("%.20f" % t) By building the Cython script, the computational time is now around just a single second for summing 1 billion numbers after changing the loop to use indices. So, the time is reduced from 120 seconds to just 1 second. This is what we expected from Cython. Note that nothing wrong happens when we used the Python style for looping through the array. No indication to help us figure out why the code is not optimized. Thus, we have to look carefully for each part of the code for the possibility of optimization. Note that regular Python takes more than 500 seconds for executing the above code while Cython just takes around 1 second. Thus, Cython is 500x times faster than Python for summing 1 billion numbers. Super. Remember that we sacrificed by the Python simplicity for reducing the computational time. In my opinion, reducing the time by 500x factor worth the effort for optimizing the code using Cython. Reaching 500x faster code is great but still, there is an improvement which is discussed in the next section. There are a number of factors that causes the code to be slower as discussed in the Cython documentation which are: Bounds checking for making sure the indices are within the range of the array.Using negative indices for accessing array elements. Bounds checking for making sure the indices are within the range of the array. Using negative indices for accessing array elements. These 2 features are active when Cython executes the code. You can use a negative index such as -1 to access the last element in the array. Cython also makes sure no index is out of the range and the code will not crash if that happens. If you are not in need of such features, you can disable it to save more time. This is by adding the following lines. cimport [email protected](False)@cython.wraparound(False) The new code after disabling such features is as follows: import timeimport numpycimport numpycimport cythonctypedef numpy.int_t [email protected](False) # turn off bounds-checking for entire [email protected](False) # turn off negative index wrapping for entire functiondef do_calc(numpy.ndarray[DTYPE_t, ndim=1] arr): cdef int maxval cdef unsigned long long int total cdef int k cdef double t1, t2, t cdef int arr_shape = arr.shape[0] t1=time.time()# for k in arr:# total = total + k for k in range(arr_shape): total = total + arr[k] print "Total =", total t2=time.time() t = t2-t1 print("%.20f" % t) After building and running the Cython script, the time is around 0.09 seconds for summing numbers from 0 to 100000000. Compared to the computational time of the Python script which is around 500 seconds, Cython is over 5000 times faster than Python. In case of using the numpy.sum() function as in the next code, the time is around 0.38 seconds. That is Cython is 4 times faster. import numpyimport timearr = numpy.arange(100000000)t1 = time.time()result = numpy.sum(arr)t2 = time.time()t = t2 - t1print("%.20f" % t) This tutorial used Cython to boost the performance of NumPy array processing. We accomplished this in four different ways: We began by specifying the data type of the NumPy array using the numpy.ndarray. We saw that this type is available in the definition file imported using the cimport keyword. Just assigning the numpy.ndarray type to a variable is a start–but it's not enough. There are still two pieces of information to be provided: the data type of the array elements, and the dimensionality of the array. Both have a big impact on processing time. These details are only accepted when the NumPy arrays are defined as a function argument, or as a local variable inside a function. We therefore add the Cython code at these points. You can also specify the return data type of the function. The third way to reduce processing time is to avoid Pythonic looping, in which a variable is assigned value by value from the array. Instead, just loop through the array using indexing. This leads to a major reduction in time. Finally, you can reduce some extra milliseconds by disabling some checks that are done by default in Cython for each function. These include “bounds checking” and “wrapping around.” Disabling these features depends on your exact needs. For example, if you use negative indexing, then you need the wrapping around feature enabled. This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient. This tutorial discussed using Cython for manipulating NumPy arrays with a speed of more than 5000x times Python processing alone. The key for reducing the computational time is to specify the data types for the variables, and to index the array rather than iterate through it. In the next tutorial, we will summarize and advance on our knowledge thus far by using Cython to reduce the computational time for a Python implementation of the genetic algorithm.
[ { "code": null, "e": 377, "s": 172, "text": "This tutorial will show you how to speed up the processing of NumPy arrays using Cython. By explicitly specifying the data types of variables in Python, Cython can give drastic speed increases at runtime." }, { "code": null, "e": 431, "s": 377, "text": "The sections covered in this tutorial are as follows:" }, { "code": null, "e": 460, "s": 431, "text": "Looping through NumPy arrays" }, { "code": null, "e": 493, "s": 460, "text": "The Cython type for NumPy arrays" }, { "code": null, "e": 527, "s": 493, "text": "Data type of NumPy array elements" }, { "code": null, "e": 562, "s": 527, "text": "NumPy array as a function argument" }, { "code": null, "e": 606, "s": 562, "text": "Indexing, not iterating, over a NumPy Array" }, { "code": null, "e": 653, "s": 606, "text": "Disabling bounds checking and negative indices" }, { "code": null, "e": 661, "s": 653, "text": "Summary" }, { "code": null, "e": 799, "s": 661, "text": "For an introduction to Cython and how to use it, check out my post on using Cython to boost Python scripts. Otherwise, let’s get started!" }, { "code": null, "e": 819, "s": 799, "text": "blog.paperspace.com" }, { "code": null, "e": 1092, "s": 819, "text": "We’ll start with the same code as in the previous tutorial, except here we’ll iterate through a NumPy array rather than a list. The NumPy array is created in the arr variable using the arrange() function, which returns one billion numbers starting from 0 with a step of 1." }, { "code": null, "e": 1274, "s": 1092, "text": "import timeimport numpytotal = 0arr = numpy.arange(1000000000)t1 = time.time()for k in arr: total = total + kt2 = time.time()print(\"Total = \", total)t = t2 - t1print(\"%.20f\" % t)" }, { "code": null, "e": 1430, "s": 1274, "text": "I’m running this on a machine with Core i7–6500U CPU @ 2.5 GHz, and 16 GB DDR3 RAM. The Python code completed in 458 seconds (7.63 minutes). It’s too long." }, { "code": null, "e": 1715, "s": 1430, "text": "Let’s see how much time it takes to complete after editing the Cython script created in the previous tutorial, as given below. The only change is the inclusion of the NumPy array in the for loop. Note that you have to rebuild the Cython script using the command below before using it." }, { "code": null, "e": 1751, "s": 1715, "text": "python setup.py build_ext --inplace" }, { "code": null, "e": 1902, "s": 1751, "text": "The Cython script in its current form completed in 128 seconds (2.13 minutes). Still long, but it’s a start. Let’s see how we can make it even faster." }, { "code": null, "e": 2322, "s": 1902, "text": "Previously we saw that Cython code runs very quickly after explicitly defining C types for the variables used. This is also the case for the NumPy array. If we leave the NumPy array in its current form, Cython works exactly as regular Python does by creating an object for each number in the array. To make things run faster we need to define a C data type for the NumPy array as well, just like for any other variable." }, { "code": null, "e": 2769, "s": 2322, "text": "The data type for NumPy arrays is ndarray, which stands for n-dimensional array. If you used the keyword int for creating a variable of type integer, then you can use ndarray for creating a variable for a NumPy array. Note that ndarray must be called using NumPy, because ndarray is inside NumPy. So, the syntax for creating a NumPy array variable is numpy.ndarray. The code listed below creates a variable named arr with data type NumPy ndarray." }, { "code": null, "e": 2971, "s": 2769, "text": "The first important thing to note is that NumPy is imported using the regular keyword import in the second line. In the third line, you may notice that NumPy is also imported using the keyword cimport." }, { "code": null, "e": 3046, "s": 2971, "text": "It’s time to see that a Cython file can be classified into two categories:" }, { "code": null, "e": 3095, "s": 3046, "text": "Definition file (.pxd)Implementation file (.pyx)" }, { "code": null, "e": 3118, "s": 3095, "text": "Definition file (.pxd)" }, { "code": null, "e": 3145, "s": 3118, "text": "Implementation file (.pyx)" }, { "code": null, "e": 3489, "s": 3145, "text": "The definition file has the extension .pxd and is used to hold C declarations, such as data types to be imported and used in other Cython files. The other file is the implementation file with extension .pyx, which we are currently using to write Cython code. Within this file, we can import a definition file to use what is declared within it." }, { "code": null, "e": 3741, "s": 3489, "text": "The code below is to be written inside an implementation file with extension .pyx. The cimport numpy statement imports a definition file in Cython named “numpy”. The is done because the Cython “numpy” file has the data types for handling NumPy arrays." }, { "code": null, "e": 4261, "s": 3741, "text": "The code below defines the variables discussed previously, which are maxval, total, k, t1, t2, and t. There is a new variable named arr which holds the array, with data type numpy.ndarray. Previously two import statements were used, namely import numpy and cimport numpy. Which one is relevant here? Here we'll use need cimport numpy, not regular import. This is what lets us access the numpy.ndarray type declared within the Cython numpy definition file, so we can define the type of the arr variable to numpy.ndarray." }, { "code": null, "e": 4461, "s": 4261, "text": "The maxval variable is set equal to the length of the NumPy array. We can start by creating an array of length 10,000 and increase this number later to compare how Cython improves compared to Python." }, { "code": null, "e": 4775, "s": 4461, "text": "import timeimport numpycimport numpycdef unsigned long long int maxvalcdef unsigned long long int totalcdef int kcdef double t1, t2, tcdef numpy.ndarray arrmaxval = 10000arr = numpy.arange(maxval)t1 = time.time()for k in arr: total = total + kprint \"Total =\", totalt2 = time.time()t = t2 - t1print(\"%.20f\" % t)" }, { "code": null, "e": 5001, "s": 4775, "text": "After creating a variable of type numpy.ndarray and defining its length, next is to create the array using the numpy.arange() function. Notice that here we're using the Python NumPy, imported using the import numpy statement." }, { "code": null, "e": 5166, "s": 5001, "text": "By running the above code, Cython took just 0.001 seconds to complete. For Python, the code took 0.003 seconds. Cython is nearly 3x faster than Python in this case." }, { "code": null, "e": 5514, "s": 5166, "text": "When the maxsize variable is set to 1 million, the Cython code runs in 0.096 seconds while Python takes 0.293 seconds (Cython is also 3x faster). When working with 100 million, Cython takes 10.220 seconds compared to 37.173 with Python. For 1 billion, Cython takes 120 seconds, whereas Python takes 458. Still, Cython can do better. Let's see how." }, { "code": null, "e": 5769, "s": 5514, "text": "The first improvement is related to the datatype of the array. The datatype of the NumPy array arr is defined according to the next line. Note that all we did is define the type of the array, but we can give more information to Cython to simplify things." }, { "code": null, "e": 5988, "s": 5769, "text": "Note that there is nothing that can warn you that there is a part of the code that needs to be optimized. Everything will work; you have to investigate your code to find the parts that could be optimized to run faster." }, { "code": null, "e": 6011, "s": 5988, "text": "cdef numpy.ndarray arr" }, { "code": null, "e": 6108, "s": 6011, "text": "In addition to defining the datatype of the array, we can define two more pieces of information:" }, { "code": null, "e": 6156, "s": 6108, "text": "Datatype for array elementsNumber of dimensions" }, { "code": null, "e": 6184, "s": 6156, "text": "Datatype for array elements" }, { "code": null, "e": 6205, "s": 6184, "text": "Number of dimensions" }, { "code": null, "e": 6458, "s": 6205, "text": "The datatype of the array elements is int and defined according to the line below. The numpy imported using cimport has a type corresponding to each type in NumPy but with _t at the end. For example, int in regular NumPy corresponds to int_t in Cython." }, { "code": null, "e": 6692, "s": 6458, "text": "The argument is ndim, which specifies the number of dimensions in the array. It is set to 1 here. Note that its default value is also 1, and thus can be omitted from our example. If more dimensions are being used, we must specify it." }, { "code": null, "e": 6736, "s": 6692, "text": "cdef numpy.ndarray[numpy.int_t, ndim=1] arr" }, { "code": null, "e": 7129, "s": 6736, "text": "Unfortunately, you are only permitted to define the type of the NumPy array this way when it is an argument inside a function, or a local variable in the function– not inside the script body. I hope Cython overcomes this issue soon. We now need to edit the previous code to add it within a function which will be created in the next section. For now, let’s create the array after defining it." }, { "code": null, "e": 7468, "s": 7129, "text": "Note that we defined the type of the variable arr to be numpy.ndarray, but do not forget that this is the type of the container. This container has elements and these elements are translated as objects if nothing else is specified. To force these elements to be integers, the dtype argument is set to numpy.int according to the next line." }, { "code": null, "e": 7512, "s": 7468, "text": "arr = numpy.arange(maxval, dtype=numpy.int)" }, { "code": null, "e": 7730, "s": 7512, "text": "The numpy used here is the one imported using the cimport keyword. Generally, whenever you find the keyword numpy used to define a variable, then make sure it is the one imported from Cython using the cimport keyword." }, { "code": null, "e": 7882, "s": 7730, "text": "After preparing the array, next is to create a function that accepts a variable of type numpy.ndarray as listed below. The function is named do_calc()." }, { "code": null, "e": 8244, "s": 7882, "text": "import timeimport numpycimport numpyctypedef numpy.int_t DTYPE_tdef do_calc(numpy.ndarray[DTYPE_t, ndim=1] arr): cdef int maxval cdef unsigned long long int total cdef int k cdef double t1, t2, t t1 = time.time() for k in arr: total = total + k print \"Total = \", total t2 = time.time() t = t2 - t1 print(\"%.20f\" % t)" }, { "code": null, "e": 8343, "s": 8244, "text": "After building the Cython script, next we call the function do_calc() according to the code below." }, { "code": null, "e": 8445, "s": 8343, "text": "import test_cythonimport numpyarr = numpy.arange(1000000000, dtype=numpy.int)test_cython.do_calc(arr)" }, { "code": null, "e": 8729, "s": 8445, "text": "The computational time in this case is reduced from 120 seconds to 98 seconds. This makes Cython 5x faster than Python for summing 1 billion numbers. As you might expect by now, to me this is still not fast enough. We'll see another trick to speed up computation in the next section." }, { "code": null, "e": 9006, "s": 8729, "text": "Cython just reduced the computational time by 5x factor which is something not to encourage me using Cython. But it is not a problem of Cython but a problem of using it. The problem is exactly how the loop is created. Let’s have a closer look at the loop which is given below." }, { "code": null, "e": 9235, "s": 9006, "text": "In the previous tutorial, something very important is mentioned which is that Python is just an interface. An interface just makes things easier to the user. Note that the easy way is not always an efficient way to do something." }, { "code": null, "e": 9620, "s": 9235, "text": "Python has a special way of iterating over arrays which are implemented in the loop below. The loop variable k loops through the arr NumPy array where element by element is fetched from the array. The variable k is assigned to such the returned element. Looping through the array this way is a style introduced in Python but it is not the way that C uses for looping through an array." }, { "code": null, "e": 9655, "s": 9620, "text": "for k in arr: total = total + k" }, { "code": null, "e": 10125, "s": 9655, "text": "The normal way for looping through an array for programming languages is to create indices starting from 0 (sometimes from 1) until reaching the last index in the array. Each index is used for indexing the array to return the corresponding element. This is the normal way for looping through an array. Because C does not know how to loop through the array in the Python style, then the above loop is executed in Python style and thus takes much time for being executed." }, { "code": null, "e": 10295, "s": 10125, "text": "In order to overcome this issue, we need to create a loop in the normal style that uses indices for accessing the array elements. The new loop is implemented as follows." }, { "code": null, "e": 10527, "s": 10295, "text": "At first, there is a new variable named arr_shape used to store the number of elements within the array. In our example, there is only a single dimension and its length is returned by indexing the result of arr.shape using index 0." }, { "code": null, "e": 10716, "s": 10527, "text": "The arr_shape variable is then fed to the range() function which returns the indices for accessing the array elements. In this case, the variable k represents an index, not an array value." }, { "code": null, "e": 10804, "s": 10716, "text": "Inside the loop, the elements are returned by indexing the variable arr by the index k." }, { "code": null, "e": 10890, "s": 10804, "text": "cdef int arr_shape = arr.shape[0]for k in range(arr_shape): total = total + arr[k]" }, { "code": null, "e": 11009, "s": 10890, "text": "Let’s edit the Cython script to include the above loop. The new Script is listed below. The old loop is commented out." }, { "code": null, "e": 11459, "s": 11009, "text": "import timeimport numpycimport numpyctypedef numpy.int_t DTYPE_tdef do_calc(numpy.ndarray[DTYPE_t, ndim=1] arr): cdef int maxval cdef unsigned long long int total cdef int k cdef double t1, t2, t cdef int arr_shape = arr.shape[0] t1=time.time()# for k in arr:# total = total + k for k in range(arr_shape): total = total + arr[k] print \"Total =\", total t2=time.time() t = t2-t1 print(\"%.20f\" % t)" }, { "code": null, "e": 11715, "s": 11459, "text": "By building the Cython script, the computational time is now around just a single second for summing 1 billion numbers after changing the loop to use indices. So, the time is reduced from 120 seconds to just 1 second. This is what we expected from Cython." }, { "code": null, "e": 11970, "s": 11715, "text": "Note that nothing wrong happens when we used the Python style for looping through the array. No indication to help us figure out why the code is not optimized. Thus, we have to look carefully for each part of the code for the possibility of optimization." }, { "code": null, "e": 12370, "s": 11970, "text": "Note that regular Python takes more than 500 seconds for executing the above code while Cython just takes around 1 second. Thus, Cython is 500x times faster than Python for summing 1 billion numbers. Super. Remember that we sacrificed by the Python simplicity for reducing the computational time. In my opinion, reducing the time by 500x factor worth the effort for optimizing the code using Cython." }, { "code": null, "e": 12480, "s": 12370, "text": "Reaching 500x faster code is great but still, there is an improvement which is discussed in the next section." }, { "code": null, "e": 12596, "s": 12480, "text": "There are a number of factors that causes the code to be slower as discussed in the Cython documentation which are:" }, { "code": null, "e": 12727, "s": 12596, "text": "Bounds checking for making sure the indices are within the range of the array.Using negative indices for accessing array elements." }, { "code": null, "e": 12806, "s": 12727, "text": "Bounds checking for making sure the indices are within the range of the array." }, { "code": null, "e": 12859, "s": 12806, "text": "Using negative indices for accessing array elements." }, { "code": null, "e": 13214, "s": 12859, "text": "These 2 features are active when Cython executes the code. You can use a negative index such as -1 to access the last element in the array. Cython also makes sure no index is out of the range and the code will not crash if that happens. If you are not in need of such features, you can disable it to save more time. This is by adding the following lines." }, { "code": null, "e": 13280, "s": 13214, "text": "cimport [email protected](False)@cython.wraparound(False)" }, { "code": null, "e": 13338, "s": 13280, "text": "The new code after disabling such features is as follows:" }, { "code": null, "e": 13952, "s": 13338, "text": "import timeimport numpycimport numpycimport cythonctypedef numpy.int_t [email protected](False) # turn off bounds-checking for entire [email protected](False) # turn off negative index wrapping for entire functiondef do_calc(numpy.ndarray[DTYPE_t, ndim=1] arr): cdef int maxval cdef unsigned long long int total cdef int k cdef double t1, t2, t cdef int arr_shape = arr.shape[0] t1=time.time()# for k in arr:# total = total + k for k in range(arr_shape): total = total + arr[k] print \"Total =\", total t2=time.time() t = t2-t1 print(\"%.20f\" % t)" }, { "code": null, "e": 14202, "s": 13952, "text": "After building and running the Cython script, the time is around 0.09 seconds for summing numbers from 0 to 100000000. Compared to the computational time of the Python script which is around 500 seconds, Cython is over 5000 times faster than Python." }, { "code": null, "e": 14332, "s": 14202, "text": "In case of using the numpy.sum() function as in the next code, the time is around 0.38 seconds. That is Cython is 4 times faster." }, { "code": null, "e": 14469, "s": 14332, "text": "import numpyimport timearr = numpy.arange(100000000)t1 = time.time()result = numpy.sum(arr)t2 = time.time()t = t2 - t1print(\"%.20f\" % t)" }, { "code": null, "e": 14592, "s": 14469, "text": "This tutorial used Cython to boost the performance of NumPy array processing. We accomplished this in four different ways:" }, { "code": null, "e": 14767, "s": 14592, "text": "We began by specifying the data type of the NumPy array using the numpy.ndarray. We saw that this type is available in the definition file imported using the cimport keyword." }, { "code": null, "e": 15026, "s": 14767, "text": "Just assigning the numpy.ndarray type to a variable is a start–but it's not enough. There are still two pieces of information to be provided: the data type of the array elements, and the dimensionality of the array. Both have a big impact on processing time." }, { "code": null, "e": 15267, "s": 15026, "text": "These details are only accepted when the NumPy arrays are defined as a function argument, or as a local variable inside a function. We therefore add the Cython code at these points. You can also specify the return data type of the function." }, { "code": null, "e": 15494, "s": 15267, "text": "The third way to reduce processing time is to avoid Pythonic looping, in which a variable is assigned value by value from the array. Instead, just loop through the array using indexing. This leads to a major reduction in time." }, { "code": null, "e": 15824, "s": 15494, "text": "Finally, you can reduce some extra milliseconds by disabling some checks that are done by default in Cython for each function. These include “bounds checking” and “wrapping around.” Disabling these features depends on your exact needs. For example, if you use negative indexing, then you need the wrapping around feature enabled." }, { "code": null, "e": 15946, "s": 15824, "text": "This article was originally published on the Paperspace blog. You can run the code for my tutorials for free on Gradient." }, { "code": null, "e": 16223, "s": 15946, "text": "This tutorial discussed using Cython for manipulating NumPy arrays with a speed of more than 5000x times Python processing alone. The key for reducing the computational time is to specify the data types for the variables, and to index the array rather than iterate through it." } ]
A guy with a mental problem | Practice | GeeksforGeeks
A guy has to reach his home and does not want to be late. He takes train to reach home. He has a mental illness, so he always switches train at every station. For eg: If he starts with train A then at station 2 he will switch his train to train B and so on. Similarly, if he starts with train B then he will switch to train A at station 2 and so on. Please help him to find the minimum total time he would take to reach his home. Example 1: Input: N = 3 A[] = {2, 1, 2} B[] = {3, 2, 1} Output: 5 Explanation: If he chose train A initially, then time to reach home will be : 2 + 2 + 2 = 6 If he Chose train B initially, then time to reach home will be : 3 + 1 + 1 = 5 5 is minimum hence the answer. Your Task: You don't need to read input or print anything. Your task is to complete the function minTime() which takes the array A[], B[] and its size N as inputs and returns the minimum total time in seconds to reach home. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 106 1 ≤ Ai, Bi ≤ 106 0 arvind16yadav2 weeks ago /*JAVA CODE*/ /*Time : 0.7 / 7.3 (Ten time faster)*/ public long minTime(long a[], long b[], long n) { // Your code goes here long time_a = 0; long time_b = 0; // time for time_a i.e, start with a for(long i = 0; i<n; i+=2){ time_a += a[(int)i]; } for(long i=1; i<n; i+=2){ time_a += b[(int)i]; } // time for time_b i.e, start with b for(long i = 0; i<n; i+=2){ time_b += b[(int)i]; } for(long i=1; i<n; i+=2){ time_b += a[(int)i]; } return (time_a < time_b) ? time_a : time_b; } 0 divyabhatia5191 month ago JAVA Solution :- public long minTime(long a[], long b[], long n) { // Your code goes here long a1 = 0 , b1 = 0; for(int i = 0; i < n; i++){ if(i % 2 == 0){ a1 += a[i]; b1 += b[i]; }else{ a1 += b[i]; b1 += a[i]; } } return Math.min(a1 , b1); } 0 princejee20191 month ago C++ || EASY TO UNDERSTAND long long minTime(long long a[], long long b[], long long n){ long long ans =0,ans2=0; for(int i =0;i<n;i++){ if(i%2==0) ans+=a[i]; else ans+=b[i]; } for(int i =0;i<n;i++){ if(i%2!=0) ans2+=a[i]; else ans2+=b[i]; } long long mi = min(ans,ans2); return mi; } 0 hasnainraza1998hr2 months ago C++ long long minTime(long long a[], long long b[], long long n) { long long ATime=0; long long BTime=0; for(int i=0;i<n;i++){ if(i%2==0){ ATime += a[i]; BTime += b[i]; } else{ ATime += b[i]; BTime += a[i]; } } return min(ATime,BTime); } 0 mananpushkar3 months ago long long minTime(long long a[], long long b[], long long n) { long long sum1=0; long long sum2=0; sum1+=a[0]; sum2+=b[0]; for(long long int i=1;i<n;i++) { if(i%2==0) { sum1+=a[i]; sum2+=b[i]; } else { sum1+=b[i]; sum2+=a[i]; } } if(sum1<sum2) return sum1; else return sum2; } 0 lasthoneybadger3 months ago // Your code goes here long a1 = 0 , b1 = 0; for(int i = 0; i < n; i++){ if(i % 2 == 0){ a1 += a[i]; b1 += b[i]; }else{ a1 += b[i]; b1 += a[i]; } } return Math.min(a1 , b1); 0 mayank20214 months ago C++ : in one for Looplong long minTime(long long a[], long long b[], long long n) { long long sum_first=0, sum_second=0; for(int i=0; i<n; ) { sum_first = sum_first + a[i]; sum_second=sum_second + b[i]; if(i+1<n) { sum_first = sum_first + b[i+1]; sum_second=sum_second + a[i+1]; } i=i+2; } //cout<<sum_first<<" "<<sum_second<<endl; return (sum_first< sum_second)? sum_first:sum_second; } 0 user_i9s04 months ago // Your code goes here long long s=0,t=0,u=0,v=0; for(long long i=0;i<n;i=i+2){ s=s+a[i]; u=u+b[i]; } for(long long j=1;j<n;j=j+2){ t=t+b[j]; v=v+a[j]; } long long total1=s+t; long long total2=u+v; if(total1>total2){ return total2; } return total1; 0 debujjal46 months ago long long sum1=0; long long sum2=0; for(int i=0;i<n;i++){ if(i%2==0){ sum1+=a[i]; sum2+=b[i]; }else{ sum1+=b[i]; sum2+=a[i]; } } if(sum1<sum2){ return sum1; }else{ return sum2; } 0 sagarmish12346 months ago C++ 0.4 solution (ternary magic) long long minTime(long long a[], long long b[], long long n) { long long A=0,B=0; int flag=1; for(int i=0;i<n;i++){ A+= flag?a[i]:b[i]; B+= flag?b[i]:a[i]; flag = flag?0:1; } return min(A,B); // Your code goes here } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 656, "s": 226, "text": "A guy has to reach his home and does not want to be late. He takes train to reach home. He has a mental illness, so he always switches train at every station.\nFor eg: If he starts with train A then at station 2 he will switch his train to train B and so on. Similarly, if he starts with train B then he will switch to train A at station 2 and so on. Please help him to find the minimum total time he would take to reach his home." }, { "code": null, "e": 669, "s": 658, "text": "Example 1:" }, { "code": null, "e": 927, "s": 669, "text": "Input:\nN = 3\nA[] = {2, 1, 2}\nB[] = {3, 2, 1}\nOutput:\n5\nExplanation:\nIf he chose train A initially, then time to\nreach home will be : 2 + 2 + 2 = 6 \nIf he Chose train B initially, then time to\nreach home will be : 3 + 1 + 1 = 5\n5 is minimum hence the answer." }, { "code": null, "e": 1155, "s": 929, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function minTime() which takes the array A[], B[] and its size N as inputs and returns the minimum total time in seconds to reach home." }, { "code": null, "e": 1218, "s": 1155, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1262, "s": 1220, "text": "Constraints:\n1 ≤ N ≤ 106\n1 ≤ Ai, Bi ≤ 106" }, { "code": null, "e": 1264, "s": 1262, "text": "0" }, { "code": null, "e": 1289, "s": 1264, "text": "arvind16yadav2 weeks ago" }, { "code": null, "e": 1303, "s": 1289, "text": "/*JAVA CODE*/" }, { "code": null, "e": 1343, "s": 1303, "text": "/*Time : 0.7 / 7.3 (Ten time faster)*/" }, { "code": null, "e": 1940, "s": 1343, "text": "public long minTime(long a[], long b[], long n) { // Your code goes here long time_a = 0; long time_b = 0; // time for time_a i.e, start with a for(long i = 0; i<n; i+=2){ time_a += a[(int)i]; } for(long i=1; i<n; i+=2){ time_a += b[(int)i]; } // time for time_b i.e, start with b for(long i = 0; i<n; i+=2){ time_b += b[(int)i]; } for(long i=1; i<n; i+=2){ time_b += a[(int)i]; } return (time_a < time_b) ? time_a : time_b; }" }, { "code": null, "e": 1942, "s": 1940, "text": "0" }, { "code": null, "e": 1968, "s": 1942, "text": "divyabhatia5191 month ago" }, { "code": null, "e": 1985, "s": 1968, "text": "JAVA Solution :-" }, { "code": null, "e": 2339, "s": 1987, "text": "public long minTime(long a[], long b[], long n) { // Your code goes here long a1 = 0 , b1 = 0; for(int i = 0; i < n; i++){ if(i % 2 == 0){ a1 += a[i]; b1 += b[i]; }else{ a1 += b[i]; b1 += a[i]; } } return Math.min(a1 , b1); }" }, { "code": null, "e": 2341, "s": 2339, "text": "0" }, { "code": null, "e": 2366, "s": 2341, "text": "princejee20191 month ago" }, { "code": null, "e": 2392, "s": 2366, "text": "C++ || EASY TO UNDERSTAND" }, { "code": null, "e": 2734, "s": 2392, "text": "long long minTime(long long a[], long long b[], long long n){ long long ans =0,ans2=0; for(int i =0;i<n;i++){ if(i%2==0) ans+=a[i]; else ans+=b[i]; } for(int i =0;i<n;i++){ if(i%2!=0) ans2+=a[i]; else ans2+=b[i]; } long long mi = min(ans,ans2); return mi; }" }, { "code": null, "e": 2736, "s": 2734, "text": "0" }, { "code": null, "e": 2766, "s": 2736, "text": "hasnainraza1998hr2 months ago" }, { "code": null, "e": 2770, "s": 2766, "text": "C++" }, { "code": null, "e": 3126, "s": 2770, "text": "long long minTime(long long a[], long long b[], long long n) { long long ATime=0; long long BTime=0; for(int i=0;i<n;i++){ if(i%2==0){ ATime += a[i]; BTime += b[i]; } else{ ATime += b[i]; BTime += a[i]; } } return min(ATime,BTime); }" }, { "code": null, "e": 3128, "s": 3126, "text": "0" }, { "code": null, "e": 3153, "s": 3128, "text": "mananpushkar3 months ago" }, { "code": null, "e": 3600, "s": 3153, "text": "long long minTime(long long a[], long long b[], long long n) { long long sum1=0; long long sum2=0; sum1+=a[0]; sum2+=b[0]; for(long long int i=1;i<n;i++) { if(i%2==0) { sum1+=a[i]; sum2+=b[i]; } else { sum1+=b[i]; sum2+=a[i]; } } if(sum1<sum2) return sum1; else return sum2; }" }, { "code": null, "e": 3604, "s": 3602, "text": "0" }, { "code": null, "e": 3632, "s": 3604, "text": "lasthoneybadger3 months ago" }, { "code": null, "e": 3939, "s": 3632, "text": "// Your code goes here \n long a1 = 0 , b1 = 0;\n for(int i = 0; i < n; i++){\n if(i % 2 == 0){\n a1 += a[i];\n b1 += b[i];\n }else{\n a1 += b[i];\n b1 += a[i];\n }\n }\n return Math.min(a1 , b1);" }, { "code": null, "e": 3941, "s": 3939, "text": "0" }, { "code": null, "e": 3964, "s": 3941, "text": "mayank20214 months ago" }, { "code": null, "e": 4559, "s": 3964, "text": "C++ : in one for Looplong long minTime(long long a[], long long b[], long long n) { long long sum_first=0, sum_second=0; for(int i=0; i<n; ) { sum_first = sum_first + a[i]; sum_second=sum_second + b[i]; if(i+1<n) { sum_first = sum_first + b[i+1]; sum_second=sum_second + a[i+1]; } i=i+2; } //cout<<sum_first<<\" \"<<sum_second<<endl; return (sum_first< sum_second)? sum_first:sum_second; }" }, { "code": null, "e": 4561, "s": 4559, "text": "0" }, { "code": null, "e": 4583, "s": 4561, "text": "user_i9s04 months ago" }, { "code": null, "e": 4943, "s": 4583, "text": " // Your code goes here long long s=0,t=0,u=0,v=0; for(long long i=0;i<n;i=i+2){ s=s+a[i]; u=u+b[i]; } for(long long j=1;j<n;j=j+2){ t=t+b[j]; v=v+a[j]; } long long total1=s+t; long long total2=u+v; if(total1>total2){ return total2; } return total1;" }, { "code": null, "e": 4945, "s": 4943, "text": "0" }, { "code": null, "e": 4967, "s": 4945, "text": "debujjal46 months ago" }, { "code": null, "e": 5303, "s": 4967, "text": "long long sum1=0;\n long long sum2=0;\n for(int i=0;i<n;i++){\n if(i%2==0){\n sum1+=a[i];\n sum2+=b[i];\n }else{\n sum1+=b[i];\n sum2+=a[i];\n }\n }\n if(sum1<sum2){\n return sum1;\n }else{\n return sum2;\n }" }, { "code": null, "e": 5305, "s": 5303, "text": "0" }, { "code": null, "e": 5331, "s": 5305, "text": "sagarmish12346 months ago" }, { "code": null, "e": 5364, "s": 5331, "text": "C++ 0.4 solution (ternary magic)" }, { "code": null, "e": 5675, "s": 5364, "text": "long long minTime(long long a[], long long b[], long long n)\n {\n long long A=0,B=0;\n int flag=1;\n for(int i=0;i<n;i++){\n A+= flag?a[i]:b[i];\n B+= flag?b[i]:a[i];\n flag = flag?0:1;\n }\n return min(A,B);\n // Your code goes here \n }" }, { "code": null, "e": 5821, "s": 5675, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5857, "s": 5821, "text": " Login to access your submissions. " }, { "code": null, "e": 5867, "s": 5857, "text": "\nProblem\n" }, { "code": null, "e": 5877, "s": 5867, "text": "\nContest\n" }, { "code": null, "e": 5940, "s": 5877, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6088, "s": 5940, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6296, "s": 6088, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6402, "s": 6296, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Creating WYSIWYG Document Editor | Natural Language Programming - GeeksforGeeks
01 Mar, 2018 When my elder son and I finished writing our Plain English compiler, we decided to test its usefulness by adding a what-you-see-is-what-you-get document editor that we could then use to document our system. Two birds with one stone! Document View We call this facility the Writer. This is what our instruction manual looks like when you open it in the Writer: We call this Document View: one line per page. Whole pages (and groups of pages, contiguous or not) can be selected, copied, cut, pasted, duplicated and printed in this view. They can also be saved in Adobe PDF format so folks without the Writer can read them. Page View When you open a page, you see that page exactly as it will appear when it is printed (or saved as a PDF page), albeit with sky-blue grid lines to aid in tasteful layout. This is how page 8 of our instruction manual appears on the screen: In this view, whole pages can be enlarged, reduced, rotated, and spell-checked. And various text and graphic “shapes” can be added, deleted, moved, sized, colored, flipped, mirrored, rotated, copied, cut, pasted, duplicated, grouped, etc. The Home, End, Page Up, and Page Down keys can be used to conveniently flip through the pages, without returning to Document View. Externalized Pages Documents (and parts of documents) can be saved, as mentioned above, as PDFs. But the native format for permanent storage is much simpler, and is text only. Consider, for example, the document below, which has just one page with four shapes on it: a pink ellipse, a green triangle, a blue square, and a text box with “ABC” in it: If you use our “Open as Text” command (or any other text editor) to open this document, this is what you’ll see: ream cal-3024 page 15840 12240 1 1440 ellipse 0 0 0 0 1000 875 1440 1440 2880 2880 polygon 0 0 0 1500 1000 875 4 4320 1440 5760 2880 4320 2880 4320 1440 rectangle 0 0 0 2100 1000 875 7200 1440 8640 2880 0 text 0 0 0 -1 0 0 10080 1440 14400 2880 0 "title" "osmosian" 1440 "center" 0 0 0 yes "ABC" end end end One entry for the whole document, one for each page, and one for each shape on the page. And not a single “<" in sight! It would be too much to paste the 4,000 Plain English sentences that define the whole Writer here. They are included in the source code that comes with our system www.osmosian.com/cal-4700.zip. For now, let’s settle for a sample routine: To group any selected shapes on a page: If the page is nil, exit. Create a group shape. Put "group" into the group shape's kind. Put the page's scale into the group shape's scale. Move the page's shapes to some original shapes. Loop. Put the original shapes' first into a shape. If the shape is nil, break. Remove the shape from the original shapes. If the shape is not selected, append the shape to the page's shapes; repeat. Deselect the shape. Append the shape to the group shape's shapes. Repeat. Append the group shape to the page's shapes. Select the group shape. Adjust the group shape. Shapes on pages are drawn back-to-front, so the newly grouped shapes will appear on top of the other shapes on the page. Not a Toy Please keep in mind that this is facility is not a “toy.” We used it, as I mentioned above, to write the documentation for our system. And since then it’s been used to produce an 800-page illustrated “teach your kid to read” course that you can see here: www.rhymingreader.com. Not to mention several other books for children, numerous training manuals, and presentation materials of all kinds, large and small. This is one of my all-time favorite pages, developed by a grade school teacher in an attempt to settle an age-old question: QED. GBlog Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar GET and POST requests using Python Top 10 Projects For Beginners To Practice HTML and CSS Skills Working with csv files in Python SDE SHEET - A Complete Guide for SDE Preparation XML parsing in Python Working with zip files in Python Python | Simple GUI calculator using Tkinter Simple Chat Room using Python
[ { "code": null, "e": 25136, "s": 25108, "text": "\n01 Mar, 2018" }, { "code": null, "e": 25369, "s": 25136, "text": "When my elder son and I finished writing our Plain English compiler, we decided to test its usefulness by adding a what-you-see-is-what-you-get document editor that we could then use to document our system. Two birds with one stone!" }, { "code": null, "e": 25383, "s": 25369, "text": "Document View" }, { "code": null, "e": 25496, "s": 25383, "text": "We call this facility the Writer. This is what our instruction manual looks like when you open it in the Writer:" }, { "code": null, "e": 25757, "s": 25496, "text": "We call this Document View: one line per page. Whole pages (and groups of pages, contiguous or not) can be selected, copied, cut, pasted, duplicated and printed in this view. They can also be saved in Adobe PDF format so folks without the Writer can read them." }, { "code": null, "e": 25767, "s": 25757, "text": "Page View" }, { "code": null, "e": 26005, "s": 25767, "text": "When you open a page, you see that page exactly as it will appear when it is printed (or saved as a PDF page), albeit with sky-blue grid lines to aid in tasteful layout. This is how page 8 of our instruction manual appears on the screen:" }, { "code": null, "e": 26375, "s": 26005, "text": "In this view, whole pages can be enlarged, reduced, rotated, and spell-checked. And various text and graphic “shapes” can be added, deleted, moved, sized, colored, flipped, mirrored, rotated, copied, cut, pasted, duplicated, grouped, etc. The Home, End, Page Up, and Page Down keys can be used to conveniently flip through the pages, without returning to Document View." }, { "code": null, "e": 26394, "s": 26375, "text": "Externalized Pages" }, { "code": null, "e": 26724, "s": 26394, "text": "Documents (and parts of documents) can be saved, as mentioned above, as PDFs. But the native format for permanent storage is much simpler, and is text only. Consider, for example, the document below, which has just one page with four shapes on it: a pink ellipse, a green triangle, a blue square, and a text box with “ABC” in it:" }, { "code": null, "e": 26837, "s": 26724, "text": "If you use our “Open as Text” command (or any other text editor) to open this document, this is what you’ll see:" }, { "code": null, "e": 27176, "s": 26837, "text": "ream cal-3024\n page 15840 12240 1 1440\n ellipse 0 0 0 0 1000 875 1440 1440 2880 2880\n polygon 0 0 0 1500 1000 875 4 4320 1440 5760 2880 4320 2880 4320 1440\n rectangle 0 0 0 2100 1000 875 7200 1440 8640 2880 0\n text 0 0 0 -1 0 0 10080 1440 14400 2880 0 \"title\" \"osmosian\" 1440 \"center\" 0 0 0 yes\n \"ABC\"\n end\n end\nend" }, { "code": null, "e": 27296, "s": 27176, "text": "One entry for the whole document, one for each page, and one for each shape on the page. And not a single “<\" in sight!" }, { "code": null, "e": 27534, "s": 27296, "text": "It would be too much to paste the 4,000 Plain English sentences that define the whole Writer here. They are included in the source code that comes with our system www.osmosian.com/cal-4700.zip. For now, let’s settle for a sample routine:" }, { "code": null, "e": 28131, "s": 27534, "text": "To group any selected shapes on a page:\nIf the page is nil, exit.\nCreate a group shape.\nPut \"group\" into the group shape's kind.\nPut the page's scale into the group shape's scale.\nMove the page's shapes to some original shapes.\nLoop.\nPut the original shapes' first into a shape.\nIf the shape is nil, break.\nRemove the shape from the original shapes.\nIf the shape is not selected, append the shape to the page's shapes; repeat.\nDeselect the shape.\nAppend the shape to the group shape's shapes.\nRepeat. \nAppend the group shape to the page's shapes.\nSelect the group shape.\nAdjust the group shape.\n" }, { "code": null, "e": 28252, "s": 28131, "text": "Shapes on pages are drawn back-to-front, so the newly grouped shapes will appear on top of the other shapes on the page." }, { "code": null, "e": 28262, "s": 28252, "text": "Not a Toy" }, { "code": null, "e": 28798, "s": 28262, "text": "Please keep in mind that this is facility is not a “toy.” We used it, as I mentioned above, to write the documentation for our system. And since then it’s been used to produce an 800-page illustrated “teach your kid to read” course that you can see here: www.rhymingreader.com. Not to mention several other books for children, numerous training manuals, and presentation materials of all kinds, large and small. This is one of my all-time favorite pages, developed by a grade school teacher in an attempt to settle an age-old question:" }, { "code": null, "e": 28803, "s": 28798, "text": "QED." }, { "code": null, "e": 28809, "s": 28803, "text": "GBlog" }, { "code": null, "e": 28817, "s": 28809, "text": "Project" }, { "code": null, "e": 28915, "s": 28817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28957, "s": 28915, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28982, "s": 28957, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 29017, "s": 28982, "text": "GET and POST requests using Python" }, { "code": null, "e": 29079, "s": 29017, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29112, "s": 29079, "text": "Working with csv files in Python" }, { "code": null, "e": 29161, "s": 29112, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 29183, "s": 29161, "text": "XML parsing in Python" }, { "code": null, "e": 29216, "s": 29183, "text": "Working with zip files in Python" }, { "code": null, "e": 29261, "s": 29216, "text": "Python | Simple GUI calculator using Tkinter" } ]
Multivariate outlier detection in Python | by Philip Wilkinson | Towards Data Science
In my previous medium article I introduced five different methods for Univariate outlier detection: Distribution plot, Z-score, Boxplot, Tukey fences and clustering. This highlighted the fact that several different methods can be used to detect outliers in your data, but that each of these can lead to different conclusions. As such, in selecting which method to use you should pay attention to the context of the data and what domain knowledge would also suggest would be classed as an outlier. Often however, data is collected from multiple sources, sensors and time periods creating multiple variables that could interact with your target variable. This means that analysis or machine learning methods are often applied in the cases where you have more than one variable to analyse. This means that it is often more crucial to be able to detect outliers as a result of the interaction between these variables rather than just detecting outliers from a single variable. This article therefore seeks to identify several different methods for this purpose. As before, the Pokémon dataset is used to demonstrate these methods, with data from 801 Pokémon from 7 seasons. This will focus on the Attack and Defense attributes from this dataset to be able to detect any potential anomalies as seen in the picture below. Of course, any anomalies in the dataset by these methods may not actually be anomalies, but we can make a choice in light of these results. As we can see from this plot there is generally a positive linear relationship between defense and attack in this dataset but there appears to be a few outliers. Box plot and Tukey fences One of the first methods that can be used as a baseline for being able to detect outliers from mutli-variate datasets is that of boxplots and Tukey fences. While these are able to detect outliers from a single variable distribution, rather than the interaction between them, we can use this as a baseline to compare to other methods later one. We can first visualise this as: #create the plotax = sns.boxplot(data = pokemon[["attack", "defense"]], orient = "h", palette = "Set2")#add labelsax.set_xlabel("Value", fontsize = 20, labelpad = 20)ax.set_ylabel("Attributes", fontsize = 20, labelpad = 20)ax.set_title("Boxplot of pokemon Attack \nand Defense attributes", fontsize = 20, pad = 20)#edit ticksax.tick_params(which = "both", labelsize = 15) This suggests that there could be outliers at the upper end of both distributions. To extract these we can use Tukey fences based on values that are above the upper bound of the upper quartile plus 1.5 times the inter-quartile range and below the lower bound of the lower quartile less 1.5 times the inter-quartile range: #create a function to calculate IQR boundsdef IQR_bounds(dataframe, column_name, multiple): """Extract the upper and lower bound for outlier detection using IQR Input: dataframe: Dataframe you want to extract the upper and lower bound from column_name: column name you want to extract upper and lower bound for multiple: The multiple to use to extract this Output: lower_bound = lower bound for column upper_bound = upper bound for column""" #extract the quantiles for the column lower_quantile = dataframe[column_name].quantile(0.25) upper_quantile = dataframe[column_name].quantile(0.75) #cauclat IQR IQR = upper_quantile - lower_quantile #extract lower and upper bound lower_bound = lower_quantile - multiple * IQR upper_bound = upper_quantile + multiple * IQR #retrun these values return lower_bound, upper_bound#set the columns we wantcolumns = ["attack", "defense"]#create a dictionary to store the boundscolumn_bounds = {}#iteratre over each column to extract boundsfor column in columns: #extract normal and extreme bounds lower_bound, upper_bound = IQR_bounds(pokemon, column, 1.5) #send them to the dictionary column_bounds[column] = [lower_bound, upper_bound]#create the normal dataframepokemon_IQR_AD = pokemon[(pokemon["attack"] < column_bounds["attack"][0]) | (pokemon["attack"] > column_bounds["attack"][1]) | (pokemon["defense"] < column_bounds["defense"][0]) | (pokemon["defense"] > column_bounds["defense"][1]) ] Where we get 15 potential outliers detection from the entire dataset. As we can see, this results in outliers that are above 180 attack and/or greater than 150 defense. This therefore suggests linear cut offs for identifying these outliers, but does so on the basis of single variates, rather than there interaction. Isolation forest The first method that is capable of dealing with the interaction between these variables is that of Isolation forest. This is often a good starting point, especially for higher dimension datasets. It is a tree ensemble method that is built on the basis of decision trees, just like random forests, whereby trees are partitioned by first randomly selecting a feature and then selecting a random split value between the maximum and minimum value of the selected feature. In principle, outliers are less frequent than regular observations and are different in terms of their value. Thus, by using random partitions, they should be identified as closer to the root of the tree, with fewer splits necessary. For this, the algorithm requires us to specify the contamination parameter which tells the algorithm how much of the data is expected to be anomalous. In our case, following the Tukey fences analysis, this can be set to 0.02 to signify we think that 2% of the data may be anomalous, equating to 16 points. This can be implemented as: from sklearn.ensemble import IsolationForest#create the method instanceisf = IsolationForest(n_estimators = 100, random_state = 42, contamination = 0.02)#use fit_predict on the data as we are using all the datapreds = isf.fit_predict(pokemon[["attack", "defense"]])#extract outliers from the datapokemon["iso_forest_outliers"] = predspokemon["iso_forest_outliers"] = pokemon["iso_forest_outliers"].astype(str)#extract the scores from the data in terms of strength of outlierpokemon["iso_forest_scores"] = isf.decision_function(pokemon[["attack", "defense"]])#print how many outliers the data suggestsprint(pokemon["iso_forest_outliers"].value_counts())# Out:1 785-1 16 Which we have 16 outliers as expected. We can then plot this as: #this plot will be repeated so it is better to create a functiondef scatter_plot(dataframe, x, y, color, title, hover_name): """Create a plotly express scatter plot with x and y values with a colour Input: dataframe: Dataframe containing columns for x, y, colour and hover_name data x: The column to go on the x axis y: Column name to go on the y axis color: Column name to specify colour title: Title for plot hover_name: column name for hover Returns: Scatter plot figure """ #create the base scatter plot fig = px.scatter(dataframe, x = x, y=y, color = color, hover_name = hover_name) #set the layout conditions fig.update_layout(title = title, title_x = 0.5) #show the figure fig.show()#create scatter plotscatter_plot(pokemon, "attack", "defense", "iso_forest_outliers", "Isolation Forest Outlier Detection", "name") Where we can see that unlike Tukey Fences, there is no clear cut off at the top or bottom of each variable and that points in the lower left hand corner have also been identified as outliers. We can see the range of scores assigned to these variables on the basis of their position in the decision trees as well. #create the same plot focusing on the scores from the datasetscatter_plot(pokemon, "attack", "defense", "iso_forest_scores", "Isolation Forest Outlier Detection Scores", "name") Where we can see what points may have been classed as outliers, with points in the centre mass receiving higher scores suggesting these are core points, while those on the periphery receiving lower scores suggesting they could be outliers. We can also use the univariate anomaly detection methods to be able to inform the choice of the contamination percentage by identifying outliers from the scores results as: Which these methods can be used to suggest where to set the cut-off for the contamination parameter and can be used in the same way for all following algorithms where a score can be extracted from. Local outlier factor Another algorithm that can be used is the Local Outlier Factor algorithm. This is a calculation that examines the neighbors of a point to be able to find its density and then compares this to the density of its neighbors. If the density of a point is found to be much smaller than that of its neighbors, suggesting isolation, than this could be identified as an outlier. The benefit of this algorithm is that it takes into account both the local and global properties of the dataset into account as it focuses on how isolated the sample is in respect to its neighbors. For this, we need to specify the number of neighbors (default 20) to compare the density to, and the distance metric to be used (the default is “minkowski” which generalises both the Euclidean and Manhattan distance). This can thus be applied as: #import the algorithmfrom sklearn.neighbors import LocalOutlierFactor#initialise the algorithmlof = LocalOutlierFactor(n_neighbors = 20)#fit it to the training data, since we don't use it for novelty than this is finey_pred = lof.fit_predict(pokemon[["attack", "defense"]])#extract the predictions as stringspokemon["lof_outliers"] = y_pred.astype(str)#print the number of outliers relative to non-outliersprint(pokemon["lof_outliers"].value_counts())#extract the outlier scorespokemon["lof_scores"] = lof.negative_outlier_factor_#Out:1 767-1 34 Where using the default value of 20 neighbors gives us 39 potential outliers. We can again examine the distribution of the outliers and the scores: As again, we can see that similar to the previous algorithm outliers are detected on the edge of the main mass of points. This will be because of the emphasis on density where points lying outside of the main region are likely to be identified as outliers as they don’t have points surrounding them completely. As before, we can also use univariate anomaly detection methods to analyse the scores to adjust the hyperparameters in the original algorithm. DBScan Similarly, DBScan is another algorithm that can also detect outliers on the basis of distance between points. This is a clustering algorithm and behaves differently to LOF by selecting points not already assigned to a cluster, determines if it is a core point by seeing if there at least a given number of samples within a given distance. If so, then it is designated as a core point along with all points within direct reach of that point as identified by the distance metric. This is then repeated for each point within the cluster until the edge of the cluster is identified where there are no more points within the specified distance that can be identified as core points (having the minimum number of points within the specified distance). If a point does not fall within any of the potential clusters then it is deemed as an outlier on the basis that it does not fit within the existing density or cluster of points. This can be implemented as: #import the algorithmfrom sklearn.cluster import DBSCAN#initiate the algorithm#set the distance to 20, and min_samples as 5outlier_detection = DBSCAN(eps = 20, metric = "euclidean", min_samples = 10, n_jobs = -1)#fit_predict the algorithm to the existing dataclusters = outlier_detection.fit_predict(pokemon[["attack", "defense"]])#extract the labels from the algorithmpokemon["dbscan_outliers"] = clusters#label all others as inliers pokemon["dbscan_outliers"] = pokemon["dbscan_outliers"].apply(lambda x: str(1) if x>-1 else str(-1))#print the vaue countsprint(pokemon["dbscan_outliers"].value_counts())# Out:1 787-1 14 With the results as: The key difference here is that only the upper edges of both attributes were selected as outliers from this algorithm, similar to that of the Tukey Fences. This is because they will be beyond the reach of core points where points in the lower left will be within the minimum distance of core points. The benefit of this is that it can be used when the distribution of values in the feature space cannot be assumed, it is easily implemented in Sklearn and it is intuitive to understand. But, selecting the optimal parameters is often difficult and it struggles to be used in a predictive capacity. Elliptic envelope Elliptic envelope is another anomaly detection algorithm but one that assumes a Gaussian distribution as part of the data. This works by creating an imaginary elliptical area around a given dataset where values falling inside that ellipses are taken to be normal data, and anything falling outside that are assumed to be outliers. Implementation of this model, as for Isolation Forest, requires the specification of the contamination parameter to suggest how many outliers are to be expected for the model. As before, we can set this to 0.02 and this can be implemented as: #import the necessary library and functionalityfrom sklearn.covariance import EllipticEnvelope#create the model, set the contamination as 0.02EE_model = EllipticEnvelope(contamination = 0.02)#implement the model on the dataoutliers = EE_model.fit_predict(pokemon[["attack", "defense"]])#extract the labelspokemon["EE_outliers"] = outliers#change the labelspokemon["EE_outliers"] = pokemon["EE_outliers"].apply(lambda x: str(-1) if x == -1 else str(1))#extract the scorepokemon["EE_scores"] = EE_model.score_samples(pokemon[["attack", "defense"]])#print the value counts for inlier and outliersprint(pokemon["EE_outliers"].value_counts())#out:1 785-1 16 We can then visualise the results and scores as follows: We can see here that the ellipses has been identified surrounding the centre of the distribution of points (i.e. the centre mass). The score itself is the negative Mahalanobis distance which is the inverse of the measure of distance between the point and the distribution (the ellipses). Thus, points further away from the distribution receive lower scores. A primary difference between the points detected by the algorithm as compared to before is that points towards the centre left have not been identified as outliers here, suggesting these these have been counted within the ellipses. Difficulty with this method include the requirement of normality in distribution of the variables and that as before we do not know the exact value of the contamination parameter. However, assuming normality, as before univariate analysis can be undertaken on the scores to identify outliers. Ensemble Finally, one way to strengthen the confidence in these methods is to not only use a single one but to combine the predictions of all methods. This can be done as: #extract the sum of the outlier countpokemon['outliers_sum'] = (pokemon['iso_forest_outliers'].astype(int)+ pokemon['lof_outliers'].astype(int)+ pokemon['dbscan_outliers'].astype(int)+ pokemon['EE_outliers'].astype(int))#print the value counts for each scaleprint(pokemon["outliers_sum"].value_counts())# out: 4 758 2 24 0 9-4 8-2 2 Where from this only 8 were identified as outliers in all algorithms. We can thus visualise this as: Where we can see where predictions from different algorithms overlap. At this point, it is subjective judgement as to which algorithm to trust, whether that is a single one or multiple, and will depend on domain expertise in that particular context. From this example, the eight Pokémon identified are given as: Where the ensemble results are taken to be the key metric. Beyond this, other algorithms can also be used including: One Class SVM, PCA and autoencoders. The choice of this of course will depend on the domain, the tools available and the dimensionality of the dataset. However, these results show that not all algorithms will produce the same result and that some subjective judgement will be required. Code available: https://github.com/PhilipDW183/Outlier_detection Dataset available: https://www.kaggle.com/rounakbanik/pokemon?select=pokemon.csv
[ { "code": null, "e": 669, "s": 172, "text": "In my previous medium article I introduced five different methods for Univariate outlier detection: Distribution plot, Z-score, Boxplot, Tukey fences and clustering. This highlighted the fact that several different methods can be used to detect outliers in your data, but that each of these can lead to different conclusions. As such, in selecting which method to use you should pay attention to the context of the data and what domain knowledge would also suggest would be classed as an outlier." }, { "code": null, "e": 1230, "s": 669, "text": "Often however, data is collected from multiple sources, sensors and time periods creating multiple variables that could interact with your target variable. This means that analysis or machine learning methods are often applied in the cases where you have more than one variable to analyse. This means that it is often more crucial to be able to detect outliers as a result of the interaction between these variables rather than just detecting outliers from a single variable. This article therefore seeks to identify several different methods for this purpose." }, { "code": null, "e": 1630, "s": 1230, "text": "As before, the Pokémon dataset is used to demonstrate these methods, with data from 801 Pokémon from 7 seasons. This will focus on the Attack and Defense attributes from this dataset to be able to detect any potential anomalies as seen in the picture below. Of course, any anomalies in the dataset by these methods may not actually be anomalies, but we can make a choice in light of these results." }, { "code": null, "e": 1792, "s": 1630, "text": "As we can see from this plot there is generally a positive linear relationship between defense and attack in this dataset but there appears to be a few outliers." }, { "code": null, "e": 1818, "s": 1792, "text": "Box plot and Tukey fences" }, { "code": null, "e": 2194, "s": 1818, "text": "One of the first methods that can be used as a baseline for being able to detect outliers from mutli-variate datasets is that of boxplots and Tukey fences. While these are able to detect outliers from a single variable distribution, rather than the interaction between them, we can use this as a baseline to compare to other methods later one. We can first visualise this as:" }, { "code": null, "e": 2577, "s": 2194, "text": "#create the plotax = sns.boxplot(data = pokemon[[\"attack\", \"defense\"]], orient = \"h\", palette = \"Set2\")#add labelsax.set_xlabel(\"Value\", fontsize = 20, labelpad = 20)ax.set_ylabel(\"Attributes\", fontsize = 20, labelpad = 20)ax.set_title(\"Boxplot of pokemon Attack \\nand Defense attributes\", fontsize = 20, pad = 20)#edit ticksax.tick_params(which = \"both\", labelsize = 15)" }, { "code": null, "e": 2899, "s": 2577, "text": "This suggests that there could be outliers at the upper end of both distributions. To extract these we can use Tukey fences based on values that are above the upper bound of the upper quartile plus 1.5 times the inter-quartile range and below the lower bound of the lower quartile less 1.5 times the inter-quartile range:" }, { "code": null, "e": 4538, "s": 2899, "text": "#create a function to calculate IQR boundsdef IQR_bounds(dataframe, column_name, multiple): \"\"\"Extract the upper and lower bound for outlier detection using IQR Input: dataframe: Dataframe you want to extract the upper and lower bound from column_name: column name you want to extract upper and lower bound for multiple: The multiple to use to extract this Output: lower_bound = lower bound for column upper_bound = upper bound for column\"\"\" #extract the quantiles for the column lower_quantile = dataframe[column_name].quantile(0.25) upper_quantile = dataframe[column_name].quantile(0.75) #cauclat IQR IQR = upper_quantile - lower_quantile #extract lower and upper bound lower_bound = lower_quantile - multiple * IQR upper_bound = upper_quantile + multiple * IQR #retrun these values return lower_bound, upper_bound#set the columns we wantcolumns = [\"attack\", \"defense\"]#create a dictionary to store the boundscolumn_bounds = {}#iteratre over each column to extract boundsfor column in columns: #extract normal and extreme bounds lower_bound, upper_bound = IQR_bounds(pokemon, column, 1.5) #send them to the dictionary column_bounds[column] = [lower_bound, upper_bound]#create the normal dataframepokemon_IQR_AD = pokemon[(pokemon[\"attack\"] < column_bounds[\"attack\"][0]) | (pokemon[\"attack\"] > column_bounds[\"attack\"][1]) | (pokemon[\"defense\"] < column_bounds[\"defense\"][0]) | (pokemon[\"defense\"] > column_bounds[\"defense\"][1]) ]" }, { "code": null, "e": 4855, "s": 4538, "text": "Where we get 15 potential outliers detection from the entire dataset. As we can see, this results in outliers that are above 180 attack and/or greater than 150 defense. This therefore suggests linear cut offs for identifying these outliers, but does so on the basis of single variates, rather than there interaction." }, { "code": null, "e": 4872, "s": 4855, "text": "Isolation forest" }, { "code": null, "e": 5575, "s": 4872, "text": "The first method that is capable of dealing with the interaction between these variables is that of Isolation forest. This is often a good starting point, especially for higher dimension datasets. It is a tree ensemble method that is built on the basis of decision trees, just like random forests, whereby trees are partitioned by first randomly selecting a feature and then selecting a random split value between the maximum and minimum value of the selected feature. In principle, outliers are less frequent than regular observations and are different in terms of their value. Thus, by using random partitions, they should be identified as closer to the root of the tree, with fewer splits necessary." }, { "code": null, "e": 5909, "s": 5575, "text": "For this, the algorithm requires us to specify the contamination parameter which tells the algorithm how much of the data is expected to be anomalous. In our case, following the Tukey fences analysis, this can be set to 0.02 to signify we think that 2% of the data may be anomalous, equating to 16 points. This can be implemented as:" }, { "code": null, "e": 6583, "s": 5909, "text": "from sklearn.ensemble import IsolationForest#create the method instanceisf = IsolationForest(n_estimators = 100, random_state = 42, contamination = 0.02)#use fit_predict on the data as we are using all the datapreds = isf.fit_predict(pokemon[[\"attack\", \"defense\"]])#extract outliers from the datapokemon[\"iso_forest_outliers\"] = predspokemon[\"iso_forest_outliers\"] = pokemon[\"iso_forest_outliers\"].astype(str)#extract the scores from the data in terms of strength of outlierpokemon[\"iso_forest_scores\"] = isf.decision_function(pokemon[[\"attack\", \"defense\"]])#print how many outliers the data suggestsprint(pokemon[\"iso_forest_outliers\"].value_counts())# Out:1 785-1 16" }, { "code": null, "e": 6648, "s": 6583, "text": "Which we have 16 outliers as expected. We can then plot this as:" }, { "code": null, "e": 7643, "s": 6648, "text": "#this plot will be repeated so it is better to create a functiondef scatter_plot(dataframe, x, y, color, title, hover_name): \"\"\"Create a plotly express scatter plot with x and y values with a colour Input: dataframe: Dataframe containing columns for x, y, colour and hover_name data x: The column to go on the x axis y: Column name to go on the y axis color: Column name to specify colour title: Title for plot hover_name: column name for hover Returns: Scatter plot figure \"\"\" #create the base scatter plot fig = px.scatter(dataframe, x = x, y=y, color = color, hover_name = hover_name) #set the layout conditions fig.update_layout(title = title, title_x = 0.5) #show the figure fig.show()#create scatter plotscatter_plot(pokemon, \"attack\", \"defense\", \"iso_forest_outliers\", \"Isolation Forest Outlier Detection\", \"name\")" }, { "code": null, "e": 7956, "s": 7643, "text": "Where we can see that unlike Tukey Fences, there is no clear cut off at the top or bottom of each variable and that points in the lower left hand corner have also been identified as outliers. We can see the range of scores assigned to these variables on the basis of their position in the decision trees as well." }, { "code": null, "e": 8157, "s": 7956, "text": "#create the same plot focusing on the scores from the datasetscatter_plot(pokemon, \"attack\", \"defense\", \"iso_forest_scores\", \"Isolation Forest Outlier Detection Scores\", \"name\")" }, { "code": null, "e": 8397, "s": 8157, "text": "Where we can see what points may have been classed as outliers, with points in the centre mass receiving higher scores suggesting these are core points, while those on the periphery receiving lower scores suggesting they could be outliers." }, { "code": null, "e": 8570, "s": 8397, "text": "We can also use the univariate anomaly detection methods to be able to inform the choice of the contamination percentage by identifying outliers from the scores results as:" }, { "code": null, "e": 8768, "s": 8570, "text": "Which these methods can be used to suggest where to set the cut-off for the contamination parameter and can be used in the same way for all following algorithms where a score can be extracted from." }, { "code": null, "e": 8789, "s": 8768, "text": "Local outlier factor" }, { "code": null, "e": 9160, "s": 8789, "text": "Another algorithm that can be used is the Local Outlier Factor algorithm. This is a calculation that examines the neighbors of a point to be able to find its density and then compares this to the density of its neighbors. If the density of a point is found to be much smaller than that of its neighbors, suggesting isolation, than this could be identified as an outlier." }, { "code": null, "e": 9605, "s": 9160, "text": "The benefit of this algorithm is that it takes into account both the local and global properties of the dataset into account as it focuses on how isolated the sample is in respect to its neighbors. For this, we need to specify the number of neighbors (default 20) to compare the density to, and the distance metric to be used (the default is “minkowski” which generalises both the Euclidean and Manhattan distance). This can thus be applied as:" }, { "code": null, "e": 10154, "s": 9605, "text": "#import the algorithmfrom sklearn.neighbors import LocalOutlierFactor#initialise the algorithmlof = LocalOutlierFactor(n_neighbors = 20)#fit it to the training data, since we don't use it for novelty than this is finey_pred = lof.fit_predict(pokemon[[\"attack\", \"defense\"]])#extract the predictions as stringspokemon[\"lof_outliers\"] = y_pred.astype(str)#print the number of outliers relative to non-outliersprint(pokemon[\"lof_outliers\"].value_counts())#extract the outlier scorespokemon[\"lof_scores\"] = lof.negative_outlier_factor_#Out:1 767-1 34" }, { "code": null, "e": 10302, "s": 10154, "text": "Where using the default value of 20 neighbors gives us 39 potential outliers. We can again examine the distribution of the outliers and the scores:" }, { "code": null, "e": 10756, "s": 10302, "text": "As again, we can see that similar to the previous algorithm outliers are detected on the edge of the main mass of points. This will be because of the emphasis on density where points lying outside of the main region are likely to be identified as outliers as they don’t have points surrounding them completely. As before, we can also use univariate anomaly detection methods to analyse the scores to adjust the hyperparameters in the original algorithm." }, { "code": null, "e": 10763, "s": 10756, "text": "DBScan" }, { "code": null, "e": 11509, "s": 10763, "text": "Similarly, DBScan is another algorithm that can also detect outliers on the basis of distance between points. This is a clustering algorithm and behaves differently to LOF by selecting points not already assigned to a cluster, determines if it is a core point by seeing if there at least a given number of samples within a given distance. If so, then it is designated as a core point along with all points within direct reach of that point as identified by the distance metric. This is then repeated for each point within the cluster until the edge of the cluster is identified where there are no more points within the specified distance that can be identified as core points (having the minimum number of points within the specified distance)." }, { "code": null, "e": 11715, "s": 11509, "text": "If a point does not fall within any of the potential clusters then it is deemed as an outlier on the basis that it does not fit within the existing density or cluster of points. This can be implemented as:" }, { "code": null, "e": 12342, "s": 11715, "text": "#import the algorithmfrom sklearn.cluster import DBSCAN#initiate the algorithm#set the distance to 20, and min_samples as 5outlier_detection = DBSCAN(eps = 20, metric = \"euclidean\", min_samples = 10, n_jobs = -1)#fit_predict the algorithm to the existing dataclusters = outlier_detection.fit_predict(pokemon[[\"attack\", \"defense\"]])#extract the labels from the algorithmpokemon[\"dbscan_outliers\"] = clusters#label all others as inliers pokemon[\"dbscan_outliers\"] = pokemon[\"dbscan_outliers\"].apply(lambda x: str(1) if x>-1 else str(-1))#print the vaue countsprint(pokemon[\"dbscan_outliers\"].value_counts())# Out:1 787-1 14" }, { "code": null, "e": 12363, "s": 12342, "text": "With the results as:" }, { "code": null, "e": 12663, "s": 12363, "text": "The key difference here is that only the upper edges of both attributes were selected as outliers from this algorithm, similar to that of the Tukey Fences. This is because they will be beyond the reach of core points where points in the lower left will be within the minimum distance of core points." }, { "code": null, "e": 12960, "s": 12663, "text": "The benefit of this is that it can be used when the distribution of values in the feature space cannot be assumed, it is easily implemented in Sklearn and it is intuitive to understand. But, selecting the optimal parameters is often difficult and it struggles to be used in a predictive capacity." }, { "code": null, "e": 12978, "s": 12960, "text": "Elliptic envelope" }, { "code": null, "e": 13309, "s": 12978, "text": "Elliptic envelope is another anomaly detection algorithm but one that assumes a Gaussian distribution as part of the data. This works by creating an imaginary elliptical area around a given dataset where values falling inside that ellipses are taken to be normal data, and anything falling outside that are assumed to be outliers." }, { "code": null, "e": 13552, "s": 13309, "text": "Implementation of this model, as for Isolation Forest, requires the specification of the contamination parameter to suggest how many outliers are to be expected for the model. As before, we can set this to 0.02 and this can be implemented as:" }, { "code": null, "e": 14208, "s": 13552, "text": "#import the necessary library and functionalityfrom sklearn.covariance import EllipticEnvelope#create the model, set the contamination as 0.02EE_model = EllipticEnvelope(contamination = 0.02)#implement the model on the dataoutliers = EE_model.fit_predict(pokemon[[\"attack\", \"defense\"]])#extract the labelspokemon[\"EE_outliers\"] = outliers#change the labelspokemon[\"EE_outliers\"] = pokemon[\"EE_outliers\"].apply(lambda x: str(-1) if x == -1 else str(1))#extract the scorepokemon[\"EE_scores\"] = EE_model.score_samples(pokemon[[\"attack\", \"defense\"]])#print the value counts for inlier and outliersprint(pokemon[\"EE_outliers\"].value_counts())#out:1 785-1 16" }, { "code": null, "e": 14265, "s": 14208, "text": "We can then visualise the results and scores as follows:" }, { "code": null, "e": 14623, "s": 14265, "text": "We can see here that the ellipses has been identified surrounding the centre of the distribution of points (i.e. the centre mass). The score itself is the negative Mahalanobis distance which is the inverse of the measure of distance between the point and the distribution (the ellipses). Thus, points further away from the distribution receive lower scores." }, { "code": null, "e": 14855, "s": 14623, "text": "A primary difference between the points detected by the algorithm as compared to before is that points towards the centre left have not been identified as outliers here, suggesting these these have been counted within the ellipses." }, { "code": null, "e": 15148, "s": 14855, "text": "Difficulty with this method include the requirement of normality in distribution of the variables and that as before we do not know the exact value of the contamination parameter. However, assuming normality, as before univariate analysis can be undertaken on the scores to identify outliers." }, { "code": null, "e": 15157, "s": 15148, "text": "Ensemble" }, { "code": null, "e": 15320, "s": 15157, "text": "Finally, one way to strengthen the confidence in these methods is to not only use a single one but to combine the predictions of all methods. This can be done as:" }, { "code": null, "e": 15752, "s": 15320, "text": "#extract the sum of the outlier countpokemon['outliers_sum'] = (pokemon['iso_forest_outliers'].astype(int)+ pokemon['lof_outliers'].astype(int)+ pokemon['dbscan_outliers'].astype(int)+ pokemon['EE_outliers'].astype(int))#print the value counts for each scaleprint(pokemon[\"outliers_sum\"].value_counts())# out: 4 758 2 24 0 9-4 8-2 2" }, { "code": null, "e": 15853, "s": 15752, "text": "Where from this only 8 were identified as outliers in all algorithms. We can thus visualise this as:" }, { "code": null, "e": 16103, "s": 15853, "text": "Where we can see where predictions from different algorithms overlap. At this point, it is subjective judgement as to which algorithm to trust, whether that is a single one or multiple, and will depend on domain expertise in that particular context." }, { "code": null, "e": 16166, "s": 16103, "text": "From this example, the eight Pokémon identified are given as:" }, { "code": null, "e": 16225, "s": 16166, "text": "Where the ensemble results are taken to be the key metric." }, { "code": null, "e": 16569, "s": 16225, "text": "Beyond this, other algorithms can also be used including: One Class SVM, PCA and autoencoders. The choice of this of course will depend on the domain, the tools available and the dimensionality of the dataset. However, these results show that not all algorithms will produce the same result and that some subjective judgement will be required." }, { "code": null, "e": 16634, "s": 16569, "text": "Code available: https://github.com/PhilipDW183/Outlier_detection" } ]
Find the Number of Substrings of One String Present in Other using C++
In this article, we are given two strings, and we need to find out how many substrings of the 1st string can be found in the 2nd string(the exact substring can occur multiple times). For example Input : string1 = “fogl” string2 = “google” Output : 6 Explanation : substrings of string1 present in string2 are [ “o”, “g”, “l”, “og”, “gl”, “ogl” ]. Input : string1 = “ajva” string2 = “java” Output : 5 Explanation : substrings of string1 present in string2 are [ “a”, “j”, “v”, “a”, “va” ]. Let's discuss how we can solve this problem of finding several substrings present in another string; looking at the examples; we understood that first, we have to see all the substrings of string1 and then we have to check each substring whether it is present in another string or not, If yes then increment the counter and after operating whole string check the result stored in the counter. Here is the C++ syntax which we can use as an input to solve the given problem − #include<iostream> #include<string> using namespace std; int main() { string str1 = "ajva"; string str2 = "java"; int count = 0;// counter to store result int n = str1.length(); for (int i = 0; i < n; i++) { string str3; // string3 is initialised to store all substrings of string1 for (int j = i; j < n; j++) { str3 += str1[j]; // checking whether substring present in another string or not if (str2.find(str3) != string::npos) count++; } } cout << "Number of substrings of one string present in other : "<< count; return 0; } Number of substrings of one string present in other : 5 Firstly, in this code, we are giving value to both the strings and initializing the counter with 0. We are going through the whole string and finding all the substrings possible of str1 and storing them in str3. Then we check each substring of str1, whether present in str2 or not; if yes, then increment the counter by 1 and we are finally printing the output stored in the counter variable. This article finds the simple solution of finding the number of substrings of one string present in another string. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.
[ { "code": null, "e": 1257, "s": 1062, "text": "In this article, we are given two strings, and we need to find out how many substrings of the 1st string can be found in the 2nd string(the exact substring can occur multiple times). For example" }, { "code": null, "e": 1558, "s": 1257, "text": "Input : string1 = “fogl”\n string2 = “google”\nOutput : 6\nExplanation : substrings of string1 present in string2 are [ “o”, “g”, “l”, “og”, “gl”,\n“ogl” ].\n\nInput : string1 = “ajva”\n string2 = “java”\nOutput : 5\nExplanation : substrings of string1 present in string2 are [ “a”, “j”, “v”, “a”, “va” ]." }, { "code": null, "e": 1951, "s": 1558, "text": "Let's discuss how we can solve this problem of finding several substrings present in another string; looking at the examples; we understood that first, we have to see all the substrings of string1 and then we have to check each substring whether it is present in another string or not, If yes then increment the counter and after operating whole string check the result stored in the counter." }, { "code": null, "e": 2032, "s": 1951, "text": "Here is the C++ syntax which we can use as an input to solve the given problem −" }, { "code": null, "e": 2645, "s": 2032, "text": "#include<iostream>\n#include<string>\nusing namespace std;\n\nint main() {\n string str1 = \"ajva\";\n string str2 = \"java\";\n int count = 0;// counter to store result\n int n = str1.length();\n\n for (int i = 0; i < n; i++) {\n\n string str3; // string3 is initialised to store all substrings of string1\n for (int j = i; j < n; j++) {\n str3 += str1[j];\n\n // checking whether substring present in another string or not\n if (str2.find(str3) != string::npos)\n count++;\n }\n }\n cout << \"Number of substrings of one string present in other : \"<< count;\n return 0;\n}" }, { "code": null, "e": 2701, "s": 2645, "text": "Number of substrings of one string present in other : 5" }, { "code": null, "e": 3094, "s": 2701, "text": "Firstly, in this code, we are giving value to both the strings and initializing the counter with 0. We are going through the whole string and finding all the substrings possible of str1 and storing them in str3. Then we check each substring of str1, whether present in str2 or not; if yes, then increment the counter by 1 and we are finally printing the output stored in the counter variable." }, { "code": null, "e": 3344, "s": 3094, "text": "This article finds the simple solution of finding the number of substrings of one string present in another string. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful." } ]
Image Augmentation for Deep Learning | by Suki Lau | Towards Data Science
Deep networks need large amount of training data to achieve good performance. To build a powerful image classifier using very little training data, image augmentation is usually required to boost the performance of deep networks. Image augmentation artificially creates training images through different ways of processing or combination of multiple processing, such as random rotation, shifts, shear and flips, etc. An augmented image generator can be easily created using ImageDataGenerator API in Keras. ImageDataGenerator generates batches of image data with real-time data augmentation. The most basic codes to create and configure ImageDataGenerator and train deep neural network with augmented images are as follows. datagen = ImageDataGenerator()datagen.fit(train)X_batch, y_batch = datagen.flow(X_train, y_train, batch_size=batch_size)model.fit_generator(datagen, samples_per_epoch=len(train), epochs=epochs) We can experiment with the following code to create augmented images with the desired properties. In our case, the following data generator generates a batch of 9 augmented images with rotation by 30 degrees and horizontal shift by 0.5. datagen = ImageDataGenerator(rotation_range=30, horizontal_flip=0.5)datagen.fit(img)i=0for img_batch in datagen.flow(img, batch_size=9): for img in img_batch: plt.subplot(330 + 1 + i) plt.imshow(img) i=i+1 if i >= batch_size: break Apart from the standard techniques of data augmentation provided by the ImageDataGenerator class in Keras, we can use custom functions to generate augmented images. For example, you may want to adjust the contrast of images using contrast stretching. Contrast stretching is a simple image processing technique that enhances the contrast by rescaling (“stretching”) the range of intensity values of an image to a desired range of values. Histogram equalization is another image processing technique to increase global contrast of an image using the image intensity histogram. The equalized image has a linear cumulative distribution function. This method needs no parameter, but it sometimes results an unnatural looking image. An alternative is adaptive histogram equalization (AHE) which improves local contrast of an image by computing several histograms corresponding to different sections of an image (differs from ordinary histogram equalization which uses only one histogram to adjust global contrast), and uses them for local contrast adjustment. However, AHE has a tendency to over-amplify noise in relatively homogeneous regions of an image. Contrast limited adaptive histogram equalization (CLAHE) was developed to prevent the over-amplification of noise resulted from AHE. In gist, it limits the contrast enhancement of AHE by clipping the histogram at a predefined value before computing the cumulative distribution function. To implement custom preprocessing function for augmentation in Keras, we first define our custom function and pass it to ImageDataGenerator as an argument. For instance, we can implement AHE using the following code. def AHE(img): img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.03) return img_adapteqdatagen = ImageDataGenerator(rotation_range=30, horizontal_flip=0.5, preprocessing_function=AHE) Source code Image Augmentation for Deep Learning With Keras Building powerful image classification models using very little data
[ { "code": null, "e": 464, "s": 47, "text": "Deep networks need large amount of training data to achieve good performance. To build a powerful image classifier using very little training data, image augmentation is usually required to boost the performance of deep networks. Image augmentation artificially creates training images through different ways of processing or combination of multiple processing, such as random rotation, shifts, shear and flips, etc." }, { "code": null, "e": 771, "s": 464, "text": "An augmented image generator can be easily created using ImageDataGenerator API in Keras. ImageDataGenerator generates batches of image data with real-time data augmentation. The most basic codes to create and configure ImageDataGenerator and train deep neural network with augmented images are as follows." }, { "code": null, "e": 965, "s": 771, "text": "datagen = ImageDataGenerator()datagen.fit(train)X_batch, y_batch = datagen.flow(X_train, y_train, batch_size=batch_size)model.fit_generator(datagen, samples_per_epoch=len(train), epochs=epochs)" }, { "code": null, "e": 1202, "s": 965, "text": "We can experiment with the following code to create augmented images with the desired properties. In our case, the following data generator generates a batch of 9 augmented images with rotation by 30 degrees and horizontal shift by 0.5." }, { "code": null, "e": 1472, "s": 1202, "text": "datagen = ImageDataGenerator(rotation_range=30, horizontal_flip=0.5)datagen.fit(img)i=0for img_batch in datagen.flow(img, batch_size=9): for img in img_batch: plt.subplot(330 + 1 + i) plt.imshow(img) i=i+1 if i >= batch_size: break" }, { "code": null, "e": 1909, "s": 1472, "text": "Apart from the standard techniques of data augmentation provided by the ImageDataGenerator class in Keras, we can use custom functions to generate augmented images. For example, you may want to adjust the contrast of images using contrast stretching. Contrast stretching is a simple image processing technique that enhances the contrast by rescaling (“stretching”) the range of intensity values of an image to a desired range of values." }, { "code": null, "e": 2199, "s": 1909, "text": "Histogram equalization is another image processing technique to increase global contrast of an image using the image intensity histogram. The equalized image has a linear cumulative distribution function. This method needs no parameter, but it sometimes results an unnatural looking image." }, { "code": null, "e": 2623, "s": 2199, "text": "An alternative is adaptive histogram equalization (AHE) which improves local contrast of an image by computing several histograms corresponding to different sections of an image (differs from ordinary histogram equalization which uses only one histogram to adjust global contrast), and uses them for local contrast adjustment. However, AHE has a tendency to over-amplify noise in relatively homogeneous regions of an image." }, { "code": null, "e": 2910, "s": 2623, "text": "Contrast limited adaptive histogram equalization (CLAHE) was developed to prevent the over-amplification of noise resulted from AHE. In gist, it limits the contrast enhancement of AHE by clipping the histogram at a predefined value before computing the cumulative distribution function." }, { "code": null, "e": 3127, "s": 2910, "text": "To implement custom preprocessing function for augmentation in Keras, we first define our custom function and pass it to ImageDataGenerator as an argument. For instance, we can implement AHE using the following code." }, { "code": null, "e": 3326, "s": 3127, "text": "def AHE(img): img_adapteq = exposure.equalize_adapthist(img, clip_limit=0.03) return img_adapteqdatagen = ImageDataGenerator(rotation_range=30, horizontal_flip=0.5, preprocessing_function=AHE)" }, { "code": null, "e": 3338, "s": 3326, "text": "Source code" }, { "code": null, "e": 3386, "s": 3338, "text": "Image Augmentation for Deep Learning With Keras" } ]
C++ | Virtual Functions | Question 6
28 Jun, 2021 Predict the output of following program. #include<iostream>using namespace std;class Base{public: virtual void show() = 0;}; class Derived : public Base { }; int main(void){ Derived q; return 0;} (A) Compiler Error: there cannot be an empty derived class(B) Compiler Error: Derived is abstract(C) No compiler ErrorAnswer: (B)Explanation: If we don’t override the pure virtual function in derived class, then derived class also becomes abstract class. Quiz of this Question C++-Virtual Functions Virtual Functions C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ C++ | Function Overloading and Default Arguments | Question 2 C++ | Static Keyword | Question 3 C++ | References | Question 4 C++ | new and delete | Question 4 C++ | const keyword | Question 1
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 93, "s": 52, "text": "Predict the output of following program." }, { "code": "#include<iostream>using namespace std;class Base{public: virtual void show() = 0;}; class Derived : public Base { }; int main(void){ Derived q; return 0;}", "e": 259, "s": 93, "text": null }, { "code": null, "e": 514, "s": 259, "text": "(A) Compiler Error: there cannot be an empty derived class(B) Compiler Error: Derived is abstract(C) No compiler ErrorAnswer: (B)Explanation: If we don’t override the pure virtual function in derived class, then derived class also becomes abstract class." }, { "code": null, "e": 536, "s": 514, "text": "Quiz of this Question" }, { "code": null, "e": 558, "s": 536, "text": "C++-Virtual Functions" }, { "code": null, "e": 576, "s": 558, "text": "Virtual Functions" }, { "code": null, "e": 587, "s": 576, "text": "C Language" }, { "code": null, "e": 596, "s": 587, "text": "C++ Quiz" }, { "code": null, "e": 694, "s": 596, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 711, "s": 694, "text": "Substring in C++" }, { "code": null, "e": 733, "s": 711, "text": "Function Pointer in C" }, { "code": null, "e": 768, "s": 733, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 814, "s": 768, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 859, "s": 814, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 921, "s": 859, "text": "C++ | Function Overloading and Default Arguments | Question 2" }, { "code": null, "e": 955, "s": 921, "text": "C++ | Static Keyword | Question 3" }, { "code": null, "e": 985, "s": 955, "text": "C++ | References | Question 4" }, { "code": null, "e": 1019, "s": 985, "text": "C++ | new and delete | Question 4" } ]
Template Metaprogramming in C++
19 Aug, 2021 Predict the output of following C++ program. CPP #include <iostream>using namespace std; template<int n> struct funStruct{ enum { val = 2*funStruct<n-1>::val };}; template<> struct funStruct<0>{ enum { val = 1 };}; int main(){ cout << funStruct<8>::val << endl; return 0;} Output: 256 The program calculates “2 raise to the power 8 (or 2^8)”. In fact, the structure funStruct can be used to calculate 2^n for any known n (or constant n). The special thing about above program is: calculation is done at compile time. So, it is compiler that calculates 2^8. To understand how compiler does this, let us consider the following facts about templates and enums:1) We can pass nontype parameters (parameters that are not data types) to class/function templates. 2) Like other const expressions, values of enumeration constants are evaluated at compile time. 3) When compiler sees a new argument to a template, compiler creates a new instance of the template.Let us take a closer look at the original program. When compiler sees funStruct<8>::val, it tries to create an instance of funStruct with parameter as 8, it turns out that funStruct<7> must also be created as enumeration constant val must be evaluated at compile time. For funStruct<7>, compiler need funStruct<6> and so on. Finally, compiler uses funStruct<1>::val and compile time recursion terminates. So, using templates, we can write programs that do computation at compile time, such programs are called template metaprograms. Template metaprogramming is in fact Turing-complete, meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram. Template Metaprogramming is generally not used in practical programs, it is an interesting concept though. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. varshagumber28 kapoorsagar226 C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Aug, 2021" }, { "code": null, "e": 98, "s": 52, "text": "Predict the output of following C++ program. " }, { "code": null, "e": 102, "s": 98, "text": "CPP" }, { "code": "#include <iostream>using namespace std; template<int n> struct funStruct{ enum { val = 2*funStruct<n-1>::val };}; template<> struct funStruct<0>{ enum { val = 1 };}; int main(){ cout << funStruct<8>::val << endl; return 0;}", "e": 338, "s": 102, "text": null }, { "code": null, "e": 347, "s": 338, "text": "Output: " }, { "code": null, "e": 351, "s": 347, "text": "256" }, { "code": null, "e": 1959, "s": 351, "text": "The program calculates “2 raise to the power 8 (or 2^8)”. In fact, the structure funStruct can be used to calculate 2^n for any known n (or constant n). The special thing about above program is: calculation is done at compile time. So, it is compiler that calculates 2^8. To understand how compiler does this, let us consider the following facts about templates and enums:1) We can pass nontype parameters (parameters that are not data types) to class/function templates. 2) Like other const expressions, values of enumeration constants are evaluated at compile time. 3) When compiler sees a new argument to a template, compiler creates a new instance of the template.Let us take a closer look at the original program. When compiler sees funStruct<8>::val, it tries to create an instance of funStruct with parameter as 8, it turns out that funStruct<7> must also be created as enumeration constant val must be evaluated at compile time. For funStruct<7>, compiler need funStruct<6> and so on. Finally, compiler uses funStruct<1>::val and compile time recursion terminates. So, using templates, we can write programs that do computation at compile time, such programs are called template metaprograms. Template metaprogramming is in fact Turing-complete, meaning that any computation expressible by a computer program can be computed, in some form, by a template metaprogram. Template Metaprogramming is generally not used in practical programs, it is an interesting concept though. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 1974, "s": 1959, "text": "varshagumber28" }, { "code": null, "e": 1989, "s": 1974, "text": "kapoorsagar226" }, { "code": null, "e": 2000, "s": 1989, "text": "C Language" }, { "code": null, "e": 2004, "s": 2000, "text": "C++" }, { "code": null, "e": 2008, "s": 2004, "text": "CPP" } ]
How to Pad an Integer Number With Leading Zeroes in C#?
26 May, 2020 Given a Number N, the task is to pad this number with P number of leading zeros in C#. Examples: Input: N = 123 , P = 4 Output: 0123 Input: N = -3 , P = 5 Output: -00003 Method 1: Using string Format() method : The Format() method is used to replace one or more format items in the specified string with the string representation of a specified object. Step 1: Get the Number N and number of leading zeros P. Step 2: Convert the number to string and to pad the string, use the string.Format() method with the formatted string argument “{0:0000}” for P= 4. val = string.Format("{0:0000}", N); Step 3: Return the padded string. Example : C# // C# program to pad an integer// number with leading zerosusing System; class GFG{ // Function to pad an integer number // with leading zeros static string pad_an_int(int N, int P) { // string used in Format() method string s = "{0:"; for( int i=0 ; i<P ; i++) { s += "0"; } s += "}"; // use of string.Format() method string value = string.Format(s, N); // return output return value; } // driver code public static void Main(string[] args) { int N = 123; // Number to be pad int P = 5; // Number of leading zeros Console.WriteLine("Before Padding: " + N); // Function calling Console.WriteLine("After Padding: " + pad_an_int(N, P)); }} Output: Before Padding: 123 After Padding: 00123 Method 2: Using ToString() method : The ToString() method is used to convert the numeric value of the current instance to its equivalent string representation. Step 1: Get the Number N and number of leading zeros P. Step 2: Convert the number to string using the ToString() method and to pad the string use the formatted string argument “0000” for P= 4. val = N.ToString("0000"); Step 3: Return the padded string. Example : C# // C# program to pad an integer// number with leading zerosusing System; public class GFG{ // Function to pad an integer number // with leading zeros static string pad_an_int(int N, int P) { // string used in ToString() method string s = ""; for( int i=0 ; i<P ; i++) { s += "0"; } // use of ToString() method string value = N.ToString(s); // return output return value; } // driver code public static void Main(string[] args) { int N = 123; // Number to be pad int P = 5; // Number of leading zeros Console.WriteLine("Before Padding: " + N); // Function calling Console.WriteLine("After Padding: " + pad_an_int(N, P)); }} Output: Before Padding: 123 After Padding: 00123 Method 3: Using PadLeft() method : The PadLeft() method is used to right-aligns the characters in String by padding them. Step 1: Get the Number N and number of leading zeros P. Step 2: Convert the number to string using the ToString() method. val = N.ToString(); Step 3: Then pad the string by using the PadLeft() method. pad_str = val.PadLeft(P, '0'); Step 4: Return the padded string. Example : C# // C# program to pad an integer// number with leading zerosusing System; public class GFG{ // Function to pad an integer number // with leading zeros static string pad_an_int(int N, int P) { // use of ToString() method string value = N.ToString(); // use of the PadLeft() method string pad_str = value.PadLeft(P, '0'); // return output return pad_str; } // driver code public static void Main(string[] args) { int N = 123; // Number to be pad int P = 5; // Number of leading zeros Console.WriteLine("Before Padding: " + N); // Function calling Console.WriteLine("After Padding: " + pad_an_int(N, P)); }} Output: Before Padding: 123 After Padding: 00123 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | Class and Object Extension Method in C# Difference between Ref and Out keywords in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2020" }, { "code": null, "e": 115, "s": 28, "text": "Given a Number N, the task is to pad this number with P number of leading zeros in C#." }, { "code": null, "e": 125, "s": 115, "text": "Examples:" }, { "code": null, "e": 202, "s": 125, "text": "Input: N = 123 , P = 4\nOutput: 0123\n \nInput: N = -3 , P = 5\nOutput: -00003\n" }, { "code": null, "e": 385, "s": 202, "text": "Method 1: Using string Format() method : The Format() method is used to replace one or more format items in the specified string with the string representation of a specified object." }, { "code": null, "e": 441, "s": 385, "text": "Step 1: Get the Number N and number of leading zeros P." }, { "code": null, "e": 588, "s": 441, "text": "Step 2: Convert the number to string and to pad the string, use the string.Format() method with the formatted string argument “{0:0000}” for P= 4." }, { "code": null, "e": 625, "s": 588, "text": "val = string.Format(\"{0:0000}\", N);\n" }, { "code": null, "e": 659, "s": 625, "text": "Step 3: Return the padded string." }, { "code": null, "e": 669, "s": 659, "text": "Example :" }, { "code": null, "e": 672, "s": 669, "text": "C#" }, { "code": "// C# program to pad an integer// number with leading zerosusing System; class GFG{ // Function to pad an integer number // with leading zeros static string pad_an_int(int N, int P) { // string used in Format() method string s = \"{0:\"; for( int i=0 ; i<P ; i++) { s += \"0\"; } s += \"}\"; // use of string.Format() method string value = string.Format(s, N); // return output return value; } // driver code public static void Main(string[] args) { int N = 123; // Number to be pad int P = 5; // Number of leading zeros Console.WriteLine(\"Before Padding: \" + N); // Function calling Console.WriteLine(\"After Padding: \" + pad_an_int(N, P)); }}", "e": 1507, "s": 672, "text": null }, { "code": null, "e": 1515, "s": 1507, "text": "Output:" }, { "code": null, "e": 1557, "s": 1515, "text": "Before Padding: 123\nAfter Padding: 00123\n" }, { "code": null, "e": 1717, "s": 1557, "text": "Method 2: Using ToString() method : The ToString() method is used to convert the numeric value of the current instance to its equivalent string representation." }, { "code": null, "e": 1773, "s": 1717, "text": "Step 1: Get the Number N and number of leading zeros P." }, { "code": null, "e": 1911, "s": 1773, "text": "Step 2: Convert the number to string using the ToString() method and to pad the string use the formatted string argument “0000” for P= 4." }, { "code": null, "e": 1938, "s": 1911, "text": "val = N.ToString(\"0000\");\n" }, { "code": null, "e": 1972, "s": 1938, "text": "Step 3: Return the padded string." }, { "code": null, "e": 1982, "s": 1972, "text": "Example :" }, { "code": null, "e": 1985, "s": 1982, "text": "C#" }, { "code": "// C# program to pad an integer// number with leading zerosusing System; public class GFG{ // Function to pad an integer number // with leading zeros static string pad_an_int(int N, int P) { // string used in ToString() method string s = \"\"; for( int i=0 ; i<P ; i++) { s += \"0\"; } // use of ToString() method string value = N.ToString(s); // return output return value; } // driver code public static void Main(string[] args) { int N = 123; // Number to be pad int P = 5; // Number of leading zeros Console.WriteLine(\"Before Padding: \" + N); // Function calling Console.WriteLine(\"After Padding: \" + pad_an_int(N, P)); }}", "e": 2798, "s": 1985, "text": null }, { "code": null, "e": 2806, "s": 2798, "text": "Output:" }, { "code": null, "e": 2848, "s": 2806, "text": "Before Padding: 123\nAfter Padding: 00123\n" }, { "code": null, "e": 2970, "s": 2848, "text": "Method 3: Using PadLeft() method : The PadLeft() method is used to right-aligns the characters in String by padding them." }, { "code": null, "e": 3026, "s": 2970, "text": "Step 1: Get the Number N and number of leading zeros P." }, { "code": null, "e": 3092, "s": 3026, "text": "Step 2: Convert the number to string using the ToString() method." }, { "code": null, "e": 3113, "s": 3092, "text": "val = N.ToString();\n" }, { "code": null, "e": 3172, "s": 3113, "text": "Step 3: Then pad the string by using the PadLeft() method." }, { "code": null, "e": 3204, "s": 3172, "text": "pad_str = val.PadLeft(P, '0');\n" }, { "code": null, "e": 3238, "s": 3204, "text": "Step 4: Return the padded string." }, { "code": null, "e": 3248, "s": 3238, "text": "Example :" }, { "code": null, "e": 3251, "s": 3248, "text": "C#" }, { "code": "// C# program to pad an integer// number with leading zerosusing System; public class GFG{ // Function to pad an integer number // with leading zeros static string pad_an_int(int N, int P) { // use of ToString() method string value = N.ToString(); // use of the PadLeft() method string pad_str = value.PadLeft(P, '0'); // return output return pad_str; } // driver code public static void Main(string[] args) { int N = 123; // Number to be pad int P = 5; // Number of leading zeros Console.WriteLine(\"Before Padding: \" + N); // Function calling Console.WriteLine(\"After Padding: \" + pad_an_int(N, P)); }}", "e": 4013, "s": 3251, "text": null }, { "code": null, "e": 4021, "s": 4013, "text": "Output:" }, { "code": null, "e": 4063, "s": 4021, "text": "Before Padding: 123\nAfter Padding: 00123\n" }, { "code": null, "e": 4066, "s": 4063, "text": "C#" }, { "code": null, "e": 4164, "s": 4066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4195, "s": 4164, "text": "Introduction to .NET Framework" }, { "code": null, "e": 4210, "s": 4195, "text": "C# | Delegates" }, { "code": null, "e": 4253, "s": 4210, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4302, "s": 4253, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4325, "s": 4302, "text": "C# | Method Overriding" }, { "code": null, "e": 4341, "s": 4325, "text": "C# | Data Types" }, { "code": null, "e": 4359, "s": 4341, "text": "C# | Constructors" }, { "code": null, "e": 4381, "s": 4359, "text": "C# | Class and Object" }, { "code": null, "e": 4404, "s": 4381, "text": "Extension Method in C#" } ]
Postfix to Prefix Conversion
24 May, 2022 Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands. Simply of the form (operand1 operand2 operator). Example : AB+CD-* (Infix : (A+B) * (C-D) ) Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). Example : *+AB-CD (Infix : (A+B) * (C-D) )Given a Postfix expression, convert it into a Prefix expression. Conversion of Postfix expression directly to Prefix without going through the process of converting them first to Infix and then to Prefix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression). Examples: Input : Postfix : AB+CD-* Output : Prefix : *+AB-CD Explanation : Postfix to Infix : (A+B) * (C-D) Infix to Prefix : *+AB-CD Input : Postfix : ABC/-AK/L-* Output : Prefix : *-A/BC-/AKL Explanation : Postfix to Infix : ((A-(B/C))*((A/K)-L)) Infix to Prefix : *-A/BC-/AKL Algorithm for Postfix to Prefix: Read the Postfix expression from left to right If the symbol is an operand, then push it onto the Stack If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator before them. string = operator + operand2 + operand1 And push the resultant string back to Stack Repeat the above steps until end of Postfix expression. Below is the implementation of the above idea: C++ Java Python3 C# Javascript // CPP Program to convert postfix to prefix#include <bits/stdc++.h>using namespace std; // function to check if character is operator or notbool isOperator(char x){ switch (x) { case '+': case '-': case '/': case '*': return true; } return false;} // Convert postfix to Prefix expressionstring postToPre(string post_exp){ stack<string> s; // length of expression int length = post_exp.size(); // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = post_exp[i] + op2 + op1; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, post_exp[i])); } } string ans = ""; while (!s.empty()) { ans += s.top(); s.pop(); } return ans;} // Driver Codeint main(){ string post_exp = "ABC/-AK/L-*"; // Function call cout << "Prefix : " << postToPre(post_exp); return 0;} // Java Program to convert postfix to prefiximport java.util.*; class GFG { // function to check if character // is operator or not static boolean isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression static String postToPre(String post_exp) { Stack<String> s = new Stack<String>(); // length of expression int length = post_exp.length(); // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp.charAt(i))) { // pop two operands from stack String op1 = s.peek(); s.pop(); String op2 = s.peek(); s.pop(); // concat the operands and operator String temp = post_exp.charAt(i) + op2 + op1; // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(post_exp.charAt(i) + ""); } } // concatenate all strings in stack and return the // answer String ans = ""; for (String i : s) ans += i; return ans; } // Driver Code public static void main(String args[]) { String post_exp = "ABC/-AK/L-*"; // Function call System.out.println("Prefix : " + postToPre(post_exp)); }} // This code is contributed by Arnab Kundu # Python3 Program to convert postfix to prefix # function to check if# character is operator or not def isOperator(x): if x == "+": return True if x == "-": return True if x == "/": return True if x == "*": return True return False # Convert postfix to Prefix expression def postToPre(post_exp): s = [] # length of expression length = len(post_exp) # reading from right to left for i in range(length): # check if symbol is operator if (isOperator(post_exp[i])): # pop two operands from stack op1 = s[-1] s.pop() op2 = s[-1] s.pop() # concat the operands and operator temp = post_exp[i] + op2 + op1 # Push string temp back to stack s.append(temp) # if symbol is an operand else: # push the operand to the stack s.append(post_exp[i]) ans = "" for i in s: ans += i return ans # Driver Codeif __name__ == "__main__": post_exp = "AB+CD-" # Function call print("Prefix : ", postToPre(post_exp)) # This code is contributed by AnkitRai01 // C# Program to convert postfix to prefixusing System;using System.Collections; class GFG { // function to check if character // is operator or not static Boolean isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression static String postToPre(String post_exp) { Stack s = new Stack(); // length of expression int length = post_exp.Length; // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // Pop two operands from stack String op1 = (String)s.Peek(); s.Pop(); String op2 = (String)s.Peek(); s.Pop(); // concat the operands and operator String temp = post_exp[i] + op2 + op1; // Push String temp back to stack s.Push(temp); } // if symbol is an operand else { // Push the operand to the stack s.Push(post_exp[i] + ""); } } String ans = ""; while (s.Count > 0) ans += s.Pop(); return ans; } // Driver Code public static void Main(String[] args) { String post_exp = "ABC/-AK/L-*"; // Function call Console.WriteLine("Prefix : " + postToPre(post_exp)); }} // This code is contributed by Arnab Kundu <script> // Javascript Program to convert postfix to prefix // function to check if character // is operator or not function isOperator(x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression function postToPre(post_exp) { let s = []; // length of expression let length = post_exp.length; // reading from right to left for (let i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // Pop two operands from stack let op1 = s[s.length - 1]; s.pop(); let op2 = s[s.length - 1]; s.pop(); // concat the operands and operator let temp = post_exp[i] + op2 + op1; // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // Push the operand to the stack s.push(post_exp[i] + ""); } } let ans = ""; while (s.length > 0) ans += s.pop(); return ans; } let post_exp = "ABC/-AK/L-*"; // Function call document.write("Prefix : " + postToPre(post_exp)); // This code is contributed by suresh07.</script> Prefix : *-A/BC-/AKL Time Complexity: O(N) where N is the length of the string Auxiliary Space: O(N) where N is the stack size. andrew1234 brizyyy bvkhadiravana ankthon hunter2000 suresh07 catiksh98 rohitkumarsinghcna expression-evaluation Mathematical Stack Strings Strings Mathematical Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Stack Data Structure (Introduction and Program) Stack in Python Stack Class in Java Check for Balanced Brackets in an expression (well-formedness) using Stack Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n24 May, 2022" }, { "code": null, "e": 262, "s": 52, "text": "Postfix: An expression is called the postfix expression if the operator appears in the expression after the operands. Simply of the form (operand1 operand2 operator). Example : AB+CD-* (Infix : (A+B) * (C-D) )" }, { "code": null, "e": 802, "s": 262, "text": "Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2). Example : *+AB-CD (Infix : (A+B) * (C-D) )Given a Postfix expression, convert it into a Prefix expression. Conversion of Postfix expression directly to Prefix without going through the process of converting them first to Infix and then to Prefix is much better in terms of computation and better understanding the expression (Computers evaluate using Postfix expression). " }, { "code": null, "e": 813, "s": 802, "text": "Examples: " }, { "code": null, "e": 1119, "s": 813, "text": "Input : Postfix : AB+CD-*\nOutput : Prefix : *+AB-CD\nExplanation : Postfix to Infix : (A+B) * (C-D)\n Infix to Prefix : *+AB-CD\n\nInput : Postfix : ABC/-AK/L-*\nOutput : Prefix : *-A/BC-/AKL\nExplanation : Postfix to Infix : ((A-(B/C))*((A/K)-L))\n Infix to Prefix : *-A/BC-/AKL " }, { "code": null, "e": 1154, "s": 1119, "text": "Algorithm for Postfix to Prefix: " }, { "code": null, "e": 1201, "s": 1154, "text": "Read the Postfix expression from left to right" }, { "code": null, "e": 1258, "s": 1201, "text": "If the symbol is an operand, then push it onto the Stack" }, { "code": null, "e": 1489, "s": 1258, "text": "If the symbol is an operator, then pop two operands from the Stack Create a string by concatenating the two operands and the operator before them. string = operator + operand2 + operand1 And push the resultant string back to Stack" }, { "code": null, "e": 1545, "s": 1489, "text": "Repeat the above steps until end of Postfix expression." }, { "code": null, "e": 1593, "s": 1545, "text": " Below is the implementation of the above idea:" }, { "code": null, "e": 1597, "s": 1593, "text": "C++" }, { "code": null, "e": 1602, "s": 1597, "text": "Java" }, { "code": null, "e": 1610, "s": 1602, "text": "Python3" }, { "code": null, "e": 1613, "s": 1610, "text": "C#" }, { "code": null, "e": 1624, "s": 1613, "text": "Javascript" }, { "code": "// CPP Program to convert postfix to prefix#include <bits/stdc++.h>using namespace std; // function to check if character is operator or notbool isOperator(char x){ switch (x) { case '+': case '-': case '/': case '*': return true; } return false;} // Convert postfix to Prefix expressionstring postToPre(string post_exp){ stack<string> s; // length of expression int length = post_exp.size(); // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = post_exp[i] + op2 + op1; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, post_exp[i])); } } string ans = \"\"; while (!s.empty()) { ans += s.top(); s.pop(); } return ans;} // Driver Codeint main(){ string post_exp = \"ABC/-AK/L-*\"; // Function call cout << \"Prefix : \" << postToPre(post_exp); return 0;}", "e": 2931, "s": 1624, "text": null }, { "code": "// Java Program to convert postfix to prefiximport java.util.*; class GFG { // function to check if character // is operator or not static boolean isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression static String postToPre(String post_exp) { Stack<String> s = new Stack<String>(); // length of expression int length = post_exp.length(); // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp.charAt(i))) { // pop two operands from stack String op1 = s.peek(); s.pop(); String op2 = s.peek(); s.pop(); // concat the operands and operator String temp = post_exp.charAt(i) + op2 + op1; // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(post_exp.charAt(i) + \"\"); } } // concatenate all strings in stack and return the // answer String ans = \"\"; for (String i : s) ans += i; return ans; } // Driver Code public static void main(String args[]) { String post_exp = \"ABC/-AK/L-*\"; // Function call System.out.println(\"Prefix : \" + postToPre(post_exp)); }} // This code is contributed by Arnab Kundu", "e": 4652, "s": 2931, "text": null }, { "code": "# Python3 Program to convert postfix to prefix # function to check if# character is operator or not def isOperator(x): if x == \"+\": return True if x == \"-\": return True if x == \"/\": return True if x == \"*\": return True return False # Convert postfix to Prefix expression def postToPre(post_exp): s = [] # length of expression length = len(post_exp) # reading from right to left for i in range(length): # check if symbol is operator if (isOperator(post_exp[i])): # pop two operands from stack op1 = s[-1] s.pop() op2 = s[-1] s.pop() # concat the operands and operator temp = post_exp[i] + op2 + op1 # Push string temp back to stack s.append(temp) # if symbol is an operand else: # push the operand to the stack s.append(post_exp[i]) ans = \"\" for i in s: ans += i return ans # Driver Codeif __name__ == \"__main__\": post_exp = \"AB+CD-\" # Function call print(\"Prefix : \", postToPre(post_exp)) # This code is contributed by AnkitRai01", "e": 5842, "s": 4652, "text": null }, { "code": "// C# Program to convert postfix to prefixusing System;using System.Collections; class GFG { // function to check if character // is operator or not static Boolean isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression static String postToPre(String post_exp) { Stack s = new Stack(); // length of expression int length = post_exp.Length; // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // Pop two operands from stack String op1 = (String)s.Peek(); s.Pop(); String op2 = (String)s.Peek(); s.Pop(); // concat the operands and operator String temp = post_exp[i] + op2 + op1; // Push String temp back to stack s.Push(temp); } // if symbol is an operand else { // Push the operand to the stack s.Push(post_exp[i] + \"\"); } } String ans = \"\"; while (s.Count > 0) ans += s.Pop(); return ans; } // Driver Code public static void Main(String[] args) { String post_exp = \"ABC/-AK/L-*\"; // Function call Console.WriteLine(\"Prefix : \" + postToPre(post_exp)); }} // This code is contributed by Arnab Kundu", "e": 7474, "s": 5842, "text": null }, { "code": "<script> // Javascript Program to convert postfix to prefix // function to check if character // is operator or not function isOperator(x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression function postToPre(post_exp) { let s = []; // length of expression let length = post_exp.length; // reading from right to left for (let i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // Pop two operands from stack let op1 = s[s.length - 1]; s.pop(); let op2 = s[s.length - 1]; s.pop(); // concat the operands and operator let temp = post_exp[i] + op2 + op1; // Push String temp back to stack s.push(temp); } // if symbol is an operand else { // Push the operand to the stack s.push(post_exp[i] + \"\"); } } let ans = \"\"; while (s.length > 0) ans += s.pop(); return ans; } let post_exp = \"ABC/-AK/L-*\"; // Function call document.write(\"Prefix : \" + postToPre(post_exp)); // This code is contributed by suresh07.</script>", "e": 8950, "s": 7474, "text": null }, { "code": null, "e": 8971, "s": 8950, "text": "Prefix : *-A/BC-/AKL" }, { "code": null, "e": 9029, "s": 8971, "text": "Time Complexity: O(N) where N is the length of the string" }, { "code": null, "e": 9078, "s": 9029, "text": "Auxiliary Space: O(N) where N is the stack size." }, { "code": null, "e": 9089, "s": 9078, "text": "andrew1234" }, { "code": null, "e": 9097, "s": 9089, "text": "brizyyy" }, { "code": null, "e": 9111, "s": 9097, "text": "bvkhadiravana" }, { "code": null, "e": 9119, "s": 9111, "text": "ankthon" }, { "code": null, "e": 9130, "s": 9119, "text": "hunter2000" }, { "code": null, "e": 9139, "s": 9130, "text": "suresh07" }, { "code": null, "e": 9149, "s": 9139, "text": "catiksh98" }, { "code": null, "e": 9168, "s": 9149, "text": "rohitkumarsinghcna" }, { "code": null, "e": 9190, "s": 9168, "text": "expression-evaluation" }, { "code": null, "e": 9203, "s": 9190, "text": "Mathematical" }, { "code": null, "e": 9209, "s": 9203, "text": "Stack" }, { "code": null, "e": 9217, "s": 9209, "text": "Strings" }, { "code": null, "e": 9225, "s": 9217, "text": "Strings" }, { "code": null, "e": 9238, "s": 9225, "text": "Mathematical" }, { "code": null, "e": 9244, "s": 9238, "text": "Stack" }, { "code": null, "e": 9342, "s": 9244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9372, "s": 9342, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9415, "s": 9372, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9475, "s": 9415, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9490, "s": 9475, "text": "C++ Data Types" }, { "code": null, "e": 9514, "s": 9490, "text": "Merge two sorted arrays" }, { "code": null, "e": 9562, "s": 9514, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 9578, "s": 9562, "text": "Stack in Python" }, { "code": null, "e": 9598, "s": 9578, "text": "Stack Class in Java" }, { "code": null, "e": 9673, "s": 9598, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Python | Reverse each word in a sentence
29 Jun, 2022 Given a long sentence, reverse each word of the sentence individually in the sentence itself. Examples: Input : Geeks For Geeks is good to learn Output : skeeG roF skeeG si doog ot nrael Input : Split Reverse Join Output : tilpS esreveR nioJ We shall use Python’s built in library function to reverse each word individually in the string itself. Prerequisites : 1. split() 2. Reversing Techniques in Python 3. List Comprehension Method in python 4. join() First split the sentence into list of words. Reverse each word of the string in the list individually. Join the words in the list to form a new sentence. Below is the implementation of above idea. Python3 # Python code to Reverse each word# of a Sentence individually # Function to Reverse wordsdef reverseWordSentence(Sentence): # Splitting the Sentence into list of words. words = Sentence.split(" ") # Reversing each word and creating # a new list of words # List Comprehension Technique newWords = [word[::-1] for word in words] # Joining the new list of words # to for a new Sentence newSentence = " ".join(newWords) return newSentence # Driver's CodeSentence = "GeeksforGeeks is good to learn"# Calling the reverseWordSentence# Function to get the newSentenceprint(reverseWordSentence(Sentence)) Output: skeeGrofskeeG si doog ot nrael Python is well known for its short codes. We shall do the same task but with lesser line of codes. Python3 # Python code to Reverse each word# of a Sentence individually # Function to Reverse wordsdef reverseWordSentence(Sentence): # All in One line return ' '.join(word[::-1] for word in Sentence.split(" ")) # Driver's CodeSentence = "Geeks for Geeks"print(reverseWordSentence(Sentence)) Output: skeeG rof skeeG Approach#3: Using re.sub() function We can use re.sub() function to replace the words in sentence with reversed words in sentence. We capture the word in string with the help of group method and replace it with reversed word. Python3 # Python code to Reverse each word# of a Sentence individuallyimport re# Function to Reverse wordsdef reverseWordSentence(Sentence): # substiting revrese word in place of word in sentence newSentence = re.sub('(\w+)', lambda x : x.group()[::-1], Sentence) return newSentence # Driver's CodeSentence = "GeeksforGeeks is good to learn"# Calling the reverseWordSentence# Function to get the newSentenceprint(reverseWordSentence(Sentence)) Output: skeeGrofskeeG si doog ot nrael Akanksha_Rai shubham_singh satyam00so python-string Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jun, 2022" }, { "code": null, "e": 158, "s": 54, "text": "Given a long sentence, reverse each word of the sentence individually in the sentence itself. Examples:" }, { "code": null, "e": 297, "s": 158, "text": "Input : Geeks For Geeks is good to learn\nOutput : skeeG roF skeeG si doog ot nrael\n\nInput : Split Reverse Join\nOutput : tilpS esreveR nioJ" }, { "code": null, "e": 511, "s": 297, "text": "We shall use Python’s built in library function to reverse each word individually in the string itself. Prerequisites : 1. split() 2. Reversing Techniques in Python 3. List Comprehension Method in python 4. join()" }, { "code": null, "e": 556, "s": 511, "text": "First split the sentence into list of words." }, { "code": null, "e": 614, "s": 556, "text": "Reverse each word of the string in the list individually." }, { "code": null, "e": 665, "s": 614, "text": "Join the words in the list to form a new sentence." }, { "code": null, "e": 708, "s": 665, "text": "Below is the implementation of above idea." }, { "code": null, "e": 716, "s": 708, "text": "Python3" }, { "code": "# Python code to Reverse each word# of a Sentence individually # Function to Reverse wordsdef reverseWordSentence(Sentence): # Splitting the Sentence into list of words. words = Sentence.split(\" \") # Reversing each word and creating # a new list of words # List Comprehension Technique newWords = [word[::-1] for word in words] # Joining the new list of words # to for a new Sentence newSentence = \" \".join(newWords) return newSentence # Driver's CodeSentence = \"GeeksforGeeks is good to learn\"# Calling the reverseWordSentence# Function to get the newSentenceprint(reverseWordSentence(Sentence))", "e": 1355, "s": 716, "text": null }, { "code": null, "e": 1363, "s": 1355, "text": "Output:" }, { "code": null, "e": 1394, "s": 1363, "text": "skeeGrofskeeG si doog ot nrael" }, { "code": null, "e": 1494, "s": 1394, "text": "Python is well known for its short codes. We shall do the same task but with lesser line of codes. " }, { "code": null, "e": 1502, "s": 1494, "text": "Python3" }, { "code": "# Python code to Reverse each word# of a Sentence individually # Function to Reverse wordsdef reverseWordSentence(Sentence): # All in One line return ' '.join(word[::-1] for word in Sentence.split(\" \")) # Driver's CodeSentence = \"Geeks for Geeks\"print(reverseWordSentence(Sentence)) ", "e": 1795, "s": 1502, "text": null }, { "code": null, "e": 1803, "s": 1795, "text": "Output:" }, { "code": null, "e": 1819, "s": 1803, "text": "skeeG rof skeeG" }, { "code": null, "e": 2046, "s": 1819, "text": "Approach#3: Using re.sub() function We can use re.sub() function to replace the words in sentence with reversed words in sentence. We capture the word in string with the help of group method and replace it with reversed word. " }, { "code": null, "e": 2054, "s": 2046, "text": "Python3" }, { "code": "# Python code to Reverse each word# of a Sentence individuallyimport re# Function to Reverse wordsdef reverseWordSentence(Sentence): # substiting revrese word in place of word in sentence newSentence = re.sub('(\\w+)', lambda x : x.group()[::-1], Sentence) return newSentence # Driver's CodeSentence = \"GeeksforGeeks is good to learn\"# Calling the reverseWordSentence# Function to get the newSentenceprint(reverseWordSentence(Sentence))", "e": 2501, "s": 2054, "text": null }, { "code": null, "e": 2509, "s": 2501, "text": "Output:" }, { "code": null, "e": 2540, "s": 2509, "text": "skeeGrofskeeG si doog ot nrael" }, { "code": null, "e": 2553, "s": 2540, "text": "Akanksha_Rai" }, { "code": null, "e": 2567, "s": 2553, "text": "shubham_singh" }, { "code": null, "e": 2578, "s": 2567, "text": "satyam00so" }, { "code": null, "e": 2592, "s": 2578, "text": "python-string" }, { "code": null, "e": 2599, "s": 2592, "text": "Python" }, { "code": null, "e": 2697, "s": 2599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2715, "s": 2697, "text": "Python Dictionary" }, { "code": null, "e": 2757, "s": 2715, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2779, "s": 2757, "text": "Enumerate() in Python" }, { "code": null, "e": 2814, "s": 2779, "text": "Read a file line by line in Python" }, { "code": null, "e": 2840, "s": 2814, "text": "Python String | replace()" }, { "code": null, "e": 2872, "s": 2840, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2901, "s": 2872, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2928, "s": 2901, "text": "Python Classes and Objects" }, { "code": null, "e": 2958, "s": 2928, "text": "Iterate over a list in Python" } ]
Performing Database Operations in Java | SQL CREATE, INSERT, UPDATE, DELETE and SELECT
16 Jun, 2022 This article is going to help you in learning how to do basic database operations using JDBC (Java Database Connectivity) API. These basic operations are INSERT, SELECT, UPDATE and DELETE statements in SQL language. Although the target database system is Oracle Database, but the same techniques can be applied to other database systems as well because of the query syntax used is standard SQL is generally supported by all relational database systems.Prerequisites : JDK Oracle Database (Download Oracle Database Express Edition 11g release 2) JDBC driver for Oracle Database (Download Oracle Database 11g release 2 JDBC drivers).You need to add ojdbc6.jar to project library. You need to go through this article before continuing for better understanding.Creating a user in Oracle Database and granting required permissions : Open oracle using cmd. For that type sqlplus in cmd and press Enter. Create a user-id protected by a password. This user-id is called child user. create user identified by ; Grant required permissions to child user. For simplicity we grant database administrator privilege to child user. conn / as sysdba; grant dba to ; Create a sample table with blank fields : CREATE TABLE userid( id varchar2(30) NOT NULL PRIMARY KEY, pwd varchar2(30) NOT NULL, fullname varchar2(50), email varchar2(50) ); Principal JDBC interfaces and classes Let’s take an overview look at the JDBC’s main interfaces and classes which we’ll use in this article. They are all available under the java.sql package: Class.forName() : Here we load the driver’s class file into memory at the runtime. No need of using new or creation of object. Class.forName("oracle.jdbc.driver.OracleDriver"); DriverManager: This class is used to register driver for a specific database type (e.g. Oracle Database in this tutorial) and to establish a database connection with the server via its getConnection() method. Connection: This interface represents an established database connection (session) from which we can create statements to execute queries and retrieve results, get metadata about the database, close connection, etc. Connection con = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1"); Statement and PreparedStatement: These interfaces are used to execute static SQL query and parameterized SQL query, respectively. Statement is the super interface of the PreparedStatement interface. Their commonly used methods are:boolean execute(String sql): executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only.int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected). boolean execute(String sql): executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only.int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected). boolean execute(String sql): executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only. int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected). Statement stmt = con.createStatement(); String q1 = "insert into userid values ('" +id+ "', '" +pwd+ "', '" +fullname+ "', '" +email+ "')"; int x = stmt.executeUpdate(q1); ResultSet executeQuery(String sql): executes a SELECT statement and returns a ResultSet object which contains results returned by the query. Statement stmt = con.createStatement(); String q1 = "select * from userid WHERE id = '" + id + "' AND pwd = '" + pwd + "'"; ResultSet rs = stmt.executeQuery(q1); ResultSet: contains table data returned by a SELECT query. Use this object to iterate over rows in the result set using next() method. SQLException: this checked exception is declared to be thrown by all the above methods, so we have to catch this exception explicitly when calling the above classes’ methods. Connecting to the Database The Oracle Database server listens on the default port 1521 at localhost. The following code snippet connects to the database name userid by the user login1 and password pwd1. Java // Java program to illustrate// Connecting to the Databaseimport java.sql.*; public class connect{ public static void main(String args[]) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); // Establishing Connection Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1"); if (con != null) System.out.println("Connected"); else System.out.println("Not Connected"); con.close(); } catch(Exception e) { System.out.println(e); } }} Output : Connected Note: Here oracle in database URL in getConnection() method specifies SID of Oracle Database. For Oracle database 11g it is orcl and for oracle database 10g it is xe. Implementing Insert Statement Java // Java program to illustrate// inserting to the Databaseimport java.sql.*; public class insert1{ public static void main(String args[]) { String id = "id1"; String pwd = "pwd1"; String fullname = "geeks for geeks"; String email = "[email protected]"; try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(" jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1"); Statement stmt = con.createStatement(); // Inserting data in database String q1 = "insert into userid values('" +id+ "', '" +pwd+ "', '" +fullname+ "', '" +email+ "')"; int x = stmt.executeUpdate(q1); if (x > 0) System.out.println("Successfully Inserted"); else System.out.println("Insert Failed"); con.close(); } catch(Exception e) { System.out.println(e); } }} Output : Successfully Registered Implementing Update Statement Java // Java program to illustrate// updating the Databaseimport java.sql.*; public class update1{ public static void main(String args[]) { String id = "id1"; String pwd = "pwd1"; String newPwd = "newpwd"; try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(" jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1"); Statement stmt = con.createStatement(); // Updating database String q1 = "UPDATE userid set pwd = '" + newPwd + "' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'"; int x = stmt.executeUpdate(q1); if (x > 0) System.out.println("Password Successfully Updated"); else System.out.println("ERROR OCCURRED :("); con.close(); } catch(Exception e) { System.out.println(e); } }} Output : Password Successfully Updated Implementing Delete Statement Java // Java program to illustrate// deleting from Databaseimport java.sql.*; public class delete{ public static void main(String args[]) { String id = "id2"; String pwd = "pwd2"; try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(" jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1"); Statement stmt = con.createStatement(); // Deleting from database String q1 = "DELETE from userid WHERE id = '" + id + "' AND pwd = '" + pwd + "'"; int x = stmt.executeUpdate(q1); if (x > 0) System.out.println("One User Successfully Deleted"); else System.out.println("ERROR OCCURRED :("); con.close(); } catch(Exception e) { System.out.println(e); } }} Output : One User Successfully Deleted Implementing Select Statement Java // Java program to illustrate// selecting from Databaseimport java.sql.*; public class select{ public static void main(String args[]) { String id = "id1"; String pwd = "pwd1"; try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(" jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1"); Statement stmt = con.createStatement(); // SELECT query String q1 = "select * from userid WHERE id = '" + id + "' AND pwd = '" + pwd + "'"; ResultSet rs = stmt.executeQuery(q1); if (rs.next()) { System.out.println("User-Id : " + rs.getString(1)); System.out.println("Full Name :" + rs.getString(3)); System.out.println("E-mail :" + rs.getString(4)); } else { System.out.println("No such user id is already registered"); } con.close(); } catch(Exception e) { System.out.println(e); } }} Output : User-Id : id1 Full Name : geeks for geeks E-mail :[email protected] Note : Here the column index here is 1-based, the first column will be at index 1, the second at index 2, and so on. For other data types, the ResultSet provide appropriate getter methods: getString() getInt() getFloat() getDate() getTimestamp() ..... This article is contributed by Sangeet Anand. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. khushboogoyal499 sagartomar9927 nikhatkhan11 JDBC Java SQL Java SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java SQL | DDL, DQL, DML, DCL and TCL Commands SQL | Join (Inner, Left, Right and Full Joins) SQL | WITH clause How to find Nth highest salary from a table CTE in SQL
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Jun, 2022" }, { "code": null, "e": 523, "s": 54, "text": "This article is going to help you in learning how to do basic database operations using JDBC (Java Database Connectivity) API. These basic operations are INSERT, SELECT, UPDATE and DELETE statements in SQL language. Although the target database system is Oracle Database, but the same techniques can be applied to other database systems as well because of the query syntax used is standard SQL is generally supported by all relational database systems.Prerequisites : " }, { "code": null, "e": 527, "s": 523, "text": "JDK" }, { "code": null, "e": 600, "s": 527, "text": "Oracle Database (Download Oracle Database Express Edition 11g release 2)" }, { "code": null, "e": 733, "s": 600, "text": "JDBC driver for Oracle Database (Download Oracle Database 11g release 2 JDBC drivers).You need to add ojdbc6.jar to project library." }, { "code": null, "e": 885, "s": 733, "text": "You need to go through this article before continuing for better understanding.Creating a user in Oracle Database and granting required permissions : " }, { "code": null, "e": 954, "s": 885, "text": "Open oracle using cmd. For that type sqlplus in cmd and press Enter." }, { "code": null, "e": 1032, "s": 954, "text": "Create a user-id protected by a password. This user-id is called child user. " }, { "code": null, "e": 1061, "s": 1032, "text": "create user identified by ;" }, { "code": null, "e": 1176, "s": 1061, "text": "Grant required permissions to child user. For simplicity we grant database administrator privilege to child user. " }, { "code": null, "e": 1209, "s": 1176, "text": "conn / as sysdba;\ngrant dba to ;" }, { "code": null, "e": 1252, "s": 1209, "text": "Create a sample table with blank fields : " }, { "code": null, "e": 1399, "s": 1252, "text": "CREATE TABLE userid(\n id varchar2(30) NOT NULL PRIMARY KEY,\n pwd varchar2(30) NOT NULL,\n fullname varchar2(50),\n email varchar2(50)\n);" }, { "code": null, "e": 1439, "s": 1401, "text": "Principal JDBC interfaces and classes" }, { "code": null, "e": 1595, "s": 1439, "text": "Let’s take an overview look at the JDBC’s main interfaces and classes which we’ll use in this article. They are all available under the java.sql package: " }, { "code": null, "e": 1723, "s": 1595, "text": "Class.forName() : Here we load the driver’s class file into memory at the runtime. No need of using new or creation of object. " }, { "code": null, "e": 1773, "s": 1723, "text": "Class.forName(\"oracle.jdbc.driver.OracleDriver\");" }, { "code": null, "e": 1982, "s": 1773, "text": "DriverManager: This class is used to register driver for a specific database type (e.g. Oracle Database in this tutorial) and to establish a database connection with the server via its getConnection() method." }, { "code": null, "e": 2199, "s": 1982, "text": "Connection: This interface represents an established database connection (session) from which we can create statements to execute queries and retrieve results, get metadata about the database, close connection, etc. " }, { "code": null, "e": 2305, "s": 2199, "text": "Connection con = DriverManager.getConnection\n(\"jdbc:oracle:thin:@localhost:1521:orcl\", \"login1\", \"pwd1\");" }, { "code": null, "e": 2964, "s": 2305, "text": "Statement and PreparedStatement: These interfaces are used to execute static SQL query and parameterized SQL query, respectively. Statement is the super interface of the PreparedStatement interface. Their commonly used methods are:boolean execute(String sql): executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only.int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected). " }, { "code": null, "e": 3392, "s": 2964, "text": "boolean execute(String sql): executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only.int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected). " }, { "code": null, "e": 3615, "s": 3392, "text": "boolean execute(String sql): executes a general SQL statement. It returns true if the query returns a ResultSet, false if the query returns an update count or returns nothing. This method can be used with a Statement only." }, { "code": null, "e": 3821, "s": 3615, "text": "int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows affected). " }, { "code": null, "e": 4011, "s": 3821, "text": "Statement stmt = con.createStatement();\n String q1 = \"insert into userid values\n ('\" +id+ \"', '\" +pwd+ \"', '\" +fullname+ \"', '\" +email+ \"')\";\n int x = stmt.executeUpdate(q1);" }, { "code": null, "e": 4153, "s": 4011, "text": "ResultSet executeQuery(String sql): executes a SELECT statement and returns a ResultSet object which contains results returned by the query. " }, { "code": null, "e": 4334, "s": 4153, "text": "Statement stmt = con.createStatement();\n String q1 = \"select * from userid WHERE id = '\" + id + \"' \n AND pwd = '\" + pwd + \"'\";\n ResultSet rs = stmt.executeQuery(q1);" }, { "code": null, "e": 4469, "s": 4334, "text": "ResultSet: contains table data returned by a SELECT query. Use this object to iterate over rows in the result set using next() method." }, { "code": null, "e": 4644, "s": 4469, "text": "SQLException: this checked exception is declared to be thrown by all the above methods, so we have to catch this exception explicitly when calling the above classes’ methods." }, { "code": null, "e": 4671, "s": 4644, "text": "Connecting to the Database" }, { "code": null, "e": 4847, "s": 4671, "text": "The Oracle Database server listens on the default port 1521 at localhost. The following code snippet connects to the database name userid by the user login1 and password pwd1." }, { "code": null, "e": 4852, "s": 4847, "text": "Java" }, { "code": "// Java program to illustrate// Connecting to the Databaseimport java.sql.*; public class connect{ public static void main(String args[]) { try { Class.forName(\"oracle.jdbc.driver.OracleDriver\"); // Establishing Connection Connection con = DriverManager.getConnection( \"jdbc:oracle:thin:@localhost:1521:orcl\", \"login1\", \"pwd1\"); if (con != null) System.out.println(\"Connected\"); else System.out.println(\"Not Connected\"); con.close(); } catch(Exception e) { System.out.println(e); } }}", "e": 5568, "s": 4852, "text": null }, { "code": null, "e": 5587, "s": 5568, "text": "Output :\nConnected" }, { "code": null, "e": 5755, "s": 5587, "text": "Note: Here oracle in database URL in getConnection() method specifies SID of Oracle Database. For Oracle database 11g it is orcl and for oracle database 10g it is xe. " }, { "code": null, "e": 5785, "s": 5755, "text": "Implementing Insert Statement" }, { "code": null, "e": 5790, "s": 5785, "text": "Java" }, { "code": "// Java program to illustrate// inserting to the Databaseimport java.sql.*; public class insert1{ public static void main(String args[]) { String id = \"id1\"; String pwd = \"pwd1\"; String fullname = \"geeks for geeks\"; String email = \"[email protected]\"; try { Class.forName(\"oracle.jdbc.driver.OracleDriver\"); Connection con = DriverManager.getConnection(\" jdbc:oracle:thin:@localhost:1521:orcl\", \"login1\", \"pwd1\"); Statement stmt = con.createStatement(); // Inserting data in database String q1 = \"insert into userid values('\" +id+ \"', '\" +pwd+ \"', '\" +fullname+ \"', '\" +email+ \"')\"; int x = stmt.executeUpdate(q1); if (x > 0) System.out.println(\"Successfully Inserted\"); else System.out.println(\"Insert Failed\"); con.close(); } catch(Exception e) { System.out.println(e); } }}", "e": 6897, "s": 5790, "text": null }, { "code": null, "e": 6930, "s": 6897, "text": "Output :\nSuccessfully Registered" }, { "code": null, "e": 6960, "s": 6930, "text": "Implementing Update Statement" }, { "code": null, "e": 6965, "s": 6960, "text": "Java" }, { "code": "// Java program to illustrate// updating the Databaseimport java.sql.*; public class update1{ public static void main(String args[]) { String id = \"id1\"; String pwd = \"pwd1\"; String newPwd = \"newpwd\"; try { Class.forName(\"oracle.jdbc.driver.OracleDriver\"); Connection con = DriverManager.getConnection(\" jdbc:oracle:thin:@localhost:1521:orcl\", \"login1\", \"pwd1\"); Statement stmt = con.createStatement(); // Updating database String q1 = \"UPDATE userid set pwd = '\" + newPwd + \"' WHERE id = '\" +id+ \"' AND pwd = '\" + pwd + \"'\"; int x = stmt.executeUpdate(q1); if (x > 0) System.out.println(\"Password Successfully Updated\"); else System.out.println(\"ERROR OCCURRED :(\"); con.close(); } catch(Exception e) { System.out.println(e); } }}", "e": 8008, "s": 6965, "text": null }, { "code": null, "e": 8047, "s": 8008, "text": "Output :\nPassword Successfully Updated" }, { "code": null, "e": 8077, "s": 8047, "text": "Implementing Delete Statement" }, { "code": null, "e": 8082, "s": 8077, "text": "Java" }, { "code": "// Java program to illustrate// deleting from Databaseimport java.sql.*; public class delete{ public static void main(String args[]) { String id = \"id2\"; String pwd = \"pwd2\"; try { Class.forName(\"oracle.jdbc.driver.OracleDriver\"); Connection con = DriverManager.getConnection(\" jdbc:oracle:thin:@localhost:1521:orcl\", \"login1\", \"pwd1\"); Statement stmt = con.createStatement(); // Deleting from database String q1 = \"DELETE from userid WHERE id = '\" + id + \"' AND pwd = '\" + pwd + \"'\"; int x = stmt.executeUpdate(q1); if (x > 0) System.out.println(\"One User Successfully Deleted\"); else System.out.println(\"ERROR OCCURRED :(\"); con.close(); } catch(Exception e) { System.out.println(e); } }}", "e": 9095, "s": 8082, "text": null }, { "code": null, "e": 9134, "s": 9095, "text": "Output :\nOne User Successfully Deleted" }, { "code": null, "e": 9164, "s": 9134, "text": "Implementing Select Statement" }, { "code": null, "e": 9169, "s": 9164, "text": "Java" }, { "code": "// Java program to illustrate// selecting from Databaseimport java.sql.*; public class select{ public static void main(String args[]) { String id = \"id1\"; String pwd = \"pwd1\"; try { Class.forName(\"oracle.jdbc.driver.OracleDriver\"); Connection con = DriverManager.getConnection(\" jdbc:oracle:thin:@localhost:1521:orcl\", \"login1\", \"pwd1\"); Statement stmt = con.createStatement(); // SELECT query String q1 = \"select * from userid WHERE id = '\" + id + \"' AND pwd = '\" + pwd + \"'\"; ResultSet rs = stmt.executeQuery(q1); if (rs.next()) { System.out.println(\"User-Id : \" + rs.getString(1)); System.out.println(\"Full Name :\" + rs.getString(3)); System.out.println(\"E-mail :\" + rs.getString(4)); } else { System.out.println(\"No such user id is already registered\"); } con.close(); } catch(Exception e) { System.out.println(e); } }}", "e": 10339, "s": 9169, "text": null }, { "code": null, "e": 10414, "s": 10339, "text": "Output :\nUser-Id : id1\nFull Name : geeks for geeks\nE-mail :[email protected]" }, { "code": null, "e": 10603, "s": 10414, "text": "Note : Here the column index here is 1-based, the first column will be at index 1, the second at index 2, and so on. For other data types, the ResultSet provide appropriate getter methods:" }, { "code": null, "e": 10615, "s": 10603, "text": "getString()" }, { "code": null, "e": 10624, "s": 10615, "text": "getInt()" }, { "code": null, "e": 10635, "s": 10624, "text": "getFloat()" }, { "code": null, "e": 10645, "s": 10635, "text": "getDate()" }, { "code": null, "e": 10660, "s": 10645, "text": "getTimestamp()" }, { "code": null, "e": 10666, "s": 10660, "text": "....." }, { "code": null, "e": 11087, "s": 10666, "text": "This article is contributed by Sangeet Anand. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 11104, "s": 11087, "text": "khushboogoyal499" }, { "code": null, "e": 11119, "s": 11104, "text": "sagartomar9927" }, { "code": null, "e": 11132, "s": 11119, "text": "nikhatkhan11" }, { "code": null, "e": 11137, "s": 11132, "text": "JDBC" }, { "code": null, "e": 11142, "s": 11137, "text": "Java" }, { "code": null, "e": 11146, "s": 11142, "text": "SQL" }, { "code": null, "e": 11151, "s": 11146, "text": "Java" }, { "code": null, "e": 11155, "s": 11151, "text": "SQL" }, { "code": null, "e": 11253, "s": 11155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11304, "s": 11253, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 11335, "s": 11304, "text": "How to iterate any Map in Java" }, { "code": null, "e": 11354, "s": 11335, "text": "Interfaces in Java" }, { "code": null, "e": 11384, "s": 11354, "text": "HashMap in Java with Examples" }, { "code": null, "e": 11402, "s": 11384, "text": "ArrayList in Java" }, { "code": null, "e": 11444, "s": 11402, "text": "SQL | DDL, DQL, DML, DCL and TCL Commands" }, { "code": null, "e": 11491, "s": 11444, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 11509, "s": 11491, "text": "SQL | WITH clause" }, { "code": null, "e": 11553, "s": 11509, "text": "How to find Nth highest salary from a table" } ]