title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Facial recognition login system using Deep learning + ReactJS | by Dhruvil Shah | Towards Data Science
You must have seen a facial recognition login system in apps or websites. If you are an app developer or a website developer you may want to add facial recognition as a login phase in your system. Here, we are going to build a very easy-to-adapt login system from scratch that you can integrate into any app or system for login aspects. We will build this system in 2 conspicuous steps. These steps include creating a Flask server that contains our deep learning model and creating a ReactJS app for login. ReactJS application could communicate with our deep learning model with the help of the Flask server. It can send the image of the person and the model can return the true identity of the person in the image. These all will be clear once we start coding. Let’s get to the coding part and create our login system. Take a look at the below figure to clear any misgivings about our system to be built. Facial Recognition and Facial Verification are two different things. Facial recognition is concerned with identifying who is the person in the image by detecting the face while facial verification determines if the given two images are of the same person or not. Here, to build our login system we will require a model that can detect faces from the images and convert the facial details into a 128-dimensional vector which we can use later for facial recognition or verification purposes. We can use the FaceNet model provided by Hiroki Taniai so that we do not have to build one from scratch and need to worry about the hyperparameters. This FaceNet model has been trained on the MS-Celeb-1M dataset and expects a color image of size 160x160 pixels. The model can be downloaded from here: Keras FaceNet Pre-Trained Model. First, let’s import important modules for our Flask server that contains our deep learning model. # Import all the necessary files!import osimport tensorflow as tffrom tensorflow.keras import layersfrom tensorflow.keras import Modelfrom tensorflow.python.keras.backend import set_sessionfrom flask import Flask, requestfrom flask_cors import CORSimport cv2import jsonimport numpy as npimport base64from datetime import datetime Some important steps for our API to work. You can learn more about why we use sessions in Flask here. graph = tf.get_default_graph()app = Flask(__name__)CORS(app)sess = tf.Session()set_session(sess) Finally, we will load our model. model = tf.keras.models.load_model('facenet_keras.h5') Let’s create a function that converts the given image into a 128-dimensional vector. This function takes the image path and our model as parameters and outputs the vector that contains information of the image. def img_to_encoding(path, model): img1 = cv2.imread(path, 1) img = img1[...,::-1] dim = (160, 160) # resize image if(img.shape != (160, 160, 3)): img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) x_train = np.array([img]) embedding = model.predict(x_train) return embedding Let’s create a sample database that stores the identity of the people. You can store some identities beforehand if you want. You can give an image of a person as an argument to the img_to_encoding method along with the model and you will get the 128-dimensional vector which you can store as a value to the database dictionary with the person’s name being the key. database = {}database["Klaus"] = img_to_encoding("images/klaus.jpg", model)database["Levi"] = img_to_encoding("images/captain_levi.jpg", model)database["Eren"] = img_to_encoding("images/eren.jpg", model)database["Armin"] = img_to_encoding("images/armin.jpg", model) Let’s create a function that will return the identity of the person in the image using the database. It will compute the distance as shown above for all the entries in the database and the new image and find the minimum distance. If the minimum distance is larger than the threshold it will show that the person is not registered otherwise it will return the identity with the minimum distance. def who_is_it(image_path, database, model): encoding = img_to_encoding(image_path, model) min_dist = 1000 #Looping over the names and encodings in the database. for (name, db_enc) in database.items(): dist = np.linalg.norm(encoding-db_enc) if dist < min_dist: min_dist = dist identity = name if min_dist > 5: print("Not in the database.") else: print ("it's " + str(identity) + ", the distance is " + str(min_dist)) return min_dist, identity Finally, we want our Flask server to do two tasks: 1) Register the user to the database dictionary if not registered 2) Identify the identity of the user from an image. We will create routes for our API. First, we will create a route that identifies the user from an image and returns the identity. This route will receive base64 data of the image from React app captured by the user at a time and it will return the identity of the user if registered or it will send a hint that the user is not registered so that our React app knows whether to log in. Note: Go here if you want to know the reason behind using the TensorFlow sessions. app.route('/verify', methods=['POST'])def verify(): img_data = request.get_json()['image64'] img_name = str(int(datetime.timestamp(datetime.now()))) with open('images/'+img_name+'.jpg', "wb") as fh: fh.write(base64.b64decode(img_data[22:])) path = 'images/'+img_name+'.jpg' global sess global graph with graph.as_default(): set_session(sess) min_dist, identity = who_is_it(path, database, model) os.remove(path) if min_dist > 5: return json.dumps({"identity": 0}) return json.dumps({"identity": str(identity)}) Above we created a temporary image file for our purposes and after checking for the identity of the user we removed it as it is not useful to us. We are naming this file with the help of the timestamp. Time to create our second route that will register the new person into the database. It will receive the user’s name and the base64 data of the user’s image from the React app. It will compute the 128-dimensional vector for the image and store it into the database dictionary. If registered successfully it will send the status code of 200 otherwise it will send 500 status code (internal error). @app.route('/register', methods=['POST'])def register(): try: username = request.get_json()['username'] img_data = request.get_json()['image64'] with open('images/'+username+'.jpg', "wb") as fh: fh.write(base64.b64decode(img_data[22:])) path = 'images/'+username+'.jpg'global sess global graph with graph.as_default(): set_session(sess) database[username] = img_to_encoding(path, model) return json.dumps({"status": 200}) except: return json.dumps({"status": 500}) That is all for the deep learning part of the system. There are chances that you are still unclear about how these all will fit into the system we are building. Let’s take a look at the flow of the system after creating our Flask server. The front-end coding of the application is out of the scope for this project. Details on the front-end will not be discussed here but you can download the whole code from the project link. The home page will look like this: We will discuss the two important React components that will be used in our app — <Verify/> (for signing in) and <Signup/> (for signing up). The app.js file (that contains <App/> component) will contain the following code. import React, {Component} from 'react';import './App.css';import './css/main.css';import './css/util.css';import {Signup} from './signup.js';import {Verify} from './verify.js';export class App extends Component { constructor(props){ super(props); this.state = { signup : false, verify : false }; this.backhome = this.backhome.bind(this); } backhome(){ this.setState({ signup: false, verify: false }) } signup(){ this.setState({ signup: true, verify: false }) } verify(){ this.setState({ signup: false, verify: true }) } render(){ let home = ( <div> <div className="limiter"> <div className="container-login100"> <div className="wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33"> <form className="login100-form validate-form flex-sb flex-w"> <span className="login100-form-title p-b-53"> Sign In Or Up :) </span> <div className="container-login100-form-btn m-t-17"> <button onClick={this.verify.bind(this)} className="login100-form-btn"> Sign In </button> </div> <div className="container-login100-form-btn m-t-17"> <button onClick={this.signup.bind(this)} className="login100-form-btn"> Sign Up </button> </div> <div className="w-full text-center p-t-55"> <span className="txt2"> </span> <a href="#" className="txt2 bo1"> </a> </div> </form> </div> </div> </div> <div id="dropDownSelect1"></div></div>)return ( <div> {!this.state.signup && !this.state.verify ? home : ''} {this.state.signup ? <Signup backhome={this.backhome}/> : ''} {this.state.verify? <Verify backhome={this.backhome}/> : ''} </div> ) }}export default App; Some methods control which component to render next. For example, this.signup method will change the state value so that the <Signup/> component is rendered. Similarly, this.verify method will cause the app to render the <Verify/> component. this.backhome method is for coming back to the main page. The rest of the code is self-explanatory. Let’s dive into the first component that is <Verify/> (for signing in). Below is the code for the Verify.js file. import React, {Component} from 'react';import './css/main.css';import './css/util.css';import './verify.css';import Sketch from "react-p5";const axios = require('axios');let video;export class Verify extends Component {constructor(props){ super(props); this.state = { verify : false, idenity: ' ' }; }setup(p5='', canvasParentRef='') { p5.noCanvas(); video = p5.createCapture(p5.VIDEO); }//to shut off the camerastop(){ const tracks = document.querySelector("video").srcObject.getTracks(); tracks.forEach(function(track) { track.stop(); }); }logout(){ this.stop(); this.props.backhome(); }setup2(){ const button = document.getElementById('submit'); button.addEventListener('click', async event => { video.loadPixels(); console.log(video.canvas); const image64 = video.canvas.toDataURL(); const data = { image64 }; const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }; const response = await axios.post('http://localhost:5000/verify', {'image64':image64}); console.log(response.data.identity); if(response.data.identity){ this.stop(); this.setState({ verify:true, idenity: response.data.identity }) } else { this.stop(); alert("Not a registered user!") this.props.backhome(); } }); }render(){let verify = (<div> <div className="limiter"> <div className="container-login100"> <div className="wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33"> <span className="login100-form-title p-b-53"> Sign In With </span> <input/> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <Sketch setup={this.setup} draw={this.draw}/> <div className="container-login100-form-btn m-t-17"> <button id="submit" onClick={this.setup2.bind(this)} className="login100-form-btn"> Sign In </button> </div> <div className="container-login100-form-btn m-t-17"> <button onClick={this.logout.bind(this)} className="login100-form-btn"> Back! </button> </div> </div> </div> </div> <div id="dropDownSelect1"></div></div> )return (<div > {this.state.verify? <div><h1>Welcome, {this.state.idenity}.</h1> <button onClick={this.props.backhome} className="container-login100-form-btn">Logout!</button> </div> : verify } </div>) }}export default Verify; For capturing the image of the user we will use the p5.js library. You can learn about how to use it here or you can directly copy the code and run it as there is no need to learn the entire library just for this particular application. After getting the response from our server we will shut the camera off and render the next component accordingly. Below is the first output of the <Verify/> component. We are getting an error as we first need to register with our username and face. For doing so we will create the <Signup/> component as shown below. import React, {Component} from 'react';import './css/main.css';import './css/util.css';import './signup.css';import Sketch from "react-p5";const axios = require('axios');let video;export class Signup extends Component { constructor(props){ super(props); this.state = { signup : true }; } setup(p5, canvasParentRef) { p5.noCanvas(); video = p5.createCapture(p5.VIDEO); const v = document.querySelector("video"); let st = "position: absolute; top: 255px;" v.setAttribute("style", st); }setup2(){ const button = document.getElementById('submit'); button.addEventListener('click', async event => { const mood = document.getElementById('mood').value; video.loadPixels(); console.log(video.canvas); const image64 = video.canvas.toDataURL(); const data = { mood, image64 }; const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }; console.log(image64); const response = await axios.post('http://localhost:5000/register', {'image64':image64, 'username':mood}); if(response.status==200){ const tracks = document.querySelector("video").srcObject.getTracks(); tracks.forEach(function(track) { track.stop(); }); }; this.props.backhome(); } ); } logout(){ const tracks = document.querySelector("video").srcObject.getTracks(); tracks.forEach(function(track) { track.stop(); }); this.props.backhome(); }render(){let signup = ( <div> <div className="limiter"> <div className="container-login100"> <div className="wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33"> <span className="login100-form-title p-b-53"> Sign Up With </span> <div className="p-t-31 p-b-9"> <span className="txt1"> Username </span> </div> <div className="wrap-input100 validate-input" data-validate = "Username is required"> <input id="mood" className="input100" type="text" name="username" /> <span className="focus-input100"></span> </div> <input/> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <br/><br/><br/><br/>{this.state.signup?<Sketch id="s" setup={this.setup} draw={this.draw}/>:''} <div className="container-login100-form-btn m-t-17"> <button id="submit" onClick={this.setup2.bind(this)} className="login100-form-btn"> Sign Up </button> </div> <div className="container-login100-form-btn m-t-17"> <button onClick={this.logout.bind(this)} className="login100-form-btn"> Back! </button> </div> </div> </div> </div> <div id="dropDownSelect1"></div> </div> ) return (<div > { signup } </div> ) }}export default Signup; When we click on the ‘Sign up’ button on the home page the camera will start and the user will enter the name and click on the ‘Sign up’ button there. This component is responsible for taking our username and image and sending them to the ‘/register’ route of the Flask server we created earlier. The server will encode our image into the 128-dimensional vector and store it the database dictionary with our username as key and vector as value. As soon as our React app gets a status of 200 it will render the homepage again and this shows that the user has been successfully registered. Below is how the output of the above code looks. Now, after signing up we should be able to log in without any fail. Let’s try again to log in. After the login phase, there could be any page or website you want. For this article, I have kept it simple. After a successful login, the app will simply prompt a welcome message for the user. You can get all of the code shown above from GitHub. You can also find me on LinkedIn. We saw how we can integrate Deep learning and ReactJS to build a simple facial recognition login application. This app is supposed to be the login phase of any application or website you want. After the successful login, you can customize the next phase. We used deep learning to do the face recognition and verification for our application but we had to go through loading the model and managing the images. We can also use pre-programmed libraries. There is a module called face-api.js in JavaScript’s Node Package Manager (npm) which is implemented on the top of TensorFlow. You can check out this library here. To conclude, the facial recognition field is advancing very fast and this article shows a very simple approach compared to the ones used in the industry by companies like Facebook. Highly advanced facial recognition systems can detect sentiments of the person by looking at the face or detect the gender or even estimate the age of the person.
[ { "code": null, "e": 509, "s": 172, "text": "You must have seen a facial recognition login system in apps or websites. If you are an app developer or a website developer you may want to add facial recognition as a login phase in your system. Here, we are going to build a very easy-to-adapt login system from scratch that you can integrate into any app or system for login aspects." }, { "code": null, "e": 1078, "s": 509, "text": "We will build this system in 2 conspicuous steps. These steps include creating a Flask server that contains our deep learning model and creating a ReactJS app for login. ReactJS application could communicate with our deep learning model with the help of the Flask server. It can send the image of the person and the model can return the true identity of the person in the image. These all will be clear once we start coding. Let’s get to the coding part and create our login system. Take a look at the below figure to clear any misgivings about our system to be built." }, { "code": null, "e": 1568, "s": 1078, "text": "Facial Recognition and Facial Verification are two different things. Facial recognition is concerned with identifying who is the person in the image by detecting the face while facial verification determines if the given two images are of the same person or not. Here, to build our login system we will require a model that can detect faces from the images and convert the facial details into a 128-dimensional vector which we can use later for facial recognition or verification purposes." }, { "code": null, "e": 1902, "s": 1568, "text": "We can use the FaceNet model provided by Hiroki Taniai so that we do not have to build one from scratch and need to worry about the hyperparameters. This FaceNet model has been trained on the MS-Celeb-1M dataset and expects a color image of size 160x160 pixels. The model can be downloaded from here: Keras FaceNet Pre-Trained Model." }, { "code": null, "e": 2000, "s": 1902, "text": "First, let’s import important modules for our Flask server that contains our deep learning model." }, { "code": null, "e": 2330, "s": 2000, "text": "# Import all the necessary files!import osimport tensorflow as tffrom tensorflow.keras import layersfrom tensorflow.keras import Modelfrom tensorflow.python.keras.backend import set_sessionfrom flask import Flask, requestfrom flask_cors import CORSimport cv2import jsonimport numpy as npimport base64from datetime import datetime" }, { "code": null, "e": 2432, "s": 2330, "text": "Some important steps for our API to work. You can learn more about why we use sessions in Flask here." }, { "code": null, "e": 2529, "s": 2432, "text": "graph = tf.get_default_graph()app = Flask(__name__)CORS(app)sess = tf.Session()set_session(sess)" }, { "code": null, "e": 2562, "s": 2529, "text": "Finally, we will load our model." }, { "code": null, "e": 2617, "s": 2562, "text": "model = tf.keras.models.load_model('facenet_keras.h5')" }, { "code": null, "e": 2828, "s": 2617, "text": "Let’s create a function that converts the given image into a 128-dimensional vector. This function takes the image path and our model as parameters and outputs the vector that contains information of the image." }, { "code": null, "e": 3122, "s": 2828, "text": "def img_to_encoding(path, model): img1 = cv2.imread(path, 1) img = img1[...,::-1] dim = (160, 160) # resize image if(img.shape != (160, 160, 3)): img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) x_train = np.array([img]) embedding = model.predict(x_train) return embedding" }, { "code": null, "e": 3487, "s": 3122, "text": "Let’s create a sample database that stores the identity of the people. You can store some identities beforehand if you want. You can give an image of a person as an argument to the img_to_encoding method along with the model and you will get the 128-dimensional vector which you can store as a value to the database dictionary with the person’s name being the key." }, { "code": null, "e": 3753, "s": 3487, "text": "database = {}database[\"Klaus\"] = img_to_encoding(\"images/klaus.jpg\", model)database[\"Levi\"] = img_to_encoding(\"images/captain_levi.jpg\", model)database[\"Eren\"] = img_to_encoding(\"images/eren.jpg\", model)database[\"Armin\"] = img_to_encoding(\"images/armin.jpg\", model)" }, { "code": null, "e": 4148, "s": 3753, "text": "Let’s create a function that will return the identity of the person in the image using the database. It will compute the distance as shown above for all the entries in the database and the new image and find the minimum distance. If the minimum distance is larger than the threshold it will show that the person is not registered otherwise it will return the identity with the minimum distance." }, { "code": null, "e": 4661, "s": 4148, "text": "def who_is_it(image_path, database, model): encoding = img_to_encoding(image_path, model) min_dist = 1000 #Looping over the names and encodings in the database. for (name, db_enc) in database.items(): dist = np.linalg.norm(encoding-db_enc) if dist < min_dist: min_dist = dist identity = name if min_dist > 5: print(\"Not in the database.\") else: print (\"it's \" + str(identity) + \", the distance is \" + str(min_dist)) return min_dist, identity" }, { "code": null, "e": 5298, "s": 4661, "text": "Finally, we want our Flask server to do two tasks: 1) Register the user to the database dictionary if not registered 2) Identify the identity of the user from an image. We will create routes for our API. First, we will create a route that identifies the user from an image and returns the identity. This route will receive base64 data of the image from React app captured by the user at a time and it will return the identity of the user if registered or it will send a hint that the user is not registered so that our React app knows whether to log in. Note: Go here if you want to know the reason behind using the TensorFlow sessions." }, { "code": null, "e": 5867, "s": 5298, "text": "app.route('/verify', methods=['POST'])def verify(): img_data = request.get_json()['image64'] img_name = str(int(datetime.timestamp(datetime.now()))) with open('images/'+img_name+'.jpg', \"wb\") as fh: fh.write(base64.b64decode(img_data[22:])) path = 'images/'+img_name+'.jpg' global sess global graph with graph.as_default(): set_session(sess) min_dist, identity = who_is_it(path, database, model) os.remove(path) if min_dist > 5: return json.dumps({\"identity\": 0}) return json.dumps({\"identity\": str(identity)})" }, { "code": null, "e": 6069, "s": 5867, "text": "Above we created a temporary image file for our purposes and after checking for the identity of the user we removed it as it is not useful to us. We are naming this file with the help of the timestamp." }, { "code": null, "e": 6466, "s": 6069, "text": "Time to create our second route that will register the new person into the database. It will receive the user’s name and the base64 data of the user’s image from the React app. It will compute the 128-dimensional vector for the image and store it into the database dictionary. If registered successfully it will send the status code of 200 otherwise it will send 500 status code (internal error)." }, { "code": null, "e": 7030, "s": 6466, "text": "@app.route('/register', methods=['POST'])def register(): try: username = request.get_json()['username'] img_data = request.get_json()['image64'] with open('images/'+username+'.jpg', \"wb\") as fh: fh.write(base64.b64decode(img_data[22:])) path = 'images/'+username+'.jpg'global sess global graph with graph.as_default(): set_session(sess) database[username] = img_to_encoding(path, model) return json.dumps({\"status\": 200}) except: return json.dumps({\"status\": 500})" }, { "code": null, "e": 7268, "s": 7030, "text": "That is all for the deep learning part of the system. There are chances that you are still unclear about how these all will fit into the system we are building. Let’s take a look at the flow of the system after creating our Flask server." }, { "code": null, "e": 7492, "s": 7268, "text": "The front-end coding of the application is out of the scope for this project. Details on the front-end will not be discussed here but you can download the whole code from the project link. The home page will look like this:" }, { "code": null, "e": 7633, "s": 7492, "text": "We will discuss the two important React components that will be used in our app — <Verify/> (for signing in) and <Signup/> (for signing up)." }, { "code": null, "e": 7715, "s": 7633, "text": "The app.js file (that contains <App/> component) will contain the following code." }, { "code": null, "e": 9506, "s": 7715, "text": "import React, {Component} from 'react';import './App.css';import './css/main.css';import './css/util.css';import {Signup} from './signup.js';import {Verify} from './verify.js';export class App extends Component { constructor(props){ super(props); this.state = { signup : false, verify : false }; this.backhome = this.backhome.bind(this); } backhome(){ this.setState({ signup: false, verify: false }) } signup(){ this.setState({ signup: true, verify: false }) } verify(){ this.setState({ signup: false, verify: true }) } render(){ let home = ( <div> <div className=\"limiter\"> <div className=\"container-login100\"> <div className=\"wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33\"> <form className=\"login100-form validate-form flex-sb flex-w\"> <span className=\"login100-form-title p-b-53\"> Sign In Or Up :) </span> <div className=\"container-login100-form-btn m-t-17\"> <button onClick={this.verify.bind(this)} className=\"login100-form-btn\"> Sign In </button> </div> <div className=\"container-login100-form-btn m-t-17\"> <button onClick={this.signup.bind(this)} className=\"login100-form-btn\"> Sign Up </button> </div> <div className=\"w-full text-center p-t-55\"> <span className=\"txt2\"> </span> <a href=\"#\" className=\"txt2 bo1\"> </a> </div> </form> </div> </div> </div> <div id=\"dropDownSelect1\"></div></div>)return ( <div> {!this.state.signup && !this.state.verify ? home : ''} {this.state.signup ? <Signup backhome={this.backhome}/> : ''} {this.state.verify? <Verify backhome={this.backhome}/> : ''} </div> ) }}export default App;" }, { "code": null, "e": 9848, "s": 9506, "text": "Some methods control which component to render next. For example, this.signup method will change the state value so that the <Signup/> component is rendered. Similarly, this.verify method will cause the app to render the <Verify/> component. this.backhome method is for coming back to the main page. The rest of the code is self-explanatory." }, { "code": null, "e": 9962, "s": 9848, "text": "Let’s dive into the first component that is <Verify/> (for signing in). Below is the code for the Verify.js file." }, { "code": null, "e": 12658, "s": 9962, "text": "import React, {Component} from 'react';import './css/main.css';import './css/util.css';import './verify.css';import Sketch from \"react-p5\";const axios = require('axios');let video;export class Verify extends Component {constructor(props){ super(props); this.state = { verify : false, idenity: ' ' }; }setup(p5='', canvasParentRef='') { p5.noCanvas(); video = p5.createCapture(p5.VIDEO); }//to shut off the camerastop(){ const tracks = document.querySelector(\"video\").srcObject.getTracks(); tracks.forEach(function(track) { track.stop(); }); }logout(){ this.stop(); this.props.backhome(); }setup2(){ const button = document.getElementById('submit'); button.addEventListener('click', async event => { video.loadPixels(); console.log(video.canvas); const image64 = video.canvas.toDataURL(); const data = { image64 }; const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }; const response = await axios.post('http://localhost:5000/verify', {'image64':image64}); console.log(response.data.identity); if(response.data.identity){ this.stop(); this.setState({ verify:true, idenity: response.data.identity }) } else { this.stop(); alert(\"Not a registered user!\") this.props.backhome(); } }); }render(){let verify = (<div> <div className=\"limiter\"> <div className=\"container-login100\"> <div className=\"wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33\"> <span className=\"login100-form-title p-b-53\"> Sign In With </span> <input/> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <Sketch setup={this.setup} draw={this.draw}/> <div className=\"container-login100-form-btn m-t-17\"> <button id=\"submit\" onClick={this.setup2.bind(this)} className=\"login100-form-btn\"> Sign In </button> </div> <div className=\"container-login100-form-btn m-t-17\"> <button onClick={this.logout.bind(this)} className=\"login100-form-btn\"> Back! </button> </div> </div> </div> </div> <div id=\"dropDownSelect1\"></div></div> )return (<div > {this.state.verify? <div><h1>Welcome, {this.state.idenity}.</h1> <button onClick={this.props.backhome} className=\"container-login100-form-btn\">Logout!</button> </div> : verify } </div>) }}export default Verify;" }, { "code": null, "e": 13009, "s": 12658, "text": "For capturing the image of the user we will use the p5.js library. You can learn about how to use it here or you can directly copy the code and run it as there is no need to learn the entire library just for this particular application. After getting the response from our server we will shut the camera off and render the next component accordingly." }, { "code": null, "e": 13063, "s": 13009, "text": "Below is the first output of the <Verify/> component." }, { "code": null, "e": 13212, "s": 13063, "text": "We are getting an error as we first need to register with our username and face. For doing so we will create the <Signup/> component as shown below." }, { "code": null, "e": 16220, "s": 13212, "text": "import React, {Component} from 'react';import './css/main.css';import './css/util.css';import './signup.css';import Sketch from \"react-p5\";const axios = require('axios');let video;export class Signup extends Component { constructor(props){ super(props); this.state = { signup : true }; } setup(p5, canvasParentRef) { p5.noCanvas(); video = p5.createCapture(p5.VIDEO); const v = document.querySelector(\"video\"); let st = \"position: absolute; top: 255px;\" v.setAttribute(\"style\", st); }setup2(){ const button = document.getElementById('submit'); button.addEventListener('click', async event => { const mood = document.getElementById('mood').value; video.loadPixels(); console.log(video.canvas); const image64 = video.canvas.toDataURL(); const data = { mood, image64 }; const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }; console.log(image64); const response = await axios.post('http://localhost:5000/register', {'image64':image64, 'username':mood}); if(response.status==200){ const tracks = document.querySelector(\"video\").srcObject.getTracks(); tracks.forEach(function(track) { track.stop(); }); }; this.props.backhome(); } ); } logout(){ const tracks = document.querySelector(\"video\").srcObject.getTracks(); tracks.forEach(function(track) { track.stop(); }); this.props.backhome(); }render(){let signup = ( <div> <div className=\"limiter\"> <div className=\"container-login100\"> <div className=\"wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33\"> <span className=\"login100-form-title p-b-53\"> Sign Up With </span> <div className=\"p-t-31 p-b-9\"> <span className=\"txt1\"> Username </span> </div> <div className=\"wrap-input100 validate-input\" data-validate = \"Username is required\"> <input id=\"mood\" className=\"input100\" type=\"text\" name=\"username\" /> <span className=\"focus-input100\"></span> </div> <input/> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <br/><br/><br/><br/>{this.state.signup?<Sketch id=\"s\" setup={this.setup} draw={this.draw}/>:''} <div className=\"container-login100-form-btn m-t-17\"> <button id=\"submit\" onClick={this.setup2.bind(this)} className=\"login100-form-btn\"> Sign Up </button> </div> <div className=\"container-login100-form-btn m-t-17\"> <button onClick={this.logout.bind(this)} className=\"login100-form-btn\"> Back! </button> </div> </div> </div> </div> <div id=\"dropDownSelect1\"></div> </div> ) return (<div > { signup } </div> ) }}export default Signup;" }, { "code": null, "e": 16808, "s": 16220, "text": "When we click on the ‘Sign up’ button on the home page the camera will start and the user will enter the name and click on the ‘Sign up’ button there. This component is responsible for taking our username and image and sending them to the ‘/register’ route of the Flask server we created earlier. The server will encode our image into the 128-dimensional vector and store it the database dictionary with our username as key and vector as value. As soon as our React app gets a status of 200 it will render the homepage again and this shows that the user has been successfully registered." }, { "code": null, "e": 16857, "s": 16808, "text": "Below is how the output of the above code looks." }, { "code": null, "e": 16952, "s": 16857, "text": "Now, after signing up we should be able to log in without any fail. Let’s try again to log in." }, { "code": null, "e": 17146, "s": 16952, "text": "After the login phase, there could be any page or website you want. For this article, I have kept it simple. After a successful login, the app will simply prompt a welcome message for the user." }, { "code": null, "e": 17233, "s": 17146, "text": "You can get all of the code shown above from GitHub. You can also find me on LinkedIn." }, { "code": null, "e": 17488, "s": 17233, "text": "We saw how we can integrate Deep learning and ReactJS to build a simple facial recognition login application. This app is supposed to be the login phase of any application or website you want. After the successful login, you can customize the next phase." }, { "code": null, "e": 17848, "s": 17488, "text": "We used deep learning to do the face recognition and verification for our application but we had to go through loading the model and managing the images. We can also use pre-programmed libraries. There is a module called face-api.js in JavaScript’s Node Package Manager (npm) which is implemented on the top of TensorFlow. You can check out this library here." } ]
WebRTC - Voice Demo
In this chapter, we are going to build a client application that allows two users on separate devices to communicate using WebRTC audio streams. Our application will have two pages. One for login and the other for making an audio call to another user. The two pages will be the div tags. Most input is done through simple event handlers. To create a WebRTC connection clients have to be able to transfer messages without using a WebRTC peer connection. This is where we will use HTML5 WebSockets − a bidirectional socket connection between two endpoints − a web server and a web browser. Now let's start using the WebSocket library. Create the server.js file and insert the following code − //require our websocket library var WebSocketServer = require('ws').Server; //creating a websocket server at port 9090 var wss = new WebSocketServer({port: 9090}); //when a user connects to our sever wss.on('connection', function(connection) { console.log("user connected"); //when server gets a message from a connected user connection.on('message', function(message) { console.log("Got message from a user:", message); }); connection.send("Hello from server"); }); The first line requires the WebSocket library which we have already installed. Then we create a socket server on the port 9090. Next, we listen to the connection event. This code will be executed when a user makes a WebSocket connection to the server. We then listen to any messages sent by the user. Finally, we send a response to the connected user saying “Hello from server”. In our signaling server, we will use a string-based username for each connection so we know where to send messages. Let's change our connection handler a bit − connection.on('message', function(message) { var data; //accepting only JSON messages try { data = JSON.parse(message); } catch (e) { console.log("Invalid JSON"); data = {}; } }); This way we accept only JSON messages. Next, we need to store all connected users somewhere. We will use a simple Javascript object for it. Change the top of our file − //require our websocket library var WebSocketServer = require('ws').Server; //creating a websocket server at port 9090 var wss = new WebSocketServer({port: 9090}); //all connected to the server users var users = {}; We are going to add a type field for every message coming from the client. For example if a user wants to login, he sends the login type message. Let's define it − connection.on('message', function(message) { var data; //accepting only JSON messages try { data = JSON.parse(message); } catch (e) { console.log("Invalid JSON"); data = {}; } //switching type of the user message switch (data.type) { //when a user tries to login case "login": console.log("User logged:", data.name); //if anyone is logged in with this username then refuse if(users[data.name]) { sendTo(connection, { type: "login", success: false }); } else { //save user connection on the server users[data.name] = connection; connection.name = data.name; sendTo(connection, { type: "login", success: true }); } break; default: sendTo(connection, { type: "error", message: "Command no found: " + data.type }); break; } }); If the user sends a message with the login type, we − Check if anyone has already logged in with this username. If so, then tell the user that he hasn't successfully logged in. If no one is using this username, we add username as a key to the connection object. If a command is not recognized we send an error. The following code is a helper function for sending messages to a connection. Add it to the server.js file − function sendTo(connection, message) { connection.send(JSON.stringify(message)); } When the user disconnects we should clean up its connection. We can delete the user when the close event is fired. Add the following code to the connection handler− connection.on("close", function() { if(connection.name) { delete users[connection.name]; } }); After successful login the user wants to call another. He should make an offer to another user to achieve it. Add the offer handler − case "offer": //for ex. UserA wants to call UserB console.log("Sending offer to: ", data.name); //if UserB exists then send him offer details var conn = users[data.name]; if(conn != null) { //setting that UserA connected with UserB connection.otherName = data.name; sendTo(conn, { type: "offer", offer: data.offer, name: connection.name }); } break; Firstly, we get the connection of the user we are trying to call. If it exists we send him offer details. We also add otherName to the connection object. This is made for the simplicity of finding it later. Answering to the response has a similar pattern that we used in the offer handler. Our server just passes through all messages as answer to another user. Add the following code after the offer handler − case "answer": console.log("Sending answer to: ", data.name); //for ex. UserB answers UserA var conn = users[data.name]; if(conn != null) { connection.otherName = data.name; sendTo(conn, { type: "answer", answer: data.answer }); } break; The final part is handling ICE candidate between users. We use the same technique just passing messages between users. The main difference is that candidate messages might happen multiple times per user in any order. Add the candidate handler − case "candidate": console.log("Sending candidate to:",data.name); var conn = users[data.name]; if(conn != null) { sendTo(conn, { type: "candidate", candidate: data.candidate }); } break; To allow our users to disconnect from another user we should implement the hanging up function. It will also tell the server to delete all user references. Add the leave handler − case "leave": console.log("Disconnecting from", data.name); var conn = users[data.name]; conn.otherName = null; //notify the other user so he can disconnect his peer connection if(conn != null) { sendTo(conn, { type: "leave" }); } break; This will also send the other user the leave event so he can disconnect his peer connection accordingly. We should also handle the case when a user drops his connection from the signaling server. Let's modify our close handler − connection.on("close", function() { if(connection.name) { delete users[connection.name]; if(connection.otherName) { console.log("Disconnecting from ", connection.otherName); var conn = users[connection.otherName]; conn.otherName = null; if(conn != null) { sendTo(conn, { type: "leave" }); } } } }); The following is the entire code of our signaling server − //require our websocket library var WebSocketServer = require('ws').Server; //creating a websocket server at port 9090 var wss = new WebSocketServer({port: 9090}); //all connected to the server users var users = {}; //when a user connects to our sever wss.on('connection', function(connection) { console.log("User connected"); //when server gets a message from a connected user connection.on('message', function(message) { var data; //accepting only JSON messages try { data = JSON.parse(message); } catch (e) { console.log("Invalid JSON"); data = {}; } //switching type of the user message switch (data.type) { //when a user tries to login case "login": console.log("User logged", data.name); //if anyone is logged in with this username then refuse if(users[data.name]) { sendTo(connection, { type: "login", success: false }); } else { //save user connection on the server users[data.name] = connection; connection.name = data.name; sendTo(connection, { type: "login", success: true }); } break; case "offer": //for ex. UserA wants to call UserB console.log("Sending offer to: ", data.name); //if UserB exists then send him offer details var conn = users[data.name]; if(conn != null) { //setting that UserA connected with UserB connection.otherName = data.name; sendTo(conn, { type: "offer", offer: data.offer, name: connection.name }); } break; case "answer": console.log("Sending answer to: ", data.name); //for ex. UserB answers UserA var conn = users[data.name]; if(conn != null) { connection.otherName = data.name; sendTo(conn, { type: "answer", answer: data.answer }); } break; case "candidate": console.log("Sending candidate to:",data.name); var conn = users[data.name]; if(conn != null) { sendTo(conn, { type: "candidate", candidate: data.candidate }); } break; case "leave": console.log("Disconnecting from", data.name); var conn = users[data.name]; conn.otherName = null; //notify the other user so he can disconnect his peer connection if(conn != null) { sendTo(conn, { type: "leave" }); } break; default: sendTo(connection, { type: "error", message: "Command not found: " + data.type }); break; } }); //when user exits, for example closes a browser window //this may help if we are still in "offer","answer" or "candidate" state connection.on("close", function() { if(connection.name) { delete users[connection.name]; if(connection.otherName) { console.log("Disconnecting from ", connection.otherName); var conn = users[connection.otherName]; conn.otherName = null; if(conn != null) { sendTo(conn, { type: "leave" }); } } } }); connection.send("Hello world"); }); function sendTo(connection, message) { connection.send(JSON.stringify(message)); } One way to test this application is opening two browser tabs and trying to make an audio call to each other. First of all, we need to install the bootstrap library. Bootstrap is a frontend framework for developing web applications. You can learn more at http://getbootstrap.com/. Create a folder called, for example, “audiochat”. This will be our root application folder. Inside this folder create a file package.json (it is necessary for managing npm dependencies) and add the following − { "name": "webrtc-audiochat", "version": "0.1.0", "description": "webrtc-audiochat", "author": "Author", "license": "BSD-2-Clause" } Then run npm install bootstrap. This will install the bootstrap library in the audiochat/node_modules folder. Now we need to create a basic HTML page. Create an index.html file in the root folder with the following code − <html> <head> <title>WebRTC Voice Demo</title> <link rel = "stylesheet" href = "node_modules/bootstrap/dist/css/bootstrap.min.css"/> </head> <style> body { background: #eee; padding: 5% 0; } </style> <body> <div id = "loginPage" class = "container text-center"> <div class = "row"> <div class = "col-md-4 col-md-offset-4"> <h2>WebRTC Voice Demo. Please sign in</h2> <label for = "usernameInput" class = "sr-only">Login</label> <input type = "email" id = "usernameInput" class = "form-control formgroup" placeholder = "Login" required = "" autofocus = ""> <button id = "loginBtn" class = "btn btn-lg btn-primary btnblock"> Sign in</button> </div> </div> </div> <div id = "callPage" class = "call-page"> <div class = "row"> <div class = "col-md-6 text-right"> Local audio: <audio id = "localAudio" controls autoplay></audio> </div> <div class = "col-md-6 text-left"> Remote audio: <audio id = "remoteAudio" controls autoplay></audio> </div> </div> <div class = "row text-center"> <div class = "col-md-12"> <input id = "callToUsernameInput" type = "text" placeholder = "username to call" /> <button id = "callBtn" class = "btn-success btn">Call</button> <button id = "hangUpBtn" class = "btn-danger btn">Hang Up</button> </div> </div> </div> <script src = "client.js"></script> </body> </html> This page should be familiar to you. We have added the bootstrap css file. We have also defined two pages. Finally, we have created several text fields and buttons for getting information from the user. You should see the two audio elements for local and remote audio streams. Notice that we have added a link to a client.js file. Now we need to establish a connection with our signaling server. Create the client.js file in the root folder with the following code − //our username var name; var connectedUser; //connecting to our signaling server var conn = new WebSocket('ws://localhost:9090'); conn.onopen = function () { console.log("Connected to the signaling server"); }; //when we got a message from a signaling server conn.onmessage = function (msg) { console.log("Got message", msg.data); var data = JSON.parse(msg.data); switch(data.type) { case "login": handleLogin(data.success); break; //when somebody wants to call us case "offer": handleOffer(data.offer, data.name); break; case "answer": handleAnswer(data.answer); break; //when a remote peer sends an ice candidate to us case "candidate": handleCandidate(data.candidate); break; case "leave": handleLeave(); break; default: break; } }; conn.onerror = function (err) { console.log("Got error", err); }; //alias for sending JSON encoded messages function send(message) { //attach the other peer username to our messages if (connectedUser) { message.name = connectedUser; } conn.send(JSON.stringify(message)); }; Now run our signaling server via node server. Then, inside the root folder run the static command and open the page inside the browser. You should see the following console output − The next step is implementing a user log in with a unique username. We simply send a username to the server, which then tell us whether it is taken or not. Add the following code to your client.js file − //****** //UI selectors block //****** var loginPage = document.querySelector('#loginPage'); var usernameInput = document.querySelector('#usernameInput'); var loginBtn = document.querySelector('#loginBtn'); var callPage = document.querySelector('#callPage'); var callToUsernameInput = document.querySelector('#callToUsernameInput'); var callBtn = document.querySelector('#callBtn'); var hangUpBtn = document.querySelector('#hangUpBtn'); callPage.style.display = "none"; // Login when the user clicks the button loginBtn.addEventListener("click", function (event) { name = usernameInput.value; if (name.length > 0) { send({ type: "login", name: name }); } }); function handleLogin(success) { if (success === false) { alert("Ooops...try a different username"); } else { loginPage.style.display = "none"; callPage.style.display = "block"; //********************** //Starting a peer connection //********************** } }; Firstly, we select some references to the elements on the page. The we hide the call page. Then, we add an event listener on the login button. When the user clicks it, we send his username to the server. Finally, we implement the handleLogin callback. If the login was successful, we show the call page and starting to set up a peer connection. To start a peer connection we need − Obtain an audio stream from a microphone Create the RTCPeerConnection object Add the following code to the “UI selectors block” − var localAudio = document.querySelector('#localAudio'); var remoteAudio = document.querySelector('#remoteAudio'); var yourConn; var stream; Modify the handleLogin function − function handleLogin(success) { if (success === false) { alert("Ooops...try a different username"); } else { loginPage.style.display = "none"; callPage.style.display = "block"; //********************** //Starting a peer connection //********************** //getting local audio stream navigator.webkitGetUserMedia({ video: false, audio: true }, function (myStream) { stream = myStream; //displaying local audio stream on the page localAudio.src = window.URL.createObjectURL(stream); //using Google public stun server var configuration = { "iceServers": [{ "url": "stun:stun2.1.google.com:19302" }] }; yourConn = new webkitRTCPeerConnection(configuration); // setup stream listening yourConn.addStream(stream); //when a remote user adds stream to the peer connection, we display it yourConn.onaddstream = function (e) { remoteAudio.src = window.URL.createObjectURL(e.stream); }; // Setup ice handling yourConn.onicecandidate = function (event) { if (event.candidate) { send({ type: "candidate", }); } }; }, function (error) { console.log(error); }); } }; Now if you run the code, the page should allow you to log in and display your local audio stream on the page. Now we are ready to initiate a call. Firstly, we send an offer to another user. Once a user gets the offer, he creates an answer and start trading ICE candidates. Add the following code to the client.js file − //initiating a call callBtn.addEventListener("click", function () { var callToUsername = callToUsernameInput.value; if (callToUsername.length > 0) { connectedUser = callToUsername; // create an offer yourConn.createOffer(function (offer) { send({ type: "offer", offer: offer }); yourConn.setLocalDescription(offer); }, function (error) { alert("Error when creating an offer"); }); } }); //when somebody sends us an offer function handleOffer(offer, name) { connectedUser = name; yourConn.setRemoteDescription(new RTCSessionDescription(offer)); //create an answer to an offer yourConn.createAnswer(function (answer) { yourConn.setLocalDescription(answer); send({ type: "answer", answer: answer }); }, function (error) { alert("Error when creating an answer"); }); }; //when we got an answer from a remote user function handleAnswer(answer) { yourConn.setRemoteDescription(new RTCSessionDescription(answer)); }; //when we got an ice candidate from a remote user function handleCandidate(candidate) { yourConn.addIceCandidate(new RTCIceCandidate(candidate)); }; We add a click handler to the Call button, which initiates an offer. Then we implement several handlers expected by the onmessage handler. They will be processed asynchronously until both the users have made a connection. The last step is implementing the hang-up feature. This will stop transmitting data and tell the other user to close the call. Add the following code − //hang up hangUpBtn.addEventListener("click", function () { send({ type: "leave" }); handleLeave(); }); function handleLeave() { connectedUser = null; remoteAudio.src = null; yourConn.close(); yourConn.onicecandidate = null; yourConn.onaddstream = null; }; When the user clicks on the Hang Up button − It will send a “leave” message to the other user It will close the RTCPeerConnection and destroy the connection locally Now run the code. You should be able to log in to the server using two browser tabs. You can then make an audio call to the tab and hang up the call. The following is the entire client.js file − //our username var name; var connectedUser; //connecting to our signaling server var conn = new WebSocket('ws://localhost:9090'); conn.onopen = function () { console.log("Connected to the signaling server"); }; //when we got a message from a signaling server conn.onmessage = function (msg) { console.log("Got message", msg.data); var data = JSON.parse(msg.data); switch(data.type) { case "login": handleLogin(data.success); break; //when somebody wants to call us case "offer": handleOffer(data.offer, data.name); break; case "answer": handleAnswer(data.answer); break; //when a remote peer sends an ice candidate to us case "candidate": handleCandidate(data.candidate); break; case "leave": handleLeave(); break; default: break; } }; conn.onerror = function (err) { console.log("Got error", err); }; //alias for sending JSON encoded messages function send(message) { //attach the other peer username to our messages if (connectedUser) { message.name = connectedUser; } conn.send(JSON.stringify(message)); }; //****** //UI selectors block //****** var loginPage = document.querySelector('#loginPage'); var usernameInput = document.querySelector('#usernameInput'); var loginBtn = document.querySelector('#loginBtn'); var callPage = document.querySelector('#callPage'); var callToUsernameInput = document.querySelector('#callToUsernameInput'); var callBtn = document.querySelector('#callBtn'); var hangUpBtn = document.querySelector('#hangUpBtn'); var localAudio = document.querySelector('#localAudio'); var remoteAudio = document.querySelector('#remoteAudio'); var yourConn; var stream; callPage.style.display = "none"; // Login when the user clicks the button loginBtn.addEventListener("click", function (event) { name = usernameInput.value; if (name.length > 0) { send({ type: "login", name: name }); } }); function handleLogin(success) { if (success === false) { alert("Ooops...try a different username"); } else { loginPage.style.display = "none"; callPage.style.display = "block"; //********************** //Starting a peer connection //********************** //getting local audio stream navigator.webkitGetUserMedia({ video: false, audio: true }, function (myStream) { stream = myStream; //displaying local audio stream on the page localAudio.src = window.URL.createObjectURL(stream); //using Google public stun server var configuration = { "iceServers": [{ "url": "stun:stun2.1.google.com:19302" }] }; yourConn = new webkitRTCPeerConnection(configuration); // setup stream listening yourConn.addStream(stream); //when a remote user adds stream to the peer connection, we display it yourConn.onaddstream = function (e) { remoteAudio.src = window.URL.createObjectURL(e.stream); }; // Setup ice handling yourConn.onicecandidate = function (event) { if (event.candidate) { send({ type: "candidate", candidate: event.candidate }); } }; }, function (error) { console.log(error); }); } }; //initiating a call callBtn.addEventListener("click", function () { var callToUsername = callToUsernameInput.value; if (callToUsername.length > 0) { connectedUser = callToUsername; // create an offer yourConn.createOffer(function (offer) { send({ type: "offer", offer: offer }); yourConn.setLocalDescription(offer); }, function (error) { alert("Error when creating an offer"); }); } }); //when somebody sends us an offer function handleOffer(offer, name) { connectedUser = name; yourConn.setRemoteDescription(new RTCSessionDescription(offer)); //create an answer to an offer yourConn.createAnswer(function (answer) { yourConn.setLocalDescription(answer); send({ type: "answer", answer: answer }); }, function (error) { alert("Error when creating an answer"); }); }; //when we got an answer from a remote user function handleAnswer(answer) { yourConn.setRemoteDescription(new RTCSessionDescription(answer)); }; //when we got an ice candidate from a remote user function handleCandidate(candidate) { yourConn.addIceCandidate(new RTCIceCandidate(candidate)); }; //hang up hangUpBtn.addEventListener("click", function () { send({ type: "leave" }); handleLeave(); }); function handleLeave() { connectedUser = null; remoteAudio.src = null; yourConn.close(); yourConn.onicecandidate = null; yourConn.onaddstream = null; }; Print Add Notes Bookmark this page
[ { "code": null, "e": 2139, "s": 1887, "text": "In this chapter, we are going to build a client application that allows two users on separate devices to communicate using WebRTC audio streams. Our application will have two pages. One for login and the other for making an audio call to another user." }, { "code": null, "e": 2225, "s": 2139, "text": "The two pages will be the div tags. Most input is done through simple event handlers." }, { "code": null, "e": 2578, "s": 2225, "text": "To create a WebRTC connection clients have to be able to transfer messages without using a WebRTC peer connection. This is where we will use HTML5 WebSockets − a bidirectional socket connection between two endpoints − a web server and a web browser. Now let's start using the WebSocket library. Create the server.js file and insert the following code −" }, { "code": null, "e": 3085, "s": 2578, "text": "//require our websocket library \nvar WebSocketServer = require('ws').Server; \n\n//creating a websocket server at port 9090 \nvar wss = new WebSocketServer({port: 9090});\n \n//when a user connects to our sever \nwss.on('connection', function(connection) { \n console.log(\"user connected\"); \n\t\n //when server gets a message from a connected user \n connection.on('message', function(message) { \n console.log(\"Got message from a user:\", message); \n }); \n\t\n connection.send(\"Hello from server\"); \n});" }, { "code": null, "e": 3464, "s": 3085, "text": "The first line requires the WebSocket library which we have already installed. Then we create a socket server on the port 9090. Next, we listen to the connection event. This code will be executed when a user makes a WebSocket connection to the server. We then listen to any messages sent by the user. Finally, we send a response to the connected user saying “Hello from server”." }, { "code": null, "e": 3624, "s": 3464, "text": "In our signaling server, we will use a string-based username for each connection so we know where to send messages. Let's change our connection handler a bit −" }, { "code": null, "e": 3847, "s": 3624, "text": "connection.on('message', function(message) { \n var data; \n\t\n //accepting only JSON messages \n try { \n data = JSON.parse(message); \n } catch (e) { \n console.log(\"Invalid JSON\");\n data = {}; \n } \n});" }, { "code": null, "e": 4016, "s": 3847, "text": "This way we accept only JSON messages. Next, we need to store all connected users somewhere. We will use a simple Javascript object for it. Change the top of our file −" }, { "code": null, "e": 4239, "s": 4016, "text": "//require our websocket library \nvar WebSocketServer = require('ws').Server; \n\n//creating a websocket server at port 9090 \nvar wss = new WebSocketServer({port: 9090}); \n\n//all connected to the server users \nvar users = {};" }, { "code": null, "e": 4403, "s": 4239, "text": "We are going to add a type field for every message coming from the client. For example if a user wants to login, he sends the login type message. Let's define it −" }, { "code": null, "e": 5497, "s": 4403, "text": "connection.on('message', function(message) {\n \n var data; \n //accepting only JSON messages \n try { \n data = JSON.parse(message); \n } catch (e) { \n console.log(\"Invalid JSON\"); \n data = {}; \n } \n\t\n //switching type of the user message \n switch (data.type) { \n //when a user tries to login \n case \"login\": \n console.log(\"User logged:\", data.name); \n\t\t\t\n //if anyone is logged in with this username then refuse \n if(users[data.name]) { \n sendTo(connection, { \n type: \"login\",\n success: false \n }); \n } else { \n //save user connection on the server \n users[data.name] = connection; \n connection.name = data.name; \n\t\t\t\t\n sendTo(connection, { \n type: \"login\", \n success: true \n }); \n } \n\t\t\t\n break;\n\t\t\t\n default: \n sendTo(connection, { \n type: \"error\", \n message: \"Command no found: \" + data.type \n }); \n\t\t\t\n break; \n } \n});" }, { "code": null, "e": 5551, "s": 5497, "text": "If the user sends a message with the login type, we −" }, { "code": null, "e": 5609, "s": 5551, "text": "Check if anyone has already logged in with this username." }, { "code": null, "e": 5674, "s": 5609, "text": "If so, then tell the user that he hasn't successfully logged in." }, { "code": null, "e": 5759, "s": 5674, "text": "If no one is using this username, we add username as a key to the connection object." }, { "code": null, "e": 5808, "s": 5759, "text": "If a command is not recognized we send an error." }, { "code": null, "e": 5917, "s": 5808, "text": "The following code is a helper function for sending messages to a connection. Add it to the server.js file −" }, { "code": null, "e": 6005, "s": 5917, "text": "function sendTo(connection, message) { \n connection.send(JSON.stringify(message)); \n}" }, { "code": null, "e": 6170, "s": 6005, "text": "When the user disconnects we should clean up its connection. We can delete the user when the close event is fired. Add the following code to the connection handler−" }, { "code": null, "e": 6281, "s": 6170, "text": "connection.on(\"close\", function() { \n if(connection.name) { \n delete users[connection.name]; \n } \n});" }, { "code": null, "e": 6415, "s": 6281, "text": "After successful login the user wants to call another. He should make an offer to another user to achieve it. Add the offer handler −" }, { "code": null, "e": 6857, "s": 6415, "text": "case \"offer\": \n //for ex. UserA wants to call UserB \n console.log(\"Sending offer to: \", data.name); \n\t\n //if UserB exists then send him offer details \n var conn = users[data.name]; \n\t\n if(conn != null) { \n //setting that UserA connected with UserB \n connection.otherName = data.name; \n sendTo(conn, { \n type: \"offer\", \n offer: data.offer, \n name: connection.name \n });\n }\t\t\n\t\n break;" }, { "code": null, "e": 7064, "s": 6857, "text": "Firstly, we get the connection of the user we are trying to call. If it exists we send him offer details. We also add otherName to the connection object. This is made for the simplicity of finding it later." }, { "code": null, "e": 7267, "s": 7064, "text": "Answering to the response has a similar pattern that we used in the offer handler. Our server just passes through all messages as answer to another user. Add the following code after the offer handler −" }, { "code": null, "e": 7575, "s": 7267, "text": "case \"answer\": \n console.log(\"Sending answer to: \", data.name); \n //for ex. UserB answers UserA\n var conn = users[data.name]; \n\t\n if(conn != null) { \n connection.otherName = data.name;\n\t\t\n sendTo(conn, { \n type: \"answer\", \n answer: data.answer \n }); \n } \n\t\n break;" }, { "code": null, "e": 7820, "s": 7575, "text": "The final part is handling ICE candidate between users. We use the same technique just passing messages between users. The main difference is that candidate messages might happen multiple times per user in any order. Add the candidate handler −" }, { "code": null, "e": 8064, "s": 7820, "text": "case \"candidate\": \n console.log(\"Sending candidate to:\",data.name); \n var conn = users[data.name];\n\t\n if(conn != null) { \n sendTo(conn, { \n type: \"candidate\", \n candidate: data.candidate \n }); \n } \n\t\n break;" }, { "code": null, "e": 8244, "s": 8064, "text": "To allow our users to disconnect from another user we should implement the hanging up function. It will also tell the server to delete all user references. Add the leave handler −" }, { "code": null, "e": 8538, "s": 8244, "text": "case \"leave\": \n console.log(\"Disconnecting from\", data.name); \n var conn = users[data.name]; \n conn.otherName = null; \n\t\n //notify the other user so he can disconnect his peer connection \n if(conn != null) { \n sendTo(conn, {\n type: \"leave\" \n }); \n } \n\t\n break;" }, { "code": null, "e": 8767, "s": 8538, "text": "This will also send the other user the leave event so he can disconnect his peer connection accordingly. We should also handle the case when a user drops his connection from the signaling server. Let's modify our close handler −" }, { "code": null, "e": 9198, "s": 8767, "text": "connection.on(\"close\", function() { \n\n if(connection.name) { \n delete users[connection.name]; \n\t\t\n if(connection.otherName) { \n console.log(\"Disconnecting from \", connection.otherName); \n var conn = users[connection.otherName]; \n conn.otherName = null;\n\t\t\t\n if(conn != null) { \n sendTo(conn, { \n type: \"leave\" \n }); \n }\n\t\t\t\n } \n } \n});" }, { "code": null, "e": 9257, "s": 9198, "text": "The following is the entire code of our signaling server −" }, { "code": null, "e": 13395, "s": 9257, "text": "//require our websocket library \nvar WebSocketServer = require('ws').Server; \n\n//creating a websocket server at port 9090 \nvar wss = new WebSocketServer({port: 9090}); \n\n//all connected to the server users \nvar users = {};\n\n//when a user connects to our sever \nwss.on('connection', function(connection) {\n \n console.log(\"User connected\");\n\t\n //when server gets a message from a connected user \n connection.on('message', function(message) { \n\t\n var data;\n\t\t\n //accepting only JSON messages \n try { \n data = JSON.parse(message); \n } catch (e) { \n console.log(\"Invalid JSON\"); \n data = {}; \n }\n\t\t\n //switching type of the user message \n switch (data.type) { \n //when a user tries to login \n case \"login\": \n console.log(\"User logged\", data.name); \n\t\t\t\t\n //if anyone is logged in with this username then refuse \n if(users[data.name]) { \n sendTo(connection, { \n type: \"login\", \n success: false \n }); \n } else { \n //save user connection on the server \n users[data.name] = connection; \n connection.name = data.name;\n\t\t\t\t\t\n sendTo(connection, { \n type: \"login\", \n success: true \n }); \n } \n\t\t\t\t\n break;\n\t\t\t\t\n case \"offer\": \n //for ex. UserA wants to call UserB \n console.log(\"Sending offer to: \", data.name); \n\t\t\t\t\n //if UserB exists then send him offer details \n var conn = users[data.name]; \n\t\t\t\t\n if(conn != null) { \n //setting that UserA connected with UserB \n connection.otherName = data.name; \n\t\t\t\t\t\n sendTo(conn, { \n type: \"offer\", \n offer: data.offer, \n name: connection.name \n }); \n } \n\t\t\t\t\n break;\n\t\t\t\t\n case \"answer\": \n console.log(\"Sending answer to: \", data.name); \n //for ex. UserB answers UserA \n var conn = users[data.name]; \n\t\t\t\t\n if(conn != null) { \n connection.otherName = data.name; \n sendTo(conn, { \n type: \"answer\", \n answer: data.answer \n });\n } \n\t\t\t\t\n break;\n\t\t\t\t\n case \"candidate\": \n console.log(\"Sending candidate to:\",data.name); \n var conn = users[data.name]; \n\t\t\t\t\n if(conn != null) { \n sendTo(conn, { \n type: \"candidate\", \n candidate: data.candidate \n }); \n } \n\t\t\t\t\n break;\n\t\t\t\t\n case \"leave\": \n console.log(\"Disconnecting from\", data.name); \n var conn = users[data.name]; \n conn.otherName = null; \n\t\t\t\t\n //notify the other user so he can disconnect his peer connection \n if(conn != null) { \n sendTo(conn, { \n type: \"leave\" \n }); \n } \n\t\t\t\t\n break;\n\t\t\t\t\n default: \n sendTo(connection, { \n type: \"error\", \n message: \"Command not found: \" + data.type \n });\n\t\t\t\t\n break; \n } \n });\n\t\n //when user exits, for example closes a browser window \n //this may help if we are still in \"offer\",\"answer\" or \"candidate\" state \n connection.on(\"close\", function() { \n\t\n if(connection.name) { \n delete users[connection.name]; \n\t\t\t\n if(connection.otherName) { \n console.log(\"Disconnecting from \", connection.otherName); \n var conn = users[connection.otherName]; \n conn.otherName = null; \n\t\t\t\t\n if(conn != null) { \n sendTo(conn, { \n type: \"leave\" \n }); \n } \n } \n } \n }); \n\t\n connection.send(\"Hello world\"); \n}); \n \nfunction sendTo(connection, message) { \n connection.send(JSON.stringify(message)); \n}" }, { "code": null, "e": 13504, "s": 13395, "text": "One way to test this application is opening two browser tabs and trying to make an audio call to each other." }, { "code": null, "e": 13885, "s": 13504, "text": "First of all, we need to install the bootstrap library. Bootstrap is a frontend framework for developing web applications. You can learn more at http://getbootstrap.com/. Create a folder called, for example, “audiochat”. This will be our root application folder. Inside this folder create a file package.json (it is necessary for managing npm dependencies) and add the following −" }, { "code": null, "e": 14039, "s": 13885, "text": "{ \n \"name\": \"webrtc-audiochat\", \n \"version\": \"0.1.0\", \n \"description\": \"webrtc-audiochat\", \n \"author\": \"Author\", \n \"license\": \"BSD-2-Clause\" \n}" }, { "code": null, "e": 14149, "s": 14039, "text": "Then run npm install bootstrap. This will install the bootstrap library in the audiochat/node_modules folder." }, { "code": null, "e": 14261, "s": 14149, "text": "Now we need to create a basic HTML page. Create an index.html file in the root folder with the following code −" }, { "code": null, "e": 16126, "s": 14261, "text": "<html>\n \n <head> \n <title>WebRTC Voice Demo</title> \n <link rel = \"stylesheet\" href = \"node_modules/bootstrap/dist/css/bootstrap.min.css\"/> \n </head>\n \n <style> \n body { \n background: #eee; \n padding: 5% 0; \n } \n </style>\n\t\n <body> \n <div id = \"loginPage\" class = \"container text-center\"> \n\t\t\n <div class = \"row\"> \n <div class = \"col-md-4 col-md-offset-4\">\n\t\t\t\t\n <h2>WebRTC Voice Demo. Please sign in</h2>\n\t\t\t\t\n <label for = \"usernameInput\" class = \"sr-only\">Login</label> \n <input type = \"email\" id = \"usernameInput\" \n class = \"form-control formgroup\"\n placeholder = \"Login\" required = \"\" autofocus = \"\"> \n <button id = \"loginBtn\" class = \"btn btn-lg btn-primary btnblock\">\n Sign in</button> \n </div> \n </div> \n\t\t\t\n </div>\n\t\t\n <div id = \"callPage\" class = \"call-page\">\n\t\t\n <div class = \"row\"> \n\t\t\t\n <div class = \"col-md-6 text-right\"> \n Local audio: <audio id = \"localAudio\" \n controls autoplay></audio> \n </div>\n\t\t\t\t\n <div class = \"col-md-6 text-left\"> \n Remote audio: <audio id = \"remoteAudio\" \n controls autoplay></audio> \n </div> \n\t\t\t\t\n </div> \n\t\t\t\n <div class = \"row text-center\"> \n <div class = \"col-md-12\"> \n <input id = \"callToUsernameInput\" \n type = \"text\" placeholder = \"username to call\" /> \n <button id = \"callBtn\" class = \"btn-success btn\">Call</button> \n <button id = \"hangUpBtn\" class = \"btn-danger btn\">Hang Up</button> \n </div> \n </div>\n\t\t\t\n </div> \n\t\t\n <script src = \"client.js\"></script> \n\t\t\n </body>\n\t\n</html>" }, { "code": null, "e": 16457, "s": 16126, "text": "This page should be familiar to you. We have added the bootstrap css file. We have also defined two pages. Finally, we have created several text fields and buttons for getting information from the user. You should see the two audio elements for local and remote audio streams. Notice that we have added a link to a client.js file." }, { "code": null, "e": 16593, "s": 16457, "text": "Now we need to establish a connection with our signaling server. Create the client.js file in the root folder with the following code −" }, { "code": null, "e": 17844, "s": 16593, "text": "//our username \nvar name; \nvar connectedUser;\n \n//connecting to our signaling server \nvar conn = new WebSocket('ws://localhost:9090');\n \nconn.onopen = function () { \n console.log(\"Connected to the signaling server\"); \n}; \n \n//when we got a message from a signaling server \nconn.onmessage = function (msg) { \n console.log(\"Got message\", msg.data); \n var data = JSON.parse(msg.data); \n\t\n switch(data.type) { \n case \"login\": \n handleLogin(data.success); \n break; \n //when somebody wants to call us \n case \"offer\": \n handleOffer(data.offer, data.name); \n break; \n case \"answer\": \n handleAnswer(data.answer); \n break; \n //when a remote peer sends an ice candidate to us \n case \"candidate\": \n handleCandidate(data.candidate); \n break;\n case \"leave\": \n handleLeave(); \n break; \n default: \n break; \n } \n};\n \nconn.onerror = function (err) { \n console.log(\"Got error\", err); \n};\n \n//alias for sending JSON encoded messages \nfunction send(message) { \n //attach the other peer username to our messages\n if (connectedUser) { \n message.name = connectedUser; \n } \n\t\n conn.send(JSON.stringify(message)); \n};" }, { "code": null, "e": 18026, "s": 17844, "text": "Now run our signaling server via node server. Then, inside the root folder run the static command and open the page inside the browser. You should see the following console output −" }, { "code": null, "e": 18230, "s": 18026, "text": "The next step is implementing a user log in with a unique username. We simply send a username to the server, which then tell us whether it is taken or not. Add the following code to your client.js file −" }, { "code": null, "e": 19290, "s": 18230, "text": "//****** \n//UI selectors block \n//******\n\nvar loginPage = document.querySelector('#loginPage'); \nvar usernameInput = document.querySelector('#usernameInput'); \nvar loginBtn = document.querySelector('#loginBtn');\n \nvar callPage = document.querySelector('#callPage'); \nvar callToUsernameInput = document.querySelector('#callToUsernameInput');\nvar callBtn = document.querySelector('#callBtn');\n \nvar hangUpBtn = document.querySelector('#hangUpBtn');\n \ncallPage.style.display = \"none\";\n \n// Login when the user clicks the button \nloginBtn.addEventListener(\"click\", function (event) { \n name = usernameInput.value;\n\t\n if (name.length > 0) { \n send({\n type: \"login\", \n name: name \n }); \n } \n\t\n}); \n \nfunction handleLogin(success) { \n if (success === false) { \n alert(\"Ooops...try a different username\"); \n } else { \n loginPage.style.display = \"none\"; \n callPage.style.display = \"block\"; \n\t\t\n //********************** \n //Starting a peer connection \n //**********************\n\t\t \n } \n\t\n};" }, { "code": null, "e": 19635, "s": 19290, "text": "Firstly, we select some references to the elements on the page. The we hide the call page. Then, we add an event listener on the login button. When the user clicks it, we send his username to the server. Finally, we implement the handleLogin callback. If the login was successful, we show the call page and starting to set up a peer connection." }, { "code": null, "e": 19672, "s": 19635, "text": "To start a peer connection we need −" }, { "code": null, "e": 19713, "s": 19672, "text": "Obtain an audio stream from a microphone" }, { "code": null, "e": 19749, "s": 19713, "text": "Create the RTCPeerConnection object" }, { "code": null, "e": 19802, "s": 19749, "text": "Add the following code to the “UI selectors block” −" }, { "code": null, "e": 19946, "s": 19802, "text": "var localAudio = document.querySelector('#localAudio'); \nvar remoteAudio = document.querySelector('#remoteAudio'); \n\nvar yourConn; \nvar stream;" }, { "code": null, "e": 19980, "s": 19946, "text": "Modify the handleLogin function −" }, { "code": null, "e": 21415, "s": 19980, "text": "function handleLogin(success) { \n if (success === false) { \n alert(\"Ooops...try a different username\"); \n } else { \n loginPage.style.display = \"none\"; \n callPage.style.display = \"block\";\n\t\t\n //********************** \n //Starting a peer connection \n //********************** \n\t\t\n //getting local audio stream \n navigator.webkitGetUserMedia({ video: false, audio: true }, function (myStream) { \n stream = myStream; \n\t\t\t\n //displaying local audio stream on the page\n localAudio.src = window.URL.createObjectURL(stream);\n\t\t\t\n //using Google public stun server \n var configuration = { \n \"iceServers\": [{ \"url\": \"stun:stun2.1.google.com:19302\" }] \n }; \n\t\t\t\n yourConn = new webkitRTCPeerConnection(configuration); \n\t\t\t\n // setup stream listening \n yourConn.addStream(stream); \n\t\t\t\n //when a remote user adds stream to the peer connection, we display it \n yourConn.onaddstream = function (e) { \n remoteAudio.src = window.URL.createObjectURL(e.stream); \n }; \n\t\t\t\n // Setup ice handling \n yourConn.onicecandidate = function (event) { \n if (event.candidate) { \n send({ \n type: \"candidate\", \n }); \n } \n }; \n\t\t\t\n }, function (error) { \n console.log(error); \n }); \n\t\t\n } \n};" }, { "code": null, "e": 21525, "s": 21415, "text": "Now if you run the code, the page should allow you to log in and display your local audio stream on the page." }, { "code": null, "e": 21735, "s": 21525, "text": "Now we are ready to initiate a call. Firstly, we send an offer to another user. Once a user gets the offer, he creates an answer and start trading ICE candidates. Add the following code to the client.js file −" }, { "code": null, "e": 23025, "s": 21735, "text": "//initiating a call \ncallBtn.addEventListener(\"click\", function () { \n var callToUsername = callToUsernameInput.value; \n\t\n if (callToUsername.length > 0) { \n connectedUser = callToUsername; \n\t\t\n // create an offer \n yourConn.createOffer(function (offer) { \n send({ \n type: \"offer\", \n offer: offer \n }); \n\t\t\t\n yourConn.setLocalDescription(offer); \n\t\t\t\n }, function (error) { \n alert(\"Error when creating an offer\"); \n }); \n } \n\t\n});\n \n//when somebody sends us an offer \nfunction handleOffer(offer, name) { \n connectedUser = name; \n yourConn.setRemoteDescription(new RTCSessionDescription(offer)); \n\t\n //create an answer to an offer \n yourConn.createAnswer(function (answer) { \n yourConn.setLocalDescription(answer); \n\t\t\n send({ \n type: \"answer\",\n answer: answer \n }); \n\t\t\n }, function (error) { \n alert(\"Error when creating an answer\"); \n }); \n\t\n};\n \n//when we got an answer from a remote user \nfunction handleAnswer(answer) { \n yourConn.setRemoteDescription(new RTCSessionDescription(answer)); \n};\n \n//when we got an ice candidate from a remote user \nfunction handleCandidate(candidate) { \n yourConn.addIceCandidate(new RTCIceCandidate(candidate)); \n};" }, { "code": null, "e": 23247, "s": 23025, "text": "We add a click handler to the Call button, which initiates an offer. Then we implement several handlers expected by the onmessage handler. They will be processed asynchronously until both the users have made a connection." }, { "code": null, "e": 23399, "s": 23247, "text": "The last step is implementing the hang-up feature. This will stop transmitting data and tell the other user to close the call. Add the following code −" }, { "code": null, "e": 23704, "s": 23399, "text": "//hang up \nhangUpBtn.addEventListener(\"click\", function () { \n send({ \n type: \"leave\" \n }); \n\t\n handleLeave(); \n});\n \nfunction handleLeave() { \n connectedUser = null; \n remoteAudio.src = null;\n\t\n yourConn.close(); \n yourConn.onicecandidate = null; \n yourConn.onaddstream = null;\n};" }, { "code": null, "e": 23749, "s": 23704, "text": "When the user clicks on the Hang Up button −" }, { "code": null, "e": 23798, "s": 23749, "text": "It will send a “leave” message to the other user" }, { "code": null, "e": 23869, "s": 23798, "text": "It will close the RTCPeerConnection and destroy the connection locally" }, { "code": null, "e": 24019, "s": 23869, "text": "Now run the code. You should be able to log in to the server using two browser tabs. You can then make an audio call to the tab and hang up the call." }, { "code": null, "e": 24064, "s": 24019, "text": "The following is the entire client.js file −" }, { "code": null, "e": 29257, "s": 24064, "text": "//our username \nvar name; \nvar connectedUser;\n \n//connecting to our signaling server \nvar conn = new WebSocket('ws://localhost:9090');\n \nconn.onopen = function () { \n console.log(\"Connected to the signaling server\"); \n};\n \n//when we got a message from a signaling server \nconn.onmessage = function (msg) { \n console.log(\"Got message\", msg.data); \n var data = JSON.parse(msg.data); \n\t\n switch(data.type) { \n case \"login\": \n handleLogin(data.success); \n break; \n //when somebody wants to call us \n case \"offer\": \n handleOffer(data.offer, data.name); \n break; \n case \"answer\": \n handleAnswer(data.answer); \n break; \n //when a remote peer sends an ice candidate to us \n case \"candidate\": \n handleCandidate(data.candidate); \n break; \n case \"leave\": \n handleLeave(); \n break; \n default: \n break; \n } \n}; \n\nconn.onerror = function (err) { \n console.log(\"Got error\", err); \n};\n \n//alias for sending JSON encoded messages \nfunction send(message) { \n //attach the other peer username to our messages \n if (connectedUser) { \n message.name = connectedUser; \n } \n\t\n conn.send(JSON.stringify(message)); \n};\n \n//****** \n//UI selectors block \n//****** \n\nvar loginPage = document.querySelector('#loginPage'); \nvar usernameInput = document.querySelector('#usernameInput'); \nvar loginBtn = document.querySelector('#loginBtn');\n\nvar callPage = document.querySelector('#callPage'); \nvar callToUsernameInput = document.querySelector('#callToUsernameInput');\nvar callBtn = document.querySelector('#callBtn'); \n\nvar hangUpBtn = document.querySelector('#hangUpBtn'); \nvar localAudio = document.querySelector('#localAudio'); \nvar remoteAudio = document.querySelector('#remoteAudio'); \n\nvar yourConn; \nvar stream; \n\ncallPage.style.display = \"none\";\n \n// Login when the user clicks the button \nloginBtn.addEventListener(\"click\", function (event) { \n name = usernameInput.value; \n\t\n if (name.length > 0) { \n send({ \n type: \"login\", \n name: name \n }); \n } \n\t\n});\n \nfunction handleLogin(success) { \n if (success === false) { \n alert(\"Ooops...try a different username\"); \n } else { \n loginPage.style.display = \"none\"; \n callPage.style.display = \"block\"; \n\t\t\n //********************** \n //Starting a peer connection \n //********************** \n\t\t\n //getting local audio stream \n navigator.webkitGetUserMedia({ video: false, audio: true }, function (myStream) { \n stream = myStream; \n\t\t\t\n //displaying local audio stream on the page \n localAudio.src = window.URL.createObjectURL(stream);\n\t\t\t\n //using Google public stun server \n var configuration = { \n \"iceServers\": [{ \"url\": \"stun:stun2.1.google.com:19302\" }] \n }; \n\t\t\t\n yourConn = new webkitRTCPeerConnection(configuration); \n\t\t\t\n // setup stream listening \n yourConn.addStream(stream); \n\t\t\t\n //when a remote user adds stream to the peer connection, we display it \n yourConn.onaddstream = function (e) { \n remoteAudio.src = window.URL.createObjectURL(e.stream); \n }; \n\t\t\t\n // Setup ice handling \n yourConn.onicecandidate = function (event) { \n if (event.candidate) { \n send({ \n type: \"candidate\", \n candidate: event.candidate \n }); \n } \n }; \n\t\t\t\n }, function (error) { \n console.log(error); \n }); \n\t\t\n } \n};\n \n//initiating a call \ncallBtn.addEventListener(\"click\", function () { \n var callToUsername = callToUsernameInput.value; \n\t\n if (callToUsername.length > 0) { \n connectedUser = callToUsername; \n\t\t\n // create an offer \n yourConn.createOffer(function (offer) { \n send({\n type: \"offer\", \n offer: offer \n }); \n\t\t\t\n yourConn.setLocalDescription(offer); \n }, function (error) { \n alert(\"Error when creating an offer\"); \n }); \n } \n});\n \n//when somebody sends us an offer \nfunction handleOffer(offer, name) { \n connectedUser = name; \n yourConn.setRemoteDescription(new RTCSessionDescription(offer)); \n\t\n //create an answer to an offer \n yourConn.createAnswer(function (answer) { \n yourConn.setLocalDescription(answer); \n\t\t\n send({ \n type: \"answer\", \n answer: answer \n });\n\t\t\n }, function (error) { \n alert(\"Error when creating an answer\"); \n }); \n\t\n};\n \n//when we got an answer from a remote user \nfunction handleAnswer(answer) { \n yourConn.setRemoteDescription(new RTCSessionDescription(answer)); \n};\n \n//when we got an ice candidate from a remote user \nfunction handleCandidate(candidate) { \n yourConn.addIceCandidate(new RTCIceCandidate(candidate)); \n};\n \n//hang up\nhangUpBtn.addEventListener(\"click\", function () { \n send({ \n type: \"leave\" \n }); \n\t\n handleLeave(); \n});\n \nfunction handleLeave() { \n connectedUser = null; \n remoteAudio.src = null; \n\t\n yourConn.close(); \n yourConn.onicecandidate = null; \n yourConn.onaddstream = null; \n};" }, { "code": null, "e": 29264, "s": 29257, "text": " Print" }, { "code": null, "e": 29275, "s": 29264, "text": " Add Notes" } ]
How to read and write a file using Javascript?
You cannot read or write files in JS on client side(browsers). This can be done on serverside using the fs module in Node.js. It provides sync and async functions to read and write files on the file system. Let us look at the exmaples of reading and writing files using the fs module on node.js Let us create a js file named main.js having the following code − var fs = require("fs"); console.log("Going to write into existing file"); // Open a new file with name input.txt and write Simply Easy Learning! to it. fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) { if (err) { return console.error(err); } console.log("Data written successfully!"); console.log("Let's read newly written data"); // Read the newly written file and print all of its content on the console fs.readFile('input.txt', function (err, data) { if (err) { return console.error(err); } console.log("Asynchronous read: " + data.toString()); }); }); Now run the main.js to see the result − $ node main.js Going to write into existing file Data written successfully! Let's read newly written data Asynchronous read: Simply Easy Learning! You can read more about how fs module works in node and how to use it at https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm.
[ { "code": null, "e": 1357, "s": 1062, "text": "You cannot read or write files in JS on client side(browsers). This can be done on serverside using the fs module in Node.js. It provides sync and async functions to read and write files on the file system. Let us look at the exmaples of reading and writing files using the fs module on node.js" }, { "code": null, "e": 1423, "s": 1357, "text": "Let us create a js file named main.js having the following code −" }, { "code": null, "e": 2050, "s": 1423, "text": "var fs = require(\"fs\");\nconsole.log(\"Going to write into existing file\");\n// Open a new file with name input.txt and write Simply Easy Learning! to it.\nfs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {\n if (err) {\n return console.error(err);\n }\n console.log(\"Data written successfully!\");\n console.log(\"Let's read newly written data\");\n // Read the newly written file and print all of its content on the console\n fs.readFile('input.txt', function (err, data) {\n if (err) {\n return console.error(err);\n }\n console.log(\"Asynchronous read: \" + data.toString());\n });\n});" }, { "code": null, "e": 2090, "s": 2050, "text": "Now run the main.js to see the result −" }, { "code": null, "e": 2105, "s": 2090, "text": "$ node main.js" }, { "code": null, "e": 2237, "s": 2105, "text": "Going to write into existing file\nData written successfully!\nLet's read newly written data\nAsynchronous read: Simply Easy Learning!" }, { "code": null, "e": 2372, "s": 2237, "text": "You can read more about how fs module works in node and how to use it at https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm." } ]
Grouping Matching in Perl
From a regular-expression point of view in Perl, there is no difference between the following two expressions except that the former is slightly clearer. $string =~ /(\S+)\s+(\S+)/; and $string =~ /\S+\s+\S+/; However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string. my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/); As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows − Live Demo #!/usr/bin/perl $time = "12:05:30"; $time =~ m/(\d+):(\d+):(\d+)/; my ($hours, $minutes, $seconds) = ($1, $2, $3); print "Hours : $hours, Minutes: $minutes, Second: $seconds\n"; When above program is executed, it produces the following result − Hours : 12, Minutes: 05, Second: 30 When groups are used in substitution expressions, the $x syntax can be used in the replacement text. Thus, we could reformat a date string using this − Live Demo #!/usr/bin/perl $date = '03/26/1999'; $date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#; print "$date\n"; When above program is executed, it produces the following result − 1999/03/26
[ { "code": null, "e": 1216, "s": 1062, "text": "From a regular-expression point of view in Perl, there is no difference between the following two expressions except that the former is slightly clearer." }, { "code": null, "e": 1272, "s": 1216, "text": "$string =~ /(\\S+)\\s+(\\S+)/;\nand\n$string =~ /\\S+\\s+\\S+/;" }, { "code": null, "e": 1564, "s": 1272, "text": "However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string." }, { "code": null, "e": 1631, "s": 1564, "text": "my ($hours, $minutes, $seconds) = ($time =~ m/(\\d+):(\\d+):(\\d+)/);" }, { "code": null, "e": 1857, "s": 1631, "text": "As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows −" }, { "code": null, "e": 1868, "s": 1857, "text": " Live Demo" }, { "code": null, "e": 2046, "s": 1868, "text": "#!/usr/bin/perl\n$time = \"12:05:30\";\n$time =~ m/(\\d+):(\\d+):(\\d+)/;\nmy ($hours, $minutes, $seconds) = ($1, $2, $3);\nprint \"Hours : $hours, Minutes: $minutes, Second: $seconds\\n\";" }, { "code": null, "e": 2113, "s": 2046, "text": "When above program is executed, it produces the following result −" }, { "code": null, "e": 2149, "s": 2113, "text": "Hours : 12, Minutes: 05, Second: 30" }, { "code": null, "e": 2301, "s": 2149, "text": "When groups are used in substitution expressions, the $x syntax can be used in the replacement text. Thus, we could reformat a date string using this −" }, { "code": null, "e": 2312, "s": 2301, "text": " Live Demo" }, { "code": null, "e": 2407, "s": 2312, "text": "#!/usr/bin/perl\n$date = '03/26/1999';\n$date =~ s#(\\d+)/(\\d+)/(\\d+)#$3/$1/$2#;\nprint \"$date\\n\";" }, { "code": null, "e": 2474, "s": 2407, "text": "When above program is executed, it produces the following result −" }, { "code": null, "e": 2485, "s": 2474, "text": "1999/03/26" } ]
Tryit Editor v3.7
Tryit: HTML responsive page
[]
How to gray out (disable) a Tkinter Frame?
A Tkinter frame widget can contain a group of widgets. We can change the state of widgets in the frame by enabling or disabling the state of its underlying frame. To disable all the widgets inside that particular frame, we have to select all the children widgets that are lying inside that frame using winfor_children() and change the state using state=(‘disabled’ or ‘enable’) attribute. In this example, we will create a button and an entry widget. Initially, the state of entry widget is disabled. But when we click the button, it will enable all the widgets in the frame. #Import the required Libraries from tkinter import * from tkinter import ttk #Define a Function to enable the frame def enable(children): for child in children: child.configure(state='enable') #Create an instance of tkinter frame win = Tk() #Set the geometry of tkinter frame win.geometry("750x250") #Creates top frame frame1 = LabelFrame(win, width= 400, height= 180, bd=5) frame1.pack() #Create an Entry widget in Frame2 entry1 = ttk.Entry(frame1, width= 40) entry1.insert(INSERT,"Enter Your Name") entry1.pack() entry2= ttk.Entry(frame1, width= 40) entry2.insert(INSERT, "Enter Your Email") entry2.pack() #Creates bottom frame frame2 = LabelFrame(win, width= 150, height=100) frame2.pack() #Create a Button to enable frame button1 = ttk.Button(frame2, text="Enable", command=lambda: enable(frame1.winfo_children())) button1.pack() for child in frame1.winfo_children(): child.configure(state='disable') win.mainloop() Running the above code will display a window that contains two Label Frames. Each frame contains an entry widget and a button to enable or disable the frame. When we click the "Enable" button, it will activate Frame1.
[ { "code": null, "e": 1451, "s": 1062, "text": "A Tkinter frame widget can contain a group of widgets. We can change the state of widgets in the frame by enabling or disabling the state of its underlying frame. To disable all the widgets inside that particular frame, we have to select all the children widgets that are lying inside that frame using winfor_children() and change the state using state=(‘disabled’ or ‘enable’) attribute." }, { "code": null, "e": 1638, "s": 1451, "text": "In this example, we will create a button and an entry widget. Initially, the state of entry widget is disabled. But when we click the button, it will enable all the widgets in the frame." }, { "code": null, "e": 2578, "s": 1638, "text": "#Import the required Libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n#Define a Function to enable the frame\ndef enable(children):\n for child in children:\n child.configure(state='enable')\n\n#Create an instance of tkinter frame\nwin = Tk()\n\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n\n#Creates top frame\nframe1 = LabelFrame(win, width= 400, height= 180, bd=5)\nframe1.pack()\n\n#Create an Entry widget in Frame2\nentry1 = ttk.Entry(frame1, width= 40)\nentry1.insert(INSERT,\"Enter Your Name\")\nentry1.pack()\nentry2= ttk.Entry(frame1, width= 40)\nentry2.insert(INSERT, \"Enter Your Email\")\nentry2.pack()\n\n#Creates bottom frame\nframe2 = LabelFrame(win, width= 150, height=100)\nframe2.pack()\n\n#Create a Button to enable frame\nbutton1 = ttk.Button(frame2, text=\"Enable\", command=lambda: enable(frame1.winfo_children()))\nbutton1.pack()\nfor child in frame1.winfo_children():\n child.configure(state='disable')\n\nwin.mainloop()" }, { "code": null, "e": 2736, "s": 2578, "text": "Running the above code will display a window that contains two Label Frames. Each frame contains an entry widget and a button to enable or disable the frame." }, { "code": null, "e": 2796, "s": 2736, "text": "When we click the \"Enable\" button, it will activate Frame1." } ]
How to know the current position within a file in Python?
You can get the current position of the file object using the tell method. For example, if there is a file called my_file with text Hello\nworld, f = open('my_file.txt', 'r') f.readline() print f.tell() f.close() The above code will give the output as 6 as it would be pointing just at the beginning of the word 'world'.
[ { "code": null, "e": 1208, "s": 1062, "text": "You can get the current position of the file object using the tell method. For example, if there is a file called my_file with text Hello\\nworld," }, { "code": null, "e": 1275, "s": 1208, "text": "f = open('my_file.txt', 'r')\nf.readline()\nprint f.tell()\nf.close()" }, { "code": null, "e": 1383, "s": 1275, "text": "The above code will give the output as 6 as it would be pointing just at the beginning of the word 'world'." } ]
Program to find amount of water in a given glass - GeeksforGeeks
14 Feb, 2022 There are some glasses with equal capacity as 1 litre. The glasses are kept as follows: 1 2 3 4 5 6 7 8 9 10 You can put water to the only top glass. If you put more than 1-litre water to 1st glass, water overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both 2nd glass and 3rd glass and so on. If you have X litre of water and you put that water in a top glass, how much water will be contained by the jth glass in an ith row? Example. If you will put 2 litres on top. 1st – 1 litre 2nd – 1/2 litre 3rd – 1/2 litre For 2 Liters Water The approach is similar to Method 2 of the Pascal’s Triangle. If we take a closer look at the problem, the problem boils down to Pascal’s Triangle. 1 ---------------- 1 2 3 ---------------- 2 4 5 6 ------------ 3 7 8 9 10 --------- 4 Each glass contributes to the two glasses down the glass. Initially, we put all water in the first glass. Then we keep 1 litre (or less than 1 litre) in it and move rest of the water to two glasses down to it. We follow the same process for the two glasses and all other glasses till the ith row. There will be i*(i+1)/2 glasses till ith row. C++ Java Python3 C# PHP Javascript // Program to find the amount of water in j-th glass// of i-th row#include <stdio.h>#include <stdlib.h>#include <string.h> // Returns the amount of water in jth glass of ith rowfloat findWater(int i, int j, float X){ // A row number i has maximum i columns. So input // column number must be less than i if (j > i) { printf("Incorrect Inputn"); exit(0); } // There will be i*(i+1)/2 glasses till ith row // (including ith row) float glass[i * (i + 1) / 2]; // Initialize all glasses as empty memset(glass, 0, sizeof(glass)); // Put all water in first glass int index = 0; glass[index] = X; // Now let the water flow to the downward glasses // till the row number is less than or/ equal to i (given row) // correction : X can be zero for side glasses as they have lower rate to fill for (int row = 1; row <= i ; ++row) { // Fill glasses in a given row. Number of // columns in a row is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than or equal to // capacity in current glass glass[index] = (X >= 1.0f) ? 1.0f : X; // Get the remaining amount X = (X >= 1.0f) ? (X - 1) : 0.0f; // Distribute the remaining amount to // the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; } } // The index of jth glass in ith row will // be i*(i-1)/2 + j - 1 return glass[i*(i-1)/2 + j - 1];} // Driver program to test above functionint main(){ int i = 2, j = 2; float X = 2.0; // Total amount of water printf("Amount of water in jth glass of ith row is: %f", findWater(i, j, X)); return 0;} // Program to find the amount/// of water in j-th glass// of i-th rowimport java.lang.*; class GFG{// Returns the amount of water// in jth glass of ith rowstatic float findWater(int i, int j, float X){// A row number i has maximum i// columns. So input column// number must be less than iif (j > i){ System.out.println("Incorrect Input"); System.exit(0);} // There will be i*(i+1)/2 glasses// till ith row (including ith row)int ll = Math.round((i * (i + 1) ));float[] glass = new float[ll + 2]; // Put all water in first glassint index = 0;glass[index] = X; // Now let the water flow to the// downward glasses till the row// number is less than or/ equal// to i (given row)// correction : X can be zero for side// glasses as they have lower rate to fillfor (int row = 1; row <= i ; ++row){ // Fill glasses in a given row. Number of // columns in a row is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than or // equal to capacity in current glass glass[index] = (X >= 1.0f) ? 1.0f : X; // Get the remaining amount X = (X >= 1.0f) ? (X - 1) : 0.0f; // Distribute the remaining amount // to the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; }} // The index of jth glass in ith// row will be i*(i-1)/2 + j - 1return glass[(int)(i * (i - 1) / 2 + j - 1)];} // Driver Codepublic static void main(String[] args){ int i = 2, j = 2; float X = 2.0f; // Total amount of water System.out.println("Amount of water in jth " + "glass of ith row is: " + findWater(i, j, X));}} // This code is contributed by mits # Program to find the amount# of water in j-th glass of# i-th row # Returns the amount of water# in jth glass of ith rowdef findWater(i, j, X): # A row number i has maximum # i columns. So input column # number must be less than i if (j > i): print("Incorrect Input"); return; # There will be i*(i+1)/2 # glasses till ith row # (including ith row) # and Initialize all glasses # as empty glass = [0]*int(i *(i + 1) / 2); # Put all water # in first glass index = 0; glass[index] = X; # Now let the water flow to # the downward glasses till # the row number is less # than or/ equal to i (given # row) correction : X can be # zero for side glasses as # they have lower rate to fill for row in range(1,i): # Fill glasses in a given # row. Number of columns # in a row is equal to row number for col in range(1,row+1): # Get the water # from current glass X = glass[index]; # Keep the amount less # than or equal to # capacity in current glass glass[index] = 1.0 if (X >= 1.0) else X; # Get the remaining amount X = (X - 1) if (X >= 1.0) else 0.0; # Distribute the remaining # amount to the down two glasses glass[index + row] += (X / 2); glass[index + row + 1] += (X / 2); index+=1; # The index of jth glass # in ith row will # be i*(i-1)/2 + j - 1 return glass[int(i * (i - 1) /2 + j - 1)]; # Driver Codeif __name__ == "__main__": i = 2; j = 2; X = 2.0;# Total amount of water res=repr(findWater(i, j, X)); print("Amount of water in jth glass of ith row is:",res.ljust(8,'0'));# This Code is contributed by mits // Program to find the amount// of water in j-th glass// of i-th rowusing System; class GFG{// Returns the amount of water// in jth glass of ith rowstatic float findWater(int i, int j, float X){// A row number i has maximum i// columns. So input column// number must be less than iif (j > i){ Console.WriteLine("Incorrect Input"); Environment.Exit(0);} // There will be i*(i+1)/2 glasses// till ith row (including ith row)int ll = (int)Math.Round((double)(i * (i + 1)));float[] glass = new float[ll + 2]; // Put all water in first glassint index = 0;glass[index] = X; // Now let the water flow to the// downward glasses till the row// number is less than or/ equal// to i (given row)// correction : X can be zero// for side glasses as they have// lower rate to fillfor (int row = 1; row <= i ; ++row){ // Fill glasses in a given row. // Number of columns in a row // is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than // or equal to capacity in // current glass glass[index] = (X >= 1.0f) ? 1.0f : X; // Get the remaining amount X = (X >= 1.0f) ? (X - 1) : 0.0f; // Distribute the remaining amount // to the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; }} // The index of jth glass in ith// row will be i*(i-1)/2 + j - 1return glass[(int)(i * (i - 1) / 2 + j - 1)];} // Driver Codestatic void Main(){ int i = 2, j = 2; float X = 2.0f; // Total amount of water Console.WriteLine("Amount of water in jth " + "glass of ith row is: " + findWater(i, j, X));}} // This code is contributed by mits <?php// Program to find the amount// of water in j-th glass of// i-th row // Returns the amount of water// in jth glass of ith rowfunction findWater($i, $j, $X){ // A row number i has maximum // i columns. So input column // number must be less than i if ($j > $i) { echo "Incorrect Input\n"; return; } // There will be i*(i+1)/2 // glasses till ith row // (including ith row) // and Initialize all glasses // as empty $glass = array_fill(0, (int)($i * ($i + 1) / 2), 0); // Put all water // in first glass $index = 0; $glass[$index] = $X; // Now let the water flow to // the downward glasses till // the row number is less // than or/ equal to i (given // row) correction : X can be // zero for side glasses as // they have lower rate to fill for ($row = 1; $row < $i ; ++$row) { // Fill glasses in a given // row. Number of columns // in a row is equal to row number for ($col = 1; $col <= $row; ++$col, ++$index) { // Get the water // from current glass $X = $glass[$index]; // Keep the amount less // than or equal to // capacity in current glass $glass[$index] = ($X >= 1.0) ? 1.0 : $X; // Get the remaining amount $X = ($X >= 1.0) ? ($X - 1) : 0.0; // Distribute the remaining // amount to the down two glasses $glass[$index + $row] += (double)($X / 2); $glass[$index + $row + 1] += (double)($X / 2); } } // The index of jth glass // in ith row will // be i*(i-1)/2 + j - 1 return $glass[(int)($i * ($i - 1) / 2 + $j - 1)];} // Driver Code$i = 2;$j = 2;$X = 2.0; // Total amount of waterecho "Amount of water in jth " , "glass of ith row is: ". str_pad(findWater($i, $j, $X), 8, '0'); // This Code is contributed by mits?> <script> // Program to find the amount/// of water in j-th glass// of i-th row// Returns the amount of water// in jth glass of ith rowfunction findWater(i , j, X){// A row number i has maximum i// columns. So input column// number must be less than iif (j > i){ document.write("Incorrect Input");} // There will be i*(i+1)/2 glasses// till ith row (including ith row)var ll = Math.round((i * (i + 1) ));glass = Array.from({length: ll+2}, (_, i) => 0.0); // Put all water in first glassvar index = 0;glass[index] = X; // Now let the water flow to the// downward glasses till the row// number is less than or/ equal// to i (given row)// correction : X can be zero for side// glasses as they have lower rate to fillfor (row = 1; row <= i ; ++row){ // Fill glasses in a given row. Number of // columns in a row is equal to row number for (col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than or // equal to capacity in current glass glass[index] = (X >= 1.0) ? 1.0 : X; // Get the remaining amount X = (X >= 1.0) ? (X - 1) : 0.0; // Distribute the remaining amount // to the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; }} // The index of jth glass in ith// row will be i*(i-1)/2 + j - 1return glass[parseInt((i * (i - 1) / 2 + j - 1))];} // Driver Codevar i = 2, j = 2;var X = 2.0; // Total amount of waterdocument.write("Amount of water in jth " + "glass of ith row is: " + findWater(i, j, X)); // This code is contributed by 29AjayKumar </script> Output: Amount of water in jth glass of ith row is: 0.500000 Time Complexity: O(i*(i+1)/2) or O(i^2) Auxiliary Space: O(i*(i+1)/2) or O(i^2) This article is compiled by Rahul and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Method 2 (Using BFS Traversal) we will discuss another approach to this problem. First, we add a Triplet(row, col,rem-water) in the queue which indicates the starting value of the first element and fills 1-litre water. Then we simply apply bfs i.e. and we add left(row+1, col-1,rem-water) Triplet and right(row+1, col+1,rem-water) Triplet into the queue with half of the remaining water in first Triplet and another half into the next Triplet. Following is the implementation of this solution. C++ Java Python3 C# Javascript // CPP program for above approach#include<bits/stdc++.h>using namespace std; // Program to find the amount // of water in j-th glass// of i-th rowvoid findWater(float k, int i, int j){ // stores how much amount of water // present in every glass float dp[i+1][2*i + 1]; bool vis[i+1][2*i + 1]; // initialize dp and visited arrays for(int n=0;n<i+1;n++) { for(int m=0;m<(2*i+1);m++) { dp[n][m] = 0; vis[n][m] = false; } } // store Triplet i.e curr-row , curr-col queue<pair<int,int>>q; dp[0][i] = k; // we take the center of the first row for // the location of the first glass q.push({0,i}); vis[0][i] = true; // this while loop runs unless the queue is not empty while(!q.empty()) { // First we remove the pair from the queue pair<int,int>temp = q.front(); q.pop(); int n = temp.first; int m = temp.second; // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(i == n) break; float x = dp[n][m]; if(float((x-1.0)/2.0) < 0) { dp[n+1][m-1] += 0; dp[n+1][m+1] += 0; } else { dp[n+1][m-1] += float((x-1.0)/2.0); dp[n+1][m+1] += float((x-1.0)/2.0); } if(vis[n+1][m-1]==false) { q.push({n+1,m-1}); vis[n+1][m-1] = true; } if(vis[n+1][m+1]==false) { q.push({n+1,m+1}); vis[n+1][m+1] = true; } } if(dp[i-1][2*j-1]>1) dp[i-1][2*j-1] = 1.0; cout<<"Amount of water in jth glass of ith row is: "; // print the result for jth glass of ith row cout<<fixed<<setprecision(6)<<dp[i-1][2*j-1]<<endl; } // Driver Codeint main(){ //k->water in litres float k; cin>>k; //i->rows j->cols int i,j; cin>>i>>j; // Function Call findWater(k,i,j); return 0;} // This code is contributed by Sagar Jangra and Naresh Saharan // Program to find the amount /// of water in j-th glass// of i-th rowimport java.io.*;import java.util.*; // class Triplet which stores curr row// curr col and curr rem-water// of every glassclass Triplet{ int row; int col; double rem_water; Triplet(int row,int col,double rem_water) { this.row=row;this.col=col;this.rem_water=rem_water; }} class GFG{ // Returns the amount of water // in jth glass of ith row public static double findWater(int i,int j,int totalWater) { // stores how much amount of water present in every glass double dp[][] = new double[i+1][2*i+1]; // store Triplet i.e curr-row , curr-col, rem-water Queue<Triplet> queue = new LinkedList<>(); // we take the center of the first row for // the location of the first glass queue.add(new Triplet(0,i,totalWater)); // this while loop runs unless the queue is not empty while(!queue.isEmpty()) { // First we remove the Triplet from the queue Triplet curr = queue.remove(); // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(curr.row == i) break; // As we know maximum capacity of every glass // is 1 unit. so first we check the capacity // of curr glass is full or not. if(dp[curr.row][curr.col] != 1.0) { // calculate the remaining capacity of water for curr glass double rem_water = 1-dp[curr.row][curr.col]; // if the remaining capacity of water for curr glass // is greater than then the remaining capacity of total // water then we put all remaining water into curr glass if(rem_water > curr.rem_water) { dp[curr.row][curr.col] += curr.rem_water; curr.rem_water = 0; } else { dp[curr.row][curr.col] += rem_water; curr.rem_water -= rem_water; } } // if remaining capacity of total water is not equal to // zero then we add left and right glass of the next row // and gives half capacity of total water to both the // glass if(curr.rem_water != 0) { queue.add(new Triplet(curr.row + 1,curr.col - 1,curr.rem_water/2.0)); queue.add(new Triplet(curr.row + 1,curr.col + 1,curr.rem_water/2.0)); } } // return the result for jth glass of ith row return dp[i-1][2*j-1]; } // Driver Code public static void main (String[] args) { int i = 2, j = 2; int totalWater = 2; // Total amount of water System.out.print("Amount of water in jth glass of ith row is:"); System.out.format("%.6f", findWater(i, j, totalWater)); } } // this code is contributed by Naresh Saharan and Sagar Jangra # Program to find the amount# of water in j-th glass of i-th row # class Triplet which stores curr row# curr col and curr rem-water# of every glassclass Triplet: def __init__(self, row, col, rem_water): self.row = row self.col = col self.rem_water = rem_water # Returns the amount of water# in jth glass of ith rowdef findWater(i, j, totalWater): # stores how much amount of water present in every glass dp = [[0.0 for i in range(2*i+1)] for j in range(i+1)] # store Triplet i.e curr-row , curr-col, rem-water queue = [] # we take the center of the first row for # the location of the first glass queue.append(Triplet(0,i,totalWater)) # this while loop runs unless the queue is not empty while len(queue) != 0: # First we remove the Triplet from the queue curr = queue.pop(0) # as we know we have to calculate the # amount of water in jth glass # of ith row . so first we check if we find solutions # for the the every glass of i'th row. # so, if we have calculated the result # then we break the loop # and return our answer if curr.row == i: break # As we know maximum capacity of every glass # is 1 unit. so first we check the capacity # of curr glass is full or not. if dp[curr.row][curr.col] != 1.0: # calculate the remaining capacity of water for curr glass rem_water = 1-dp[curr.row][curr.col] # if the remaining capacity of water for curr glass # is greater than then the remaining capacity of total # water then we put all remaining water into curr glass if rem_water > curr.rem_water: dp[curr.row][curr.col] += curr.rem_water curr.rem_water = 0 else: dp[curr.row][curr.col] += rem_water curr.rem_water -= rem_water # if remaining capacity of total water is not equal to # zero then we add left and right glass of the next row # and gives half capacity of total water to both the # glass if curr.rem_water != 0: queue.append(Triplet(curr.row + 1,curr.col - 1,(curr.rem_water/2))) queue.append(Triplet(curr.row + 1,curr.col + 1,(curr.rem_water/2))) # return the result for jth glass of ith row return dp[i - 1][2 * j - 1] i, j = 2, 2totalWater = 2 # Total amount of waterprint("Amount of water in jth glass of ith row is:", end = "")print("{0:.6f}".format(findWater(i, j, totalWater))) # This code is contributed by decode2207. // Program to find the amount/// of water in j-th glassusing System;using System.Collections.Generic;class GFG { // class Triplet which stores curr row // curr col and curr rem-water // of every glass class Triplet { public int row, col; public double rem_water; public Triplet(int row, int col, double rem_water) { this.row = row; this.col = col; this.rem_water = rem_water; } } // Returns the amount of water // in jth glass of ith row public static double findWater(int i, int j, int totalWater) { // stores how much amount of water present in every glass double[,] dp = new double[i+1,2*i+1]; // store Triplet i.e curr-row , curr-col, rem-water List<Triplet> queue = new List<Triplet>(); // we take the center of the first row for // the location of the first glass queue.Add(new Triplet(0,i,totalWater)); // this while loop runs unless the queue is not empty while(queue.Count > 0) { // First we remove the Triplet from the queue Triplet curr = queue[0]; queue.RemoveAt(0); // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(curr.row == i) break; // As we know maximum capacity of every glass // is 1 unit. so first we check the capacity // of curr glass is full or not. if(dp[curr.row,curr.col] != 1.0) { // calculate the remaining capacity of water for curr glass double rem_water = 1-dp[curr.row,curr.col]; // if the remaining capacity of water for curr glass // is greater than then the remaining capacity of total // water then we put all remaining water into curr glass if(rem_water > curr.rem_water) { dp[curr.row,curr.col] += curr.rem_water; curr.rem_water = 0; } else { dp[curr.row,curr.col] += rem_water; curr.rem_water -= rem_water; } } // if remaining capacity of total water is not equal to // zero then we add left and right glass of the next row // and gives half capacity of total water to both the // glass if(curr.rem_water != 0) { queue.Add(new Triplet(curr.row + 1,curr.col - 1,curr.rem_water/2.0)); queue.Add(new Triplet(curr.row + 1,curr.col + 1,curr.rem_water/2.0)); } } // return the result for jth glass of ith row return dp[i - 1, 2 * j - 1]; } static void Main() { int i = 2, j = 2; int totalWater = 2; // Total amount of water Console.Write("Amount of water in jth glass of ith row is:"); Console.Write(findWater(i, j, totalWater).ToString("0.000000")); }} // This code is contributed by divyeshrabadiya07. <script>// Program to find the amount/// of water in j-th glass// of i-th row // class Triplet which stores curr row// curr col and curr rem-water// of every glassclass Triplet{ constructor(row,col,rem_water) { this.row=row; this.col=col; this.rem_water=rem_water; }} // Returns the amount of water // in jth glass of ith rowfunction findWater(i,j,totalWater){ // stores how much amount of water present in every glass let dp = new Array(i+1); for(let k=0;k<dp.length;k++) { dp[k]=new Array((2*i)+1); for(let l=0;l<dp[k].length;l++) { dp[k][l]=0; } } // store Triplet i.e curr-row , curr-col, rem-water let queue = []; // we take the center of the first row for // the location of the first glass queue.push(new Triplet(0,i,totalWater)); // this while loop runs unless the queue is not empty while(queue.length!=0) { // First we remove the Triplet from the queue let curr = queue.shift(); // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(curr.row == i) break; // As we know maximum capacity of every glass // is 1 unit. so first we check the capacity // of curr glass is full or not. if(dp[curr.row][curr.col] != 1.0) { // calculate the remaining capacity of water for curr glass let rem_water = 1-dp[curr.row][curr.col]; // if the remaining capacity of water for curr glass // is greater than then the remaining capacity of total // water then we put all remaining water into curr glass if(rem_water > curr.rem_water) { dp[curr.row][curr.col] += curr.rem_water; curr.rem_water = 0; } else { dp[curr.row][curr.col] += rem_water; curr.rem_water -= rem_water; } } // if remaining capacity of total water is not equal to // zero then we add left and right glass of the next row // and gives half capacity of total water to both the // glass if(curr.rem_water != 0) { queue.push(new Triplet(curr.row + 1,curr.col - 1,(curr.rem_water/2))); queue.push(new Triplet(curr.row + 1,curr.col + 1,(curr.rem_water/2))); } } // return the result for jth glass of ith row return dp[i-1][2*j-1];} // Driver Codelet i = 2, j = 2;let totalWater = 2; // Total amount of waterdocument.write("Amount of water in jth glass of ith row is:");document.write(findWater(i, j, totalWater).toFixed(6)); // This code is contributed by rag2127</script> Amount of water in jth glass of ith row is:0.500000 Time Complexity: O(2^i) Space Complexity: O(i^2) Pradeep Joshi Mithun Kumar naresh_saharan151 29AjayKumar rag2127 kk9826225 divyeshrabadiya07 decode2207 simranarora5sos Amazon D-E-Shaw Dynamic Programming Mathematical Recursion Amazon D-E-Shaw Dynamic Programming Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Longest Palindromic Substring | Set 1 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Program to find GCD or HCF of two numbers
[ { "code": null, "e": 24223, "s": 24195, "text": "\n14 Feb, 2022" }, { "code": null, "e": 24312, "s": 24223, "text": "There are some glasses with equal capacity as 1 litre. The glasses are kept as follows: " }, { "code": null, "e": 24411, "s": 24312, "text": " 1\n 2 3\n 4 5 6\n 7 8 9 10" }, { "code": null, "e": 24633, "s": 24411, "text": "You can put water to the only top glass. If you put more than 1-litre water to 1st glass, water overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both 2nd glass and 3rd glass and so on. " }, { "code": null, "e": 24766, "s": 24633, "text": "If you have X litre of water and you put that water in a top glass, how much water will be contained by the jth glass in an ith row?" }, { "code": null, "e": 24854, "s": 24766, "text": "Example. If you will put 2 litres on top. 1st – 1 litre 2nd – 1/2 litre 3rd – 1/2 litre" }, { "code": null, "e": 24874, "s": 24854, "text": " For 2 Liters Water" }, { "code": null, "e": 25024, "s": 24874, "text": "The approach is similar to Method 2 of the Pascal’s Triangle. If we take a closer look at the problem, the problem boils down to Pascal’s Triangle. " }, { "code": null, "e": 25208, "s": 25024, "text": " 1 ---------------- 1\n 2 3 ---------------- 2\n 4 5 6 ------------ 3\n 7 8 9 10 --------- 4" }, { "code": null, "e": 25552, "s": 25208, "text": "Each glass contributes to the two glasses down the glass. Initially, we put all water in the first glass. Then we keep 1 litre (or less than 1 litre) in it and move rest of the water to two glasses down to it. We follow the same process for the two glasses and all other glasses till the ith row. There will be i*(i+1)/2 glasses till ith row. " }, { "code": null, "e": 25556, "s": 25552, "text": "C++" }, { "code": null, "e": 25561, "s": 25556, "text": "Java" }, { "code": null, "e": 25569, "s": 25561, "text": "Python3" }, { "code": null, "e": 25572, "s": 25569, "text": "C#" }, { "code": null, "e": 25576, "s": 25572, "text": "PHP" }, { "code": null, "e": 25587, "s": 25576, "text": "Javascript" }, { "code": "// Program to find the amount of water in j-th glass// of i-th row#include <stdio.h>#include <stdlib.h>#include <string.h> // Returns the amount of water in jth glass of ith rowfloat findWater(int i, int j, float X){ // A row number i has maximum i columns. So input // column number must be less than i if (j > i) { printf(\"Incorrect Inputn\"); exit(0); } // There will be i*(i+1)/2 glasses till ith row // (including ith row) float glass[i * (i + 1) / 2]; // Initialize all glasses as empty memset(glass, 0, sizeof(glass)); // Put all water in first glass int index = 0; glass[index] = X; // Now let the water flow to the downward glasses // till the row number is less than or/ equal to i (given row) // correction : X can be zero for side glasses as they have lower rate to fill for (int row = 1; row <= i ; ++row) { // Fill glasses in a given row. Number of // columns in a row is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than or equal to // capacity in current glass glass[index] = (X >= 1.0f) ? 1.0f : X; // Get the remaining amount X = (X >= 1.0f) ? (X - 1) : 0.0f; // Distribute the remaining amount to // the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; } } // The index of jth glass in ith row will // be i*(i-1)/2 + j - 1 return glass[i*(i-1)/2 + j - 1];} // Driver program to test above functionint main(){ int i = 2, j = 2; float X = 2.0; // Total amount of water printf(\"Amount of water in jth glass of ith row is: %f\", findWater(i, j, X)); return 0;}", "e": 27461, "s": 25587, "text": null }, { "code": "// Program to find the amount/// of water in j-th glass// of i-th rowimport java.lang.*; class GFG{// Returns the amount of water// in jth glass of ith rowstatic float findWater(int i, int j, float X){// A row number i has maximum i// columns. So input column// number must be less than iif (j > i){ System.out.println(\"Incorrect Input\"); System.exit(0);} // There will be i*(i+1)/2 glasses// till ith row (including ith row)int ll = Math.round((i * (i + 1) ));float[] glass = new float[ll + 2]; // Put all water in first glassint index = 0;glass[index] = X; // Now let the water flow to the// downward glasses till the row// number is less than or/ equal// to i (given row)// correction : X can be zero for side// glasses as they have lower rate to fillfor (int row = 1; row <= i ; ++row){ // Fill glasses in a given row. Number of // columns in a row is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than or // equal to capacity in current glass glass[index] = (X >= 1.0f) ? 1.0f : X; // Get the remaining amount X = (X >= 1.0f) ? (X - 1) : 0.0f; // Distribute the remaining amount // to the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; }} // The index of jth glass in ith// row will be i*(i-1)/2 + j - 1return glass[(int)(i * (i - 1) / 2 + j - 1)];} // Driver Codepublic static void main(String[] args){ int i = 2, j = 2; float X = 2.0f; // Total amount of water System.out.println(\"Amount of water in jth \" + \"glass of ith row is: \" + findWater(i, j, X));}} // This code is contributed by mits", "e": 29309, "s": 27461, "text": null }, { "code": "# Program to find the amount# of water in j-th glass of# i-th row # Returns the amount of water# in jth glass of ith rowdef findWater(i, j, X): # A row number i has maximum # i columns. So input column # number must be less than i if (j > i): print(\"Incorrect Input\"); return; # There will be i*(i+1)/2 # glasses till ith row # (including ith row) # and Initialize all glasses # as empty glass = [0]*int(i *(i + 1) / 2); # Put all water # in first glass index = 0; glass[index] = X; # Now let the water flow to # the downward glasses till # the row number is less # than or/ equal to i (given # row) correction : X can be # zero for side glasses as # they have lower rate to fill for row in range(1,i): # Fill glasses in a given # row. Number of columns # in a row is equal to row number for col in range(1,row+1): # Get the water # from current glass X = glass[index]; # Keep the amount less # than or equal to # capacity in current glass glass[index] = 1.0 if (X >= 1.0) else X; # Get the remaining amount X = (X - 1) if (X >= 1.0) else 0.0; # Distribute the remaining # amount to the down two glasses glass[index + row] += (X / 2); glass[index + row + 1] += (X / 2); index+=1; # The index of jth glass # in ith row will # be i*(i-1)/2 + j - 1 return glass[int(i * (i - 1) /2 + j - 1)]; # Driver Codeif __name__ == \"__main__\": i = 2; j = 2; X = 2.0;# Total amount of water res=repr(findWater(i, j, X)); print(\"Amount of water in jth glass of ith row is:\",res.ljust(8,'0'));# This Code is contributed by mits", "e": 31121, "s": 29309, "text": null }, { "code": "// Program to find the amount// of water in j-th glass// of i-th rowusing System; class GFG{// Returns the amount of water// in jth glass of ith rowstatic float findWater(int i, int j, float X){// A row number i has maximum i// columns. So input column// number must be less than iif (j > i){ Console.WriteLine(\"Incorrect Input\"); Environment.Exit(0);} // There will be i*(i+1)/2 glasses// till ith row (including ith row)int ll = (int)Math.Round((double)(i * (i + 1)));float[] glass = new float[ll + 2]; // Put all water in first glassint index = 0;glass[index] = X; // Now let the water flow to the// downward glasses till the row// number is less than or/ equal// to i (given row)// correction : X can be zero// for side glasses as they have// lower rate to fillfor (int row = 1; row <= i ; ++row){ // Fill glasses in a given row. // Number of columns in a row // is equal to row number for (int col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than // or equal to capacity in // current glass glass[index] = (X >= 1.0f) ? 1.0f : X; // Get the remaining amount X = (X >= 1.0f) ? (X - 1) : 0.0f; // Distribute the remaining amount // to the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; }} // The index of jth glass in ith// row will be i*(i-1)/2 + j - 1return glass[(int)(i * (i - 1) / 2 + j - 1)];} // Driver Codestatic void Main(){ int i = 2, j = 2; float X = 2.0f; // Total amount of water Console.WriteLine(\"Amount of water in jth \" + \"glass of ith row is: \" + findWater(i, j, X));}} // This code is contributed by mits", "e": 33000, "s": 31121, "text": null }, { "code": "<?php// Program to find the amount// of water in j-th glass of// i-th row // Returns the amount of water// in jth glass of ith rowfunction findWater($i, $j, $X){ // A row number i has maximum // i columns. So input column // number must be less than i if ($j > $i) { echo \"Incorrect Input\\n\"; return; } // There will be i*(i+1)/2 // glasses till ith row // (including ith row) // and Initialize all glasses // as empty $glass = array_fill(0, (int)($i * ($i + 1) / 2), 0); // Put all water // in first glass $index = 0; $glass[$index] = $X; // Now let the water flow to // the downward glasses till // the row number is less // than or/ equal to i (given // row) correction : X can be // zero for side glasses as // they have lower rate to fill for ($row = 1; $row < $i ; ++$row) { // Fill glasses in a given // row. Number of columns // in a row is equal to row number for ($col = 1; $col <= $row; ++$col, ++$index) { // Get the water // from current glass $X = $glass[$index]; // Keep the amount less // than or equal to // capacity in current glass $glass[$index] = ($X >= 1.0) ? 1.0 : $X; // Get the remaining amount $X = ($X >= 1.0) ? ($X - 1) : 0.0; // Distribute the remaining // amount to the down two glasses $glass[$index + $row] += (double)($X / 2); $glass[$index + $row + 1] += (double)($X / 2); } } // The index of jth glass // in ith row will // be i*(i-1)/2 + j - 1 return $glass[(int)($i * ($i - 1) / 2 + $j - 1)];} // Driver Code$i = 2;$j = 2;$X = 2.0; // Total amount of waterecho \"Amount of water in jth \" , \"glass of ith row is: \". str_pad(findWater($i, $j, $X), 8, '0'); // This Code is contributed by mits?>", "e": 35071, "s": 33000, "text": null }, { "code": "<script> // Program to find the amount/// of water in j-th glass// of i-th row// Returns the amount of water// in jth glass of ith rowfunction findWater(i , j, X){// A row number i has maximum i// columns. So input column// number must be less than iif (j > i){ document.write(\"Incorrect Input\");} // There will be i*(i+1)/2 glasses// till ith row (including ith row)var ll = Math.round((i * (i + 1) ));glass = Array.from({length: ll+2}, (_, i) => 0.0); // Put all water in first glassvar index = 0;glass[index] = X; // Now let the water flow to the// downward glasses till the row// number is less than or/ equal// to i (given row)// correction : X can be zero for side// glasses as they have lower rate to fillfor (row = 1; row <= i ; ++row){ // Fill glasses in a given row. Number of // columns in a row is equal to row number for (col = 1; col <= row; ++col, ++index) { // Get the water from current glass X = glass[index]; // Keep the amount less than or // equal to capacity in current glass glass[index] = (X >= 1.0) ? 1.0 : X; // Get the remaining amount X = (X >= 1.0) ? (X - 1) : 0.0; // Distribute the remaining amount // to the down two glasses glass[index + row] += X / 2; glass[index + row + 1] += X / 2; }} // The index of jth glass in ith// row will be i*(i-1)/2 + j - 1return glass[parseInt((i * (i - 1) / 2 + j - 1))];} // Driver Codevar i = 2, j = 2;var X = 2.0; // Total amount of waterdocument.write(\"Amount of water in jth \" + \"glass of ith row is: \" + findWater(i, j, X)); // This code is contributed by 29AjayKumar </script>", "e": 36820, "s": 35071, "text": null }, { "code": null, "e": 36829, "s": 36820, "text": "Output: " }, { "code": null, "e": 36882, "s": 36829, "text": "Amount of water in jth glass of ith row is: 0.500000" }, { "code": null, "e": 36962, "s": 36882, "text": "Time Complexity: O(i*(i+1)/2) or O(i^2) Auxiliary Space: O(i*(i+1)/2) or O(i^2)" }, { "code": null, "e": 37156, "s": 36962, "text": "This article is compiled by Rahul and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 37187, "s": 37156, "text": "Method 2 (Using BFS Traversal)" }, { "code": null, "e": 37601, "s": 37187, "text": "we will discuss another approach to this problem. First, we add a Triplet(row, col,rem-water) in the queue which indicates the starting value of the first element and fills 1-litre water. Then we simply apply bfs i.e. and we add left(row+1, col-1,rem-water) Triplet and right(row+1, col+1,rem-water) Triplet into the queue with half of the remaining water in first Triplet and another half into the next Triplet." }, { "code": null, "e": 37651, "s": 37601, "text": "Following is the implementation of this solution." }, { "code": null, "e": 37655, "s": 37651, "text": "C++" }, { "code": null, "e": 37660, "s": 37655, "text": "Java" }, { "code": null, "e": 37668, "s": 37660, "text": "Python3" }, { "code": null, "e": 37671, "s": 37668, "text": "C#" }, { "code": null, "e": 37682, "s": 37671, "text": "Javascript" }, { "code": "// CPP program for above approach#include<bits/stdc++.h>using namespace std; // Program to find the amount // of water in j-th glass// of i-th rowvoid findWater(float k, int i, int j){ // stores how much amount of water // present in every glass float dp[i+1][2*i + 1]; bool vis[i+1][2*i + 1]; // initialize dp and visited arrays for(int n=0;n<i+1;n++) { for(int m=0;m<(2*i+1);m++) { dp[n][m] = 0; vis[n][m] = false; } } // store Triplet i.e curr-row , curr-col queue<pair<int,int>>q; dp[0][i] = k; // we take the center of the first row for // the location of the first glass q.push({0,i}); vis[0][i] = true; // this while loop runs unless the queue is not empty while(!q.empty()) { // First we remove the pair from the queue pair<int,int>temp = q.front(); q.pop(); int n = temp.first; int m = temp.second; // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(i == n) break; float x = dp[n][m]; if(float((x-1.0)/2.0) < 0) { dp[n+1][m-1] += 0; dp[n+1][m+1] += 0; } else { dp[n+1][m-1] += float((x-1.0)/2.0); dp[n+1][m+1] += float((x-1.0)/2.0); } if(vis[n+1][m-1]==false) { q.push({n+1,m-1}); vis[n+1][m-1] = true; } if(vis[n+1][m+1]==false) { q.push({n+1,m+1}); vis[n+1][m+1] = true; } } if(dp[i-1][2*j-1]>1) dp[i-1][2*j-1] = 1.0; cout<<\"Amount of water in jth glass of ith row is: \"; // print the result for jth glass of ith row cout<<fixed<<setprecision(6)<<dp[i-1][2*j-1]<<endl; } // Driver Codeint main(){ //k->water in litres float k; cin>>k; //i->rows j->cols int i,j; cin>>i>>j; // Function Call findWater(k,i,j); return 0;} // This code is contributed by Sagar Jangra and Naresh Saharan", "e": 40019, "s": 37682, "text": null }, { "code": "// Program to find the amount /// of water in j-th glass// of i-th rowimport java.io.*;import java.util.*; // class Triplet which stores curr row// curr col and curr rem-water// of every glassclass Triplet{ int row; int col; double rem_water; Triplet(int row,int col,double rem_water) { this.row=row;this.col=col;this.rem_water=rem_water; }} class GFG{ // Returns the amount of water // in jth glass of ith row public static double findWater(int i,int j,int totalWater) { // stores how much amount of water present in every glass double dp[][] = new double[i+1][2*i+1]; // store Triplet i.e curr-row , curr-col, rem-water Queue<Triplet> queue = new LinkedList<>(); // we take the center of the first row for // the location of the first glass queue.add(new Triplet(0,i,totalWater)); // this while loop runs unless the queue is not empty while(!queue.isEmpty()) { // First we remove the Triplet from the queue Triplet curr = queue.remove(); // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(curr.row == i) break; // As we know maximum capacity of every glass // is 1 unit. so first we check the capacity // of curr glass is full or not. if(dp[curr.row][curr.col] != 1.0) { // calculate the remaining capacity of water for curr glass double rem_water = 1-dp[curr.row][curr.col]; // if the remaining capacity of water for curr glass // is greater than then the remaining capacity of total // water then we put all remaining water into curr glass if(rem_water > curr.rem_water) { dp[curr.row][curr.col] += curr.rem_water; curr.rem_water = 0; } else { dp[curr.row][curr.col] += rem_water; curr.rem_water -= rem_water; } } // if remaining capacity of total water is not equal to // zero then we add left and right glass of the next row // and gives half capacity of total water to both the // glass if(curr.rem_water != 0) { queue.add(new Triplet(curr.row + 1,curr.col - 1,curr.rem_water/2.0)); queue.add(new Triplet(curr.row + 1,curr.col + 1,curr.rem_water/2.0)); } } // return the result for jth glass of ith row return dp[i-1][2*j-1]; } // Driver Code public static void main (String[] args) { int i = 2, j = 2; int totalWater = 2; // Total amount of water System.out.print(\"Amount of water in jth glass of ith row is:\"); System.out.format(\"%.6f\", findWater(i, j, totalWater)); } } // this code is contributed by Naresh Saharan and Sagar Jangra", "e": 42974, "s": 40019, "text": null }, { "code": "# Program to find the amount# of water in j-th glass of i-th row # class Triplet which stores curr row# curr col and curr rem-water# of every glassclass Triplet: def __init__(self, row, col, rem_water): self.row = row self.col = col self.rem_water = rem_water # Returns the amount of water# in jth glass of ith rowdef findWater(i, j, totalWater): # stores how much amount of water present in every glass dp = [[0.0 for i in range(2*i+1)] for j in range(i+1)] # store Triplet i.e curr-row , curr-col, rem-water queue = [] # we take the center of the first row for # the location of the first glass queue.append(Triplet(0,i,totalWater)) # this while loop runs unless the queue is not empty while len(queue) != 0: # First we remove the Triplet from the queue curr = queue.pop(0) # as we know we have to calculate the # amount of water in jth glass # of ith row . so first we check if we find solutions # for the the every glass of i'th row. # so, if we have calculated the result # then we break the loop # and return our answer if curr.row == i: break # As we know maximum capacity of every glass # is 1 unit. so first we check the capacity # of curr glass is full or not. if dp[curr.row][curr.col] != 1.0: # calculate the remaining capacity of water for curr glass rem_water = 1-dp[curr.row][curr.col] # if the remaining capacity of water for curr glass # is greater than then the remaining capacity of total # water then we put all remaining water into curr glass if rem_water > curr.rem_water: dp[curr.row][curr.col] += curr.rem_water curr.rem_water = 0 else: dp[curr.row][curr.col] += rem_water curr.rem_water -= rem_water # if remaining capacity of total water is not equal to # zero then we add left and right glass of the next row # and gives half capacity of total water to both the # glass if curr.rem_water != 0: queue.append(Triplet(curr.row + 1,curr.col - 1,(curr.rem_water/2))) queue.append(Triplet(curr.row + 1,curr.col + 1,(curr.rem_water/2))) # return the result for jth glass of ith row return dp[i - 1][2 * j - 1] i, j = 2, 2totalWater = 2 # Total amount of waterprint(\"Amount of water in jth glass of ith row is:\", end = \"\")print(\"{0:.6f}\".format(findWater(i, j, totalWater))) # This code is contributed by decode2207.", "e": 45496, "s": 42974, "text": null }, { "code": "// Program to find the amount/// of water in j-th glassusing System;using System.Collections.Generic;class GFG { // class Triplet which stores curr row // curr col and curr rem-water // of every glass class Triplet { public int row, col; public double rem_water; public Triplet(int row, int col, double rem_water) { this.row = row; this.col = col; this.rem_water = rem_water; } } // Returns the amount of water // in jth glass of ith row public static double findWater(int i, int j, int totalWater) { // stores how much amount of water present in every glass double[,] dp = new double[i+1,2*i+1]; // store Triplet i.e curr-row , curr-col, rem-water List<Triplet> queue = new List<Triplet>(); // we take the center of the first row for // the location of the first glass queue.Add(new Triplet(0,i,totalWater)); // this while loop runs unless the queue is not empty while(queue.Count > 0) { // First we remove the Triplet from the queue Triplet curr = queue[0]; queue.RemoveAt(0); // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(curr.row == i) break; // As we know maximum capacity of every glass // is 1 unit. so first we check the capacity // of curr glass is full or not. if(dp[curr.row,curr.col] != 1.0) { // calculate the remaining capacity of water for curr glass double rem_water = 1-dp[curr.row,curr.col]; // if the remaining capacity of water for curr glass // is greater than then the remaining capacity of total // water then we put all remaining water into curr glass if(rem_water > curr.rem_water) { dp[curr.row,curr.col] += curr.rem_water; curr.rem_water = 0; } else { dp[curr.row,curr.col] += rem_water; curr.rem_water -= rem_water; } } // if remaining capacity of total water is not equal to // zero then we add left and right glass of the next row // and gives half capacity of total water to both the // glass if(curr.rem_water != 0) { queue.Add(new Triplet(curr.row + 1,curr.col - 1,curr.rem_water/2.0)); queue.Add(new Triplet(curr.row + 1,curr.col + 1,curr.rem_water/2.0)); } } // return the result for jth glass of ith row return dp[i - 1, 2 * j - 1]; } static void Main() { int i = 2, j = 2; int totalWater = 2; // Total amount of water Console.Write(\"Amount of water in jth glass of ith row is:\"); Console.Write(findWater(i, j, totalWater).ToString(\"0.000000\")); }} // This code is contributed by divyeshrabadiya07.", "e": 48556, "s": 45496, "text": null }, { "code": "<script>// Program to find the amount/// of water in j-th glass// of i-th row // class Triplet which stores curr row// curr col and curr rem-water// of every glassclass Triplet{ constructor(row,col,rem_water) { this.row=row; this.col=col; this.rem_water=rem_water; }} // Returns the amount of water // in jth glass of ith rowfunction findWater(i,j,totalWater){ // stores how much amount of water present in every glass let dp = new Array(i+1); for(let k=0;k<dp.length;k++) { dp[k]=new Array((2*i)+1); for(let l=0;l<dp[k].length;l++) { dp[k][l]=0; } } // store Triplet i.e curr-row , curr-col, rem-water let queue = []; // we take the center of the first row for // the location of the first glass queue.push(new Triplet(0,i,totalWater)); // this while loop runs unless the queue is not empty while(queue.length!=0) { // First we remove the Triplet from the queue let curr = queue.shift(); // as we know we have to calculate the // amount of water in jth glass // of ith row . so first we check if we find solutions // for the the every glass of i'th row. // so, if we have calculated the result // then we break the loop // and return our answer if(curr.row == i) break; // As we know maximum capacity of every glass // is 1 unit. so first we check the capacity // of curr glass is full or not. if(dp[curr.row][curr.col] != 1.0) { // calculate the remaining capacity of water for curr glass let rem_water = 1-dp[curr.row][curr.col]; // if the remaining capacity of water for curr glass // is greater than then the remaining capacity of total // water then we put all remaining water into curr glass if(rem_water > curr.rem_water) { dp[curr.row][curr.col] += curr.rem_water; curr.rem_water = 0; } else { dp[curr.row][curr.col] += rem_water; curr.rem_water -= rem_water; } } // if remaining capacity of total water is not equal to // zero then we add left and right glass of the next row // and gives half capacity of total water to both the // glass if(curr.rem_water != 0) { queue.push(new Triplet(curr.row + 1,curr.col - 1,(curr.rem_water/2))); queue.push(new Triplet(curr.row + 1,curr.col + 1,(curr.rem_water/2))); } } // return the result for jth glass of ith row return dp[i-1][2*j-1];} // Driver Codelet i = 2, j = 2;let totalWater = 2; // Total amount of waterdocument.write(\"Amount of water in jth glass of ith row is:\");document.write(findWater(i, j, totalWater).toFixed(6)); // This code is contributed by rag2127</script>", "e": 51447, "s": 48556, "text": null }, { "code": null, "e": 51499, "s": 51447, "text": "Amount of water in jth glass of ith row is:0.500000" }, { "code": null, "e": 51524, "s": 51499, "text": "Time Complexity: O(2^i)" }, { "code": null, "e": 51551, "s": 51524, "text": "Space Complexity: O(i^2) " }, { "code": null, "e": 51565, "s": 51551, "text": "Pradeep Joshi" }, { "code": null, "e": 51578, "s": 51565, "text": "Mithun Kumar" }, { "code": null, "e": 51596, "s": 51578, "text": "naresh_saharan151" }, { "code": null, "e": 51608, "s": 51596, "text": "29AjayKumar" }, { "code": null, "e": 51616, "s": 51608, "text": "rag2127" }, { "code": null, "e": 51626, "s": 51616, "text": "kk9826225" }, { "code": null, "e": 51644, "s": 51626, "text": "divyeshrabadiya07" }, { "code": null, "e": 51655, "s": 51644, "text": "decode2207" }, { "code": null, "e": 51671, "s": 51655, "text": "simranarora5sos" }, { "code": null, "e": 51678, "s": 51671, "text": "Amazon" }, { "code": null, "e": 51687, "s": 51678, "text": "D-E-Shaw" }, { "code": null, "e": 51707, "s": 51687, "text": "Dynamic Programming" }, { "code": null, "e": 51720, "s": 51707, "text": "Mathematical" }, { "code": null, "e": 51730, "s": 51720, "text": "Recursion" }, { "code": null, "e": 51737, "s": 51730, "text": "Amazon" }, { "code": null, "e": 51746, "s": 51737, "text": "D-E-Shaw" }, { "code": null, "e": 51766, "s": 51746, "text": "Dynamic Programming" }, { "code": null, "e": 51779, "s": 51766, "text": "Mathematical" }, { "code": null, "e": 51789, "s": 51779, "text": "Recursion" }, { "code": null, "e": 51887, "s": 51789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 51896, "s": 51887, "text": "Comments" }, { "code": null, "e": 51909, "s": 51896, "text": "Old Comments" }, { "code": null, "e": 51940, "s": 51909, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 51973, "s": 51940, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 52008, "s": 51973, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 52046, "s": 52008, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 52114, "s": 52046, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 52174, "s": 52114, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 52189, "s": 52174, "text": "C++ Data Types" }, { "code": null, "e": 52232, "s": 52189, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 52256, "s": 52232, "text": "Merge two sorted arrays" } ]
Convert a number into negative base representation in C++
In this tutorial, we will be discussing a program to convert a number into its negative base representation. For this we will be provided with a number and the corresponding negative base. Our task is to convert the given number into its negative base equivalent. We are allowing only values between -2 and -10 for negative base values. Live Demo #include <bits/stdc++.h> using namespace std; //converting integer into string string convert_str(int n){ string str; stringstream ss; ss << n; ss >> str; return str; } //converting n to negative base string convert_nb(int n, int negBase){ //negative base equivalent for zero is zero if (n == 0) return "0"; string converted = ""; while (n != 0){ //getting remainder from negative base int remainder = n % negBase; n /= negBase; //changing remainder to its absolute value if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to string add into the result converted = convert_str(remainder) + converted; } return converted; } int main() { int n = 9; int negBase = -3; cout << convert_nb(n, negBase); return 0; } 100
[ { "code": null, "e": 1171, "s": 1062, "text": "In this tutorial, we will be discussing a program to convert a number into its negative base representation." }, { "code": null, "e": 1399, "s": 1171, "text": "For this we will be provided with a number and the corresponding negative base. Our task is to convert the given number into its negative base equivalent. We are allowing only values between -2 and -10 for negative base values." }, { "code": null, "e": 1410, "s": 1399, "text": " Live Demo" }, { "code": null, "e": 2262, "s": 1410, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//converting integer into string\nstring convert_str(int n){\n string str;\n stringstream ss;\n ss << n;\n ss >> str;\n return str;\n}\n//converting n to negative base\nstring convert_nb(int n, int negBase){\n //negative base equivalent for zero is zero\n if (n == 0)\n return \"0\";\n string converted = \"\";\n while (n != 0){\n //getting remainder from negative base\n int remainder = n % negBase;\n n /= negBase;\n //changing remainder to its absolute value\n if (remainder < 0) {\n remainder += (-negBase);\n n += 1;\n }\n // convert remainder to string add into the result\n converted = convert_str(remainder) + converted;\n }\n return converted;\n}\nint main() {\n int n = 9;\n int negBase = -3;\n cout << convert_nb(n, negBase);\n return 0;\n}" }, { "code": null, "e": 2266, "s": 2262, "text": "100" } ]
Tryit Editor v3.7
Tryit: HTML table - striped rows and columns
[]
MongoDB query to return only embedded document?
It is not possible to return only embedded document. However, it will return all the documents from a collection. Let us first implement the following query to create a collection with documents >db.queryToEmbeddedDocument.insertOne({"UserName":"Larry","PostDetails":[{"UserMessage":"Hello","UserLikes":8},{"UserMessage":"Hi","UserLikes":6},{"UserMessage":"Good Morning","UserLikes":12},{"UserMessage":"Awesome","UserLikes":4}]}); { "acknowledged" : true, "insertedId" : ObjectId("5c988a9f330fd0aa0d2fe4bd") } Following is the query to display all documents from a collection with the help of find() method > db.queryToEmbeddedDocument.find().pretty(); This will produce the following output { "_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"), "UserName" : "Larry", "PostDetails" : [ { "UserMessage" : "Hello", "UserLikes" : 8 }, { "UserMessage" : "Hi", "UserLikes" : 6 }, { "UserMessage" : "Good Morning", "UserLikes" : 12 }, { "UserMessage" : "Awesome", "UserLikes" : 4 } ] } Following is the query to return all the documents from a collection > db.queryToEmbeddedDocument.find({"PostDetails.UserLikes": {$gte: 8}},{PostDetails:1}).pretty(); This will produce the following output { "_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"), "PostDetails" : [ { "UserMessage" : "Hello", "UserLikes" : 8 }, { "UserMessage" : "Hi", "UserLikes" : 6 }, { "UserMessage" : "Good Morning", "UserLikes" : 12 }, { "UserMessage" : "Awesome", "UserLikes" : 4 } ] } Look at the above sample output, we are getting all the documents while we want only those documents in which “UserLikes” are greater than or equal to 8.
[ { "code": null, "e": 1257, "s": 1062, "text": "It is not possible to return only embedded document. However, it will return all the documents from a collection. Let us first implement the following query to create a collection with documents" }, { "code": null, "e": 1578, "s": 1257, "text": ">db.queryToEmbeddedDocument.insertOne({\"UserName\":\"Larry\",\"PostDetails\":[{\"UserMessage\":\"Hello\",\"UserLikes\":8},{\"UserMessage\":\"Hi\",\"UserLikes\":6},{\"UserMessage\":\"Good Morning\",\"UserLikes\":12},{\"UserMessage\":\"Awesome\",\"UserLikes\":4}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c988a9f330fd0aa0d2fe4bd\")\n}" }, { "code": null, "e": 1675, "s": 1578, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 1721, "s": 1675, "text": "> db.queryToEmbeddedDocument.find().pretty();" }, { "code": null, "e": 1760, "s": 1721, "text": "This will produce the following output" }, { "code": null, "e": 2174, "s": 1760, "text": "{\n \"_id\" : ObjectId(\"5c988a9f330fd0aa0d2fe4bd\"),\n \"UserName\" : \"Larry\",\n \"PostDetails\" : [\n {\n \"UserMessage\" : \"Hello\",\n \"UserLikes\" : 8\n },\n {\n \"UserMessage\" : \"Hi\",\n \"UserLikes\" : 6\n },\n {\n \"UserMessage\" : \"Good Morning\",\n \"UserLikes\" : 12\n },\n {\n \"UserMessage\" : \"Awesome\",\n \"UserLikes\" : 4\n }\n ]\n}" }, { "code": null, "e": 2243, "s": 2174, "text": "Following is the query to return all the documents from a collection" }, { "code": null, "e": 2341, "s": 2243, "text": "> db.queryToEmbeddedDocument.find({\"PostDetails.UserLikes\": {$gte: 8}},{PostDetails:1}).pretty();" }, { "code": null, "e": 2380, "s": 2341, "text": "This will produce the following output" }, { "code": null, "e": 2769, "s": 2380, "text": "{\n \"_id\" : ObjectId(\"5c988a9f330fd0aa0d2fe4bd\"),\n \"PostDetails\" : [\n {\n \"UserMessage\" : \"Hello\",\n \"UserLikes\" : 8\n },\n {\n \"UserMessage\" : \"Hi\",\n \"UserLikes\" : 6\n },\n {\n \"UserMessage\" : \"Good Morning\",\n \"UserLikes\" : 12\n },\n {\n \"UserMessage\" : \"Awesome\",\n \"UserLikes\" : 4\n }\n ]\n}" }, { "code": null, "e": 2923, "s": 2769, "text": "Look at the above sample output, we are getting all the documents while we want only those documents in which “UserLikes” are greater than or equal to 8." } ]
Creating animations using Transformations in OpenGL - GeeksforGeeks
31 Oct, 2019 Animation is the illusion of making us think that an object is really moving on the screen. But underneath they are just complex algorithms updating and drawing different objects. Aim: A complex animation of a walking dinosaur in 2D.Method: Using Transformations of individual body parts.See this Video: Algorithm There are 3 main transformations in Computer Graphics – Translation, Rotation and Scaling. All can be implemented using very simple mathematics. Translation: X = x + tx, tx is the amount of translation in x-axis Y = y + ty, ty is the amount of translation in y-axis Rotation: X = xcosA - ysinA, A is the angle of rotation. Y = xsinA + ycosA Scaling: X = x*Sx, Sx is Scaling Factor Y = y*Sy, Sy is Scaling Factor For drawing figures, Bresenham’s Line drawing algorithm will be used together with the above equations to draw each line according to need. Implementation The body of the dinosaur is split up into 8 main portions –Head, upperBody, Tail, downBody, and the four legs The parts are stores as text files with comma seperated coordinates, which are imported during running of the program: headDino PolyDino tailDino backlegFDino backlegRDino bodydownDino bodyupDino frontlegFDino frontlegRDino The centres of rotation of each object were stored in a separate file: centrePts Since, all files were created by hand, there was room for little errors which were corrected in the following file: offsetDino Note: Please download all the above files before running the program and keep in the same directory.Each one will have its own object storing the following: All the lines of the object in a big array The number of lines The current amount of translation The centre of rotation The offsets The current amount of rotation The direction of rotation The program will work in the following order: THe OpenGL window will startAll the files will be read and stored in there respective objectsAn infinite while loop will be startedThe screen will be clearedA line will be drawn depicting the grasslandAll the parts will be updatedAll the parts will be drawnThe body translation value will be decremented, and if the dinosaur is out of the window, it will be reset.The loop will go to its next iteration THe OpenGL window will start All the files will be read and stored in there respective objects An infinite while loop will be started The screen will be cleared A line will be drawn depicting the grassland All the parts will be updated All the parts will be drawn The body translation value will be decremented, and if the dinosaur is out of the window, it will be reset. The loop will go to its next iteration During updation of an object, the rotationstate is checked andif it is overshooting the threshold of rotation, then the direction of rotation is reversed.The rotationstate is 0 if it is not to be rotated. #include <stdio.h>#include <GL/glut.h>#include <math.h> // these are the parameters#define maxHt 800#define maxWd 600#define maxLns 10000#define transSpeed 1#define rotSpeed 0.02#define rotateLimit 0.2#define boundLimitL -200#define boundLimitR 500#define grasslandy 230 // Structure for storing linestypedef struct lines { int x1, x2, y1, y2;} LINE; // Object type structure for storing each body parttypedef struct objects { LINE edge[maxLns]; int translation, cx, cy, xoffset, yoffset; float theta; int rotationState; int EdgeCount;} Object; // the different objectsObject Head, upBody, Tail, downBody, FlegF, FlegB, BlegF, BlegB;// globalint dinoTranslate = 0; // basic init function for OPENGLvoid myInit(void){ glClearColor(1.0, 1.0, 1.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, maxHt, 0, maxWd); glClear(GL_COLOR_BUFFER_BIT);} // this function translates, and rotates a point according to an object and draws itvoid rotateandshiftPt(int px, int py, Object obbj){ int xf, yf; xf = obbj.cx + (int)((float)(px - obbj.cx) * cos(obbj.theta)) - ((float)(py - obbj.cy) * sin(obbj.theta)); yf = obbj.cy + (int)((float)(px - obbj.cx) * sin(obbj.theta)) + ((float)(py - obbj.cy) * cos(obbj.theta)); glBegin(GL_POINTS); glVertex2i(obbj.translation + xf + obbj.xoffset, yf + obbj.yoffset); glEnd();} // this function draws a line using Bresenhamsvoid drawLineBresenham(int x1, int y1, int x2, int y2, Object obbj){ int Dx, Dy, Dxmul2, Dymul2, Pk, xtempi, ytempi; float lineSlope, xtemp, ytemp; Dx = abs(x2 - x1); Dy = abs(y2 - y1); Dxmul2 = 2 * Dx; Dymul2 = 2 * Dy; ytemp = (float)(y2 - y1); xtemp = (float)(x2 - x1); lineSlope = (ytemp / xtemp); if (lineSlope >= -1.0 && lineSlope <= 1.0) { Pk = Dymul2 - Dx; if (x1 > x2) { xtempi = x2; x2 = x1; x1 = xtempi; ytempi = y2; y2 = y1; y1 = ytempi; } for (xtempi = x1, ytempi = y1; xtempi <= x2; xtempi++) { rotateandshiftPt(xtempi, ytempi, obbj); if (Pk < 0) { Pk = Pk + Dymul2; } else { Pk = Pk + Dymul2 - Dxmul2; if (lineSlope >= 0.0 && lineSlope <= 1.0) ytempi = ytempi + 1; else if (lineSlope < 0.0 && lineSlope >= -1.0) ytempi = ytempi - 1; } } } else { Pk = Dxmul2 - Dy; if (y1 > y2) { xtempi = x2; x2 = x1; x1 = xtempi; ytempi = y2; y2 = y1; y1 = ytempi; } for (xtempi = x1, ytempi = y1; ytempi <= y2; ytempi++) { rotateandshiftPt(xtempi, ytempi, obbj); if (Pk < 0) { Pk = Pk + Dxmul2; } else { Pk = Pk + Dxmul2 - Dymul2; if (lineSlope > 1.0) xtempi = xtempi + 1; else if (lineSlope < -1.0) xtempi = xtempi - 1; } } }}// here all the edges are iterated and drawnvoid drawObj(Object obbj){ int i; for (i = 0; i < obbj.EdgeCount; i++) { drawLineBresenham(obbj.edge[i].x1, obbj.edge[i].y1, obbj.edge[i].x2, obbj.edge[i].y2, obbj); }} // in this function, an object is updatedvoid updateObj(Object* obbj){ obbj->translation = dinoTranslate; if (obbj->rotationState == 1) { obbj->theta = obbj->theta + rotSpeed; if (obbj->theta >= (3.14159)) obbj->theta = obbj->theta - (2.0 * 3.14159); if (obbj->theta > rotateLimit) obbj->rotationState = -1; } else if (obbj->rotationState == -1) { obbj->theta = obbj->theta - rotSpeed; if (obbj->theta <= (-3.14159)) obbj->theta = (2.0 * 3.14159) + obbj->theta; if (obbj->theta < -rotateLimit) obbj->rotationState = 1; }} // The actual function where the Dinosaur is drawnvoid drawDino(void){ // an infinite while loop for moving the dinosaur while (1) { glClear(GL_COLOR_BUFFER_BIT); // draw grassland glLineWidth(5.0); glColor3f(0.0f, 1.0f, 0.3f); glBegin(GL_LINES); glVertex2i(0, grasslandy); glVertex2i(maxHt, grasslandy); glEnd(); glPointSize(3.0); glColor3f(0.9f, 0.5f, 0.6f); // update all parts updateObj(&Head); updateObj(&upBody); updateObj(&Tail); updateObj(&downBody); updateObj(&FlegF); updateObj(&FlegB); updateObj(&BlegF); updateObj(&BlegB); // draw all parts, also draw joining parts drawObj(Head); drawObj(upBody); drawObj(Tail); drawObj(downBody); drawObj(FlegF); drawObj(FlegB); drawObj(BlegF); drawObj(BlegB); dinoTranslate--; // decreased because moving forward if (dinoTranslate <= boundLimitL) { dinoTranslate = boundLimitR; printf("\ntranslate %d", dinoTranslate); } printf("\ntranslate %d", dinoTranslate); glFlush(); }} // TAn object is stored using this functionvoid storeObj(char* str, Object* obbj){ obbj->theta = 0.0; FILE* fp; fp = fopen(str, "r"); if (fp == NULL) { printf("Could not open file"); return; } obbj->EdgeCount = 0; int count = 0, x1, y1, x2, y2; while (!feof(fp)) { count++; if (count > 2) { x1 = x2; y1 = y2; count = 2; } if (count == 1) { fscanf(fp, "%d, %d", &x1, &y1); } else { fscanf(fp, "%d, %d", &x2, &y2); printf("\n%d, %d", x2, y2); obbj->edge[obbj->EdgeCount].x1 = x1; obbj->edge[obbj->EdgeCount].y1 = y1; obbj->edge[obbj->EdgeCount].x2 = x2; obbj->edge[obbj->EdgeCount].y2 = y2; obbj->EdgeCount++; } } // printf("\nPolygon stored!"); fclose(fp);} // All parts are stored.void storeAllParts(){ FILE* fp, *fp2; int cx, cy; fp = fopen("centrePts.txt", "r"); fp2 = fopen("offsetDino.txt", "r"); if (fp == NULL || fp2 == NULL) { printf("Could not open file"); return; } // parts //---------------- // head+neck storeObj("headDino.txt", &Head); fscanf(fp, "%d, %d", &cx, &cy); Head.cx = cx; Head.cy = cy; fscanf(fp2, "%d, %d", &cx, &cy); Head.xoffset = cx; Head.yoffset = cy; Head.rotationState = 1; // upper body boundary(only translation) storeObj("bodyupDino.txt", &upBody); upBody.cx = 0; upBody.cy = 0; fscanf(fp2, "%d, %d", &cx, &cy); upBody.xoffset = cx; upBody.yoffset = cy; upBody.rotationState = 0; // tail storeObj("tailDino.txt", &Tail); fscanf(fp, "%d, %d", &cx, &cy); Tail.cx = cx; Tail.cy = cy; fscanf(fp2, "%d, %d", &cx, &cy); Tail.xoffset = cx; Tail.yoffset = cy; Tail.rotationState = -1; // back leg front storeObj("backlegFDino.txt", &BlegF); fscanf(fp, "%d, %d", &cx, &cy); BlegF.cx = cx; BlegF.cy = cy; fscanf(fp2, "%d, %d", &cx, &cy); BlegF.xoffset = cx; BlegF.yoffset = cy; BlegF.rotationState = -1; // back leg rear storeObj("backlegRDino.txt", &BlegB); fscanf(fp, "%d, %d", &cx, &cy); BlegB.cx = cx; BlegB.cy = cy; fscanf(fp2, "%d, %d", &cx, &cy); BlegB.xoffset = cx; BlegB.yoffset = cy; BlegB.rotationState = 1; // lower body boundary(only translation) storeObj("bodydownDino.txt", &downBody); downBody.cx = 0; downBody.cy = 0; fscanf(fp2, "%d, %d", &cx, &cy); downBody.xoffset = cx; downBody.yoffset = cy; downBody.rotationState = 0; // front leg rear storeObj("frontlegRDino.txt", &FlegB); fscanf(fp, "%d, %d", &cx, &cy); FlegB.cx = cx; FlegB.cy = cy; fscanf(fp2, "%d, %d", &cx, &cy); FlegB.xoffset = cx; FlegB.yoffset = cy; FlegB.rotationState = -1; // front leg front storeObj("frontlegFDino.txt", &FlegF); fscanf(fp, "%d, %d", &cx, &cy); FlegF.cx = cx; FlegF.cy = cy; fscanf(fp2, "%d, %d", &cx, &cy); FlegF.xoffset = cx; FlegF.yoffset = cy; FlegF.rotationState = 1; //------------------------ fclose(fp);} void main(int argc, char** argv){ storeAllParts(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(maxHt, maxWd); glutInitWindowPosition(0, 0); glutCreateWindow("Walking dinosaur"); myInit(); glutDisplayFunc(drawDino); // actual loop call glutMainLoop();} Output:This is a sample screenshot:Don’t forget to download the files before running the program. This article is contributed by Suprotik Dey. 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. Akanksha_Rai OpenGL GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar Top 10 Angular Libraries For Web Developers A Freshers Guide To Programming ML | Underfitting and Overfitting Virtualization In Cloud Computing and Types Top 10 Programming Languages to Learn in 2022 What is web socket and how it is different from the HTTP? Software Testing | Basics How to Install and Run Apache Kafka on Windows?
[ { "code": null, "e": 24928, "s": 24900, "text": "\n31 Oct, 2019" }, { "code": null, "e": 25108, "s": 24928, "text": "Animation is the illusion of making us think that an object is really moving on the screen. But underneath they are just complex algorithms updating and drawing different objects." }, { "code": null, "e": 25232, "s": 25108, "text": "Aim: A complex animation of a walking dinosaur in 2D.Method: Using Transformations of individual body parts.See this Video:" }, { "code": null, "e": 25242, "s": 25232, "text": "Algorithm" }, { "code": null, "e": 25387, "s": 25242, "text": "There are 3 main transformations in Computer Graphics – Translation, Rotation and Scaling. All can be implemented using very simple mathematics." }, { "code": null, "e": 25706, "s": 25387, "text": "Translation: X = x + tx, tx is the amount of translation in x-axis\n Y = y + ty, ty is the amount of translation in y-axis\n\nRotation: X = xcosA - ysinA, A is the angle of rotation.\n Y = xsinA + ycosA\n\nScaling: X = x*Sx, Sx is Scaling Factor\n Y = y*Sy, Sy is Scaling Factor\n\n" }, { "code": null, "e": 25846, "s": 25706, "text": "For drawing figures, Bresenham’s Line drawing algorithm will be used together with the above equations to draw each line according to need." }, { "code": null, "e": 25861, "s": 25846, "text": "Implementation" }, { "code": null, "e": 25971, "s": 25861, "text": "The body of the dinosaur is split up into 8 main portions –Head, upperBody, Tail, downBody, and the four legs" }, { "code": null, "e": 26090, "s": 25971, "text": "The parts are stores as text files with comma seperated coordinates, which are imported during running of the program:" }, { "code": null, "e": 26099, "s": 26090, "text": "headDino" }, { "code": null, "e": 26108, "s": 26099, "text": "PolyDino" }, { "code": null, "e": 26117, "s": 26108, "text": "tailDino" }, { "code": null, "e": 26130, "s": 26117, "text": "backlegFDino" }, { "code": null, "e": 26143, "s": 26130, "text": "backlegRDino" }, { "code": null, "e": 26156, "s": 26143, "text": "bodydownDino" }, { "code": null, "e": 26167, "s": 26156, "text": "bodyupDino" }, { "code": null, "e": 26181, "s": 26167, "text": "frontlegFDino" }, { "code": null, "e": 26195, "s": 26181, "text": "frontlegRDino" }, { "code": null, "e": 26266, "s": 26195, "text": "The centres of rotation of each object were stored in a separate file:" }, { "code": null, "e": 26276, "s": 26266, "text": "centrePts" }, { "code": null, "e": 26392, "s": 26276, "text": "Since, all files were created by hand, there was room for little errors which were corrected in the following file:" }, { "code": null, "e": 26403, "s": 26392, "text": "offsetDino" }, { "code": null, "e": 26560, "s": 26403, "text": "Note: Please download all the above files before running the program and keep in the same directory.Each one will have its own object storing the following:" }, { "code": null, "e": 26603, "s": 26560, "text": "All the lines of the object in a big array" }, { "code": null, "e": 26623, "s": 26603, "text": "The number of lines" }, { "code": null, "e": 26657, "s": 26623, "text": "The current amount of translation" }, { "code": null, "e": 26680, "s": 26657, "text": "The centre of rotation" }, { "code": null, "e": 26692, "s": 26680, "text": "The offsets" }, { "code": null, "e": 26723, "s": 26692, "text": "The current amount of rotation" }, { "code": null, "e": 26749, "s": 26723, "text": "The direction of rotation" }, { "code": null, "e": 26795, "s": 26749, "text": "The program will work in the following order:" }, { "code": null, "e": 27198, "s": 26795, "text": "THe OpenGL window will startAll the files will be read and stored in there respective objectsAn infinite while loop will be startedThe screen will be clearedA line will be drawn depicting the grasslandAll the parts will be updatedAll the parts will be drawnThe body translation value will be decremented, and if the dinosaur is out of the window, it will be reset.The loop will go to its next iteration" }, { "code": null, "e": 27227, "s": 27198, "text": "THe OpenGL window will start" }, { "code": null, "e": 27293, "s": 27227, "text": "All the files will be read and stored in there respective objects" }, { "code": null, "e": 27332, "s": 27293, "text": "An infinite while loop will be started" }, { "code": null, "e": 27359, "s": 27332, "text": "The screen will be cleared" }, { "code": null, "e": 27404, "s": 27359, "text": "A line will be drawn depicting the grassland" }, { "code": null, "e": 27434, "s": 27404, "text": "All the parts will be updated" }, { "code": null, "e": 27462, "s": 27434, "text": "All the parts will be drawn" }, { "code": null, "e": 27570, "s": 27462, "text": "The body translation value will be decremented, and if the dinosaur is out of the window, it will be reset." }, { "code": null, "e": 27609, "s": 27570, "text": "The loop will go to its next iteration" }, { "code": null, "e": 27814, "s": 27609, "text": "During updation of an object, the rotationstate is checked andif it is overshooting the threshold of rotation, then the direction of rotation is reversed.The rotationstate is 0 if it is not to be rotated." }, { "code": "#include <stdio.h>#include <GL/glut.h>#include <math.h> // these are the parameters#define maxHt 800#define maxWd 600#define maxLns 10000#define transSpeed 1#define rotSpeed 0.02#define rotateLimit 0.2#define boundLimitL -200#define boundLimitR 500#define grasslandy 230 // Structure for storing linestypedef struct lines { int x1, x2, y1, y2;} LINE; // Object type structure for storing each body parttypedef struct objects { LINE edge[maxLns]; int translation, cx, cy, xoffset, yoffset; float theta; int rotationState; int EdgeCount;} Object; // the different objectsObject Head, upBody, Tail, downBody, FlegF, FlegB, BlegF, BlegB;// globalint dinoTranslate = 0; // basic init function for OPENGLvoid myInit(void){ glClearColor(1.0, 1.0, 1.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, maxHt, 0, maxWd); glClear(GL_COLOR_BUFFER_BIT);} // this function translates, and rotates a point according to an object and draws itvoid rotateandshiftPt(int px, int py, Object obbj){ int xf, yf; xf = obbj.cx + (int)((float)(px - obbj.cx) * cos(obbj.theta)) - ((float)(py - obbj.cy) * sin(obbj.theta)); yf = obbj.cy + (int)((float)(px - obbj.cx) * sin(obbj.theta)) + ((float)(py - obbj.cy) * cos(obbj.theta)); glBegin(GL_POINTS); glVertex2i(obbj.translation + xf + obbj.xoffset, yf + obbj.yoffset); glEnd();} // this function draws a line using Bresenhamsvoid drawLineBresenham(int x1, int y1, int x2, int y2, Object obbj){ int Dx, Dy, Dxmul2, Dymul2, Pk, xtempi, ytempi; float lineSlope, xtemp, ytemp; Dx = abs(x2 - x1); Dy = abs(y2 - y1); Dxmul2 = 2 * Dx; Dymul2 = 2 * Dy; ytemp = (float)(y2 - y1); xtemp = (float)(x2 - x1); lineSlope = (ytemp / xtemp); if (lineSlope >= -1.0 && lineSlope <= 1.0) { Pk = Dymul2 - Dx; if (x1 > x2) { xtempi = x2; x2 = x1; x1 = xtempi; ytempi = y2; y2 = y1; y1 = ytempi; } for (xtempi = x1, ytempi = y1; xtempi <= x2; xtempi++) { rotateandshiftPt(xtempi, ytempi, obbj); if (Pk < 0) { Pk = Pk + Dymul2; } else { Pk = Pk + Dymul2 - Dxmul2; if (lineSlope >= 0.0 && lineSlope <= 1.0) ytempi = ytempi + 1; else if (lineSlope < 0.0 && lineSlope >= -1.0) ytempi = ytempi - 1; } } } else { Pk = Dxmul2 - Dy; if (y1 > y2) { xtempi = x2; x2 = x1; x1 = xtempi; ytempi = y2; y2 = y1; y1 = ytempi; } for (xtempi = x1, ytempi = y1; ytempi <= y2; ytempi++) { rotateandshiftPt(xtempi, ytempi, obbj); if (Pk < 0) { Pk = Pk + Dxmul2; } else { Pk = Pk + Dxmul2 - Dymul2; if (lineSlope > 1.0) xtempi = xtempi + 1; else if (lineSlope < -1.0) xtempi = xtempi - 1; } } }}// here all the edges are iterated and drawnvoid drawObj(Object obbj){ int i; for (i = 0; i < obbj.EdgeCount; i++) { drawLineBresenham(obbj.edge[i].x1, obbj.edge[i].y1, obbj.edge[i].x2, obbj.edge[i].y2, obbj); }} // in this function, an object is updatedvoid updateObj(Object* obbj){ obbj->translation = dinoTranslate; if (obbj->rotationState == 1) { obbj->theta = obbj->theta + rotSpeed; if (obbj->theta >= (3.14159)) obbj->theta = obbj->theta - (2.0 * 3.14159); if (obbj->theta > rotateLimit) obbj->rotationState = -1; } else if (obbj->rotationState == -1) { obbj->theta = obbj->theta - rotSpeed; if (obbj->theta <= (-3.14159)) obbj->theta = (2.0 * 3.14159) + obbj->theta; if (obbj->theta < -rotateLimit) obbj->rotationState = 1; }} // The actual function where the Dinosaur is drawnvoid drawDino(void){ // an infinite while loop for moving the dinosaur while (1) { glClear(GL_COLOR_BUFFER_BIT); // draw grassland glLineWidth(5.0); glColor3f(0.0f, 1.0f, 0.3f); glBegin(GL_LINES); glVertex2i(0, grasslandy); glVertex2i(maxHt, grasslandy); glEnd(); glPointSize(3.0); glColor3f(0.9f, 0.5f, 0.6f); // update all parts updateObj(&Head); updateObj(&upBody); updateObj(&Tail); updateObj(&downBody); updateObj(&FlegF); updateObj(&FlegB); updateObj(&BlegF); updateObj(&BlegB); // draw all parts, also draw joining parts drawObj(Head); drawObj(upBody); drawObj(Tail); drawObj(downBody); drawObj(FlegF); drawObj(FlegB); drawObj(BlegF); drawObj(BlegB); dinoTranslate--; // decreased because moving forward if (dinoTranslate <= boundLimitL) { dinoTranslate = boundLimitR; printf(\"\\ntranslate %d\", dinoTranslate); } printf(\"\\ntranslate %d\", dinoTranslate); glFlush(); }} // TAn object is stored using this functionvoid storeObj(char* str, Object* obbj){ obbj->theta = 0.0; FILE* fp; fp = fopen(str, \"r\"); if (fp == NULL) { printf(\"Could not open file\"); return; } obbj->EdgeCount = 0; int count = 0, x1, y1, x2, y2; while (!feof(fp)) { count++; if (count > 2) { x1 = x2; y1 = y2; count = 2; } if (count == 1) { fscanf(fp, \"%d, %d\", &x1, &y1); } else { fscanf(fp, \"%d, %d\", &x2, &y2); printf(\"\\n%d, %d\", x2, y2); obbj->edge[obbj->EdgeCount].x1 = x1; obbj->edge[obbj->EdgeCount].y1 = y1; obbj->edge[obbj->EdgeCount].x2 = x2; obbj->edge[obbj->EdgeCount].y2 = y2; obbj->EdgeCount++; } } // printf(\"\\nPolygon stored!\"); fclose(fp);} // All parts are stored.void storeAllParts(){ FILE* fp, *fp2; int cx, cy; fp = fopen(\"centrePts.txt\", \"r\"); fp2 = fopen(\"offsetDino.txt\", \"r\"); if (fp == NULL || fp2 == NULL) { printf(\"Could not open file\"); return; } // parts //---------------- // head+neck storeObj(\"headDino.txt\", &Head); fscanf(fp, \"%d, %d\", &cx, &cy); Head.cx = cx; Head.cy = cy; fscanf(fp2, \"%d, %d\", &cx, &cy); Head.xoffset = cx; Head.yoffset = cy; Head.rotationState = 1; // upper body boundary(only translation) storeObj(\"bodyupDino.txt\", &upBody); upBody.cx = 0; upBody.cy = 0; fscanf(fp2, \"%d, %d\", &cx, &cy); upBody.xoffset = cx; upBody.yoffset = cy; upBody.rotationState = 0; // tail storeObj(\"tailDino.txt\", &Tail); fscanf(fp, \"%d, %d\", &cx, &cy); Tail.cx = cx; Tail.cy = cy; fscanf(fp2, \"%d, %d\", &cx, &cy); Tail.xoffset = cx; Tail.yoffset = cy; Tail.rotationState = -1; // back leg front storeObj(\"backlegFDino.txt\", &BlegF); fscanf(fp, \"%d, %d\", &cx, &cy); BlegF.cx = cx; BlegF.cy = cy; fscanf(fp2, \"%d, %d\", &cx, &cy); BlegF.xoffset = cx; BlegF.yoffset = cy; BlegF.rotationState = -1; // back leg rear storeObj(\"backlegRDino.txt\", &BlegB); fscanf(fp, \"%d, %d\", &cx, &cy); BlegB.cx = cx; BlegB.cy = cy; fscanf(fp2, \"%d, %d\", &cx, &cy); BlegB.xoffset = cx; BlegB.yoffset = cy; BlegB.rotationState = 1; // lower body boundary(only translation) storeObj(\"bodydownDino.txt\", &downBody); downBody.cx = 0; downBody.cy = 0; fscanf(fp2, \"%d, %d\", &cx, &cy); downBody.xoffset = cx; downBody.yoffset = cy; downBody.rotationState = 0; // front leg rear storeObj(\"frontlegRDino.txt\", &FlegB); fscanf(fp, \"%d, %d\", &cx, &cy); FlegB.cx = cx; FlegB.cy = cy; fscanf(fp2, \"%d, %d\", &cx, &cy); FlegB.xoffset = cx; FlegB.yoffset = cy; FlegB.rotationState = -1; // front leg front storeObj(\"frontlegFDino.txt\", &FlegF); fscanf(fp, \"%d, %d\", &cx, &cy); FlegF.cx = cx; FlegF.cy = cy; fscanf(fp2, \"%d, %d\", &cx, &cy); FlegF.xoffset = cx; FlegF.yoffset = cy; FlegF.rotationState = 1; //------------------------ fclose(fp);} void main(int argc, char** argv){ storeAllParts(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(maxHt, maxWd); glutInitWindowPosition(0, 0); glutCreateWindow(\"Walking dinosaur\"); myInit(); glutDisplayFunc(drawDino); // actual loop call glutMainLoop();}", "e": 36395, "s": 27814, "text": null }, { "code": null, "e": 36493, "s": 36395, "text": "Output:This is a sample screenshot:Don’t forget to download the files before running the program." }, { "code": null, "e": 36793, "s": 36493, "text": "This article is contributed by Suprotik Dey. 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": 36918, "s": 36793, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 36931, "s": 36918, "text": "Akanksha_Rai" }, { "code": null, "e": 36938, "s": 36931, "text": "OpenGL" }, { "code": null, "e": 36944, "s": 36938, "text": "GBlog" }, { "code": null, "e": 37042, "s": 36944, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37051, "s": 37042, "text": "Comments" }, { "code": null, "e": 37064, "s": 37051, "text": "Old Comments" }, { "code": null, "e": 37106, "s": 37064, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 37131, "s": 37106, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37175, "s": 37131, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 37207, "s": 37175, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 37241, "s": 37207, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 37285, "s": 37241, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 37331, "s": 37285, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 37389, "s": 37331, "text": "What is web socket and how it is different from the HTTP?" }, { "code": null, "e": 37415, "s": 37389, "text": "Software Testing | Basics" } ]
Fortran - Strings
The Fortran language can treat characters as single character or contiguous strings. A character string may be only one character in length, or it could even be of zero length. In Fortran, character constants are given between a pair of double or single quotes. The intrinsic data type character stores characters and strings. The length of the string can be specified by len specifier. If no length is specified, it is 1. You can refer individual characters within a string referring by position; the left most character is at position 1. Declaring a string is same as other variables − type-specifier :: variable_name For example, Character(len = 20) :: firstname, surname you can assign a value like, character (len = 40) :: name name = “Zara Ali” The following example demonstrates declaration and use of character data type − program hello implicit none character(len = 15) :: surname, firstname character(len = 6) :: title character(len = 25)::greetings title = 'Mr.' firstname = 'Rowan' surname = 'Atkinson' greetings = 'A big hello from Mr. Beans' print *, 'Here is', title, firstname, surname print *, greetings end program hello When you compile and execute the above program it produces the following result − Here isMr. Rowan Atkinson A big hello from Mr. Bean The concatenation operator //, concatenates strings. The following example demonstrates this − program hello implicit none character(len = 15) :: surname, firstname character(len = 6) :: title character(len = 40):: name character(len = 25)::greetings title = 'Mr.' firstname = 'Rowan' surname = 'Atkinson' name = title//firstname//surname greetings = 'A big hello from Mr. Beans' print *, 'Here is', name print *, greetings end program hello When you compile and execute the above program it produces the following result − Here is Mr. Rowan Atkinson A big hello from Mr. Bean In Fortran, you can extract a substring from a string by indexing the string, giving the start and the end index of the substring in a pair of brackets. This is called extent specifier. The following example shows how to extract the substring ‘world’ from the string ‘hello world’ − program subString character(len = 11)::hello hello = "Hello World" print*, hello(7:11) end program subString When you compile and execute the above program it produces the following result − World The following example uses the date_and_time function to give the date and time string. We use extent specifiers to extract the year, date, month, hour, minutes and second information separately. program datetime implicit none character(len = 8) :: dateinfo ! ccyymmdd character(len = 4) :: year, month*2, day*2 character(len = 10) :: timeinfo ! hhmmss.sss character(len = 2) :: hour, minute, second*6 call date_and_time(dateinfo, timeinfo) ! let’s break dateinfo into year, month and day. ! dateinfo has a form of ccyymmdd, where cc = century, yy = year ! mm = month and dd = day year = dateinfo(1:4) month = dateinfo(5:6) day = dateinfo(7:8) print*, 'Date String:', dateinfo print*, 'Year:', year print *,'Month:', month print *,'Day:', day ! let’s break timeinfo into hour, minute and second. ! timeinfo has a form of hhmmss.sss, where h = hour, m = minute ! and s = second hour = timeinfo(1:2) minute = timeinfo(3:4) second = timeinfo(5:10) print*, 'Time String:', timeinfo print*, 'Hour:', hour print*, 'Minute:', minute print*, 'Second:', second end program datetime When you compile and execute the above program, it gives the detailed date and time information − Date String: 20140803 Year: 2014 Month: 08 Day: 03 Time String: 075835.466 Hour: 07 Minute: 58 Second: 35.466 The trim function takes a string, and returns the input string after removing all trailing blanks. program trimString implicit none character (len = *), parameter :: fname="Susanne", sname="Rizwan" character (len = 20) :: fullname fullname = fname//" "//sname !concatenating the strings print*,fullname,", the beautiful dancer from the east!" print*,trim(fullname),", the beautiful dancer from the east!" end program trimString When you compile and execute the above program it produces the following result − Susanne Rizwan , the beautiful dancer from the east! Susanne Rizwan, the beautiful dancer from the east! The function adjustl takes a string and returns it by removing the leading blanks and appending them as trailing blanks. The function adjustr takes a string and returns it by removing the trailing blanks and appending them as leading blanks. program hello implicit none character(len = 15) :: surname, firstname character(len = 6) :: title character(len = 40):: name character(len = 25):: greetings title = 'Mr. ' firstname = 'Rowan' surname = 'Atkinson' greetings = 'A big hello from Mr. Beans' name = adjustl(title)//adjustl(firstname)//adjustl(surname) print *, 'Here is', name print *, greetings name = adjustr(title)//adjustr(firstname)//adjustr(surname) print *, 'Here is', name print *, greetings name = trim(title)//trim(firstname)//trim(surname) print *, 'Here is', name print *, greetings end program hello When you compile and execute the above program it produces the following result − Here is Mr. Rowan Atkinson A big hello from Mr. Bean Here is Mr. Rowan Atkinson A big hello from Mr. Bean Here is Mr.RowanAtkinson A big hello from Mr. Bean The index function takes two strings and checks if the second string is a substring of the first string. If the second argument is a substring of the first argument, then it returns an integer which is the starting index of the second string in the first string, else it returns zero. program hello implicit none character(len=30) :: myString character(len=10) :: testString myString = 'This is a test' testString = 'test' if(index(myString, testString) == 0)then print *, 'test is not found' else print *, 'test is found at index: ', index(myString, testString) end if end program hello When you compile and execute the above program it produces the following result − test is found at index: 11 Print Add Notes Bookmark this page
[ { "code": null, "e": 2231, "s": 2146, "text": "The Fortran language can treat characters as single character or contiguous strings." }, { "code": null, "e": 2408, "s": 2231, "text": "A character string may be only one character in length, or it could even be of zero length. In Fortran, character constants are given between a pair of double or single quotes." }, { "code": null, "e": 2686, "s": 2408, "text": "The intrinsic data type character stores characters and strings. The length of the string can be specified by len specifier. If no length is specified, it is 1. You can refer individual characters within a string referring by position; the left most character is at position 1." }, { "code": null, "e": 2734, "s": 2686, "text": "Declaring a string is same as other variables −" }, { "code": null, "e": 2767, "s": 2734, "text": "type-specifier :: variable_name\n" }, { "code": null, "e": 2780, "s": 2767, "text": "For example," }, { "code": null, "e": 2822, "s": 2780, "text": "Character(len = 20) :: firstname, surname" }, { "code": null, "e": 2851, "s": 2822, "text": "you can assign a value like," }, { "code": null, "e": 2900, "s": 2851, "text": "character (len = 40) :: name \nname = “Zara Ali”" }, { "code": null, "e": 2980, "s": 2900, "text": "The following example demonstrates declaration and use of character data type −" }, { "code": null, "e": 3332, "s": 2980, "text": "program hello\nimplicit none\n\n character(len = 15) :: surname, firstname \n character(len = 6) :: title \n character(len = 25)::greetings\n \n title = 'Mr.' \n firstname = 'Rowan' \n surname = 'Atkinson'\n greetings = 'A big hello from Mr. Beans'\n \n print *, 'Here is', title, firstname, surname\n print *, greetings\n \nend program hello" }, { "code": null, "e": 3414, "s": 3332, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 3485, "s": 3414, "text": "Here isMr. Rowan Atkinson \nA big hello from Mr. Bean\n" }, { "code": null, "e": 3538, "s": 3485, "text": "The concatenation operator //, concatenates strings." }, { "code": null, "e": 3580, "s": 3538, "text": "The following example demonstrates this −" }, { "code": null, "e": 3981, "s": 3580, "text": "program hello\nimplicit none\n\n character(len = 15) :: surname, firstname \n character(len = 6) :: title \n character(len = 40):: name\n character(len = 25)::greetings\n \n title = 'Mr.' \n firstname = 'Rowan' \n surname = 'Atkinson'\n \n name = title//firstname//surname\n greetings = 'A big hello from Mr. Beans'\n \n print *, 'Here is', name\n print *, greetings\n \nend program hello" }, { "code": null, "e": 4063, "s": 3981, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 4124, "s": 4063, "text": "Here is Mr. Rowan Atkinson \nA big hello from Mr. Bean\n" }, { "code": null, "e": 4310, "s": 4124, "text": "In Fortran, you can extract a substring from a string by indexing the string, giving the start and the end index of the substring in a pair of brackets. This is called extent specifier." }, { "code": null, "e": 4407, "s": 4310, "text": "The following example shows how to extract the substring ‘world’ from the string ‘hello world’ −" }, { "code": null, "e": 4531, "s": 4407, "text": "program subString\n\n character(len = 11)::hello\n hello = \"Hello World\"\n print*, hello(7:11)\n \nend program subString " }, { "code": null, "e": 4613, "s": 4531, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 4620, "s": 4613, "text": "World\n" }, { "code": null, "e": 4816, "s": 4620, "text": "The following example uses the date_and_time function to give the date and time string. We use extent specifiers to extract the year, date, month, hour, minutes and second information separately." }, { "code": null, "e": 5799, "s": 4816, "text": "program datetime\nimplicit none\n\n character(len = 8) :: dateinfo ! ccyymmdd\n character(len = 4) :: year, month*2, day*2\n\n character(len = 10) :: timeinfo ! hhmmss.sss\n character(len = 2) :: hour, minute, second*6\n\n call date_and_time(dateinfo, timeinfo)\n\n ! let’s break dateinfo into year, month and day.\n ! dateinfo has a form of ccyymmdd, where cc = century, yy = year\n ! mm = month and dd = day\n\n year = dateinfo(1:4)\n month = dateinfo(5:6)\n day = dateinfo(7:8)\n\n print*, 'Date String:', dateinfo\n print*, 'Year:', year\n print *,'Month:', month\n print *,'Day:', day\n\n ! let’s break timeinfo into hour, minute and second.\n ! timeinfo has a form of hhmmss.sss, where h = hour, m = minute\n ! and s = second\n\n hour = timeinfo(1:2)\n minute = timeinfo(3:4)\n second = timeinfo(5:10)\n\n print*, 'Time String:', timeinfo\n print*, 'Hour:', hour\n print*, 'Minute:', minute\n print*, 'Second:', second \n \nend program datetime" }, { "code": null, "e": 5897, "s": 5799, "text": "When you compile and execute the above program, it gives the detailed date and time information −" }, { "code": null, "e": 6008, "s": 5897, "text": "Date String: 20140803\nYear: 2014\nMonth: 08\nDay: 03\nTime String: 075835.466\nHour: 07\nMinute: 58\nSecond: 35.466\n" }, { "code": null, "e": 6107, "s": 6008, "text": "The trim function takes a string, and returns the input string after removing all trailing blanks." }, { "code": null, "e": 6465, "s": 6107, "text": "program trimString\nimplicit none\n\n character (len = *), parameter :: fname=\"Susanne\", sname=\"Rizwan\"\n character (len = 20) :: fullname \n \n fullname = fname//\" \"//sname !concatenating the strings\n \n print*,fullname,\", the beautiful dancer from the east!\"\n print*,trim(fullname),\", the beautiful dancer from the east!\"\n \nend program trimString" }, { "code": null, "e": 6547, "s": 6465, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 6659, "s": 6547, "text": "Susanne Rizwan , the beautiful dancer from the east!\n Susanne Rizwan, the beautiful dancer from the east!\n" }, { "code": null, "e": 6780, "s": 6659, "text": "The function adjustl takes a string and returns it by removing the leading blanks and appending them as trailing blanks." }, { "code": null, "e": 6901, "s": 6780, "text": "The function adjustr takes a string and returns it by removing the trailing blanks and appending them as leading blanks." }, { "code": null, "e": 7552, "s": 6901, "text": "program hello\nimplicit none\n\n character(len = 15) :: surname, firstname \n character(len = 6) :: title \n character(len = 40):: name\n character(len = 25):: greetings\n \n title = 'Mr. ' \n firstname = 'Rowan' \n surname = 'Atkinson'\n greetings = 'A big hello from Mr. Beans'\n \n name = adjustl(title)//adjustl(firstname)//adjustl(surname)\n print *, 'Here is', name\n print *, greetings\n \n name = adjustr(title)//adjustr(firstname)//adjustr(surname)\n print *, 'Here is', name\n print *, greetings\n \n name = trim(title)//trim(firstname)//trim(surname)\n print *, 'Here is', name\n print *, greetings\n \nend program hello" }, { "code": null, "e": 7634, "s": 7552, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 7832, "s": 7634, "text": "Here is Mr. Rowan Atkinson \nA big hello from Mr. Bean\nHere is Mr. Rowan Atkinson \nA big hello from Mr. Bean\nHere is Mr.RowanAtkinson \nA big hello from Mr. Bean\n" }, { "code": null, "e": 8117, "s": 7832, "text": "The index function takes two strings and checks if the second string is a substring of the first string. If the second argument is a substring of the first argument, then it returns an integer which is the starting index of the second string in the first string, else it returns zero." }, { "code": null, "e": 8466, "s": 8117, "text": "program hello\nimplicit none\n\n character(len=30) :: myString\n character(len=10) :: testString\n \n myString = 'This is a test'\n testString = 'test'\n \n if(index(myString, testString) == 0)then\n print *, 'test is not found'\n else\n print *, 'test is found at index: ', index(myString, testString)\n end if\n \nend program hello" }, { "code": null, "e": 8548, "s": 8466, "text": "When you compile and execute the above program it produces the following result −" }, { "code": null, "e": 8576, "s": 8548, "text": "test is found at index: 11\n" }, { "code": null, "e": 8583, "s": 8576, "text": " Print" }, { "code": null, "e": 8594, "s": 8583, "text": " Add Notes" } ]
How to specify Decimal Precision and scale number in MySQL database using PHPMyAdmin?
You need to select a database when you are creating a table. Right now, I have a sample database. The snapshot is as follows: Now you need to give the table name as well as the number of columns you want: After that you need to press Go button. Now, the following section would be visible: The DECIMAL requires two parameter i.e. Total Number of Digit and second one is DigitAfterDecimalPoint. The structure of DECIMAL is as follows: DECIMAL(X,Y) Here, X is TotalNumberOfDigit and Y is DigitAfterDecimalPoint. Let us see an example: DECIMAL(6,4) Above, we will be having 6 digit sand 2 digit safter decimal point. For example, the valid range can be 24.5678 or 560.23 etc. Here is the setup in phpmyAdmin. The snapshot is as follows: After giving column name for a table, you need to use “Save” button. Here is the structure of table: There are two columns in the table DecimalPrecisionDemo. One is Id which is of type int and second one is Amount of type DECIMAL(6,4).
[ { "code": null, "e": 1188, "s": 1062, "text": "You need to select a database when you are creating a table. Right now, I have a sample database. The snapshot is as follows:" }, { "code": null, "e": 1267, "s": 1188, "text": "Now you need to give the table name as well as the number of columns you want:" }, { "code": null, "e": 1352, "s": 1267, "text": "After that you need to press Go button. Now, the following section would be visible:" }, { "code": null, "e": 1456, "s": 1352, "text": "The DECIMAL requires two parameter i.e. Total Number of Digit and second one is DigitAfterDecimalPoint." }, { "code": null, "e": 1496, "s": 1456, "text": "The structure of DECIMAL is as follows:" }, { "code": null, "e": 1509, "s": 1496, "text": "DECIMAL(X,Y)" }, { "code": null, "e": 1572, "s": 1509, "text": "Here, X is TotalNumberOfDigit and Y is DigitAfterDecimalPoint." }, { "code": null, "e": 1595, "s": 1572, "text": "Let us see an example:" }, { "code": null, "e": 1608, "s": 1595, "text": "DECIMAL(6,4)" }, { "code": null, "e": 1735, "s": 1608, "text": "Above, we will be having 6 digit sand 2 digit safter decimal point. For example, the valid range can be 24.5678 or 560.23 etc." }, { "code": null, "e": 1796, "s": 1735, "text": "Here is the setup in phpmyAdmin. The snapshot is as follows:" }, { "code": null, "e": 1897, "s": 1796, "text": "After giving column name for a table, you need to use “Save” button. Here is the structure of table:" }, { "code": null, "e": 2032, "s": 1897, "text": "There are two columns in the table DecimalPrecisionDemo. One is Id which is of type int and second one is Amount of type DECIMAL(6,4)." } ]
Divide 1 to n into two groups with minimum sum difference - GeeksforGeeks
28 Apr, 2021 Given a positive integer n such that n > 2. Divide numbers from 1 to n in two groups such that absolute difference of sum of each group is minimum. Print any two groups with their size in first line and in next line print elements of that group.Examples: Input : 5 Output : 2 5 2 3 4 3 1 Here sum of group 1 is 7 and sum of group 2 is 8. Their absolute difference is 1 which is minimum. We can have multiple correct answers. (1, 2, 5) and (3, 4) is another such group. Input : 6 Output : 2 6 4 4 5 3 2 1 We can always divide sum of n integers in two groups such that their absolute difference of their sum is 0 or 1. So sum of group at most differ by 1. We define sum of group1 as half of n elements sum.Now run a loop from n to 1 and insert i into group1 if inserting an element doesn’t exceed group1 sum otherwise insert that i into group2. C++ Java Python3 C# PHP Javascript // CPP program to divide n integers// in two groups such that absolute// difference of their sum is minimum#include <bits/stdc++.h>using namespace std; // To print vector along sizevoid printVector(vector<int> v){ // Print vector size cout << v.size() << endl; // Print vector elements for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl;} // To divide n in two groups such that// absolute difference of their sum is// minimumvoid findTwoGroup(int n){ // Find sum of all elements upto n int sum = n * (n + 1) / 2; // Sum of elements of group1 int group1Sum = sum / 2; vector<int> group1, group2; for (int i = n; i > 0; i--) { // If sum is greater then or equal // to 0 include i in group 1 // otherwise include in group2 if (group1Sum - i >= 0) { group1.push_back(i); // Decrease sum of group1 group1Sum -= i; } else { group2.push_back(i); } } // Print both the groups printVector(group1); printVector(group2);} // Driver program to test above functionsint main(){ int n = 5; findTwoGroup(n); return 0;} // Java program to divide n integers// in two groups such that absolute// difference of their sum is minimumimport java.io.*;import java.util.*; class GFG{ // To print vector along size static void printVector(Vector<Integer> v) { // Print vector size System.out.println(v.size()); // Print vector elements for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + " "); System.out.println(); } // To divide n in two groups such that // absolute difference of their sum is // minimum static void findTwoGroup(int n) { // Find sum of all elements upto n int sum = n * (n + 1) / 2; // Sum of elements of group1 int group1Sum = sum / 2; Vector<Integer> group1 = new Vector<Integer>(); Vector<Integer> group2 = new Vector<Integer>(); for (int i = n; i > 0; i--) { // If sum is greater then or equal // to 0 include i in group1 // otherwise include in group2 if (group1Sum - i >= 0) { group1.add(i); // Decrease sum of group1 group1Sum -= i; } else { group2.add(i); } } // Print both the groups printVector(group1); printVector(group2); } // Driver code public static void main (String[] args) { int n = 5; findTwoGroup(n); }} // This code is contributed by Gitanjali. # Python program to divide n integers# in two groups such that absolute# difference of their sum is minimumimport math # To print vector along sizedef printVector( v): # Print vector size print(len(v)) # Print vector elements for i in range( 0, len(v)): print(v[i] , end = " ") print() # To divide n in two groups such that# absolute difference of their sum is# minimumdef findTwoGroup(n): # Find sum of all elements upto n sum = n * (n + 1) / 2 # Sum of elements of group1 group1Sum = sum / 2 group1=[] group2=[] for i in range(n, 0, -1): # If sum is greater then or equal # to 0 include i in group 1 # otherwise include in group2 if (group1Sum - i >= 0) : group1.append(i) # Decrease sum of group1 group1Sum -= i else : group2.append(i) # Print both the groups printVector(group1) printVector(group2) # driver coden = 5findTwoGroup(n) # This code is contributed by Gitanjali. // C# program to divide n integers// in two groups such that absolute// difference of their sum is minimumusing System;using System.Collections; class GFG{// To print vector along sizestatic void printVector(ArrayList v){ // Print vector size Console.WriteLine(v.Count); // Print vector elements for (int i = 0; i < v.Count; i++) Console.Write(v[i] + " "); Console.WriteLine();} // To divide n in two groups// such that absolute difference// of their sum is minimumstatic void findTwoGroup(int n){ // Find sum of all elements upto n int sum = n * (n + 1) / 2; // Sum of elements of group1 int group1Sum = sum / 2; ArrayList group1 = new ArrayList(); ArrayList group2 = new ArrayList(); for (int i = n; i > 0; i--) { // If sum is greater then // or equal to 0 include i // in group1 otherwise // include in group2 if (group1Sum - i >= 0) { group1.Add(i); // Decrease sum of group1 group1Sum -= i; } else { group2.Add(i); } } // Print both the groups printVector(group1); printVector(group2);} // Driver codepublic static void Main(){ int n = 5; findTwoGroup(n);}} // This code is contributed by mits <?php// PHP program to divide n// integers in two groups// such that absolute// difference of their// sum is minimum // To print vector// along sizefunction printVector($v){ // Print vector size echo count($v) . "\n"; // Print vector elements for ($i = 0; $i < count($v); $i++) echo $v[$i] . " "; echo "\n";} // To divide n in two groups// such that absolute difference// of their sum is minimumfunction findTwoGroup($n){ // Find sum of all // elements upto n $sum = $n * ($n + 1) / 2; // Sum of elements // of group1 $group1Sum = (int)($sum / 2); $group1; $group2; $x = 0; $y = 0; for ($i = $n; $i > 0; $i--) { // If sum is greater then // or equal to 0 include // i in group 1 otherwise // include in group2 if ($group1Sum - $i >= 0) { $group1[$x++] = $i; // Decrease sum // of group1 $group1Sum -= $i; } else { $group2[$y++] = $i; } } // Print both the groups printVector($group1); printVector($group2);} // Driver Code$n = 5;findTwoGroup($n); // This code is contributed by mits.?> <script> // Javascript program to divide n integers// in two groups such that absolute// difference of their sum is minimum // To print vector along sizefunction printVector(v){ // Print vector size document.write( v.length + "<br>"); // Print vector elements for (var i = 0; i < v.length; i++) document.write( v[i] + " "); document.write("<br>");} // To divide n in two groups such that// absolute difference of their sum is// minimumfunction findTwoGroup(n){ // Find sum of all elements upto n var sum = n * (n + 1) / 2; // Sum of elements of group1 var group1Sum = parseInt(sum / 2); var group1 = [], group2 = []; for (var i = n; i > 0; i--) { // If sum is greater then or equal // to 0 include i in group 1 // otherwise include in group2 if (group1Sum - i >= 0) { group1.push(i); // Decrease sum of group1 group1Sum -= i; } else { group2.push(i); } } // Print both the groups printVector(group1); printVector(group2);} // Driver program to test above functionsvar n = 5;findTwoGroup(n); </script> Output: 2 5 2 3 4 3 1 Mithun Kumar itsok number-theory Greedy Mathematical number-theory Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program for First Fit algorithm in Memory Management Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Max Flow Problem Introduction Program for Worst Fit algorithm in Memory Management Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Program to find sum of elements in a given array Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 25240, "s": 25212, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25497, "s": 25240, "text": "Given a positive integer n such that n > 2. Divide numbers from 1 to n in two groups such that absolute difference of sum of each group is minimum. Print any two groups with their size in first line and in next line print elements of that group.Examples: " }, { "code": null, "e": 25802, "s": 25497, "text": "Input : 5\nOutput : 2\n 5 2\n 3\n 4 3 1\nHere sum of group 1 is 7 and sum of group 2 is 8.\nTheir absolute difference is 1 which is minimum.\nWe can have multiple correct answers. (1, 2, 5) and \n(3, 4) is another such group.\n\nInput : 6\nOutput : 2\n 6 4\n 4\n 5 3 2 1" }, { "code": null, "e": 26145, "s": 25804, "text": "We can always divide sum of n integers in two groups such that their absolute difference of their sum is 0 or 1. So sum of group at most differ by 1. We define sum of group1 as half of n elements sum.Now run a loop from n to 1 and insert i into group1 if inserting an element doesn’t exceed group1 sum otherwise insert that i into group2. " }, { "code": null, "e": 26149, "s": 26145, "text": "C++" }, { "code": null, "e": 26154, "s": 26149, "text": "Java" }, { "code": null, "e": 26162, "s": 26154, "text": "Python3" }, { "code": null, "e": 26165, "s": 26162, "text": "C#" }, { "code": null, "e": 26169, "s": 26165, "text": "PHP" }, { "code": null, "e": 26180, "s": 26169, "text": "Javascript" }, { "code": "// CPP program to divide n integers// in two groups such that absolute// difference of their sum is minimum#include <bits/stdc++.h>using namespace std; // To print vector along sizevoid printVector(vector<int> v){ // Print vector size cout << v.size() << endl; // Print vector elements for (int i = 0; i < v.size(); i++) cout << v[i] << \" \"; cout << endl;} // To divide n in two groups such that// absolute difference of their sum is// minimumvoid findTwoGroup(int n){ // Find sum of all elements upto n int sum = n * (n + 1) / 2; // Sum of elements of group1 int group1Sum = sum / 2; vector<int> group1, group2; for (int i = n; i > 0; i--) { // If sum is greater then or equal // to 0 include i in group 1 // otherwise include in group2 if (group1Sum - i >= 0) { group1.push_back(i); // Decrease sum of group1 group1Sum -= i; } else { group2.push_back(i); } } // Print both the groups printVector(group1); printVector(group2);} // Driver program to test above functionsint main(){ int n = 5; findTwoGroup(n); return 0;}", "e": 27364, "s": 26180, "text": null }, { "code": "// Java program to divide n integers// in two groups such that absolute// difference of their sum is minimumimport java.io.*;import java.util.*; class GFG{ // To print vector along size static void printVector(Vector<Integer> v) { // Print vector size System.out.println(v.size()); // Print vector elements for (int i = 0; i < v.size(); i++) System.out.print(v.get(i) + \" \"); System.out.println(); } // To divide n in two groups such that // absolute difference of their sum is // minimum static void findTwoGroup(int n) { // Find sum of all elements upto n int sum = n * (n + 1) / 2; // Sum of elements of group1 int group1Sum = sum / 2; Vector<Integer> group1 = new Vector<Integer>(); Vector<Integer> group2 = new Vector<Integer>(); for (int i = n; i > 0; i--) { // If sum is greater then or equal // to 0 include i in group1 // otherwise include in group2 if (group1Sum - i >= 0) { group1.add(i); // Decrease sum of group1 group1Sum -= i; } else { group2.add(i); } } // Print both the groups printVector(group1); printVector(group2); } // Driver code public static void main (String[] args) { int n = 5; findTwoGroup(n); }} // This code is contributed by Gitanjali.", "e": 28904, "s": 27364, "text": null }, { "code": "# Python program to divide n integers# in two groups such that absolute# difference of their sum is minimumimport math # To print vector along sizedef printVector( v): # Print vector size print(len(v)) # Print vector elements for i in range( 0, len(v)): print(v[i] , end = \" \") print() # To divide n in two groups such that# absolute difference of their sum is# minimumdef findTwoGroup(n): # Find sum of all elements upto n sum = n * (n + 1) / 2 # Sum of elements of group1 group1Sum = sum / 2 group1=[] group2=[] for i in range(n, 0, -1): # If sum is greater then or equal # to 0 include i in group 1 # otherwise include in group2 if (group1Sum - i >= 0) : group1.append(i) # Decrease sum of group1 group1Sum -= i else : group2.append(i) # Print both the groups printVector(group1) printVector(group2) # driver coden = 5findTwoGroup(n) # This code is contributed by Gitanjali.", "e": 29933, "s": 28904, "text": null }, { "code": "// C# program to divide n integers// in two groups such that absolute// difference of their sum is minimumusing System;using System.Collections; class GFG{// To print vector along sizestatic void printVector(ArrayList v){ // Print vector size Console.WriteLine(v.Count); // Print vector elements for (int i = 0; i < v.Count; i++) Console.Write(v[i] + \" \"); Console.WriteLine();} // To divide n in two groups// such that absolute difference// of their sum is minimumstatic void findTwoGroup(int n){ // Find sum of all elements upto n int sum = n * (n + 1) / 2; // Sum of elements of group1 int group1Sum = sum / 2; ArrayList group1 = new ArrayList(); ArrayList group2 = new ArrayList(); for (int i = n; i > 0; i--) { // If sum is greater then // or equal to 0 include i // in group1 otherwise // include in group2 if (group1Sum - i >= 0) { group1.Add(i); // Decrease sum of group1 group1Sum -= i; } else { group2.Add(i); } } // Print both the groups printVector(group1); printVector(group2);} // Driver codepublic static void Main(){ int n = 5; findTwoGroup(n);}} // This code is contributed by mits", "e": 31222, "s": 29933, "text": null }, { "code": "<?php// PHP program to divide n// integers in two groups// such that absolute// difference of their// sum is minimum // To print vector// along sizefunction printVector($v){ // Print vector size echo count($v) . \"\\n\"; // Print vector elements for ($i = 0; $i < count($v); $i++) echo $v[$i] . \" \"; echo \"\\n\";} // To divide n in two groups// such that absolute difference// of their sum is minimumfunction findTwoGroup($n){ // Find sum of all // elements upto n $sum = $n * ($n + 1) / 2; // Sum of elements // of group1 $group1Sum = (int)($sum / 2); $group1; $group2; $x = 0; $y = 0; for ($i = $n; $i > 0; $i--) { // If sum is greater then // or equal to 0 include // i in group 1 otherwise // include in group2 if ($group1Sum - $i >= 0) { $group1[$x++] = $i; // Decrease sum // of group1 $group1Sum -= $i; } else { $group2[$y++] = $i; } } // Print both the groups printVector($group1); printVector($group2);} // Driver Code$n = 5;findTwoGroup($n); // This code is contributed by mits.?>", "e": 32420, "s": 31222, "text": null }, { "code": "<script> // Javascript program to divide n integers// in two groups such that absolute// difference of their sum is minimum // To print vector along sizefunction printVector(v){ // Print vector size document.write( v.length + \"<br>\"); // Print vector elements for (var i = 0; i < v.length; i++) document.write( v[i] + \" \"); document.write(\"<br>\");} // To divide n in two groups such that// absolute difference of their sum is// minimumfunction findTwoGroup(n){ // Find sum of all elements upto n var sum = n * (n + 1) / 2; // Sum of elements of group1 var group1Sum = parseInt(sum / 2); var group1 = [], group2 = []; for (var i = n; i > 0; i--) { // If sum is greater then or equal // to 0 include i in group 1 // otherwise include in group2 if (group1Sum - i >= 0) { group1.push(i); // Decrease sum of group1 group1Sum -= i; } else { group2.push(i); } } // Print both the groups printVector(group1); printVector(group2);} // Driver program to test above functionsvar n = 5;findTwoGroup(n); </script>", "e": 33576, "s": 32420, "text": null }, { "code": null, "e": 33586, "s": 33576, "text": "Output: " }, { "code": null, "e": 33600, "s": 33586, "text": "2\n5 2\n3\n4 3 1" }, { "code": null, "e": 33615, "s": 33602, "text": "Mithun Kumar" }, { "code": null, "e": 33621, "s": 33615, "text": "itsok" }, { "code": null, "e": 33635, "s": 33621, "text": "number-theory" }, { "code": null, "e": 33642, "s": 33635, "text": "Greedy" }, { "code": null, "e": 33655, "s": 33642, "text": "Mathematical" }, { "code": null, "e": 33669, "s": 33655, "text": "number-theory" }, { "code": null, "e": 33676, "s": 33669, "text": "Greedy" }, { "code": null, "e": 33689, "s": 33676, "text": "Mathematical" }, { "code": null, "e": 33787, "s": 33689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33796, "s": 33787, "text": "Comments" }, { "code": null, "e": 33809, "s": 33796, "text": "Old Comments" }, { "code": null, "e": 33862, "s": 33809, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 33897, "s": 33862, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 33949, "s": 33897, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 33979, "s": 33949, "text": "Max Flow Problem Introduction" }, { "code": null, "e": 34032, "s": 33979, "text": "Program for Worst Fit algorithm in Memory Management" }, { "code": null, "e": 34062, "s": 34032, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34077, "s": 34062, "text": "C++ Data Types" }, { "code": null, "e": 34120, "s": 34077, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 34169, "s": 34120, "text": "Program to find sum of elements in a given array" } ]
7 Examples to Master SQL Joins. A comprehensive practical guide | by Soner Yıldırım | Towards Data Science
SQL is a programming language used by most relational database management systems (RDBMS) to manage data stored in tabular form (i.e. tables). A relational database consists of multiple tables that relate to each other. The relation between tables is formed with shared columns. When we are to retrieve data from a relational database, the desired data is typically spread out to multiple tables. In such cases, we use SQL joins which are used to handle tasks that include selecting rows from two or more related tables. In order to be consistent while selecting rows from different tables, SQL joins make use of the shared column. In this article, we will go over 7 examples to demonstrate how SQL joins can be used to retrieve data from multiple tables. I have prepared two tables with made up data. The first one is the customer table that contains information about the customers of a retail business. The second one is the orders table that contains information about the orders made by these customers. These two tables relate to each other by the cust_id column. Note: There are many relational database management systems such as MySQL, SQL Server, SQLite, and so on. Although they share mostly the same SQL syntax, there might be small differences. I’m using MySQL for this article. We want to see the average age of customers who made a purchase on 2020–01–17. mysql> select avg(customer.age), orders.date -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> where orders.date = '2020-01-17';+-------------------+------------+| avg(customer.age) | date |+-------------------+------------+| 32.7273 | 2020-01-17 |+-------------------+------------+ In a normal select statement, we only write the name of the columns to be selected. When we join tables, the columns are specified with the name of the table so that SQL knows where a column comes from. Then we write the names of the tables with join keyword (e.g. customer join orders). The “on” keyword is used to indicate how these tables are related. The where statement filters the rows based on the given condition. We want to see the average order amount made by customers in Austin. mysql> select avg(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> where customer.location = "Austin";+--------------------+| avg(orders.amount) |+--------------------+| 50.572629 |+--------------------+ The logic is the same. You may have noticed a small difference between the second and first examples. In the second example, we did not select the location but use it as a filtering condition in the where statement. Either option works fine. We do not have to select all the columns we use for filtering. The aggregate function is applied while selecting the column just like in normal select statements. We want to see the average order amount for each city. This is similar to the second example with a small difference. We have to also select the location column because it will be used to group the rows. mysql> select customer.location, avg(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location;+----------+--------------------+| location | avg(orders.amount) |+----------+--------------------+| Austin | 50.572629 || Dallas | 47.624540 || Houston | 50.109382 |+----------+--------------------+ We want to see the highest order amount and the age of customer who made that order. mysql> select customer.age, orders.amount -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> order by orders.amount desc -> limit 1;+------+--------+| age | amount |+------+--------+| 41 | 99.95 |+------+--------+ We select the age from customer table and amount from the orders table. One way to filter the highest amount is to sort the values in descending order and take first one. The order by statement sorts the rows based on the values in the given column. The default behavior is to sort in ascending order but we change it using the desc keyword. We want to see the highest order amount made by customer whose id is 1006. mysql> select max(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> where customer.cust_id = 1006;+--------------------+| max(orders.amount) |+--------------------+| 93.18 |+--------------------+ We use the max function on the amount column and filter the rows that belong to customer whose id is 1006. We want to see the top 5 customers from Houston in terms of the highest average order amount when there is sale. We will be using two conditions in the where statement, group the values by the cust_id column, sort the rows based on the average amount in descending order, and select the first 5 rows. mysql> select c.cust_id, avg(o.amount) as average -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where c.location = "Houston" and o.is_sale = "True" -> group by c.cust_id -> order by average desc limit 5;+---------+-----------+| cust_id | average |+---------+-----------+| 1821 | 70.150000 || 1299 | 67.405000 || 1829 | 65.225000 || 1802 | 64.295000 || 1773 | 64.012500 |+---------+-----------+ In this example, we have used an alias for each table name and the aggregated column. It makes easier to write the query because we write the table names many times. We want to find out the location of the customer who has the lowest order amount on 2020–02–09. In this example, we will implement a nested select statement to be used as a condition in the where statement. mysql> select c.cust_id, c.location -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where o.date = "2020-02-09" and o.amount = ( -> select min(amount) from orders where date = "2020-02-09" -> );+---------+----------+| cust_id | location |+---------+----------+| 1559 | Dallas |+---------+----------+ We are given two conditions. The first one is specific date that we can directly write in the where statement. The second one includes an aggregation. We need to find the minimum order amount on a given date. We can either find this value in a separate query or write a nested select statement as the condition on the order amount. In this example, we have done the latter. We have done 7 examples to cover SQL joins. The relational databases typically consist of many tables that are related based on shared columns. The data we need to retrieve from a relational database is typically spread out to multiple tables. Thus, it is very important to have a comprehensive understanding of SQL joins. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 451, "s": 172, "text": "SQL is a programming language used by most relational database management systems (RDBMS) to manage data stored in tabular form (i.e. tables). A relational database consists of multiple tables that relate to each other. The relation between tables is formed with shared columns." }, { "code": null, "e": 693, "s": 451, "text": "When we are to retrieve data from a relational database, the desired data is typically spread out to multiple tables. In such cases, we use SQL joins which are used to handle tasks that include selecting rows from two or more related tables." }, { "code": null, "e": 928, "s": 693, "text": "In order to be consistent while selecting rows from different tables, SQL joins make use of the shared column. In this article, we will go over 7 examples to demonstrate how SQL joins can be used to retrieve data from multiple tables." }, { "code": null, "e": 1078, "s": 928, "text": "I have prepared two tables with made up data. The first one is the customer table that contains information about the customers of a retail business." }, { "code": null, "e": 1181, "s": 1078, "text": "The second one is the orders table that contains information about the orders made by these customers." }, { "code": null, "e": 1242, "s": 1181, "text": "These two tables relate to each other by the cust_id column." }, { "code": null, "e": 1464, "s": 1242, "text": "Note: There are many relational database management systems such as MySQL, SQL Server, SQLite, and so on. Although they share mostly the same SQL syntax, there might be small differences. I’m using MySQL for this article." }, { "code": null, "e": 1543, "s": 1464, "text": "We want to see the average age of customers who made a purchase on 2020–01–17." }, { "code": null, "e": 1879, "s": 1543, "text": "mysql> select avg(customer.age), orders.date -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> where orders.date = '2020-01-17';+-------------------+------------+| avg(customer.age) | date |+-------------------+------------+| 32.7273 | 2020-01-17 |+-------------------+------------+" }, { "code": null, "e": 2082, "s": 1879, "text": "In a normal select statement, we only write the name of the columns to be selected. When we join tables, the columns are specified with the name of the table so that SQL knows where a column comes from." }, { "code": null, "e": 2301, "s": 2082, "text": "Then we write the names of the tables with join keyword (e.g. customer join orders). The “on” keyword is used to indicate how these tables are related. The where statement filters the rows based on the given condition." }, { "code": null, "e": 2370, "s": 2301, "text": "We want to see the average order amount made by customers in Austin." }, { "code": null, "e": 2636, "s": 2370, "text": "mysql> select avg(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> where customer.location = \"Austin\";+--------------------+| avg(orders.amount) |+--------------------+| 50.572629 |+--------------------+" }, { "code": null, "e": 2941, "s": 2636, "text": "The logic is the same. You may have noticed a small difference between the second and first examples. In the second example, we did not select the location but use it as a filtering condition in the where statement. Either option works fine. We do not have to select all the columns we use for filtering." }, { "code": null, "e": 3041, "s": 2941, "text": "The aggregate function is applied while selecting the column just like in normal select statements." }, { "code": null, "e": 3096, "s": 3041, "text": "We want to see the average order amount for each city." }, { "code": null, "e": 3245, "s": 3096, "text": "This is similar to the second example with a small difference. We have to also select the location column because it will be used to group the rows." }, { "code": null, "e": 3643, "s": 3245, "text": "mysql> select customer.location, avg(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location;+----------+--------------------+| location | avg(orders.amount) |+----------+--------------------+| Austin | 50.572629 || Dallas | 47.624540 || Houston | 50.109382 |+----------+--------------------+" }, { "code": null, "e": 3728, "s": 3643, "text": "We want to see the highest order amount and the age of customer who made that order." }, { "code": null, "e": 3985, "s": 3728, "text": "mysql> select customer.age, orders.amount -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> order by orders.amount desc -> limit 1;+------+--------+| age | amount |+------+--------+| 41 | 99.95 |+------+--------+" }, { "code": null, "e": 4327, "s": 3985, "text": "We select the age from customer table and amount from the orders table. One way to filter the highest amount is to sort the values in descending order and take first one. The order by statement sorts the rows based on the values in the given column. The default behavior is to sort in ascending order but we change it using the desc keyword." }, { "code": null, "e": 4402, "s": 4327, "text": "We want to see the highest order amount made by customer whose id is 1006." }, { "code": null, "e": 4667, "s": 4402, "text": "mysql> select max(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> where customer.cust_id = 1006;+--------------------+| max(orders.amount) |+--------------------+| 93.18 |+--------------------+" }, { "code": null, "e": 4774, "s": 4667, "text": "We use the max function on the amount column and filter the rows that belong to customer whose id is 1006." }, { "code": null, "e": 4887, "s": 4774, "text": "We want to see the top 5 customers from Houston in terms of the highest average order amount when there is sale." }, { "code": null, "e": 5075, "s": 4887, "text": "We will be using two conditions in the where statement, group the values by the cust_id column, sort the rows based on the average amount in descending order, and select the first 5 rows." }, { "code": null, "e": 5531, "s": 5075, "text": "mysql> select c.cust_id, avg(o.amount) as average -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where c.location = \"Houston\" and o.is_sale = \"True\" -> group by c.cust_id -> order by average desc limit 5;+---------+-----------+| cust_id | average |+---------+-----------+| 1821 | 70.150000 || 1299 | 67.405000 || 1829 | 65.225000 || 1802 | 64.295000 || 1773 | 64.012500 |+---------+-----------+" }, { "code": null, "e": 5697, "s": 5531, "text": "In this example, we have used an alias for each table name and the aggregated column. It makes easier to write the query because we write the table names many times." }, { "code": null, "e": 5793, "s": 5697, "text": "We want to find out the location of the customer who has the lowest order amount on 2020–02–09." }, { "code": null, "e": 5904, "s": 5793, "text": "In this example, we will implement a nested select statement to be used as a condition in the where statement." }, { "code": null, "e": 6246, "s": 5904, "text": "mysql> select c.cust_id, c.location -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where o.date = \"2020-02-09\" and o.amount = ( -> select min(amount) from orders where date = \"2020-02-09\" -> );+---------+----------+| cust_id | location |+---------+----------+| 1559 | Dallas |+---------+----------+" }, { "code": null, "e": 6455, "s": 6246, "text": "We are given two conditions. The first one is specific date that we can directly write in the where statement. The second one includes an aggregation. We need to find the minimum order amount on a given date." }, { "code": null, "e": 6620, "s": 6455, "text": "We can either find this value in a separate query or write a nested select statement as the condition on the order amount. In this example, we have done the latter." }, { "code": null, "e": 6943, "s": 6620, "text": "We have done 7 examples to cover SQL joins. The relational databases typically consist of many tables that are related based on shared columns. The data we need to retrieve from a relational database is typically spread out to multiple tables. Thus, it is very important to have a comprehensive understanding of SQL joins." } ]
The Floyd-Warshall algorithm in Javascript
Djikstra's algorithm is used to find distance/path of the shortest path from one node to all other nodes. There are cases where we need to find shortest paths from all nodes to all other nodes. This is where the All pairs shortest path algorithms come in handy. The most used all pairs shortest path algorithm is Floyd Warshall algorithm. Floyd Warshall algorithm works as follows − We initialize an N x N matrix of distances to be Infinity. Then for each edge u, v, we update this matrix to be showing the weight of this edge and for edges v, v we update the weight to be 0. We create 3 nested loops with iterators I, j and k. for every node I's distance to every node j, we consider using k as intermediate points and update the distance if we find a less than existing arr[i][j]. Instead of using a matrix, we'll use an object as we don't need to keep track of index in case we are using complex objects to represent each node. Now let us look at the implementation of the same − floydWarshallAlgorithm() { let dist = {}; for (let i = 0; i < this.nodes.length; i++) { dist[this.nodes[i]] = {}; // For existing edges assign the dist to be same as weight this.edges[this.nodes[i]].forEach(e => (dist[this.nodes[i]][e.node] = e.weight)); this.nodes.forEach(n => { // For all other nodes assign it to infinity if (dist[this.nodes[i]][n] == undefined) dist[this.nodes[i]][n] = Infinity; // For self edge assign dist to be 0 if (this.nodes[i] === n) dist[this.nodes[i]][n] = 0; }); } this.nodes.forEach(i => { this.nodes.forEach(j => { this.nodes.forEach(k => { // Check if going from i to k then from k to j is better // than directly going from i to j. If yes then update // i to j value to the new value if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; }); }); }); return dist; } } You can test this using − let g = new Graph(); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addEdge("A", "C", 100); g.addEdge("A", "B", 3); g.addEdge("A", "D", 4); g.addEdge("D", "C", 3); console.log(g.floydWarshallAlgorithm()); This will give the output − { A: { C: 7, B: 3, D: 4, A: 0 }, B: { A: 3, B: 0, C: 10, D: 7 }, C: { A: 7, D: 3, B: 10, C: 0 }, D: { A: 4, C: 3, B: 7, D: 0 } }
[ { "code": null, "e": 1401, "s": 1062, "text": "Djikstra's algorithm is used to find distance/path of the shortest path from one node to all other nodes. There are cases where we need to find shortest paths from all nodes to all other nodes. This is where the All pairs shortest path algorithms come in handy. The most used all pairs shortest path algorithm is Floyd Warshall algorithm." }, { "code": null, "e": 1445, "s": 1401, "text": "Floyd Warshall algorithm works as follows −" }, { "code": null, "e": 1504, "s": 1445, "text": "We initialize an N x N matrix of distances to be Infinity." }, { "code": null, "e": 1638, "s": 1504, "text": "Then for each edge u, v, we update this matrix to be showing the weight of this edge and for edges v, v we update the weight to be 0." }, { "code": null, "e": 1845, "s": 1638, "text": "We create 3 nested loops with iterators I, j and k. for every node I's distance to every node j, we consider using k as intermediate points and update the distance if we find a less than existing arr[i][j]." }, { "code": null, "e": 1993, "s": 1845, "text": "Instead of using a matrix, we'll use an object as we don't need to keep track of index in case we are using complex objects to represent each node." }, { "code": null, "e": 2045, "s": 1993, "text": "Now let us look at the implementation of the same −" }, { "code": null, "e": 3076, "s": 2045, "text": "floydWarshallAlgorithm() {\n let dist = {};\n for (let i = 0; i < this.nodes.length; i++) {\n dist[this.nodes[i]] = {};\n // For existing edges assign the dist to be same as weight\n this.edges[this.nodes[i]].forEach(e => (dist[this.nodes[i]][e.node] = e.weight));\n this.nodes.forEach(n => {\n // For all other nodes assign it to infinity\n if (dist[this.nodes[i]][n] == undefined)\n dist[this.nodes[i]][n] = Infinity;\n // For self edge assign dist to be 0\n if (this.nodes[i] === n) dist[this.nodes[i]][n] = 0;\n });\n }\n this.nodes.forEach(i => {\n this.nodes.forEach(j => {\n this.nodes.forEach(k => {\n // Check if going from i to k then from k to j is better\n // than directly going from i to j. If yes then update\n // i to j value to the new value\n if (dist[i][k] + dist[k][j] < dist[i][j])\n dist[i][j] = dist[i][k] + dist[k][j];\n });\n });\n });\n return dist;\n }\n}" }, { "code": null, "e": 3102, "s": 3076, "text": "You can test this using −" }, { "code": null, "e": 3328, "s": 3102, "text": "let g = new Graph();\ng.addNode(\"A\");\ng.addNode(\"B\");\ng.addNode(\"C\");\ng.addNode(\"D\");\n\ng.addEdge(\"A\", \"C\", 100);\ng.addEdge(\"A\", \"B\", 3);\ng.addEdge(\"A\", \"D\", 4);\ng.addEdge(\"D\", \"C\", 3);\n\nconsole.log(g.floydWarshallAlgorithm());" }, { "code": null, "e": 3356, "s": 3328, "text": "This will give the output −" }, { "code": null, "e": 3497, "s": 3356, "text": "{\n A: { C: 7, B: 3, D: 4, A: 0 },\n B: { A: 3, B: 0, C: 10, D: 7 },\n C: { A: 7, D: 3, B: 10, C: 0 },\n D: { A: 4, C: 3, B: 7, D: 0 }\n}" } ]
Building a Color Recognizer in Python | by Behic Guven | Towards Data Science
In this post, I will show you how to build your own color recognizer using Python. This process is also known as “Color Detection”. We will create a basic application that will help us to detect the colors in an image. The program will also return as the RGB values of the colors, which is really helpful. Many graphic designers and web designers will understand how RGB values can be helpful. Building a color recognizer is a great project to get started with Computer Vision. If you haven’t heard of Computer Vision before, this is the best time to learn about it. Most of the machine learning and artificial intelligence fields are strongly connected to Computer Vision. As we are growing and exploring, seeing the outside world has a big impact on our development. This goes the same for the machines, they see the outside world using images, and those images are turned into data values that computers can understand. In previous posts, I showed how to detect faces and also how to recognize faces in an image, these are great projects to practice python in artificial intelligence and computer vision. Let’s do some work! Getting Started Libraries Define Image Color Recognition Application Results We will use three main modules for this project. They are NumPy, Pandas and OpenCv. OpenCv is a highly optimized library with a focus on real-time applications. OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products. Source: https://opencv.org lifexplorer.medium.com As mention earlier, there are three modules we will use for this project. To use these modules we have to install the necessary libraries. Library installation is a very easy step using pip. Pip is a package management tool. We will do the installation using the command-line interface. Here is the line to install all 3 libraries at once: pip install numpy pandas opencv-python After the installation is completed, we have to import them to our program. Open a new file in your favorite code editor. Here is the code on how to import the installed libraries: import numpy as npimport pandas as pdimport cv2 OpenCv is imported as cv2. And for other libraries, we imported them “as” so that it is easier to call them in the program. Perfect! Now, we can move to our next step, where we will define the image we want to use to test our color recognizer application. You can choose any image you want. I will save my image in the same folder as my program, which makes it easier to find and import. img = cv2.imread("color_image.jpg") To give you some idea, here is the image I will use for this project: Great! Are you ready for some programming? Without losing any time let’s move to the next step. Let me ask you a nice question. Did you know that machines are so pure? Well, I think they are because they learn whatever you teach them. They are like a big white canvas. And your program is your brush :) First, we have to teach them the colors. To do that we need data that includes color names and some values to match with those colors. Since most of the colors can be defined using Red, Green, and Blue. That’s why we will use the RGB format as our data points. I found a ready csv file with around 1000 color names and the RGB values. Here is the GitHub link. We will use this csv file in our program. The screenshot of the file to give you some idea: Let’s import colors.csv file to our program using read_csv method. Since the csv file we downloaded doesn’t have column names, I will be defining them in the program. This process is known as data manipulation. index=["color", "color_name", "hex", "R", "G", "B"]csv = pd.read_csv('colors.csv', names=index, header=None) In the following steps, we will define two functions. To make the application work smoothly, we need some global variables. You will know how global variables can be helpful when working with functions. clicked = Falser = g = b = xpos = ypos = 0 This function will be called when we double click on an area of the image. It will return the color name and the RGB values of that color. This is where the magic happens! def recognize_color(R,G,B): minimum = 10000 for i in range(len(csv)): d = abs(R- int(csv.loc[i,"R"])) + abs(G- int(csv.loc[i,"G"]))+ abs(B- int(csv.loc[i,"B"])) if(d<=minimum): minimum = d cname = csv.loc[i,"color_name"] return cname This function is used to define our double click process. We will need it when creating our application part. def mouse_click(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDBLCLK: global b,g,r,xpos,ypos, clicked clicked = True xpos = x ypos = y b,g,r = img[y,x] b = int(b) g = int(g) r = int(r) I hope you are still with me! It may look a little complicated but when you start writing them in your editor, the big picture will come to life. I do my best to keep things simple and easy to understand. I will add my contact info at the end of this article, reach me if you need any help. I am glad you made it to this step. In this step, we will open the image as a new window using OpenCV methods. And in that window, we will use the functions we defined earlier. The application is so simple, it returns the color name and color values when you double click on a certain area on the image. First things first, let me show you how to open the image file as a new window using OpenCV. cv2.namedWindow('Color Recognition App') Secondly, let’s call the mouse click function that we created. This gives more functionality to our application. cv2.setMouseCallback('Color Recognition App', mouse_click) Here is the while loop to start our application window working. while(1):cv2.imshow("Color Recognition App",img) if (clicked): #cv2.rectangle(image, startpoint, endpoint, color, thickness)-1 fills entire rectangle cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1)#Creating text string to display( Color name and RGB values ) text = recognize_color(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b) #cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType ) cv2.putText(img, text,(50,50),2,0.8,(255,255,255),2,cv2.LINE_AA)#For very light colours we will display text in black colour if(r+g+b>=600): cv2.putText(img, text,(50,50),2,0.8,(0,0,0),2,cv2.LINE_AA) clicked=False If you worked with OpenCV projects, you may be familiar with this step. We have to define how to end and close the application window. Otherwise, it will run forever since we used while(1) to start the application. Adding the following lines is a good practice for your future projects. #Break the loop when user hits 'esc' key if cv2.waitKey(20) & 0xFF ==27: breakcv2.destroyAllWindows() Currently, I am working on a demonstration video for this project. I received many positive feedbacks about the demonstration videos, it gives a better understanding of the program and application process. The video will be published on my youtube channel. (Update: Video is ready and available below. Thanks 😊 ) Congrats!! You have created a cool computer vision application that recognizes colors in an image. Now, you have some idea of how to use computer vision in a real project. Hoping that you enjoyed reading my article. I will be so happy if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills. Feel free to contact me if you have any questions while implementing the code. Follow my blog and Towards Data Science to stay inspired. Thank you,
[ { "code": null, "e": 650, "s": 172, "text": "In this post, I will show you how to build your own color recognizer using Python. This process is also known as “Color Detection”. We will create a basic application that will help us to detect the colors in an image. The program will also return as the RGB values of the colors, which is really helpful. Many graphic designers and web designers will understand how RGB values can be helpful. Building a color recognizer is a great project to get started with Computer Vision." }, { "code": null, "e": 1095, "s": 650, "text": "If you haven’t heard of Computer Vision before, this is the best time to learn about it. Most of the machine learning and artificial intelligence fields are strongly connected to Computer Vision. As we are growing and exploring, seeing the outside world has a big impact on our development. This goes the same for the machines, they see the outside world using images, and those images are turned into data values that computers can understand." }, { "code": null, "e": 1300, "s": 1095, "text": "In previous posts, I showed how to detect faces and also how to recognize faces in an image, these are great projects to practice python in artificial intelligence and computer vision. Let’s do some work!" }, { "code": null, "e": 1316, "s": 1300, "text": "Getting Started" }, { "code": null, "e": 1326, "s": 1316, "text": "Libraries" }, { "code": null, "e": 1339, "s": 1326, "text": "Define Image" }, { "code": null, "e": 1357, "s": 1339, "text": "Color Recognition" }, { "code": null, "e": 1369, "s": 1357, "text": "Application" }, { "code": null, "e": 1377, "s": 1369, "text": "Results" }, { "code": null, "e": 1538, "s": 1377, "text": "We will use three main modules for this project. They are NumPy, Pandas and OpenCv. OpenCv is a highly optimized library with a focus on real-time applications." }, { "code": null, "e": 1813, "s": 1538, "text": "OpenCV (Open Source Computer Vision Library) is an open-source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in commercial products." }, { "code": null, "e": 1840, "s": 1813, "text": "Source: https://opencv.org" }, { "code": null, "e": 1863, "s": 1840, "text": "lifexplorer.medium.com" }, { "code": null, "e": 2203, "s": 1863, "text": "As mention earlier, there are three modules we will use for this project. To use these modules we have to install the necessary libraries. Library installation is a very easy step using pip. Pip is a package management tool. We will do the installation using the command-line interface. Here is the line to install all 3 libraries at once:" }, { "code": null, "e": 2242, "s": 2203, "text": "pip install numpy pandas opencv-python" }, { "code": null, "e": 2423, "s": 2242, "text": "After the installation is completed, we have to import them to our program. Open a new file in your favorite code editor. Here is the code on how to import the installed libraries:" }, { "code": null, "e": 2471, "s": 2423, "text": "import numpy as npimport pandas as pdimport cv2" }, { "code": null, "e": 2595, "s": 2471, "text": "OpenCv is imported as cv2. And for other libraries, we imported them “as” so that it is easier to call them in the program." }, { "code": null, "e": 2727, "s": 2595, "text": "Perfect! Now, we can move to our next step, where we will define the image we want to use to test our color recognizer application." }, { "code": null, "e": 2859, "s": 2727, "text": "You can choose any image you want. I will save my image in the same folder as my program, which makes it easier to find and import." }, { "code": null, "e": 2895, "s": 2859, "text": "img = cv2.imread(\"color_image.jpg\")" }, { "code": null, "e": 2965, "s": 2895, "text": "To give you some idea, here is the image I will use for this project:" }, { "code": null, "e": 3061, "s": 2965, "text": "Great! Are you ready for some programming? Without losing any time let’s move to the next step." }, { "code": null, "e": 3268, "s": 3061, "text": "Let me ask you a nice question. Did you know that machines are so pure? Well, I think they are because they learn whatever you teach them. They are like a big white canvas. And your program is your brush :)" }, { "code": null, "e": 3720, "s": 3268, "text": "First, we have to teach them the colors. To do that we need data that includes color names and some values to match with those colors. Since most of the colors can be defined using Red, Green, and Blue. That’s why we will use the RGB format as our data points. I found a ready csv file with around 1000 color names and the RGB values. Here is the GitHub link. We will use this csv file in our program. The screenshot of the file to give you some idea:" }, { "code": null, "e": 3931, "s": 3720, "text": "Let’s import colors.csv file to our program using read_csv method. Since the csv file we downloaded doesn’t have column names, I will be defining them in the program. This process is known as data manipulation." }, { "code": null, "e": 4040, "s": 3931, "text": "index=[\"color\", \"color_name\", \"hex\", \"R\", \"G\", \"B\"]csv = pd.read_csv('colors.csv', names=index, header=None)" }, { "code": null, "e": 4243, "s": 4040, "text": "In the following steps, we will define two functions. To make the application work smoothly, we need some global variables. You will know how global variables can be helpful when working with functions." }, { "code": null, "e": 4286, "s": 4243, "text": "clicked = Falser = g = b = xpos = ypos = 0" }, { "code": null, "e": 4458, "s": 4286, "text": "This function will be called when we double click on an area of the image. It will return the color name and the RGB values of that color. This is where the magic happens!" }, { "code": null, "e": 4737, "s": 4458, "text": "def recognize_color(R,G,B): minimum = 10000 for i in range(len(csv)): d = abs(R- int(csv.loc[i,\"R\"])) + abs(G- int(csv.loc[i,\"G\"]))+ abs(B- int(csv.loc[i,\"B\"])) if(d<=minimum): minimum = d cname = csv.loc[i,\"color_name\"] return cname" }, { "code": null, "e": 4847, "s": 4737, "text": "This function is used to define our double click process. We will need it when creating our application part." }, { "code": null, "e": 5102, "s": 4847, "text": "def mouse_click(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDBLCLK: global b,g,r,xpos,ypos, clicked clicked = True xpos = x ypos = y b,g,r = img[y,x] b = int(b) g = int(g) r = int(r)" }, { "code": null, "e": 5393, "s": 5102, "text": "I hope you are still with me! It may look a little complicated but when you start writing them in your editor, the big picture will come to life. I do my best to keep things simple and easy to understand. I will add my contact info at the end of this article, reach me if you need any help." }, { "code": null, "e": 5697, "s": 5393, "text": "I am glad you made it to this step. In this step, we will open the image as a new window using OpenCV methods. And in that window, we will use the functions we defined earlier. The application is so simple, it returns the color name and color values when you double click on a certain area on the image." }, { "code": null, "e": 5790, "s": 5697, "text": "First things first, let me show you how to open the image file as a new window using OpenCV." }, { "code": null, "e": 5831, "s": 5790, "text": "cv2.namedWindow('Color Recognition App')" }, { "code": null, "e": 5944, "s": 5831, "text": "Secondly, let’s call the mouse click function that we created. This gives more functionality to our application." }, { "code": null, "e": 6003, "s": 5944, "text": "cv2.setMouseCallback('Color Recognition App', mouse_click)" }, { "code": null, "e": 6067, "s": 6003, "text": "Here is the while loop to start our application window working." }, { "code": null, "e": 6784, "s": 6067, "text": "while(1):cv2.imshow(\"Color Recognition App\",img) if (clicked): #cv2.rectangle(image, startpoint, endpoint, color, thickness)-1 fills entire rectangle cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1)#Creating text string to display( Color name and RGB values ) text = recognize_color(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b) #cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType ) cv2.putText(img, text,(50,50),2,0.8,(255,255,255),2,cv2.LINE_AA)#For very light colours we will display text in black colour if(r+g+b>=600): cv2.putText(img, text,(50,50),2,0.8,(0,0,0),2,cv2.LINE_AA) clicked=False" }, { "code": null, "e": 7071, "s": 6784, "text": "If you worked with OpenCV projects, you may be familiar with this step. We have to define how to end and close the application window. Otherwise, it will run forever since we used while(1) to start the application. Adding the following lines is a good practice for your future projects." }, { "code": null, "e": 7187, "s": 7071, "text": "#Break the loop when user hits 'esc' key if cv2.waitKey(20) & 0xFF ==27: breakcv2.destroyAllWindows()" }, { "code": null, "e": 7444, "s": 7187, "text": "Currently, I am working on a demonstration video for this project. I received many positive feedbacks about the demonstration videos, it gives a better understanding of the program and application process. The video will be published on my youtube channel." }, { "code": null, "e": 7500, "s": 7444, "text": "(Update: Video is ready and available below. Thanks 😊 )" }, { "code": null, "e": 7873, "s": 7500, "text": "Congrats!! You have created a cool computer vision application that recognizes colors in an image. Now, you have some idea of how to use computer vision in a real project. Hoping that you enjoyed reading my article. I will be so happy if you learned something new today. Working on hands-on programming projects like this one is the best way to sharpen your coding skills." }, { "code": null, "e": 7952, "s": 7873, "text": "Feel free to contact me if you have any questions while implementing the code." } ]
Decimal to Binary conversion using C Programming
How to convert a decimal number to a binary number by using the function in the C programming language? In this program, we are calling a function to binary in main(). The called function to binary will perform actual conversion. The logic we are using is called function to convert decimal number to binary number is as follows − while(dno != 0){ rem = dno % 2; bno = bno + rem * f; f = f * 10; dno = dno / 2; } Finally, it returns the binary number to the main program. Following is the C program to convert a decimal number to a binary number − Live Demo #include<stdio.h> long tobinary(int); int main(){ long bno; int dno; printf(" Enter any decimal number : "); scanf("%d",&dno); bno = tobinary(dno); printf("\n The Binary value is : %ld\n\n",bno); return 0; } long tobinary(int dno){ long bno=0,rem,f=1; while(dno != 0){ rem = dno % 2; bno = bno + rem * f; f = f * 10; dno = dno / 2; } return bno;; } When the above program is executed, it produces the following result − Enter any decimal number: 12 The Binary value is: 1100 Now, try to convert binary numbers to decimal numbers. Following is the C program to convert binary number to decimal number − Live Demo #include #include <stdio.h> int todecimal(long bno); int main(){ long bno; int dno; printf("Enter a binary number: "); scanf("%ld", &bno); dno=todecimal(bno); printf("The decimal value is:%d\n",dno); return 0; } int todecimal(long bno){ int dno = 0, i = 0, rem; while (bno != 0) { rem = bno % 10; bno /= 10; dno += rem * pow(2, i); ++i; } return dno; } When the above program is executed, it produces the following result − Enter a binary number: 10011 The decimal value is:19
[ { "code": null, "e": 1166, "s": 1062, "text": "How to convert a decimal number to a binary number by using the function in the C programming language?" }, { "code": null, "e": 1292, "s": 1166, "text": "In this program, we are calling a function to binary in main(). The called function to binary will perform actual conversion." }, { "code": null, "e": 1393, "s": 1292, "text": "The logic we are using is called function to convert decimal number to binary number is as follows −" }, { "code": null, "e": 1487, "s": 1393, "text": "while(dno != 0){\n rem = dno % 2;\n bno = bno + rem * f;\n f = f * 10;\n dno = dno / 2;\n}" }, { "code": null, "e": 1546, "s": 1487, "text": "Finally, it returns the binary number to the main program." }, { "code": null, "e": 1622, "s": 1546, "text": "Following is the C program to convert a decimal number to a binary number −" }, { "code": null, "e": 1633, "s": 1622, "text": " Live Demo" }, { "code": null, "e": 2039, "s": 1633, "text": "#include<stdio.h>\nlong tobinary(int);\nint main(){\n long bno;\n int dno;\n printf(\" Enter any decimal number : \");\n scanf(\"%d\",&dno);\n bno = tobinary(dno);\n printf(\"\\n The Binary value is : %ld\\n\\n\",bno);\n return 0;\n}\nlong tobinary(int dno){\n long bno=0,rem,f=1;\n while(dno != 0){\n rem = dno % 2;\n bno = bno + rem * f;\n f = f * 10;\n dno = dno / 2;\n }\n return bno;;\n}" }, { "code": null, "e": 2110, "s": 2039, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2165, "s": 2110, "text": "Enter any decimal number: 12\nThe Binary value is: 1100" }, { "code": null, "e": 2220, "s": 2165, "text": "Now, try to convert binary numbers to decimal numbers." }, { "code": null, "e": 2292, "s": 2220, "text": "Following is the C program to convert binary number to decimal number −" }, { "code": null, "e": 2303, "s": 2292, "text": " Live Demo" }, { "code": null, "e": 2713, "s": 2303, "text": "#include\n#include <stdio.h>\nint todecimal(long bno);\nint main(){\n long bno;\n int dno;\n printf(\"Enter a binary number: \");\n scanf(\"%ld\", &bno);\n dno=todecimal(bno);\n printf(\"The decimal value is:%d\\n\",dno);\n return 0;\n}\nint todecimal(long bno){\n int dno = 0, i = 0, rem;\n while (bno != 0) {\n rem = bno % 10;\n bno /= 10;\n dno += rem * pow(2, i);\n ++i;\n }\n return dno;\n}" }, { "code": null, "e": 2784, "s": 2713, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2837, "s": 2784, "text": "Enter a binary number: 10011\nThe decimal value is:19" } ]
How to clear screen using Java?
Following is the code to clear screen using Java − Live Demo public class Demo{ public static void main(String[] args){ System.out.print("\033[H\033[2J"); System.out.flush(); } } The screen would be cleared A class named Demo contains the main function. Here, the ANSI escape code is written, that clears the screen. The flush function resets the cursor to the top of the window screen.
[ { "code": null, "e": 1113, "s": 1062, "text": "Following is the code to clear screen using Java −" }, { "code": null, "e": 1124, "s": 1113, "text": " Live Demo" }, { "code": null, "e": 1260, "s": 1124, "text": "public class Demo{\n public static void main(String[] args){\n System.out.print(\"\\033[H\\033[2J\");\n System.out.flush();\n }\n}" }, { "code": null, "e": 1288, "s": 1260, "text": "The screen would be cleared" }, { "code": null, "e": 1468, "s": 1288, "text": "A class named Demo contains the main function. Here, the ANSI escape code is written, that clears the screen. The flush function resets the cursor to the top of the window screen." } ]
Math of Q-Learning — Python. Understand where the Bellman equation... | by Omar Aflak | Towards Data Science
Q-Learning is a type of Reinforcement Learning which is a type of Machine Learning. Reinforcement learning has been used lately (typically) to teach an AI to play a game (Google DeepMind Atari, etc). Our goal is to understand a simple version of Reinforcement learning called Q-Learning, and write a program that will learn how to play a simple “game”. Let’s dive in! A Markov chain is a mathematical model that experiences transition of states with probabilistic rules. Here we have two states E and A, and the probabilities of going from one state to another (e.g. 70% chance of going to state A, starting from state E). A Markov Decision Process (MDP) is an extension of the Markov chain and it is used to model more complex environments. In this extension, we add the possibility to make a choice at every state which is called an action. We also add a reward which is a feedback from the environment for going from one state to another taking one action. In the image above, we are in the initial state don’t understand, where we have two possible actions, study and don’t study. For the study action, we may end up in different states according to a probabilistic rule. This is what we call a stochastic environment (random), in the sense that for one same action taken in the same state, we might have different results (understand and don’t understand). In reinforcement learning, this is how we model a game or environment, and our goal will be to maximize the reward we get from that environment. The reward is the feedback from the environment that tells us how good we are doing. It can be the number of coins you grab in a game for example. Our goal is to maximize the total reward. Therefore, we need to write it down. This is the total reward we can get starting at some point t in time. For example, if we use the MDP presented above. We’re initially in the state don’t understand, we take the study action which takes us randomly to don’t understand. Therefore we experienced the reward r(t+1)=-1. Now we can decide to take another action which will give r(t+2) and so on. The total reward is the sum of all the immediate rewards we get for taking actions in the environment. Defining the reward this way leads to two major problems : This sum can potentially go to infinity, which doesn’t make sense since we want to maximize it. We are accounting as much for future rewards as we do for immediate rewards. One way to fix up these problems is to use a decreasing factor for future rewards. Setting γ=1 takes us back to the first expression where every reward is equally important. Setting γ=0 results in only looking for the immediate reward (always acting for the optimal next step). Setting γ between 0 and 1 is a compromise to look more for immediate reward but still account for future rewards. We can rewrite that expression in a recursive manner, that will come handy later on. A policy is a function that tells what action to take when in a certain state. This function is usually denoted π(s,a) and yields the probability of taking action a in state s. We want to find the policy that maximizes the reward function. If we get back to the previous MDP for example, the policy can tell you the probability of taking action study when you’re in the state don’t understand. Moreover, because this is a probability distribution, the sum over all the possible actions must be equal to 1. We are going to start playing around with some equations, and for that we need to introduce new notations. This is the expected immediate reward for going from state s to state s’ through action a. This is the transition probability of going from state s to state s’ through action a. In this example : The expected immediate reward for going from state don’t understand to state don’t understand through action don’t study is equal to 0. The probability of going from state don’t understand to state understand through action study is equal to 80%. Two so-called “value functions” exist. The state value function, and the action value function. These functions are a way to measure the “value”, or how good some state is, or how good some action is, respectively. The value of a state is the expected total reward we can get starting from that state. It depends on the policy which tells how to take decisions. The value of an action taken in some state is the expected total reward we can get, starting from that state and taking that action. It also depends on the policy. Now that we are settled with notations we can finally start playing around with the math! Looking at the following diagram during the calculation can help you understand. We will start by expanding the state value function. The expected operator is linear. Next, we can expand the action value function. This form of the Q-Value is very generic. It handles stochastic environments, but we could write it in a deterministic one. Meaning, whenever you take an action you always end up in the same next state and receive the same reward. In that case, we simply do not need to make a weighted sum with probabilities, and the equation becomes: Where s’ is the state you end up in for taking action a in state s. Written, more formally, this is: You probably already came across greedy policy reading on the internet. A greedy policy is a policy where you always choose the optimal next step. In a greedy policy context, we can write a relation between the state value and the action value functions. Therefore, plugging this into the previous equation, we get the Q-Value of a (state, action) pair in a deterministic environment, following a greedy policy. Or simply, And this is the Bellman equation in the Q-Learning context ! It tells that the value of an action a in some state s is the immediate reward you get for taking that action, to which you add the maximum expected reward you can get in the next state. It actually makes sens when you think about it. Here, if you only look at the immediate reward, you surely choose to go left. Unfortunately, the game ends after and you cannot get more points. If you add the maximum expected reward of the next state, then you will most probably go to the right since the maximum expected reward of S1 is equal to zero and the maximum expected reward of S2 is probably higher than 10–5=5. You can also tweak γ to specify how important are the next rewards. Here is a simple environment which consists of a 5-by-5 grid. A treasure (T) is placed at the bottom right corner of the grid. The agent (O) starts at the top left corner of the grid. O.......................T The agent needs to get to the treasure using the 4 available actions : left, right, up, down. If the agent takes an action that leads him directly to T, he gets a reward of 1, otherwise a reward of 0. The code is well commented and it is simply what we just discussed. Now the interesting part, the Q-Learning algorithm ! I almost commented every single line of this code, so hopefully, it will be easy to understand! Put both of the above files in the same directory, and run : python3 medium_qlearning_rl.py Around the epoch number 40, the agent should have learned to get to the treasure using one of the shortest paths (8 steps). We have seen how to derive statistical formulas to find the Bellman equation and used it to teach an AI how to play a simple game. Notice that in this game, the number of possible states is finite (the number of different cells you might end up in), which is why building a Q-Table (a table of values that approaches the real value of the Q function for discrete values) is still manageable. What about a graphical game, such as Flappy Bird, Mario Bros, or Call Of Duty ? Every frame displayed by the game can be considered as a different state. In that case it’s impossible to build a Q-Table, and what we do instead is use a neural network who’s goal will be to learn the Q function. That neural network will typically take as input the current state of the game, and output the best possible action to take in that state. This is known as Deep Q Learning and is exactly how AIs such as Deep Blue or Alpha Go managed to beat world champions at Chess or Go.
[ { "code": null, "e": 539, "s": 171, "text": "Q-Learning is a type of Reinforcement Learning which is a type of Machine Learning. Reinforcement learning has been used lately (typically) to teach an AI to play a game (Google DeepMind Atari, etc). Our goal is to understand a simple version of Reinforcement learning called Q-Learning, and write a program that will learn how to play a simple “game”. Let’s dive in!" }, { "code": null, "e": 642, "s": 539, "text": "A Markov chain is a mathematical model that experiences transition of states with probabilistic rules." }, { "code": null, "e": 794, "s": 642, "text": "Here we have two states E and A, and the probabilities of going from one state to another (e.g. 70% chance of going to state A, starting from state E)." }, { "code": null, "e": 1131, "s": 794, "text": "A Markov Decision Process (MDP) is an extension of the Markov chain and it is used to model more complex environments. In this extension, we add the possibility to make a choice at every state which is called an action. We also add a reward which is a feedback from the environment for going from one state to another taking one action." }, { "code": null, "e": 1533, "s": 1131, "text": "In the image above, we are in the initial state don’t understand, where we have two possible actions, study and don’t study. For the study action, we may end up in different states according to a probabilistic rule. This is what we call a stochastic environment (random), in the sense that for one same action taken in the same state, we might have different results (understand and don’t understand)." }, { "code": null, "e": 1678, "s": 1533, "text": "In reinforcement learning, this is how we model a game or environment, and our goal will be to maximize the reward we get from that environment." }, { "code": null, "e": 1904, "s": 1678, "text": "The reward is the feedback from the environment that tells us how good we are doing. It can be the number of coins you grab in a game for example. Our goal is to maximize the total reward. Therefore, we need to write it down." }, { "code": null, "e": 1974, "s": 1904, "text": "This is the total reward we can get starting at some point t in time." }, { "code": null, "e": 2364, "s": 1974, "text": "For example, if we use the MDP presented above. We’re initially in the state don’t understand, we take the study action which takes us randomly to don’t understand. Therefore we experienced the reward r(t+1)=-1. Now we can decide to take another action which will give r(t+2) and so on. The total reward is the sum of all the immediate rewards we get for taking actions in the environment." }, { "code": null, "e": 2423, "s": 2364, "text": "Defining the reward this way leads to two major problems :" }, { "code": null, "e": 2519, "s": 2423, "text": "This sum can potentially go to infinity, which doesn’t make sense since we want to maximize it." }, { "code": null, "e": 2596, "s": 2519, "text": "We are accounting as much for future rewards as we do for immediate rewards." }, { "code": null, "e": 2679, "s": 2596, "text": "One way to fix up these problems is to use a decreasing factor for future rewards." }, { "code": null, "e": 2988, "s": 2679, "text": "Setting γ=1 takes us back to the first expression where every reward is equally important. Setting γ=0 results in only looking for the immediate reward (always acting for the optimal next step). Setting γ between 0 and 1 is a compromise to look more for immediate reward but still account for future rewards." }, { "code": null, "e": 3073, "s": 2988, "text": "We can rewrite that expression in a recursive manner, that will come handy later on." }, { "code": null, "e": 3313, "s": 3073, "text": "A policy is a function that tells what action to take when in a certain state. This function is usually denoted π(s,a) and yields the probability of taking action a in state s. We want to find the policy that maximizes the reward function." }, { "code": null, "e": 3467, "s": 3313, "text": "If we get back to the previous MDP for example, the policy can tell you the probability of taking action study when you’re in the state don’t understand." }, { "code": null, "e": 3579, "s": 3467, "text": "Moreover, because this is a probability distribution, the sum over all the possible actions must be equal to 1." }, { "code": null, "e": 3686, "s": 3579, "text": "We are going to start playing around with some equations, and for that we need to introduce new notations." }, { "code": null, "e": 3777, "s": 3686, "text": "This is the expected immediate reward for going from state s to state s’ through action a." }, { "code": null, "e": 3864, "s": 3777, "text": "This is the transition probability of going from state s to state s’ through action a." }, { "code": null, "e": 3882, "s": 3864, "text": "In this example :" }, { "code": null, "e": 4018, "s": 3882, "text": "The expected immediate reward for going from state don’t understand to state don’t understand through action don’t study is equal to 0." }, { "code": null, "e": 4129, "s": 4018, "text": "The probability of going from state don’t understand to state understand through action study is equal to 80%." }, { "code": null, "e": 4344, "s": 4129, "text": "Two so-called “value functions” exist. The state value function, and the action value function. These functions are a way to measure the “value”, or how good some state is, or how good some action is, respectively." }, { "code": null, "e": 4491, "s": 4344, "text": "The value of a state is the expected total reward we can get starting from that state. It depends on the policy which tells how to take decisions." }, { "code": null, "e": 4655, "s": 4491, "text": "The value of an action taken in some state is the expected total reward we can get, starting from that state and taking that action. It also depends on the policy." }, { "code": null, "e": 4826, "s": 4655, "text": "Now that we are settled with notations we can finally start playing around with the math! Looking at the following diagram during the calculation can help you understand." }, { "code": null, "e": 4912, "s": 4826, "text": "We will start by expanding the state value function. The expected operator is linear." }, { "code": null, "e": 4959, "s": 4912, "text": "Next, we can expand the action value function." }, { "code": null, "e": 5295, "s": 4959, "text": "This form of the Q-Value is very generic. It handles stochastic environments, but we could write it in a deterministic one. Meaning, whenever you take an action you always end up in the same next state and receive the same reward. In that case, we simply do not need to make a weighted sum with probabilities, and the equation becomes:" }, { "code": null, "e": 5396, "s": 5295, "text": "Where s’ is the state you end up in for taking action a in state s. Written, more formally, this is:" }, { "code": null, "e": 5543, "s": 5396, "text": "You probably already came across greedy policy reading on the internet. A greedy policy is a policy where you always choose the optimal next step." }, { "code": null, "e": 5651, "s": 5543, "text": "In a greedy policy context, we can write a relation between the state value and the action value functions." }, { "code": null, "e": 5808, "s": 5651, "text": "Therefore, plugging this into the previous equation, we get the Q-Value of a (state, action) pair in a deterministic environment, following a greedy policy." }, { "code": null, "e": 5819, "s": 5808, "text": "Or simply," }, { "code": null, "e": 6067, "s": 5819, "text": "And this is the Bellman equation in the Q-Learning context ! It tells that the value of an action a in some state s is the immediate reward you get for taking that action, to which you add the maximum expected reward you can get in the next state." }, { "code": null, "e": 6115, "s": 6067, "text": "It actually makes sens when you think about it." }, { "code": null, "e": 6260, "s": 6115, "text": "Here, if you only look at the immediate reward, you surely choose to go left. Unfortunately, the game ends after and you cannot get more points." }, { "code": null, "e": 6489, "s": 6260, "text": "If you add the maximum expected reward of the next state, then you will most probably go to the right since the maximum expected reward of S1 is equal to zero and the maximum expected reward of S2 is probably higher than 10–5=5." }, { "code": null, "e": 6557, "s": 6489, "text": "You can also tweak γ to specify how important are the next rewards." }, { "code": null, "e": 6741, "s": 6557, "text": "Here is a simple environment which consists of a 5-by-5 grid. A treasure (T) is placed at the bottom right corner of the grid. The agent (O) starts at the top left corner of the grid." }, { "code": null, "e": 6767, "s": 6741, "text": "O.......................T" }, { "code": null, "e": 6861, "s": 6767, "text": "The agent needs to get to the treasure using the 4 available actions : left, right, up, down." }, { "code": null, "e": 6968, "s": 6861, "text": "If the agent takes an action that leads him directly to T, he gets a reward of 1, otherwise a reward of 0." }, { "code": null, "e": 7089, "s": 6968, "text": "The code is well commented and it is simply what we just discussed. Now the interesting part, the Q-Learning algorithm !" }, { "code": null, "e": 7185, "s": 7089, "text": "I almost commented every single line of this code, so hopefully, it will be easy to understand!" }, { "code": null, "e": 7246, "s": 7185, "text": "Put both of the above files in the same directory, and run :" }, { "code": null, "e": 7277, "s": 7246, "text": "python3 medium_qlearning_rl.py" }, { "code": null, "e": 7401, "s": 7277, "text": "Around the epoch number 40, the agent should have learned to get to the treasure using one of the shortest paths (8 steps)." } ]
The Simplest Data Science Project Using Pandas & Matplotlib | by Shivangi Sareen | Towards Data Science
We try so hard to find the perfect dataset to test out and improve our skills. But the truth is that no dataset is perfect. You make it perfect or at least improve it by preprocessing the data — an essential part of any data related project. So, just pick up any dataset and get working! I experimented and the journey was nothing short of fun and full of learning. All of the code below was implemented in Jupyter Notebook. I got a hold of a dataset (from Kaggle) of forest fires in Brazil, which houses the largest rainforest on Earth — Amazon. I didn’t want to be picky and so this dataset was a complete random choice. About the data: year is the year when the forest fire happened;state is the Brazilian state;month is the month when the forest fire happened;number is the number of forest fires reported;date is the date when the forest fire was reported Going through the csv file (amazon.csv), you notice that some numbers are in decimal. 2.588 numbers of forest fires doesn't make sense. That's because the decimal is how thousands are formatted. So, 2.588 means 2588 forest fires. This can easily be accounted for when reading the csv file. You’ll also notice that the month column is in Portuguese. There's an upcoming fix for that too. When I imported the file for the first time after downloading it, I got an error: UnicodeDecodeError: 'utf-8' codec can't decode byte in position : invalid continuation byte. To fix it, I opened the csv in Sublime Text and: Save with Encoding -> UTF-8. However, this caused errors in the date column. So, I simply opened up the original csv and exported it as csv. Weird but it worked. For this project, I set up a virtual environment using virtualenv. Check out this post for all the steps. We’re using three major libraries: pandas, matplotlib, googletrans.!pip3 install the these packages (if you haven’t already) before importing them. import syssys.path.insert(1, './lib/python3.7/site-packages')import pandas as pdimport googletransimport matplotlib.pyplot as plt; plt.rcdefaults() The sys.path.insert step is done to make sure that the virtual environment’s site-packages directory is included in the system path. Read more about it in this python virtual environment post. Make sure amazon.csv is in your working directory. data = pd.read_csv("amazon.csv", thousands = '.') The thousands = "." parameter makes up for the decimal formatting. data.shape data.head() data.describe(include= "all") Gives a nice summary of the data. Such as the count of all the columns, the highest occurring value in each column (if applicable) and its frequency. data.isna().sum() None? Great! The first thought I had was to visualise the number of forest fires over the years, over the months. You need to be able to identify smaller pieces of the bigger picture. Let’s drop rows from the dataset that aren’t contributing to the number of forest fires. So, any row with number column value as 0, must be dropped. We first convert the 0s to NaN and then drop rows with NaN in the specific column number. data = data.replace(0, np.nan)data2 = data.dropna(subset=['number']) Our dataset is now reduced from 6454 to 5837 rows. data2.describe(include= "all") forest_fire_per_month = data2.groupby('month')['number'].sum() : grouping the data by month and summing the numbers. The output is a pandas series. print(forest_fire_per_month) : we notice the result is in alphabetical order. To get it back to the monthly order, we use the reindex property of dataframes : forest_fire_per_month = forest_fire_per_month.reindex(months_unique, axis=0) where, months_unique = list(data.month.unique()) Next we convert the series into a dataframe by: forest_fire_per_month = forest_fire_per_month.to_frame() forest_fire_per_month.head() This doesn’t look right. That’s because month is being considered as the index of the dataframe. To set a default index:forest_fire_per_month.reset_index(level=0, inplace=True) forest_fire_per_month.head() googletrans is a python library that implements Google Translate API. I tested it out on months_unique. translator = Translator() #create an object of Translator for month in months_unique: detected = translator.detect(month) translated = translator.translate(month) print(detected) print(translated) print("...") Member variables of the returned Translator() object: src — source language (default: auto) dest — destination language (default: en) origin — original text text — translated text pronunciation — pronunciation These variables can be individually accessed using the . operator. Example: translated.text will output the translated English text. We use an instance of Translator to translate the month column in forest_fire_per_month to English. translator2 = Translator() #create a new object of Translator. #cannot use the one defined before as that contains the latest #month’s calculated valuefor i, m in enumerate(forest_fire_per_month['month']): translated = translator2.translate(m) month1 = translated.text forest_fire_per_month.at[i, 'month'] = month1 The enumerate() function assigns an index to each item in an iterable object that can be used to reference the item later.The enumerate() function in Python is commonly used instead of the for loop. That’s because enumerate() can iterate over the index of an item, as well as the item itself. print(forest_fire_per_month) It worked on all but one case! Let’s bar graph it. plt.figure(figsize=(25, 15)) #specify width and height #plt.bar(x-values, y-values) plt.bar(forest_fire_per_month['month'],forest_fire_per_month['number'], color = (0.5,0.1,0.5,0.6)) #use .suptitle for the actual title and .title for the subheadingplt.suptitle('Amazon Forest Fires Over the Months', fontsize=20) plt.title('Using Data from Years 1998 - 2017', fontsize=20) plt.xlabel('Month', fontsize=20) plt.ylabel('Number of Forest Fires', fontsize=20)#plt.text(x-coordinate, y-coordinate, valueOfText, alignmnet)#this adds text at the top of each bar indicating its valuefor i, num in enumerate(forest_fire_per_month['number']): plt.text( i, num + 10000, num, ha='center', fontsize=15) #plt.setp is to set a property on an artist object.#plt.gca() gets the current axes (gca) instance on the current figure #matching the given keyword args.#xticklabels and yticklabels are nothing but the values of the #lables on the x and y axis.#The code below lets us set the fontsize and alignment of the x and #y axis tick labelsplt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right', fontsize=20)plt.setp(plt.gca().get_yticklabels(), fontsize=20) The output: This is a very small documentation of what can be done with this dataset. You only need to start. And the process is full of learning new things. So, just download a random dataset and get going! Super helpful resources: For googletrans For looping with enumerate()
[ { "code": null, "e": 414, "s": 172, "text": "We try so hard to find the perfect dataset to test out and improve our skills. But the truth is that no dataset is perfect. You make it perfect or at least improve it by preprocessing the data — an essential part of any data related project." }, { "code": null, "e": 538, "s": 414, "text": "So, just pick up any dataset and get working! I experimented and the journey was nothing short of fun and full of learning." }, { "code": null, "e": 597, "s": 538, "text": "All of the code below was implemented in Jupyter Notebook." }, { "code": null, "e": 795, "s": 597, "text": "I got a hold of a dataset (from Kaggle) of forest fires in Brazil, which houses the largest rainforest on Earth — Amazon. I didn’t want to be picky and so this dataset was a complete random choice." }, { "code": null, "e": 811, "s": 795, "text": "About the data:" }, { "code": null, "e": 1033, "s": 811, "text": "year is the year when the forest fire happened;state is the Brazilian state;month is the month when the forest fire happened;number is the number of forest fires reported;date is the date when the forest fire was reported" }, { "code": null, "e": 1323, "s": 1033, "text": "Going through the csv file (amazon.csv), you notice that some numbers are in decimal. 2.588 numbers of forest fires doesn't make sense. That's because the decimal is how thousands are formatted. So, 2.588 means 2588 forest fires. This can easily be accounted for when reading the csv file." }, { "code": null, "e": 1420, "s": 1323, "text": "You’ll also notice that the month column is in Portuguese. There's an upcoming fix for that too." }, { "code": null, "e": 1806, "s": 1420, "text": "When I imported the file for the first time after downloading it, I got an error: UnicodeDecodeError: 'utf-8' codec can't decode byte in position : invalid continuation byte. To fix it, I opened the csv in Sublime Text and: Save with Encoding -> UTF-8. However, this caused errors in the date column. So, I simply opened up the original csv and exported it as csv. Weird but it worked." }, { "code": null, "e": 2060, "s": 1806, "text": "For this project, I set up a virtual environment using virtualenv. Check out this post for all the steps. We’re using three major libraries: pandas, matplotlib, googletrans.!pip3 install the these packages (if you haven’t already) before importing them." }, { "code": null, "e": 2209, "s": 2060, "text": "import syssys.path.insert(1, './lib/python3.7/site-packages')import pandas as pdimport googletransimport matplotlib.pyplot as plt; plt.rcdefaults() " }, { "code": null, "e": 2402, "s": 2209, "text": "The sys.path.insert step is done to make sure that the virtual environment’s site-packages directory is included in the system path. Read more about it in this python virtual environment post." }, { "code": null, "e": 2453, "s": 2402, "text": "Make sure amazon.csv is in your working directory." }, { "code": null, "e": 2503, "s": 2453, "text": "data = pd.read_csv(\"amazon.csv\", thousands = '.')" }, { "code": null, "e": 2570, "s": 2503, "text": "The thousands = \".\" parameter makes up for the decimal formatting." }, { "code": null, "e": 2581, "s": 2570, "text": "data.shape" }, { "code": null, "e": 2593, "s": 2581, "text": "data.head()" }, { "code": null, "e": 2623, "s": 2593, "text": "data.describe(include= \"all\")" }, { "code": null, "e": 2773, "s": 2623, "text": "Gives a nice summary of the data. Such as the count of all the columns, the highest occurring value in each column (if applicable) and its frequency." }, { "code": null, "e": 2791, "s": 2773, "text": "data.isna().sum()" }, { "code": null, "e": 2804, "s": 2791, "text": "None? Great!" }, { "code": null, "e": 2975, "s": 2804, "text": "The first thought I had was to visualise the number of forest fires over the years, over the months. You need to be able to identify smaller pieces of the bigger picture." }, { "code": null, "e": 3214, "s": 2975, "text": "Let’s drop rows from the dataset that aren’t contributing to the number of forest fires. So, any row with number column value as 0, must be dropped. We first convert the 0s to NaN and then drop rows with NaN in the specific column number." }, { "code": null, "e": 3283, "s": 3214, "text": "data = data.replace(0, np.nan)data2 = data.dropna(subset=['number'])" }, { "code": null, "e": 3334, "s": 3283, "text": "Our dataset is now reduced from 6454 to 5837 rows." }, { "code": null, "e": 3365, "s": 3334, "text": "data2.describe(include= \"all\")" }, { "code": null, "e": 3513, "s": 3365, "text": "forest_fire_per_month = data2.groupby('month')['number'].sum() : grouping the data by month and summing the numbers. The output is a pandas series." }, { "code": null, "e": 3672, "s": 3513, "text": "print(forest_fire_per_month) : we notice the result is in alphabetical order. To get it back to the monthly order, we use the reindex property of dataframes :" }, { "code": null, "e": 3750, "s": 3672, "text": "forest_fire_per_month = forest_fire_per_month.reindex(months_unique, axis=0) " }, { "code": null, "e": 3757, "s": 3750, "text": "where," }, { "code": null, "e": 3799, "s": 3757, "text": "months_unique = list(data.month.unique())" }, { "code": null, "e": 3904, "s": 3799, "text": "Next we convert the series into a dataframe by: forest_fire_per_month = forest_fire_per_month.to_frame()" }, { "code": null, "e": 3933, "s": 3904, "text": "forest_fire_per_month.head()" }, { "code": null, "e": 4110, "s": 3933, "text": "This doesn’t look right. That’s because month is being considered as the index of the dataframe. To set a default index:forest_fire_per_month.reset_index(level=0, inplace=True)" }, { "code": null, "e": 4139, "s": 4110, "text": "forest_fire_per_month.head()" }, { "code": null, "e": 4243, "s": 4139, "text": "googletrans is a python library that implements Google Translate API. I tested it out on months_unique." }, { "code": null, "e": 4489, "s": 4243, "text": "translator = Translator() #create an object of Translator for month in months_unique: detected = translator.detect(month) translated = translator.translate(month) print(detected) print(translated) print(\"...\")" }, { "code": null, "e": 4543, "s": 4489, "text": "Member variables of the returned Translator() object:" }, { "code": null, "e": 4581, "s": 4543, "text": "src — source language (default: auto)" }, { "code": null, "e": 4623, "s": 4581, "text": "dest — destination language (default: en)" }, { "code": null, "e": 4646, "s": 4623, "text": "origin — original text" }, { "code": null, "e": 4669, "s": 4646, "text": "text — translated text" }, { "code": null, "e": 4699, "s": 4669, "text": "pronunciation — pronunciation" }, { "code": null, "e": 4766, "s": 4699, "text": "These variables can be individually accessed using the . operator." }, { "code": null, "e": 4832, "s": 4766, "text": "Example: translated.text will output the translated English text." }, { "code": null, "e": 4932, "s": 4832, "text": "We use an instance of Translator to translate the month column in forest_fire_per_month to English." }, { "code": null, "e": 5262, "s": 4932, "text": "translator2 = Translator() #create a new object of Translator. #cannot use the one defined before as that contains the latest #month’s calculated valuefor i, m in enumerate(forest_fire_per_month['month']): translated = translator2.translate(m) month1 = translated.text forest_fire_per_month.at[i, 'month'] = month1" }, { "code": null, "e": 5555, "s": 5262, "text": "The enumerate() function assigns an index to each item in an iterable object that can be used to reference the item later.The enumerate() function in Python is commonly used instead of the for loop. That’s because enumerate() can iterate over the index of an item, as well as the item itself." }, { "code": null, "e": 5584, "s": 5555, "text": "print(forest_fire_per_month)" }, { "code": null, "e": 5615, "s": 5584, "text": "It worked on all but one case!" }, { "code": null, "e": 5635, "s": 5615, "text": "Let’s bar graph it." }, { "code": null, "e": 6865, "s": 5635, "text": "plt.figure(figsize=(25, 15)) #specify width and height #plt.bar(x-values, y-values) plt.bar(forest_fire_per_month['month'],forest_fire_per_month['number'], color = (0.5,0.1,0.5,0.6)) #use .suptitle for the actual title and .title for the subheadingplt.suptitle('Amazon Forest Fires Over the Months', fontsize=20) plt.title('Using Data from Years 1998 - 2017', fontsize=20) plt.xlabel('Month', fontsize=20) plt.ylabel('Number of Forest Fires', fontsize=20)#plt.text(x-coordinate, y-coordinate, valueOfText, alignmnet)#this adds text at the top of each bar indicating its valuefor i, num in enumerate(forest_fire_per_month['number']): plt.text( i, num + 10000, num, ha='center', fontsize=15) #plt.setp is to set a property on an artist object.#plt.gca() gets the current axes (gca) instance on the current figure #matching the given keyword args.#xticklabels and yticklabels are nothing but the values of the #lables on the x and y axis.#The code below lets us set the fontsize and alignment of the x and #y axis tick labelsplt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right', fontsize=20)plt.setp(plt.gca().get_yticklabels(), fontsize=20)" }, { "code": null, "e": 6877, "s": 6865, "text": "The output:" }, { "code": null, "e": 7023, "s": 6877, "text": "This is a very small documentation of what can be done with this dataset. You only need to start. And the process is full of learning new things." }, { "code": null, "e": 7073, "s": 7023, "text": "So, just download a random dataset and get going!" }, { "code": null, "e": 7098, "s": 7073, "text": "Super helpful resources:" }, { "code": null, "e": 7114, "s": 7098, "text": "For googletrans" } ]
Redux - Store
A store is an immutable object tree in Redux. A store is a state container which holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer. Let us see how we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below − import { createStore } from 'redux'; import reducer from './reducers/reducer' const store = createStore(reducer); A createStore function can have three arguments. The following is the syntax − createStore(reducer, [preloadedState], [enhancer]) A reducer is a function that returns the next state of app. A preloadedState is an optional argument and is the initial state of your app. An enhancer is also an optional argument. It will help you enhance store with third-party capabilities. A store has three important methods as given below − It helps you retrieve the current state of your Redux store. The syntax for getState is as follows − store.getState() It allows you to dispatch an action to change a state in your application. The syntax for dispatch is as follows − store.dispatch({type:'ITEMS_REQUEST'}) It helps you register a callback that Redux store will call when an action has been dispatched. As soon as the Redux state has been updated, the view will re-render automatically. The syntax for dispatch is as follows − store.subscribe(()=>{ console.log(store.getState());}) Note that subscribe function returns a function for unsubscribing the listener. To unsubscribe the listener, we can use the below code − const unsubscribe = store.subscribe(()=>{console.log(store.getState());}); unsubscribe(); 56 Lectures 12.5 hours Eduonix Learning Solutions 63 Lectures 9.5 hours TELCOMA Global 129 Lectures 19.5 hours Ghulam Abbas 31 Lectures 3 hours Saumitra Vishal 55 Lectures 4 hours Saumitra Vishal Print Add Notes Bookmark this page
[ { "code": null, "e": 2054, "s": 1815, "text": "A store is an immutable object tree in Redux. A store is a state container which holds the application’s state. Redux can have only a single store in your application. Whenever a store is created in Redux, you need to specify the reducer." }, { "code": null, "e": 2256, "s": 2054, "text": "Let us see how we can create a store using the createStore method from Redux. One need to import the createStore package from the Redux library that supports the store creation process as shown below −" }, { "code": null, "e": 2371, "s": 2256, "text": "import { createStore } from 'redux';\nimport reducer from './reducers/reducer'\nconst store = createStore(reducer);\n" }, { "code": null, "e": 2450, "s": 2371, "text": "A createStore function can have three arguments. The following is the syntax −" }, { "code": null, "e": 2502, "s": 2450, "text": "createStore(reducer, [preloadedState], [enhancer])\n" }, { "code": null, "e": 2745, "s": 2502, "text": "A reducer is a function that returns the next state of app. A preloadedState is an optional argument and is the initial state of your app. An enhancer is also an optional argument. It will help you enhance store with third-party capabilities." }, { "code": null, "e": 2798, "s": 2745, "text": "A store has three important methods as given below −" }, { "code": null, "e": 2859, "s": 2798, "text": "It helps you retrieve the current state of your Redux store." }, { "code": null, "e": 2899, "s": 2859, "text": "The syntax for getState is as follows −" }, { "code": null, "e": 2917, "s": 2899, "text": "store.getState()\n" }, { "code": null, "e": 2992, "s": 2917, "text": "It allows you to dispatch an action to change a state in your application." }, { "code": null, "e": 3032, "s": 2992, "text": "The syntax for dispatch is as follows −" }, { "code": null, "e": 3072, "s": 3032, "text": "store.dispatch({type:'ITEMS_REQUEST'})\n" }, { "code": null, "e": 3252, "s": 3072, "text": "It helps you register a callback that Redux store will call when an action has been dispatched. As soon as the Redux state has been updated, the view will re-render automatically." }, { "code": null, "e": 3292, "s": 3252, "text": "The syntax for dispatch is as follows −" }, { "code": null, "e": 3348, "s": 3292, "text": "store.subscribe(()=>{ console.log(store.getState());})\n" }, { "code": null, "e": 3485, "s": 3348, "text": "Note that subscribe function returns a function for unsubscribing the listener. To unsubscribe the listener, we can use the below code −" }, { "code": null, "e": 3576, "s": 3485, "text": "const unsubscribe = store.subscribe(()=>{console.log(store.getState());});\nunsubscribe();\n" }, { "code": null, "e": 3612, "s": 3576, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3640, "s": 3612, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3675, "s": 3640, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 3691, "s": 3675, "text": " TELCOMA Global" }, { "code": null, "e": 3728, "s": 3691, "text": "\n 129 Lectures \n 19.5 hours \n" }, { "code": null, "e": 3742, "s": 3728, "text": " Ghulam Abbas" }, { "code": null, "e": 3775, "s": 3742, "text": "\n 31 Lectures \n 3 hours \n" }, { "code": null, "e": 3792, "s": 3775, "text": " Saumitra Vishal" }, { "code": null, "e": 3825, "s": 3792, "text": "\n 55 Lectures \n 4 hours \n" }, { "code": null, "e": 3842, "s": 3825, "text": " Saumitra Vishal" }, { "code": null, "e": 3849, "s": 3842, "text": " Print" }, { "code": null, "e": 3860, "s": 3849, "text": " Add Notes" } ]
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming - GeeksforGeeks
08 Feb, 2022 getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example: Input: g C++ C // C++ program to demonstrate// working of getchar_unlocked()#include <iostream>using namespace std; int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); cout << "Entered character is " << c; return 0;} // This code is contributed by SUBHAMSINGH10. // C program to demonstrate// working of getchar_unlocked()#include <stdio.h>int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); printf("Entered character is %c", c); return 0;} Output Entered character is g Following are Some Important Points: Since it is not thread-safe, all overheads of mutual exclusion are avoided and it is faster than getchar().Can be especially useful for competitive programming problems with “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”.There is no issue with using getchar_unlocked() even in a multithreaded environment as long as the thread using it is the only thread accessing file objectOne more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows-based compilers.It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all.Similarly, there are getc_unlocked() putc_unlocked(), and putchar_unlocked() which are non-thread-safe versions of getc(), putc() and putchar() respectively. Since it is not thread-safe, all overheads of mutual exclusion are avoided and it is faster than getchar(). Can be especially useful for competitive programming problems with “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”. There is no issue with using getchar_unlocked() even in a multithreaded environment as long as the thread using it is the only thread accessing file object One more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows-based compilers. It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all. Similarly, there are getc_unlocked() putc_unlocked(), and putchar_unlocked() which are non-thread-safe versions of getc(), putc() and putchar() respectively. Example: Input: g C++ C // C++ program to demonstrate// working of putchar_unlocked()#include <iostream>using namespace std;int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); putchar_unlocked(c); return 0;} //This code is contributed by Shubham Singh // C program to demonstrate// working of putchar_unlocked()#include <stdio.h>int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); putchar_unlocked(c); return 0;} Output g As an exercise, the readers may try solutions given here with getchar_unlocked() and compare performance with getchar(). This article is contributed by Ayush Saluja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 SHUBHAMSINGH10 cpp-input-output CPP-Library C Language C++ Competitive Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments fork() in C Command line arguments in C/C++ Substring in C++ Function Pointer in C TCP Server-Client implementation in C Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24437, "s": 24409, "text": "\n08 Feb, 2022" }, { "code": null, "e": 24742, "s": 24437, "text": "getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile()." }, { "code": null, "e": 24750, "s": 24742, "text": "Syntax:" }, { "code": null, "e": 24778, "s": 24750, "text": "int getchar_unlocked(void);" }, { "code": null, "e": 24787, "s": 24778, "text": "Example:" }, { "code": null, "e": 24796, "s": 24787, "text": "Input: g" }, { "code": null, "e": 24800, "s": 24796, "text": "C++" }, { "code": null, "e": 24802, "s": 24800, "text": "C" }, { "code": "// C++ program to demonstrate// working of getchar_unlocked()#include <iostream>using namespace std; int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); cout << \"Entered character is \" << c; return 0;} // This code is contributed by SUBHAMSINGH10.", "e": 25084, "s": 24802, "text": null }, { "code": "// C program to demonstrate// working of getchar_unlocked()#include <stdio.h>int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); printf(\"Entered character is %c\", c); return 0;}", "e": 25296, "s": 25084, "text": null }, { "code": null, "e": 25303, "s": 25296, "text": "Output" }, { "code": null, "e": 25327, "s": 25303, "text": "Entered character is g " }, { "code": null, "e": 25365, "s": 25327, "text": "Following are Some Important Points: " }, { "code": null, "e": 26285, "s": 25365, "text": "Since it is not thread-safe, all overheads of mutual exclusion are avoided and it is faster than getchar().Can be especially useful for competitive programming problems with “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”.There is no issue with using getchar_unlocked() even in a multithreaded environment as long as the thread using it is the only thread accessing file objectOne more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows-based compilers.It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all.Similarly, there are getc_unlocked() putc_unlocked(), and putchar_unlocked() which are non-thread-safe versions of getc(), putc() and putchar() respectively." }, { "code": null, "e": 26393, "s": 26285, "text": "Since it is not thread-safe, all overheads of mutual exclusion are avoided and it is faster than getchar()." }, { "code": null, "e": 26583, "s": 26393, "text": "Can be especially useful for competitive programming problems with “Warning: Large I/O data, be careful with certain languages (though most should be OK if the algorithm is well designed)”." }, { "code": null, "e": 26739, "s": 26583, "text": "There is no issue with using getchar_unlocked() even in a multithreaded environment as long as the thread using it is the only thread accessing file object" }, { "code": null, "e": 26885, "s": 26739, "text": "One more difference with getchar() is, it is not a C standard library function, but a POSIX function. It may not work on Windows-based compilers." }, { "code": null, "e": 27052, "s": 26885, "text": "It is a known fact that scanf() is faster than cin and getchar() is faster than scanf() in general. getchar_unlocked() is faster than getchar(), hence fastest of all." }, { "code": null, "e": 27210, "s": 27052, "text": "Similarly, there are getc_unlocked() putc_unlocked(), and putchar_unlocked() which are non-thread-safe versions of getc(), putc() and putchar() respectively." }, { "code": null, "e": 27219, "s": 27210, "text": "Example:" }, { "code": null, "e": 27228, "s": 27219, "text": "Input: g" }, { "code": null, "e": 27232, "s": 27228, "text": "C++" }, { "code": null, "e": 27234, "s": 27232, "text": "C" }, { "code": "// C++ program to demonstrate// working of putchar_unlocked()#include <iostream>using namespace std;int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); putchar_unlocked(c); return 0;} //This code is contributed by Shubham Singh", "e": 27496, "s": 27234, "text": null }, { "code": "// C program to demonstrate// working of putchar_unlocked()#include <stdio.h>int main(){ // Syntax is same as getchar() char c = getchar_unlocked(); putchar_unlocked(c); return 0;}", "e": 27691, "s": 27496, "text": null }, { "code": null, "e": 27698, "s": 27691, "text": "Output" }, { "code": null, "e": 27700, "s": 27698, "text": "g" }, { "code": null, "e": 27822, "s": 27700, "text": "As an exercise, the readers may try solutions given here with getchar_unlocked() and compare performance with getchar(). " }, { "code": null, "e": 27992, "s": 27822, "text": "This article is contributed by Ayush Saluja. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28006, "s": 27992, "text": "anshikajain26" }, { "code": null, "e": 28021, "s": 28006, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 28038, "s": 28021, "text": "cpp-input-output" }, { "code": null, "e": 28050, "s": 28038, "text": "CPP-Library" }, { "code": null, "e": 28061, "s": 28050, "text": "C Language" }, { "code": null, "e": 28065, "s": 28061, "text": "C++" }, { "code": null, "e": 28089, "s": 28065, "text": "Competitive Programming" }, { "code": null, "e": 28093, "s": 28089, "text": "CPP" }, { "code": null, "e": 28191, "s": 28093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28200, "s": 28191, "text": "Comments" }, { "code": null, "e": 28213, "s": 28200, "text": "Old Comments" }, { "code": null, "e": 28225, "s": 28213, "text": "fork() in C" }, { "code": null, "e": 28257, "s": 28225, "text": "Command line arguments in C/C++" }, { "code": null, "e": 28274, "s": 28257, "text": "Substring in C++" }, { "code": null, "e": 28296, "s": 28274, "text": "Function Pointer in C" }, { "code": null, "e": 28334, "s": 28296, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28352, "s": 28334, "text": "Vector in C++ STL" }, { "code": null, "e": 28398, "s": 28352, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28441, "s": 28398, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28460, "s": 28441, "text": "Inheritance in C++" } ]
BabylonJS - WireFrame
With wireframe, you get the skeleton of the 3D model with only lines and vertices. Let us now see how to apply wireframe for any shape. materialforbox.wireframe = true; <!doctype html> <html> <head> <meta charset = "utf-8"> <title>BabylonJs - Basic Element-Creating Scene</title> <script src = "babylon.js"></script> <style> canvas {width: 100%; height: 100%;} </style> </head> <body> <canvas id = "renderCanvas"></canvas> <script type = "text/javascript"> var canvas = document.getElementById("renderCanvas"); var engine = new BABYLON.Engine(canvas, true); var createScene = function() { var scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color3(0, 1, 0); scene.ambientColor = new BABYLON.Color3(0.3, 0.3, 0.3); var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene); camera.attachControl(canvas, true); var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene); light.intensity = 0.7; var materialforbox = new BABYLON.StandardMaterial("texture1", scene); var box = BABYLON.Mesh.CreateBox("box", '3', scene); box.material = materialforbox; materialforbox.wireframe = true; return scene; }; var scene = createScene(); engine.runRenderLoop(function() { scene.render(); }); </script> </body> </html> Print Add Notes Bookmark this page
[ { "code": null, "e": 2319, "s": 2183, "text": "With wireframe, you get the skeleton of the 3D model with only lines and vertices. Let us now see how to apply wireframe for any shape." }, { "code": null, "e": 2353, "s": 2319, "text": "materialforbox.wireframe = true;\n" }, { "code": null, "e": 3831, "s": 2353, "text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n\n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n \n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n scene.clearColor = new BABYLON.Color3(0, 1, 0);\n scene.ambientColor = new BABYLON.Color3(0.3, 0.3, 0.3);\n \n var camera = new BABYLON.ArcRotateCamera(\"Camera\", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);\n camera.attachControl(canvas, true);\n \n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(0, 1, 0), scene);\n light.intensity = 0.7;\t\n \n var materialforbox = new BABYLON.StandardMaterial(\"texture1\", scene);\n \n var box = BABYLON.Mesh.CreateBox(\"box\", '3', scene);\t\n box.material = materialforbox;\n materialforbox.wireframe = true;\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 3838, "s": 3831, "text": " Print" }, { "code": null, "e": 3849, "s": 3838, "text": " Add Notes" } ]
How to filter String list by starting value in Java?
Let’s first create a String list − List list = new ArrayList<>(); list.add("wxy"); list.add("zabc"); list.add("ddd2"); list.add("def"); list.add("ghi"); list.add("wer"); list.add("uij"); list.add("wqy"); To filter String list by starting value, use filter() and startsWith() − list.stream().filter((b) -> b.startsWith("w")) The following is an example to filter string list by starting value − import java.util.ArrayList; import java.util.List; public class Demo { public static void main(final String[] args) { List list = new ArrayList<>(); list.add("wxy"); list.add("zabc"); list.add("ddd2"); list.add("def"); list.add("ghi"); list.add("wer"); list.add("uij"); list.add("wqy"); System.out.println("List beginning with letter w = "); list.stream().filter((b) -> b.startsWith("w")) .forEach(System.out::println); } } List beginning with letter w = wxy wer wqy
[ { "code": null, "e": 1097, "s": 1062, "text": "Let’s first create a String list −" }, { "code": null, "e": 1266, "s": 1097, "text": "List list = new ArrayList<>();\nlist.add(\"wxy\");\nlist.add(\"zabc\");\nlist.add(\"ddd2\");\nlist.add(\"def\");\nlist.add(\"ghi\");\nlist.add(\"wer\");\nlist.add(\"uij\");\nlist.add(\"wqy\");" }, { "code": null, "e": 1339, "s": 1266, "text": "To filter String list by starting value, use filter() and startsWith() −" }, { "code": null, "e": 1386, "s": 1339, "text": "list.stream().filter((b) -> b.startsWith(\"w\"))" }, { "code": null, "e": 1456, "s": 1386, "text": "The following is an example to filter string list by starting value −" }, { "code": null, "e": 1958, "s": 1456, "text": "import java.util.ArrayList;\nimport java.util.List;\npublic class Demo {\n public static void main(final String[] args) {\n List list = new ArrayList<>();\n list.add(\"wxy\");\n list.add(\"zabc\");\n list.add(\"ddd2\");\n list.add(\"def\");\n list.add(\"ghi\");\n list.add(\"wer\");\n list.add(\"uij\");\n list.add(\"wqy\");\n System.out.println(\"List beginning with letter w = \");\n list.stream().filter((b) -> b.startsWith(\"w\"))\n .forEach(System.out::println);\n }\n}" }, { "code": null, "e": 2001, "s": 1958, "text": "List beginning with letter w =\nwxy\nwer\nwqy" } ]
Using networkD3 in R to create simple and clear Sankey diagrams | by Keith McNulty | Towards Data Science
I find Sankey diagrams super useful for illustrating flows of people or preferences. The networkD3 package in R offers a straightforward way to generate these diagrams without needing to know the ins and outs of the actual D3 code. To show you what I mean, I generated a Sankey diagram to show how the twelve regions of the UK contributed to the overall result of the 2016 Brexit referendum, where voters chose to leave the European Union by 17,410,742 votes to 16,141,241. If you want to see the fully interactive Sankey diagram for this, you can view the code via an RMarkdown document on RPubs here. Unfortunately only static images can be displayed on Medium. Very detailed data on the Brexit referendum can be obtained from the UK’s Electoral Commission website. The first step is to get our libraries loaded and to get the data into R. Since the data is very detailed down to the most localized voting centers, we need to aggregate all the Leave and Remain votes to get a total for each region. ## load librarieslibrary(dplyr)library(networkD3)library(tidyr)# read in EU referendum results datasetrefresults <- read.csv("EU-referendum-result-data.csv")# aggregate by regionresults <- refresults %>% dplyr::group_by(Region) %>% dplyr::summarise(Remain = sum(Remain), Leave = sum(Leave)) We then need to create two dataframes for use by networkD3 in its sankeyNetwork() function: A nodes dataframe which numbers the source nodes (ie the 12 UK regions) and the destination nodes (ie Leave and Remain), starting at zero.A links dataframe which itemized each flow using a source, target and value column. For example, the West Midlands region cast 1,755,687 votes for Leave, so in this case the source would by the node for West Midlands, the target would be the node for Leave and the value would be 1,755,687. A nodes dataframe which numbers the source nodes (ie the 12 UK regions) and the destination nodes (ie Leave and Remain), starting at zero. A links dataframe which itemized each flow using a source, target and value column. For example, the West Midlands region cast 1,755,687 votes for Leave, so in this case the source would by the node for West Midlands, the target would be the node for Leave and the value would be 1,755,687. Here is some simple code to build the data in this way: # format in prep for sankey diagramresults <- tidyr::gather(results, result, vote, -Region)# create nodes dataframeregions <- unique(as.character(results$Region))nodes <- data.frame(node = c(0:13), name = c(regions, "Leave", "Remain"))#create links dataframeresults <- merge(results, nodes, by.x = "Region", by.y = "name")results <- merge(results, nodes, by.x = "result", by.y = "name")links <- results[ , c("node.x", "node.y", "vote")]colnames(links) <- c("source", "target", "value") Now that we have our data constructed the right way, we can simply use the networkD3::sankeyNetwork() function to create the diagram. This produces a simple, effective diagram, with rollover interactivity displaying the details of each voting flow. The static version is presented here. # draw sankey networknetworkD3::sankeyNetwork(Links = links, Nodes = nodes, Source = 'source', Target = 'target', Value = 'value', NodeID = 'name', units = 'votes') Originally I was a Pure Mathematician, then I became a Psychometrician and a Data Scientist. I am passionate about applying the rigor of all those disciplines to complex people questions. I’m also a coding geek and a massive fan of Japanese RPGs. Find me on LinkedIn or on Twitter.
[ { "code": null, "e": 404, "s": 172, "text": "I find Sankey diagrams super useful for illustrating flows of people or preferences. The networkD3 package in R offers a straightforward way to generate these diagrams without needing to know the ins and outs of the actual D3 code." }, { "code": null, "e": 646, "s": 404, "text": "To show you what I mean, I generated a Sankey diagram to show how the twelve regions of the UK contributed to the overall result of the 2016 Brexit referendum, where voters chose to leave the European Union by 17,410,742 votes to 16,141,241." }, { "code": null, "e": 836, "s": 646, "text": "If you want to see the fully interactive Sankey diagram for this, you can view the code via an RMarkdown document on RPubs here. Unfortunately only static images can be displayed on Medium." }, { "code": null, "e": 1173, "s": 836, "text": "Very detailed data on the Brexit referendum can be obtained from the UK’s Electoral Commission website. The first step is to get our libraries loaded and to get the data into R. Since the data is very detailed down to the most localized voting centers, we need to aggregate all the Leave and Remain votes to get a total for each region." }, { "code": null, "e": 1468, "s": 1173, "text": "## load librarieslibrary(dplyr)library(networkD3)library(tidyr)# read in EU referendum results datasetrefresults <- read.csv(\"EU-referendum-result-data.csv\")# aggregate by regionresults <- refresults %>% dplyr::group_by(Region) %>% dplyr::summarise(Remain = sum(Remain), Leave = sum(Leave))" }, { "code": null, "e": 1560, "s": 1468, "text": "We then need to create two dataframes for use by networkD3 in its sankeyNetwork() function:" }, { "code": null, "e": 1989, "s": 1560, "text": "A nodes dataframe which numbers the source nodes (ie the 12 UK regions) and the destination nodes (ie Leave and Remain), starting at zero.A links dataframe which itemized each flow using a source, target and value column. For example, the West Midlands region cast 1,755,687 votes for Leave, so in this case the source would by the node for West Midlands, the target would be the node for Leave and the value would be 1,755,687." }, { "code": null, "e": 2128, "s": 1989, "text": "A nodes dataframe which numbers the source nodes (ie the 12 UK regions) and the destination nodes (ie Leave and Remain), starting at zero." }, { "code": null, "e": 2419, "s": 2128, "text": "A links dataframe which itemized each flow using a source, target and value column. For example, the West Midlands region cast 1,755,687 votes for Leave, so in this case the source would by the node for West Midlands, the target would be the node for Leave and the value would be 1,755,687." }, { "code": null, "e": 2475, "s": 2419, "text": "Here is some simple code to build the data in this way:" }, { "code": null, "e": 2981, "s": 2475, "text": "# format in prep for sankey diagramresults <- tidyr::gather(results, result, vote, -Region)# create nodes dataframeregions <- unique(as.character(results$Region))nodes <- data.frame(node = c(0:13), name = c(regions, \"Leave\", \"Remain\"))#create links dataframeresults <- merge(results, nodes, by.x = \"Region\", by.y = \"name\")results <- merge(results, nodes, by.x = \"result\", by.y = \"name\")links <- results[ , c(\"node.x\", \"node.y\", \"vote\")]colnames(links) <- c(\"source\", \"target\", \"value\")" }, { "code": null, "e": 3268, "s": 2981, "text": "Now that we have our data constructed the right way, we can simply use the networkD3::sankeyNetwork() function to create the diagram. This produces a simple, effective diagram, with rollover interactivity displaying the details of each voting flow. The static version is presented here." }, { "code": null, "e": 3557, "s": 3268, "text": "# draw sankey networknetworkD3::sankeyNetwork(Links = links, Nodes = nodes, Source = 'source', Target = 'target', Value = 'value', NodeID = 'name', units = 'votes')" } ]
Tryit Editor v3.7
Tryit: Responsive form
[]
A Time Complexity Question - GeeksforGeeks
27 Dec, 2021 What is the time complexity of following function fun()? Assume that log(x) returns log value in base 2. C++ C Java Python3 C# Javascript void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) cout << "GeeksforGeeks";} // This code is contributed by SHUBHAMSINGH10. void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) printf("GeeksforGeeks");} static void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) System.out.printf("GeeksforGeeks");} // This code is contributed by umadevi9616 import mathdef fun(): i = 0 j = 0 for i in range(1, n + 1): for j in range(1,math.log(i) + 1): print("GeeksforGeeks") # This code is contributed by SHUBHAMSINGH10. static void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) Console.Write("GeeksforGeeks");} // This code is contributed by umadevi9616 const fun(){ let i, j; for (i = 1; i <= n; i++) for (j = 1; j <= Math.log(i); j++) document.write("GeeksforGeeks");} // This code is contributed by SHUBHAMSINGH10. Time Complexity of the above function can be written as θ(log 1) + θ(log 2) + θ(log 3) + . . . . + θ(log n) which is θ(log n!)Order of growth of ‘log n!’ and ‘n log n’ is same for large values of n, i.e., θ(log n!) = θ(n log n). So time complexity of fun() is θ(n log n).The expression θ(log n!) = θ(n log n) can be easily derived from following Stirling’s approximation (or Stirling’s formula). log n! = n*log n - n = O(n*log(n)) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Sources: http://en.wikipedia.org/wiki/Stirling%27s_approximation vroghelia6 umadevi9616 SHUBHAMSINGH10 Analysis Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Analysis of different sorting techniques Analysis of Algorithms | Big-O analysis Analysis of Algorithms | Set 4 (Analysis of Loops) Difference between Big Oh, Big Omega and Big Theta Cyclomatic Complexity Time complexities of different data structures Complexity Analysis of Binary Search
[ { "code": null, "e": 24186, "s": 24158, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24292, "s": 24186, "text": "What is the time complexity of following function fun()? Assume that log(x) returns log value in base 2. " }, { "code": null, "e": 24296, "s": 24292, "text": "C++" }, { "code": null, "e": 24298, "s": 24296, "text": "C" }, { "code": null, "e": 24303, "s": 24298, "text": "Java" }, { "code": null, "e": 24311, "s": 24303, "text": "Python3" }, { "code": null, "e": 24314, "s": 24311, "text": "C#" }, { "code": null, "e": 24325, "s": 24314, "text": "Javascript" }, { "code": "void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) cout << \"GeeksforGeeks\";} // This code is contributed by SHUBHAMSINGH10.", "e": 24499, "s": 24325, "text": null }, { "code": "void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) printf(\"GeeksforGeeks\");}", "e": 24626, "s": 24499, "text": null }, { "code": "static void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) System.out.printf(\"GeeksforGeeks\");} // This code is contributed by umadevi9616", "e": 24814, "s": 24626, "text": null }, { "code": "import mathdef fun(): i = 0 j = 0 for i in range(1, n + 1): for j in range(1,math.log(i) + 1): print(\"GeeksforGeeks\") # This code is contributed by SHUBHAMSINGH10.", "e": 25005, "s": 24814, "text": null }, { "code": "static void fun(){ int i, j; for (i = 1; i <= n; i++) for (j = 1; j <= log(i); j++) Console.Write(\"GeeksforGeeks\");} // This code is contributed by umadevi9616", "e": 25189, "s": 25005, "text": null }, { "code": "const fun(){ let i, j; for (i = 1; i <= n; i++) for (j = 1; j <= Math.log(i); j++) document.write(\"GeeksforGeeks\");} // This code is contributed by SHUBHAMSINGH10.", "e": 25377, "s": 25189, "text": null }, { "code": null, "e": 25774, "s": 25377, "text": "Time Complexity of the above function can be written as θ(log 1) + θ(log 2) + θ(log 3) + . . . . + θ(log n) which is θ(log n!)Order of growth of ‘log n!’ and ‘n log n’ is same for large values of n, i.e., θ(log n!) = θ(n log n). So time complexity of fun() is θ(n log n).The expression θ(log n!) = θ(n log n) can be easily derived from following Stirling’s approximation (or Stirling’s formula). " }, { "code": null, "e": 25810, "s": 25774, "text": "log n! = n*log n - n = O(n*log(n)) " }, { "code": null, "e": 25999, "s": 25810, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.Sources: http://en.wikipedia.org/wiki/Stirling%27s_approximation" }, { "code": null, "e": 26010, "s": 25999, "text": "vroghelia6" }, { "code": null, "e": 26022, "s": 26010, "text": "umadevi9616" }, { "code": null, "e": 26037, "s": 26022, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 26046, "s": 26037, "text": "Analysis" }, { "code": null, "e": 26144, "s": 26046, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26153, "s": 26144, "text": "Comments" }, { "code": null, "e": 26166, "s": 26153, "text": "Old Comments" }, { "code": null, "e": 26217, "s": 26166, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 26254, "s": 26217, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 26337, "s": 26254, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 26378, "s": 26337, "text": "Analysis of different sorting techniques" }, { "code": null, "e": 26418, "s": 26378, "text": "Analysis of Algorithms | Big-O analysis" }, { "code": null, "e": 26469, "s": 26418, "text": "Analysis of Algorithms | Set 4 (Analysis of Loops)" }, { "code": null, "e": 26520, "s": 26469, "text": "Difference between Big Oh, Big Omega and Big Theta" }, { "code": null, "e": 26542, "s": 26520, "text": "Cyclomatic Complexity" }, { "code": null, "e": 26589, "s": 26542, "text": "Time complexities of different data structures" } ]
Difference between Context Free Grammar and Regular Grammar - GeeksforGeeks
31 May, 2021 Noam Chomsky has divided grammar into four types : Type Name 0 1 2 3 Chomsky Hierarchy 1. Context Free Grammar : Language generated by Context Free Grammar is accepted by Pushdown Automata It is a subset of Type 0 and Type 1 grammar and a superset of Type 3 grammar. Also called phase structured grammar. Different context-free grammars can generate the same context-free language. Classification of Context Free Grammar is done on the basis of the number of parse trees. Only one parse tree->Unambiguous. More than one parse tree->Ambiguous. Productions are in the form – A->B; A∈N i.e A is a non-terminal. B∈V*(Any string). Example – S –> AB A –> a B –> b 2. Regular Grammar : It is accepted by Finite State Automata. It is a subset of Type 0 ,Type 1 and Type 2 grammar. The language it generates is called Regular Language. Regular languages are closed under operations like Union, Intersection, Complement etc. They are the most restricted form of grammar. Productions are in the form – V –> VT / T (left-linear grammar) (or) V –> TV /T (right-linear grammar) Example – 1. S –> ab. 2. S -> aS | bS | ∊ Difference Between Context Free Grammar and Regular Grammar: GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Regular Expressions, Regular Grammar and Regular Languages Phases of a Compiler Difference between Clustered and Non-clustered index Preemptive and Non-Preemptive Scheduling Introduction of Process Synchronization Regular Expressions, Regular Grammar and Regular Languages Difference between DFA and NFA Pumping Lemma in Theory of Computation Introduction of Finite Automata Turing Machine in TOC
[ { "code": null, "e": 24450, "s": 24419, "text": " \n31 May, 2021\n" }, { "code": null, "e": 24501, "s": 24450, "text": "Noam Chomsky has divided grammar into four types :" }, { "code": null, "e": 24506, "s": 24501, "text": "Type" }, { "code": null, "e": 24511, "s": 24506, "text": "Name" }, { "code": null, "e": 24513, "s": 24511, "text": "0" }, { "code": null, "e": 24515, "s": 24513, "text": "1" }, { "code": null, "e": 24517, "s": 24515, "text": "2" }, { "code": null, "e": 24519, "s": 24517, "text": "3" }, { "code": null, "e": 24537, "s": 24519, "text": "Chomsky Hierarchy" }, { "code": null, "e": 24563, "s": 24537, "text": "1. Context Free Grammar :" }, { "code": null, "e": 24639, "s": 24563, "text": "Language generated by Context Free Grammar is accepted by Pushdown Automata" }, { "code": null, "e": 24717, "s": 24639, "text": "It is a subset of Type 0 and Type 1 grammar and a superset of Type 3 grammar." }, { "code": null, "e": 24755, "s": 24717, "text": "Also called phase structured grammar." }, { "code": null, "e": 24832, "s": 24755, "text": "Different context-free grammars can generate the same context-free language." }, { "code": null, "e": 24922, "s": 24832, "text": "Classification of Context Free Grammar is done on the basis of the number of parse trees." }, { "code": null, "e": 24956, "s": 24922, "text": "Only one parse tree->Unambiguous." }, { "code": null, "e": 24993, "s": 24956, "text": "More than one parse tree->Ambiguous." }, { "code": null, "e": 25023, "s": 24993, "text": "Productions are in the form –" }, { "code": null, "e": 25076, "s": 25023, "text": "A->B;\nA∈N i.e A is a non-terminal.\nB∈V*(Any string)." }, { "code": null, "e": 25086, "s": 25076, "text": "Example –" }, { "code": null, "e": 25108, "s": 25086, "text": "S –> AB\nA –> a\nB –> b" }, { "code": null, "e": 25129, "s": 25108, "text": "2. Regular Grammar :" }, { "code": null, "e": 25170, "s": 25129, "text": "It is accepted by Finite State Automata." }, { "code": null, "e": 25223, "s": 25170, "text": "It is a subset of Type 0 ,Type 1 and Type 2 grammar." }, { "code": null, "e": 25277, "s": 25223, "text": "The language it generates is called Regular Language." }, { "code": null, "e": 25365, "s": 25277, "text": "Regular languages are closed under operations like Union, Intersection, Complement etc." }, { "code": null, "e": 25411, "s": 25365, "text": "They are the most restricted form of grammar." }, { "code": null, "e": 25441, "s": 25411, "text": "Productions are in the form –" }, { "code": null, "e": 25516, "s": 25441, "text": "V –> VT / T (left-linear grammar)\n (or)\nV –> TV /T (right-linear grammar)" }, { "code": null, "e": 25526, "s": 25516, "text": "Example –" }, { "code": null, "e": 25560, "s": 25526, "text": "1. S –> ab. \n2. S -> aS | bS | ∊ " }, { "code": null, "e": 25621, "s": 25560, "text": "Difference Between Context Free Grammar and Regular Grammar:" }, { "code": null, "e": 25631, "s": 25621, "text": "\nGATE CS\n" }, { "code": null, "e": 25666, "s": 25631, "text": "\nTheory of Computation & Automata\n" }, { "code": null, "e": 25871, "s": 25666, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 25930, "s": 25871, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 25951, "s": 25930, "text": "Phases of a Compiler" }, { "code": null, "e": 26004, "s": 25951, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26045, "s": 26004, "text": "Preemptive and Non-Preemptive Scheduling" }, { "code": null, "e": 26085, "s": 26045, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 26144, "s": 26085, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 26175, "s": 26144, "text": "Difference between DFA and NFA" }, { "code": null, "e": 26214, "s": 26175, "text": "Pumping Lemma in Theory of Computation" }, { "code": null, "e": 26246, "s": 26214, "text": "Introduction of Finite Automata" } ]
Angular forms formatCurrency Directive - GeeksforGeeks
02 Jun, 2021 In this article, we are going to see what is formatCurrency in Angular 10 and how to use it. The formatCurrency is used to format a number as currency using locale rules. Syntax: formatCurrency(value, locale, currency, currencyCode, digitsInfo) Parameters: value: The number to format. locale: A locale code for the locale format. currency: A string containing the currency symbol or its name. currencyCode: the currency code. digitsInfo: Decimal representation options. Return Value: string: the formatted currency code. NgModule: Module used by formatCurrency is: CommonModule Approach: Create the Angular app to be used. In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatCurrency.import { LOCALE_ID, NgModule } from '@angular/core'; import { LOCALE_ID, NgModule } from '@angular/core'; In app.component.ts import formatCurrency and LOCALE_ID inject LOCALE_ID as a public variable. In app.component.html show the local variable using string interpolation Serve the angular app using ng serve to see the output. Example 1: app.component.ts import { formatCurrency } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatCurrency(10,this.locale, 'USD');constructor( @Inject(LOCALE_ID) public locale: string,){}} app.component.html <h1> GeeksforGeeks</h1> <p>Locale Currency is : {{curr}}</p> Output: Example 2: app.component.ts import { formatCurrency } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatCurrency(10,this.locale, 'INR');constructor( @Inject(LOCALE_ID) public locale: string,){}} app.component.html <h1> GeeksforGeeks</h1> <p>Locale Currency is : {{curr}}</p> Output: Reference: https://angular.io/api/common/formatCurrency Angular10 AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n02 Jun, 2021" }, { "code": null, "e": 26525, "s": 26354, "text": "In this article, we are going to see what is formatCurrency in Angular 10 and how to use it. The formatCurrency is used to format a number as currency using locale rules." }, { "code": null, "e": 26533, "s": 26525, "text": "Syntax:" }, { "code": null, "e": 26599, "s": 26533, "text": "formatCurrency(value, locale, currency, currencyCode, digitsInfo)" }, { "code": null, "e": 26611, "s": 26599, "text": "Parameters:" }, { "code": null, "e": 26640, "s": 26611, "text": "value: The number to format." }, { "code": null, "e": 26685, "s": 26640, "text": "locale: A locale code for the locale format." }, { "code": null, "e": 26748, "s": 26685, "text": "currency: A string containing the currency symbol or its name." }, { "code": null, "e": 26781, "s": 26748, "text": "currencyCode: the currency code." }, { "code": null, "e": 26825, "s": 26781, "text": "digitsInfo: Decimal representation options." }, { "code": null, "e": 26841, "s": 26827, "text": "Return Value:" }, { "code": null, "e": 26878, "s": 26841, "text": "string: the formatted currency code." }, { "code": null, "e": 26922, "s": 26878, "text": "NgModule: Module used by formatCurrency is:" }, { "code": null, "e": 26935, "s": 26922, "text": "CommonModule" }, { "code": null, "e": 26946, "s": 26935, "text": "Approach: " }, { "code": null, "e": 26981, "s": 26946, "text": "Create the Angular app to be used." }, { "code": null, "e": 27135, "s": 26981, "text": "In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatCurrency.import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 27188, "s": 27135, "text": "import { LOCALE_ID, NgModule } from '@angular/core';" }, { "code": null, "e": 27244, "s": 27188, "text": "In app.component.ts import formatCurrency and LOCALE_ID" }, { "code": null, "e": 27283, "s": 27244, "text": "inject LOCALE_ID as a public variable." }, { "code": null, "e": 27356, "s": 27283, "text": "In app.component.html show the local variable using string interpolation" }, { "code": null, "e": 27412, "s": 27356, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 27423, "s": 27412, "text": "Example 1:" }, { "code": null, "e": 27440, "s": 27423, "text": "app.component.ts" }, { "code": "import { formatCurrency } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatCurrency(10,this.locale, 'USD');constructor( @Inject(LOCALE_ID) public locale: string,){}}", "e": 27769, "s": 27440, "text": null }, { "code": null, "e": 27788, "s": 27769, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1> <p>Locale Currency is : {{curr}}</p>", "e": 27851, "s": 27788, "text": null }, { "code": null, "e": 27859, "s": 27851, "text": "Output:" }, { "code": null, "e": 27870, "s": 27859, "text": "Example 2:" }, { "code": null, "e": 27887, "s": 27870, "text": "app.component.ts" }, { "code": "import { formatCurrency } from '@angular/common'; import {Component, Inject, LOCALE_ID } from '@angular/core'; @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatCurrency(10,this.locale, 'INR');constructor( @Inject(LOCALE_ID) public locale: string,){}}", "e": 28216, "s": 27887, "text": null }, { "code": null, "e": 28235, "s": 28216, "text": "app.component.html" }, { "code": "<h1> GeeksforGeeks</h1> <p>Locale Currency is : {{curr}}</p>", "e": 28298, "s": 28235, "text": null }, { "code": null, "e": 28306, "s": 28298, "text": "Output:" }, { "code": null, "e": 28362, "s": 28306, "text": "Reference: https://angular.io/api/common/formatCurrency" }, { "code": null, "e": 28372, "s": 28362, "text": "Angular10" }, { "code": null, "e": 28393, "s": 28372, "text": "AngularJS-Directives" }, { "code": null, "e": 28403, "s": 28393, "text": "AngularJS" }, { "code": null, "e": 28420, "s": 28403, "text": "Web Technologies" }, { "code": null, "e": 28518, "s": 28420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28553, "s": 28518, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28588, "s": 28553, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 28623, "s": 28588, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 28647, "s": 28623, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28700, "s": 28647, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28740, "s": 28700, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28773, "s": 28740, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28818, "s": 28773, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28861, "s": 28818, "text": "How to fetch data from an API in ReactJS ?" } ]
Class getFields() method in Java with Examples - GeeksforGeeks
25 Jan, 2022 The getFields() method of java.lang.Class class is used to get the fields of this class, which are the fields that are public and its members. The method returns the fields of this class in the form of array of Field objects. Syntax: public Field[] getFields() Parameter: This method does not accept any parameter.Return Value: This method returns the fields of this class in the form of an array of Field objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getFields() method.Example 1: Java // Java program to demonstrate getFields() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); // Get the fields of myClass // using getFields() method System.out.println("Fields of myClass: " + Arrays.toString( myClass.getFields())); }} Class represented by myClass: class Test Fields of myClass: [public java.lang.Object Test.obj] Example 2: Java // Java program to demonstrate getFields() method import java.util.*; class Main { private Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the fields of myClass // using getFields() method System.out.println("Fields of myClass: " + Arrays.toString( myClass.getFields())); }} Fields of myClass: [] Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getFields– adnanirshad158 Java-Functions Java-lang package Java.lang.Class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 25667, "s": 25639, "text": "\n25 Jan, 2022" }, { "code": null, "e": 25903, "s": 25667, "text": "The getFields() method of java.lang.Class class is used to get the fields of this class, which are the fields that are public and its members. The method returns the fields of this class in the form of array of Field objects. Syntax: " }, { "code": null, "e": 25930, "s": 25903, "text": "public Field[] getFields()" }, { "code": null, "e": 26266, "s": 25930, "text": "Parameter: This method does not accept any parameter.Return Value: This method returns the fields of this class in the form of an array of Field objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getFields() method.Example 1: " }, { "code": null, "e": 26271, "s": 26266, "text": "Java" }, { "code": "// Java program to demonstrate getFields() method import java.util.*; public class Test { public Object obj; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); // Get the fields of myClass // using getFields() method System.out.println(\"Fields of myClass: \" + Arrays.toString( myClass.getFields())); }}", "e": 26901, "s": 26271, "text": null }, { "code": null, "e": 26996, "s": 26901, "text": "Class represented by myClass: class Test\nFields of myClass: [public java.lang.Object Test.obj]" }, { "code": null, "e": 27010, "s": 26998, "text": "Example 2: " }, { "code": null, "e": 27015, "s": 27010, "text": "Java" }, { "code": "// Java program to demonstrate getFields() method import java.util.*; class Main { private Object obj; Main() { class Arr { }; obj = new Arr(); } public static void main(String[] args) throws ClassNotFoundException { Main t = new Main(); // returns the Class object Class myClass = t.obj.getClass(); // Get the fields of myClass // using getFields() method System.out.println(\"Fields of myClass: \" + Arrays.toString( myClass.getFields())); }}", "e": 27614, "s": 27015, "text": null }, { "code": null, "e": 27636, "s": 27614, "text": "Fields of myClass: []" }, { "code": null, "e": 27724, "s": 27638, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getFields– " }, { "code": null, "e": 27739, "s": 27724, "text": "adnanirshad158" }, { "code": null, "e": 27754, "s": 27739, "text": "Java-Functions" }, { "code": null, "e": 27772, "s": 27754, "text": "Java-lang package" }, { "code": null, "e": 27788, "s": 27772, "text": "Java.lang.Class" }, { "code": null, "e": 27793, "s": 27788, "text": "Java" }, { "code": null, "e": 27798, "s": 27793, "text": "Java" }, { "code": null, "e": 27896, "s": 27798, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27947, "s": 27896, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27977, "s": 27947, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27992, "s": 27977, "text": "Stream In Java" }, { "code": null, "e": 28023, "s": 27992, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28041, "s": 28023, "text": "ArrayList in Java" }, { "code": null, "e": 28073, "s": 28041, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28093, "s": 28073, "text": "Stack Class in Java" }, { "code": null, "e": 28117, "s": 28093, "text": "Singleton Class in Java" }, { "code": null, "e": 28149, "s": 28117, "text": "Multidimensional Arrays in Java" } ]
Java Program for Binary Insertion Sort - GeeksforGeeks
28 Jun, 2021 We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration.In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search. // Java Program implementing// binary insertion sort import java.util.Arrays;class GFG{ public static void main(String[] args) { final int[] arr = {37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; new GFG().sort(arr); for(int i=0; i<arr.length; i++) System.out.print(arr[i]+" "); } public void sort(int array[]) { for (int i = 1; i < array.length; i++) { int x = array[i]; // Find location to insert using binary search int j = Math.abs(Arrays.binarySearch(array, 0, i, x) + 1); //Shifting array to one location right System.arraycopy(array, j, array, j+1, i-j); //Placing element at its correct location array[j] = x; } }} // Code contributed by Mohit Gupta_OMG Please refer complete article on Binary Insertion Sort for more details! Insertion Sort Java Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Java Program to Write into a File Java Program to Read a File to String Java Servlet and JDBC Example | Insert data in MySQL
[ { "code": null, "e": 26762, "s": 26734, "text": "\n28 Jun, 2021" }, { "code": null, "e": 27094, "s": 26762, "text": "We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration.In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search." }, { "code": "// Java Program implementing// binary insertion sort import java.util.Arrays;class GFG{ public static void main(String[] args) { final int[] arr = {37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54 }; new GFG().sort(arr); for(int i=0; i<arr.length; i++) System.out.print(arr[i]+\" \"); } public void sort(int array[]) { for (int i = 1; i < array.length; i++) { int x = array[i]; // Find location to insert using binary search int j = Math.abs(Arrays.binarySearch(array, 0, i, x) + 1); //Shifting array to one location right System.arraycopy(array, j, array, j+1, i-j); //Placing element at its correct location array[j] = x; } }} // Code contributed by Mohit Gupta_OMG ", "e": 27945, "s": 27094, "text": null }, { "code": null, "e": 28018, "s": 27945, "text": "Please refer complete article on Binary Insertion Sort for more details!" }, { "code": null, "e": 28033, "s": 28018, "text": "Insertion Sort" }, { "code": null, "e": 28047, "s": 28033, "text": "Java Programs" }, { "code": null, "e": 28055, "s": 28047, "text": "Sorting" }, { "code": null, "e": 28063, "s": 28055, "text": "Sorting" }, { "code": null, "e": 28161, "s": 28063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28209, "s": 28161, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 28260, "s": 28209, "text": "How to Get Elements By Index from HashSet in Java?" }, { "code": null, "e": 28294, "s": 28260, "text": "Java Program to Write into a File" }, { "code": null, "e": 28332, "s": 28294, "text": "Java Program to Read a File to String" } ]
ReactJS Evergreen TextInput Component - GeeksforGeeks
11 Jun, 2021 React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. TextInput Component allows the user to type the input text through a text input field. We can use the following approach in ReactJS to use the Evergreen TextInput Component. TextInput Props: required: The input element is required when this is set to true. disabled: The input element disabled when this is set to true. isInvalid: It is used to set the visual styling of _only_ the text input to be invalid. spellCheck: It is used for the native spell check functionality of the browser. placeholder: It is used to denote the placeholder text. appearance: It is used for the appearance of the TextInput. width: It is used to denote the width of the TextInput. className: It is used to pass the class name to the button. TextInputField Props: label: It is used to denote the label used above the input element. labelFor: It is used to denote the passed on the label as a htmlFor prop. required: It is used to indicate whether to show an asterix after the label or not. description: Defines optional description of the field which is under the label and above the input element. hint: It is used to define an optional hint under the input element. validationMessage: It is used to show a validation message. inputHeight: It is used to denote the height of the input element. inputWidth: It is used to denote the width of the input width. 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 evergreen-ui Step 3: After creating the ReactJS application, Install the required module using the following command: npm install evergreen-ui Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import { TextInput } from 'evergreen-ui' export default function App() { // State for Name const [name, setName] = React.useState('') return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen TextInput Component</h4> <TextInput onChange={(e) => setName(e.target.value)} placeholder="Enter your name" /> <br></br> Name: {name} </div> );} 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://evergreen.segment.com/components/text-input ReactJS-Evergreen JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to detect browser or tab closing in JavaScript ? How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25232, "s": 25204, "text": "\n11 Jun, 2021" }, { "code": null, "e": 25583, "s": 25232, "text": "React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. TextInput Component allows the user to type the input text through a text input field. We can use the following approach in ReactJS to use the Evergreen TextInput Component." }, { "code": null, "e": 25600, "s": 25583, "text": "TextInput Props:" }, { "code": null, "e": 25666, "s": 25600, "text": "required: The input element is required when this is set to true." }, { "code": null, "e": 25729, "s": 25666, "text": "disabled: The input element disabled when this is set to true." }, { "code": null, "e": 25817, "s": 25729, "text": "isInvalid: It is used to set the visual styling of _only_ the text input to be invalid." }, { "code": null, "e": 25897, "s": 25817, "text": "spellCheck: It is used for the native spell check functionality of the browser." }, { "code": null, "e": 25953, "s": 25897, "text": "placeholder: It is used to denote the placeholder text." }, { "code": null, "e": 26013, "s": 25953, "text": "appearance: It is used for the appearance of the TextInput." }, { "code": null, "e": 26069, "s": 26013, "text": "width: It is used to denote the width of the TextInput." }, { "code": null, "e": 26129, "s": 26069, "text": "className: It is used to pass the class name to the button." }, { "code": null, "e": 26151, "s": 26129, "text": "TextInputField Props:" }, { "code": null, "e": 26219, "s": 26151, "text": "label: It is used to denote the label used above the input element." }, { "code": null, "e": 26293, "s": 26219, "text": "labelFor: It is used to denote the passed on the label as a htmlFor prop." }, { "code": null, "e": 26377, "s": 26293, "text": "required: It is used to indicate whether to show an asterix after the label or not." }, { "code": null, "e": 26486, "s": 26377, "text": "description: Defines optional description of the field which is under the label and above the input element." }, { "code": null, "e": 26555, "s": 26486, "text": "hint: It is used to define an optional hint under the input element." }, { "code": null, "e": 26615, "s": 26555, "text": "validationMessage: It is used to show a validation message." }, { "code": null, "e": 26682, "s": 26615, "text": "inputHeight: It is used to denote the height of the input element." }, { "code": null, "e": 26745, "s": 26682, "text": "inputWidth: It is used to denote the width of the input width." }, { "code": null, "e": 26797, "s": 26747, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26892, "s": 26797, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 26956, "s": 26892, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 26988, "s": 26956, "text": "npx create-react-app foldername" }, { "code": null, "e": 27101, "s": 26988, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 27201, "s": 27101, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 27215, "s": 27201, "text": "cd foldername" }, { "code": null, "e": 27344, "s": 27215, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install evergreen-ui" }, { "code": null, "e": 27449, "s": 27344, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 27474, "s": 27449, "text": "npm install evergreen-ui" }, { "code": null, "e": 27526, "s": 27474, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 27544, "s": 27526, "text": "Project Structure" }, { "code": null, "e": 27674, "s": 27544, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 27681, "s": 27674, "text": "App.js" }, { "code": "import React from 'react'import { TextInput } from 'evergreen-ui' export default function App() { // State for Name const [name, setName] = React.useState('') return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen TextInput Component</h4> <TextInput onChange={(e) => setName(e.target.value)} placeholder=\"Enter your name\" /> <br></br> Name: {name} </div> );}", "e": 28137, "s": 27681, "text": null }, { "code": null, "e": 28250, "s": 28137, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28260, "s": 28250, "text": "npm start" }, { "code": null, "e": 28359, "s": 28260, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28422, "s": 28359, "text": "Reference: https://evergreen.segment.com/components/text-input" }, { "code": null, "e": 28440, "s": 28422, "text": "ReactJS-Evergreen" }, { "code": null, "e": 28451, "s": 28440, "text": "JavaScript" }, { "code": null, "e": 28459, "s": 28451, "text": "ReactJS" }, { "code": null, "e": 28476, "s": 28459, "text": "Web Technologies" }, { "code": null, "e": 28574, "s": 28476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28583, "s": 28574, "text": "Comments" }, { "code": null, "e": 28596, "s": 28583, "text": "Old Comments" }, { "code": null, "e": 28657, "s": 28596, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28698, "s": 28657, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28751, "s": 28698, "text": "How to detect browser or tab closing in JavaScript ?" }, { "code": null, "e": 28805, "s": 28751, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 28853, "s": 28805, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 28896, "s": 28853, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28941, "s": 28896, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 29006, "s": 28941, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 29074, "s": 29006, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Handling Plot Axis Spines in Python | by Elena Kosourova | Towards Data Science
Axis spines are the lines confining the plot area. Depending on the situation, we may want to remove some (or all) of them, change their color, make them less visible, regulate their width/style, or change their position. In this article, we’ll explore some handy approaches for dealing with axis spines. In many cases, we just need to remove spines. Let’s suppose that we have the following plot: import numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 5, 1)y = 2 * xplt.plot(x, y)plt.show() and we want to remove the top spine from the axes. For this purpose, we can use the set_visible() method of the object-oriented API interface (i.e. when we use ax.plot instead of plt.plot). The syntax is the following: ax.spines['top'].set_visible(False). For removing several spines, it makes sense to use a for-loop: fig, ax = plt.subplots()ax.plot(x, y)for spine in ['top', 'right']: ax.spines[spine].set_visible(False)plt.show() A more straightforward approach is to use a seaborn utility function sns.despine(). In this case, it doesn't matter if we use the object-oriented API or pyplot interface. If no argument is passed in, by default, the top and right spines will be removed: import seaborn as snsplt.plot(x, y)sns.despine()plt.show() It’s possible to remove any of the remaining spines (e.g., left=True) or to restore the spines removed by default (e.g., right=False). To remove all the 4 spines at once, we can use either set_visible() or sns.despine(), but there is a shorter way: using the plt.box() method. plt.plot(x, y)plt.box(on=False)plt.show() The set_color() and set_alpha() methods are related to the object-oriented API interface and have the syntax similar to the one for set_visible(). The set_alpha() method is convenient when we want to keep a spine but make it less evident: fig, ax = plt.subplots()ax.plot(x, y)ax.spines['left'].set_color('red')ax.spines['bottom'].set_alpha(0.2)plt.show() Let’s now try changing the width and style for some spines of our plot with the methods set_linewidth() and set_linestyle(), where the latter can take in the following values: 'solid' (by default), 'dashed', 'dashdot', or 'dotted'. fig, ax = plt.subplots()ax.plot(x, y)ax.spines['left'].set_linewidth(3)ax.spines['bottom'].set_linestyle('dashed')plt.show() It seems that the set_linestyle() method didn't work as expected. We can fix it changing the width of the same spine: fig, ax = plt.subplots()ax.plot(x, y)ax.spines['bottom'].set_linewidth(4)ax.spines['bottom'].set_linestyle('dashed')plt.show() Looks better now, but the dashes are too close to each other. To further fix it, we can adjust another property of axis spines: the capstyle, i.e the style of ending for each dash or dot. The capstyle can be projecting, butt, or round. To understand the difference between them, let’s look at the following scheme illustrating the dashes of the same length but with different capstyle: We see that the butt capstyle is the least “space-consuming”, while the default one for axis spines is projecting. Let’s adjust our plot applying the set_capstyle() method and passing in a new value: fig, ax = plt.subplots()ax.plot(x, y)ax.spines['bottom'].set_capstyle('butt')ax.spines['bottom'].set_linewidth(4)ax.spines['bottom'].set_linestyle('dashed')plt.show() There is an alternative way of providing a spine style: passing in to set_linestyle() a tuple of the following form: (offset, onoffseq), where the offset is usually 0 and onoffseq is an even-length tuple of on and off ink in points. This approach is even more convenient since it doesn't need to adjust any other parameters like width or capstyle. We can use it for making spines dashed, dotted, or having any other pattern: fig, ax = plt.subplots()ax.plot(x, y)ax.spines['top'].set_linestyle((0, (10, 10)))ax.spines['right'].set_linestyle((0, (10, 10, 1, 10)))plt.show() We can put any spine at an arbitrary position using the set_position() method and passing in a tuple of the following form: (position type, amount). The possible position types are: 'outward' — out from the plot area (or inside it, in the case of a negative value of the amount in points), 'axes' — at the specified axes coordinate, can take values from 0 to 1, 'data' — at the specified data coordinate. The last option, for example, can be useful for putting a vertical spine at 0: x1 = np.arange(-5, 5, 0.1)y1 = np.sin(x1)fig, ax = plt.subplots()plt.plot(x1, y1)ax.spines['left'].set_position(('data', 0))sns.despine()plt.show() The 'outward' position type has an equivalent in the sns.despine() function where we can pass in the optional offset parameter. This parameter can take in a single integer as an offset to all visible spines or a dictionary to specify an offset for each visible spine separately. The following 2 plots are identical: fig, ax = plt.subplots()ax.plot(x, y)ax.spines['left'].set_position(('outward', 20))sns.despine()plt.show()fig, ax = plt.subplots()ax.plot(x, y)sns.despine(offset={'left': 20})plt.show() Finally, talking about positioning spines, there is one more method that, in some cases, can turn to be useful: set_zorder(). Passing in 0 to it, we can "hide" a spine behind the plot. Let's compare the plots below: fig, ax = plt.subplots()plt.plot(x1, y1, color='red', linewidth=5)ax.spines['left'].set_position(('data', 0))ax.spines['left'].set_linewidth(5)sns.despine()plt.show()fig, ax = plt.subplots()plt.plot(x1, y1, color='red', linewidth=5)ax.spines['left'].set_zorder(0)ax.spines['left'].set_position(('data', 0))ax.spines['left'].set_linewidth(5)sns.despine()plt.show() In this article, we explored different methods and tricks for handling axis spines in matplotlib and seaborn libraries including removing them, changing their color and transparency, adjusting width/style, or changing position. Thanks for reading! You can find interesting also these articles:
[ { "code": null, "e": 476, "s": 171, "text": "Axis spines are the lines confining the plot area. Depending on the situation, we may want to remove some (or all) of them, change their color, make them less visible, regulate their width/style, or change their position. In this article, we’ll explore some handy approaches for dealing with axis spines." }, { "code": null, "e": 569, "s": 476, "text": "In many cases, we just need to remove spines. Let’s suppose that we have the following plot:" }, { "code": null, "e": 674, "s": 569, "text": "import numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 5, 1)y = 2 * xplt.plot(x, y)plt.show()" }, { "code": null, "e": 993, "s": 674, "text": "and we want to remove the top spine from the axes. For this purpose, we can use the set_visible() method of the object-oriented API interface (i.e. when we use ax.plot instead of plt.plot). The syntax is the following: ax.spines['top'].set_visible(False). For removing several spines, it makes sense to use a for-loop:" }, { "code": null, "e": 1110, "s": 993, "text": "fig, ax = plt.subplots()ax.plot(x, y)for spine in ['top', 'right']: ax.spines[spine].set_visible(False)plt.show()" }, { "code": null, "e": 1364, "s": 1110, "text": "A more straightforward approach is to use a seaborn utility function sns.despine(). In this case, it doesn't matter if we use the object-oriented API or pyplot interface. If no argument is passed in, by default, the top and right spines will be removed:" }, { "code": null, "e": 1423, "s": 1364, "text": "import seaborn as snsplt.plot(x, y)sns.despine()plt.show()" }, { "code": null, "e": 1558, "s": 1423, "text": "It’s possible to remove any of the remaining spines (e.g., left=True) or to restore the spines removed by default (e.g., right=False)." }, { "code": null, "e": 1700, "s": 1558, "text": "To remove all the 4 spines at once, we can use either set_visible() or sns.despine(), but there is a shorter way: using the plt.box() method." }, { "code": null, "e": 1742, "s": 1700, "text": "plt.plot(x, y)plt.box(on=False)plt.show()" }, { "code": null, "e": 1981, "s": 1742, "text": "The set_color() and set_alpha() methods are related to the object-oriented API interface and have the syntax similar to the one for set_visible(). The set_alpha() method is convenient when we want to keep a spine but make it less evident:" }, { "code": null, "e": 2097, "s": 1981, "text": "fig, ax = plt.subplots()ax.plot(x, y)ax.spines['left'].set_color('red')ax.spines['bottom'].set_alpha(0.2)plt.show()" }, { "code": null, "e": 2329, "s": 2097, "text": "Let’s now try changing the width and style for some spines of our plot with the methods set_linewidth() and set_linestyle(), where the latter can take in the following values: 'solid' (by default), 'dashed', 'dashdot', or 'dotted'." }, { "code": null, "e": 2454, "s": 2329, "text": "fig, ax = plt.subplots()ax.plot(x, y)ax.spines['left'].set_linewidth(3)ax.spines['bottom'].set_linestyle('dashed')plt.show()" }, { "code": null, "e": 2572, "s": 2454, "text": "It seems that the set_linestyle() method didn't work as expected. We can fix it changing the width of the same spine:" }, { "code": null, "e": 2699, "s": 2572, "text": "fig, ax = plt.subplots()ax.plot(x, y)ax.spines['bottom'].set_linewidth(4)ax.spines['bottom'].set_linestyle('dashed')plt.show()" }, { "code": null, "e": 3085, "s": 2699, "text": "Looks better now, but the dashes are too close to each other. To further fix it, we can adjust another property of axis spines: the capstyle, i.e the style of ending for each dash or dot. The capstyle can be projecting, butt, or round. To understand the difference between them, let’s look at the following scheme illustrating the dashes of the same length but with different capstyle:" }, { "code": null, "e": 3285, "s": 3085, "text": "We see that the butt capstyle is the least “space-consuming”, while the default one for axis spines is projecting. Let’s adjust our plot applying the set_capstyle() method and passing in a new value:" }, { "code": null, "e": 3452, "s": 3285, "text": "fig, ax = plt.subplots()ax.plot(x, y)ax.spines['bottom'].set_capstyle('butt')ax.spines['bottom'].set_linewidth(4)ax.spines['bottom'].set_linestyle('dashed')plt.show()" }, { "code": null, "e": 3877, "s": 3452, "text": "There is an alternative way of providing a spine style: passing in to set_linestyle() a tuple of the following form: (offset, onoffseq), where the offset is usually 0 and onoffseq is an even-length tuple of on and off ink in points. This approach is even more convenient since it doesn't need to adjust any other parameters like width or capstyle. We can use it for making spines dashed, dotted, or having any other pattern:" }, { "code": null, "e": 4024, "s": 3877, "text": "fig, ax = plt.subplots()ax.plot(x, y)ax.spines['top'].set_linestyle((0, (10, 10)))ax.spines['right'].set_linestyle((0, (10, 10, 1, 10)))plt.show()" }, { "code": null, "e": 4206, "s": 4024, "text": "We can put any spine at an arbitrary position using the set_position() method and passing in a tuple of the following form: (position type, amount). The possible position types are:" }, { "code": null, "e": 4314, "s": 4206, "text": "'outward' — out from the plot area (or inside it, in the case of a negative value of the amount in points)," }, { "code": null, "e": 4386, "s": 4314, "text": "'axes' — at the specified axes coordinate, can take values from 0 to 1," }, { "code": null, "e": 4429, "s": 4386, "text": "'data' — at the specified data coordinate." }, { "code": null, "e": 4508, "s": 4429, "text": "The last option, for example, can be useful for putting a vertical spine at 0:" }, { "code": null, "e": 4656, "s": 4508, "text": "x1 = np.arange(-5, 5, 0.1)y1 = np.sin(x1)fig, ax = plt.subplots()plt.plot(x1, y1)ax.spines['left'].set_position(('data', 0))sns.despine()plt.show()" }, { "code": null, "e": 4972, "s": 4656, "text": "The 'outward' position type has an equivalent in the sns.despine() function where we can pass in the optional offset parameter. This parameter can take in a single integer as an offset to all visible spines or a dictionary to specify an offset for each visible spine separately. The following 2 plots are identical:" }, { "code": null, "e": 5159, "s": 4972, "text": "fig, ax = plt.subplots()ax.plot(x, y)ax.spines['left'].set_position(('outward', 20))sns.despine()plt.show()fig, ax = plt.subplots()ax.plot(x, y)sns.despine(offset={'left': 20})plt.show()" }, { "code": null, "e": 5375, "s": 5159, "text": "Finally, talking about positioning spines, there is one more method that, in some cases, can turn to be useful: set_zorder(). Passing in 0 to it, we can \"hide\" a spine behind the plot. Let's compare the plots below:" }, { "code": null, "e": 5739, "s": 5375, "text": "fig, ax = plt.subplots()plt.plot(x1, y1, color='red', linewidth=5)ax.spines['left'].set_position(('data', 0))ax.spines['left'].set_linewidth(5)sns.despine()plt.show()fig, ax = plt.subplots()plt.plot(x1, y1, color='red', linewidth=5)ax.spines['left'].set_zorder(0)ax.spines['left'].set_position(('data', 0))ax.spines['left'].set_linewidth(5)sns.despine()plt.show()" }, { "code": null, "e": 5967, "s": 5739, "text": "In this article, we explored different methods and tricks for handling axis spines in matplotlib and seaborn libraries including removing them, changing their color and transparency, adjusting width/style, or changing position." }, { "code": null, "e": 5987, "s": 5967, "text": "Thanks for reading!" } ]
What is the difference between re.findall() and re.finditer() methods available in Python?
The re.findall() helps to get a list of all matching patterns. It searches from start or end of the given string. If we use method findall to search for a pattern in a given string it will return all occurrences of the pattern. While searching a pattern, it is recommended to use re.findall() always, it works like re.search() and re.match() both. import re result = re.search(r'TP', 'TP Tutorials Point TP') print result.group() TP re.finditer(pattern, string, flags=0) Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. The following code shows the use of re.finditer() method in Python regex import re s1 = 'Blue Berries' pattern = 'Blue Berries' for match in re.finditer(pattern, s1): s = match.start() e = match.end() print 'String match "%s" at %d:%d' % (s1[s:e], s, e) Strings match "Blue Berries" at 0:12
[ { "code": null, "e": 1410, "s": 1062, "text": "The re.findall() helps to get a list of all matching patterns. It searches from start or end of the given string. If we use method findall to search for a pattern in a given string it will return all occurrences of the pattern. While searching a pattern, it is recommended to use re.findall() always, it works like re.search() and re.match() both." }, { "code": null, "e": 1493, "s": 1410, "text": "import re result = re.search(r'TP', 'TP Tutorials Point TP')\n\nprint result.group()" }, { "code": null, "e": 1496, "s": 1493, "text": "TP" }, { "code": null, "e": 1534, "s": 1496, "text": "re.finditer(pattern, string, flags=0)" }, { "code": null, "e": 1773, "s": 1534, "text": " Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. " }, { "code": null, "e": 1846, "s": 1773, "text": "The following code shows the use of re.finditer() method in Python regex" }, { "code": null, "e": 2039, "s": 1846, "text": "import re s1 = 'Blue Berries'\npattern = 'Blue Berries'\nfor match in re.finditer(pattern, s1):\n s = match.start()\n e = match.end()\n print 'String match \"%s\" at %d:%d' % (s1[s:e], s, e)" }, { "code": null, "e": 2076, "s": 2039, "text": "Strings match \"Blue Berries\" at 0:12" } ]
C# | Get value of the bit at a specific position in BitArray - GeeksforGeeks
01 Feb, 2019 The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace.BitArray.Get(Int32) method is used to get the value of the bit at a specific position in the BitArray. Properties: The BitArray class is a collection class in which the capacity is always the same as the count. Elements are added to a BitArray by increasing the Length property. Elements are deleted by decreasing the Length property. Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. Syntax: public bool Get (int index); Here, index is the zero-based index of the value to get. Return Value: It returns the value of the bit at position index. Exception: This method will give ArgumentOutOfRangeException if the index is less than zero or index is greater than or equal to the number of elements in the BitArray. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to get the value of// the bit at a specific position// in the BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index 2 Console.WriteLine(myBitArr.Get(2)); // To get the value of index at index 3 Console.WriteLine(myBitArr.Get(3)); }} Output: False True Example 2: // C# code to get the value of// the bit at a specific position// in the BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index 6 // This should raise "ArgumentOutOfRangeException" // as index is greater than or equal to // the number of elements in the BitArray. Console.WriteLine(myBitArr.Get(6)); }} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index Example 3: // C# code to get the value of// the bit at a specific position// in the BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index -2 // This should raise "ArgumentOutOfRangeException" // as index is less than zero. Console.WriteLine(myBitArr.Get(-2)); }} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index Note: This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.get?view=netframework-4.7.2 CSharp-Collections-BitArray CSharp-Collections-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Constructors C# | Delegates Introduction to .NET Framework Difference between Ref and Out keywords in C# C# | Data Types
[ { "code": null, "e": 24368, "s": 24340, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24710, "s": 24368, "text": "The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on i.e, 1 and false indicates the bit is off i.e, 0. This class is contained in System.Collections namespace.BitArray.Get(Int32) method is used to get the value of the bit at a specific position in the BitArray." }, { "code": null, "e": 24722, "s": 24710, "text": "Properties:" }, { "code": null, "e": 24818, "s": 24722, "text": "The BitArray class is a collection class in which the capacity is always the same as the count." }, { "code": null, "e": 24886, "s": 24818, "text": "Elements are added to a BitArray by increasing the Length property." }, { "code": null, "e": 24942, "s": 24886, "text": "Elements are deleted by decreasing the Length property." }, { "code": null, "e": 25053, "s": 24942, "text": "Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based." }, { "code": null, "e": 25061, "s": 25053, "text": "Syntax:" }, { "code": null, "e": 25091, "s": 25061, "text": "public bool Get (int index);\n" }, { "code": null, "e": 25148, "s": 25091, "text": "Here, index is the zero-based index of the value to get." }, { "code": null, "e": 25213, "s": 25148, "text": "Return Value: It returns the value of the bit at position index." }, { "code": null, "e": 25382, "s": 25213, "text": "Exception: This method will give ArgumentOutOfRangeException if the index is less than zero or index is greater than or equal to the number of elements in the BitArray." }, { "code": null, "e": 25462, "s": 25382, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25473, "s": 25462, "text": "Example 1:" }, { "code": "// C# code to get the value of// the bit at a specific position// in the BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index 2 Console.WriteLine(myBitArr.Get(2)); // To get the value of index at index 3 Console.WriteLine(myBitArr.Get(3)); }}", "e": 26065, "s": 25473, "text": null }, { "code": null, "e": 26073, "s": 26065, "text": "Output:" }, { "code": null, "e": 26085, "s": 26073, "text": "False\nTrue\n" }, { "code": null, "e": 26096, "s": 26085, "text": "Example 2:" }, { "code": "// C# code to get the value of// the bit at a specific position// in the BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index 6 // This should raise \"ArgumentOutOfRangeException\" // as index is greater than or equal to // the number of elements in the BitArray. Console.WriteLine(myBitArr.Get(6)); }}", "e": 26751, "s": 26096, "text": null }, { "code": null, "e": 26766, "s": 26751, "text": "Runtime Error:" }, { "code": null, "e": 26930, "s": 26766, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index" }, { "code": null, "e": 26941, "s": 26930, "text": "Example 3:" }, { "code": "// C# code to get the value of// the bit at a specific position// in the BitArrayusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a BitArray BitArray myBitArr = new BitArray(5); myBitArr[0] = true; myBitArr[1] = true; myBitArr[2] = false; myBitArr[3] = true; myBitArr[4] = false; // To get the value of index at index -2 // This should raise \"ArgumentOutOfRangeException\" // as index is less than zero. Console.WriteLine(myBitArr.Get(-2)); }}", "e": 27539, "s": 26941, "text": null }, { "code": null, "e": 27554, "s": 27539, "text": "Runtime Error:" }, { "code": null, "e": 27718, "s": 27554, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index" }, { "code": null, "e": 27758, "s": 27718, "text": "Note: This method is an O(1) operation." }, { "code": null, "e": 27769, "s": 27758, "text": "Reference:" }, { "code": null, "e": 27869, "s": 27769, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.bitarray.get?view=netframework-4.7.2" }, { "code": null, "e": 27897, "s": 27869, "text": "CSharp-Collections-BitArray" }, { "code": null, "e": 27926, "s": 27897, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 27940, "s": 27926, "text": "CSharp-method" }, { "code": null, "e": 27943, "s": 27940, "text": "C#" }, { "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": 28091, "s": 28063, "text": "C# Dictionary with examples" }, { "code": null, "e": 28114, "s": 28091, "text": "C# | Method Overriding" }, { "code": null, "e": 28136, "s": 28114, "text": "C# | Class and Object" }, { "code": null, "e": 28176, "s": 28136, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28199, "s": 28176, "text": "Extension Method in C#" }, { "code": null, "e": 28217, "s": 28199, "text": "C# | Constructors" }, { "code": null, "e": 28232, "s": 28217, "text": "C# | Delegates" }, { "code": null, "e": 28263, "s": 28232, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28309, "s": 28263, "text": "Difference between Ref and Out keywords in C#" } ]
F# - Discriminated Unions
Unions, or discriminated unions allows you to build up complex data structures representing well-defined set of choices. For example, you need to build an implementation of a choice variable, which has two values yes and no. Using the Unions tool, you can design this. Discriminated unions are defined using the following syntax − type type-name = | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] type2 ...] | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...] ... Our simple implementation of ,choice, will look like the following − type choice = | Yes | No The following example uses the type choice − type choice = | Yes | No let x = Yes (* creates an instance of choice *) let y = No (* creates another instance of choice *) let main() = printfn "x: %A" x printfn "y: %A" y main() When you compile and execute the program, it yields the following output − x: Yes y: No The following example shows the implementation of the voltage states that sets a bit on high or low − type VoltageState = | High | Low let toggleSwitch = function (* pattern matching input *) | High -> Low | Low -> High let main() = let on = High let off = Low let change = toggleSwitch off printfn "Switch on state: %A" on printfn "Switch off state: %A" off printfn "Toggle off: %A" change printfn "Toggle the Changed state: %A" (toggleSwitch change) main() When you compile and execute the program, it yields the following output − Switch on state: High Switch off state: Low Toggle off: High Toggle the Changed state: Low type Shape = // here we store the radius of a circle | Circle of float // here we store the side length. | Square of float // here we store the height and width. | Rectangle of float * float let pi = 3.141592654 let area myShape = match myShape with | Circle radius -> pi * radius * radius | Square s -> s * s | Rectangle (h, w) -> h * w let radius = 12.0 let myCircle = Circle(radius) printfn "Area of circle with radius %g: %g" radius (area myCircle) let side = 15.0 let mySquare = Square(side) printfn "Area of square that has side %g: %g" side (area mySquare) let height, width = 5.0, 8.0 let myRectangle = Rectangle(height, width) printfn "Area of rectangle with height %g and width %g is %g" height width (area myRectangle) When you compile and execute the program, it yields the following output − Area of circle with radius 12: 452.389 Area of square that has side 15: 225 Area of rectangle with height 5 and width 8 is 40 Print Add Notes Bookmark this page
[ { "code": null, "e": 2430, "s": 2161, "text": "Unions, or discriminated unions allows you to build up complex data structures representing well-defined set of choices. For example, you need to build an implementation of a choice variable, which has two values yes and no. Using the Unions tool, you can design this." }, { "code": null, "e": 2492, "s": 2430, "text": "Discriminated unions are defined using the following syntax −" }, { "code": null, "e": 2674, "s": 2492, "text": "type type-name =\n | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] \ntype2 ...]\n | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...]\n...\n" }, { "code": null, "e": 2743, "s": 2674, "text": "Our simple implementation of ,choice, will look like the following −" }, { "code": null, "e": 2775, "s": 2743, "text": "type choice =\n | Yes\n | No\n" }, { "code": null, "e": 2820, "s": 2775, "text": "The following example uses the type choice −" }, { "code": null, "e": 3014, "s": 2820, "text": "type choice =\n | Yes\n | No\n\nlet x = Yes (* creates an instance of choice *)\nlet y = No (* creates another instance of choice *)\nlet main() =\n printfn \"x: %A\" x\n printfn \"y: %A\" y\nmain()" }, { "code": null, "e": 3089, "s": 3014, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3103, "s": 3089, "text": "x: Yes\ny: No\n" }, { "code": null, "e": 3205, "s": 3103, "text": "The following example shows the implementation of the voltage states that sets a bit on high or low −" }, { "code": null, "e": 3599, "s": 3205, "text": "type VoltageState =\n | High\n | Low\n\nlet toggleSwitch = function (* pattern matching input *)\n | High -> Low\n | Low -> High\n\nlet main() =\n let on = High\n let off = Low\n let change = toggleSwitch off\n\n printfn \"Switch on state: %A\" on\n printfn \"Switch off state: %A\" off\n printfn \"Toggle off: %A\" change\n printfn \"Toggle the Changed state: %A\" (toggleSwitch change)\n\nmain()" }, { "code": null, "e": 3674, "s": 3599, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3766, "s": 3674, "text": "Switch on state: High\nSwitch off state: Low\nToggle off: High\nToggle the Changed state: Low\n" }, { "code": null, "e": 4533, "s": 3766, "text": "type Shape =\n // here we store the radius of a circle\n | Circle of float\n\n // here we store the side length.\n | Square of float\n\n // here we store the height and width.\n | Rectangle of float * float\n\nlet pi = 3.141592654\n\nlet area myShape =\n match myShape with\n | Circle radius -> pi * radius * radius\n | Square s -> s * s\n | Rectangle (h, w) -> h * w\n\nlet radius = 12.0\nlet myCircle = Circle(radius)\nprintfn \"Area of circle with radius %g: %g\" radius (area myCircle)\n\nlet side = 15.0\nlet mySquare = Square(side)\nprintfn \"Area of square that has side %g: %g\" side (area mySquare)\n\nlet height, width = 5.0, 8.0\nlet myRectangle = Rectangle(height, width)\nprintfn \"Area of rectangle with height %g and width %g is %g\" height width (area myRectangle)" }, { "code": null, "e": 4608, "s": 4533, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4735, "s": 4608, "text": "Area of circle with radius 12: 452.389\nArea of square that has side 15: 225\nArea of rectangle with height 5 and width 8 is 40\n" }, { "code": null, "e": 4742, "s": 4735, "text": " Print" }, { "code": null, "e": 4753, "s": 4742, "text": " Add Notes" } ]
Merge Overlapping Intervals using C++.
Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals Given set of interval is {{12, 14}, {11, 13}, {20, 22}, {21, 23}} then Interval {12, 14} and {11, 13} overlap with each other hence merge them as {11, 14} Interval {12, 14} and {11, 13} overlap with each other hence merge them as {11, 14} Interval {20, 22} and {21, 23} overlap with each other hence merge them as {20, 23} Interval {20, 22} and {21, 23} overlap with each other hence merge them as {20, 23} 1. Sort the intervals based on increasing order of starting time 2. Push the first interval on to a stack 3. For each interval perform below steps: 3.1. If the current interval does not overlap with the top of the stack, push it. 3.2. If the current interval overlaps with top of the stack and ending time of current interval is more than that of top of stack, update stack top with the ending time of current interval. 4. Finally, stack contains the merged intervals. #include <iostream> #include <algorithm> #include <stack> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; struct interval{ int start; int end; }; bool compareInterval(interval i1, interval i2){ return (i1.start < i2.start); } void mergeOverlappingIntervals(interval *arr, int n){ if (n <= 0) { return; } stack<interval> s; sort(arr, arr + n, compareInterval); s.push(arr[0]); for (int i = 1; i < n; ++i) { interval top = s.top(); if (top.end < arr[i].start) { s.push(arr[i]); } else if(top.end < arr[i].end) { top.end = arr[i].end; s.pop(); s.push(top); } } cout << "Merged intervals: " << endl; while (!s.empty()) { interval i = s.top(); cout << "{" << i.start << ", " << i.end << "}" << " "; s.pop(); } cout << endl; } int main(){ interval arr[] = {{12, 14}, {11, 13}, {20, 22}, {21, 23}}; mergeOverlappingIntervals(arr, SIZE(arr)); return 0; } When you compile and execute the above program. It generates the following output − Merged intervals: {20, 23} {11, 14}
[ { "code": null, "e": 1221, "s": 1062, "text": "Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals" }, { "code": null, "e": 1292, "s": 1221, "text": "Given set of interval is {{12, 14}, {11, 13}, {20, 22}, {21, 23}} then" }, { "code": null, "e": 1376, "s": 1292, "text": "Interval {12, 14} and {11, 13} overlap with each other hence merge them as {11, 14}" }, { "code": null, "e": 1460, "s": 1376, "text": "Interval {12, 14} and {11, 13} overlap with each other hence merge them as {11, 14}" }, { "code": null, "e": 1544, "s": 1460, "text": "Interval {20, 22} and {21, 23} overlap with each other hence merge them as {20, 23}" }, { "code": null, "e": 1628, "s": 1544, "text": "Interval {20, 22} and {21, 23} overlap with each other hence merge them as {20, 23}" }, { "code": null, "e": 2103, "s": 1628, "text": "1. Sort the intervals based on increasing order of starting time\n2. Push the first interval on to a stack\n3. For each interval perform below steps:\n 3.1. If the current interval does not overlap with the top of the stack, push it.\n 3.2. If the current interval overlaps with top of the stack and ending time of current interval is more than that of top of stack, update stack top with the ending time of current interval.\n4. Finally, stack contains the merged intervals." }, { "code": null, "e": 3107, "s": 2103, "text": "#include <iostream>\n#include <algorithm>\n#include <stack>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nstruct interval{\n int start;\n int end;\n};\nbool compareInterval(interval i1, interval i2){\n return (i1.start < i2.start);\n}\nvoid mergeOverlappingIntervals(interval *arr, int n){\n if (n <= 0) {\n return;\n }\n stack<interval> s;\n sort(arr, arr + n, compareInterval);\n s.push(arr[0]);\n for (int i = 1; i < n; ++i) {\n interval top = s.top();\n if (top.end < arr[i].start) {\n s.push(arr[i]);\n } else if(top.end < arr[i].end) {\n top.end = arr[i].end;\n s.pop();\n s.push(top);\n }\n }\n cout << \"Merged intervals: \" << endl;\n while (!s.empty()) {\n interval i = s.top();\n cout << \"{\" << i.start << \", \" << i.end << \"}\" << \" \";\n s.pop();\n }\n cout << endl;\n}\nint main(){\n interval arr[] = {{12, 14}, {11, 13}, {20, 22}, {21, 23}};\n mergeOverlappingIntervals(arr, SIZE(arr));\n return 0;\n}" }, { "code": null, "e": 3191, "s": 3107, "text": "When you compile and execute the above program. It generates the following output −" }, { "code": null, "e": 3227, "s": 3191, "text": "Merged intervals:\n{20, 23} {11, 14}" } ]
How do nested functions work in Python?
To learn about nested function, refer the following code. In the code, you can see Inner functions can access variables from the enclosing scope, which is the local variable. def mulFunc(num1): def mul(num2): return num1 * num2 return mul res = mulFunc(15) // The following prints 300 i.e. 20*15 print(res(20)) The above prints the multiplication of num1 and num 2 i.e. 300
[ { "code": null, "e": 1237, "s": 1062, "text": "To learn about nested function, refer the following code. In the code, you can see Inner functions can access variables from the enclosing scope, which is the local variable." }, { "code": null, "e": 1385, "s": 1237, "text": "def mulFunc(num1):\n def mul(num2):\n return num1 * num2\n return mul\nres = mulFunc(15)\n// The following prints 300 i.e. 20*15\nprint(res(20))" }, { "code": null, "e": 1448, "s": 1385, "text": "The above prints the multiplication of num1 and num 2 i.e. 300" } ]
Different ways to iterate over a set in C++ - GeeksforGeeks
10 Dec, 2021 Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order. Syntax: set<datatype> setname; Here,Datatype: Set can take any data type depending on the values, e.g. int, char, float, etc. This article focuses on discussing all the methods that can be used to iterate over a set in C++. The following methods will be discussed in this article: Iterate over a set using an iterator.Iterate over a set in backward direction using reverse_iterator.Iterate over a set using range-based for loop.Iterate over a set using for_each loop. Iterate over a set using an iterator. Iterate over a set in backward direction using reverse_iterator. Iterate over a set using range-based for loop. Iterate over a set using for_each loop. Let’s start discussing each of these methods in detail. Iterating over a set using iterator. In this method, an iterator itr is created and initialized using begin() function which will point to the first element, and after every iteration, itr points to the next element in a set and it will continue to iterate until it reaches the end of the set. The following methods will be used in this approach: begin(): Returns an iterator to the first element in the set.end(): Returns an iterator to the theoretical element that follows the last element in the set. begin(): Returns an iterator to the first element in the set. end(): Returns an iterator to the theoretical element that follows the last element in the set. Below is the C++ program to implement the above approach: C++ // C++ program to implement // the above approach#include<bits/stdc++.h>using namespace std; // Function to display elements // of a setvoid display(set<int> s){ set<int>::iterator itr; // Displaying set elements for (itr = s.begin(); itr != s.end(); itr++) { cout << *itr << " "; }} // Driver codeint main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking function display() // to display elements of set display(s); return 0;} Output: 10 20 30 40 50 Iterate over a set in backward direction using reverse_iterator In this approach, a reverse_iterator itr is created and initialized using rbegin() function which will point to the last element in a set, and after every iteration, itr points to the next element in a backward direction in a set and it will continue to iterate until it reaches the beginning of the set.The following functions are used in this approach: set::rbegin(): It is a built-in function in C++ STL that returns a reverse iterator pointing to the last element in the container.set::rend(): It is an inbuilt function in C++ STL that returns a reverse iterator pointing to the theoretical element right before the first element in the set container. set::rbegin(): It is a built-in function in C++ STL that returns a reverse iterator pointing to the last element in the container. set::rend(): It is an inbuilt function in C++ STL that returns a reverse iterator pointing to the theoretical element right before the first element in the set container. Below is the C++ program to implement the above approach: C++ // C++ program to implement // the above approach#include<bits/stdc++.h>using namespace std; // Function to display elements // of the setvoid display(set<int> s){ set<int>::reverse_iterator itr; // Displaying elements of the // set for (itr = s.rbegin(); itr != s.rend(); itr++) { cout << *itr << " "; }} // Driver codeint main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking display() function display(s); return 0;} Output: 50 40 30 20 10 Iterate over a set using range-based for loop In this method, a range-based for loop will be used to iterate over all the elements in a set in a forward direction. Syntax: for ( range_declaration : range_expression ) loop_statement Parameters : range_declaration : A declaration of a named variable, whose type is the type of the element of the sequence represented by range_expression, or a reference to that type. Often uses the auto specifier for automatic type deduction. range_expression: Any expression that represents a suitable sequence or a braced-init-list. loop_statement: Any statement, typically a compound statement, which is the body of the loop. Below is the C++ program to implement the above approach: C++ // C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function to display elements// of the setvoid display(set<int> s){ // Printing the elements of // the set for (auto itr : s) { cout << itr << " "; } }// Driver codeint main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking display() function display(s); return 0;} Output: 10 20 30 40 50 Iterate over a set using for_each loop In this approach, a for_each loop accepts a function that executes over each of the container elements. Syntax: for_each (InputIterator start_iter, InputIterator last_iter, Function fnc) start_iter: The beginning position from where function operations has to be executed. last_iter: The ending position till where function has to be executed. fnc/obj_fnc: The 3rd argument is a function or an object function which operation would be applied to each element. Below is the C++ program to implement the above approach: C++ // C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; void print(int x){ cout << x << " ";} // Function to display the // elements of setvoid display(set<int> s){ for_each(s.begin(), s.end(), print);} // Driver code int main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking display() function display(s); return 0;} Output: 10 20 30 40 50 cpp-set C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Inline Functions in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL) std::string class in C++ Exception Handling in C++
[ { "code": null, "e": 24018, "s": 23990, "text": "\n10 Dec, 2021" }, { "code": null, "e": 24190, "s": 24018, "text": "Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order. " }, { "code": null, "e": 24198, "s": 24190, "text": "Syntax:" }, { "code": null, "e": 24221, "s": 24198, "text": "set<datatype> setname;" }, { "code": null, "e": 24316, "s": 24221, "text": "Here,Datatype: Set can take any data type depending on the values, e.g. int, char, float, etc." }, { "code": null, "e": 24471, "s": 24316, "text": "This article focuses on discussing all the methods that can be used to iterate over a set in C++. The following methods will be discussed in this article:" }, { "code": null, "e": 24658, "s": 24471, "text": "Iterate over a set using an iterator.Iterate over a set in backward direction using reverse_iterator.Iterate over a set using range-based for loop.Iterate over a set using for_each loop." }, { "code": null, "e": 24696, "s": 24658, "text": "Iterate over a set using an iterator." }, { "code": null, "e": 24761, "s": 24696, "text": "Iterate over a set in backward direction using reverse_iterator." }, { "code": null, "e": 24808, "s": 24761, "text": "Iterate over a set using range-based for loop." }, { "code": null, "e": 24848, "s": 24808, "text": "Iterate over a set using for_each loop." }, { "code": null, "e": 24904, "s": 24848, "text": "Let’s start discussing each of these methods in detail." }, { "code": null, "e": 24941, "s": 24904, "text": "Iterating over a set using iterator." }, { "code": null, "e": 25251, "s": 24941, "text": "In this method, an iterator itr is created and initialized using begin() function which will point to the first element, and after every iteration, itr points to the next element in a set and it will continue to iterate until it reaches the end of the set. The following methods will be used in this approach:" }, { "code": null, "e": 25408, "s": 25251, "text": "begin(): Returns an iterator to the first element in the set.end(): Returns an iterator to the theoretical element that follows the last element in the set." }, { "code": null, "e": 25470, "s": 25408, "text": "begin(): Returns an iterator to the first element in the set." }, { "code": null, "e": 25566, "s": 25470, "text": "end(): Returns an iterator to the theoretical element that follows the last element in the set." }, { "code": null, "e": 25624, "s": 25566, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 25628, "s": 25624, "text": "C++" }, { "code": "// C++ program to implement // the above approach#include<bits/stdc++.h>using namespace std; // Function to display elements // of a setvoid display(set<int> s){ set<int>::iterator itr; // Displaying set elements for (itr = s.begin(); itr != s.end(); itr++) { cout << *itr << \" \"; }} // Driver codeint main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking function display() // to display elements of set display(s); return 0;}", "e": 26204, "s": 25628, "text": null }, { "code": null, "e": 26212, "s": 26204, "text": "Output:" }, { "code": null, "e": 26228, "s": 26212, "text": "10 20 30 40 50 " }, { "code": null, "e": 26292, "s": 26228, "text": "Iterate over a set in backward direction using reverse_iterator" }, { "code": null, "e": 26647, "s": 26292, "text": "In this approach, a reverse_iterator itr is created and initialized using rbegin() function which will point to the last element in a set, and after every iteration, itr points to the next element in a backward direction in a set and it will continue to iterate until it reaches the beginning of the set.The following functions are used in this approach:" }, { "code": null, "e": 26948, "s": 26647, "text": "set::rbegin(): It is a built-in function in C++ STL that returns a reverse iterator pointing to the last element in the container.set::rend(): It is an inbuilt function in C++ STL that returns a reverse iterator pointing to the theoretical element right before the first element in the set container." }, { "code": null, "e": 27079, "s": 26948, "text": "set::rbegin(): It is a built-in function in C++ STL that returns a reverse iterator pointing to the last element in the container." }, { "code": null, "e": 27250, "s": 27079, "text": "set::rend(): It is an inbuilt function in C++ STL that returns a reverse iterator pointing to the theoretical element right before the first element in the set container." }, { "code": null, "e": 27308, "s": 27250, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 27312, "s": 27308, "text": "C++" }, { "code": "// C++ program to implement // the above approach#include<bits/stdc++.h>using namespace std; // Function to display elements // of the setvoid display(set<int> s){ set<int>::reverse_iterator itr; // Displaying elements of the // set for (itr = s.rbegin(); itr != s.rend(); itr++) { cout << *itr << \" \"; }} // Driver codeint main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking display() function display(s); return 0;}", "e": 27879, "s": 27312, "text": null }, { "code": null, "e": 27887, "s": 27879, "text": "Output:" }, { "code": null, "e": 27903, "s": 27887, "text": "50 40 30 20 10 " }, { "code": null, "e": 27949, "s": 27903, "text": "Iterate over a set using range-based for loop" }, { "code": null, "e": 28067, "s": 27949, "text": "In this method, a range-based for loop will be used to iterate over all the elements in a set in a forward direction." }, { "code": null, "e": 28075, "s": 28067, "text": "Syntax:" }, { "code": null, "e": 28122, "s": 28075, "text": "for ( range_declaration : range_expression ) " }, { "code": null, "e": 28140, "s": 28122, "text": " loop_statement" }, { "code": null, "e": 28153, "s": 28140, "text": "Parameters :" }, { "code": null, "e": 28387, "s": 28153, "text": "range_declaration : A declaration of a named variable, whose type is the type of the element of the sequence represented by range_expression, or a reference to that type. Often uses the auto specifier for automatic type deduction." }, { "code": null, "e": 28480, "s": 28387, "text": "range_expression: Any expression that represents a suitable sequence or a braced-init-list." }, { "code": null, "e": 28575, "s": 28480, "text": "loop_statement: Any statement, typically a compound statement, which is the body of the loop." }, { "code": null, "e": 28633, "s": 28575, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 28637, "s": 28633, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; // Function to display elements// of the setvoid display(set<int> s){ // Printing the elements of // the set for (auto itr : s) { cout << itr << \" \"; } }// Driver codeint main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking display() function display(s); return 0;}", "e": 29131, "s": 28637, "text": null }, { "code": null, "e": 29139, "s": 29131, "text": "Output:" }, { "code": null, "e": 29155, "s": 29139, "text": "10 20 30 40 50 " }, { "code": null, "e": 29194, "s": 29155, "text": "Iterate over a set using for_each loop" }, { "code": null, "e": 29298, "s": 29194, "text": "In this approach, a for_each loop accepts a function that executes over each of the container elements." }, { "code": null, "e": 29306, "s": 29298, "text": "Syntax:" }, { "code": null, "e": 29381, "s": 29306, "text": "for_each (InputIterator start_iter, InputIterator last_iter, Function fnc)" }, { "code": null, "e": 29467, "s": 29381, "text": "start_iter: The beginning position from where function operations has to be executed." }, { "code": null, "e": 29538, "s": 29467, "text": "last_iter: The ending position till where function has to be executed." }, { "code": null, "e": 29655, "s": 29538, "text": "fnc/obj_fnc: The 3rd argument is a function or an object function which operation would be applied to each element. " }, { "code": null, "e": 29713, "s": 29655, "text": "Below is the C++ program to implement the above approach:" }, { "code": null, "e": 29717, "s": 29713, "text": "C++" }, { "code": "// C++ program to implement// the above approach#include<bits/stdc++.h>using namespace std; void print(int x){ cout << x << \" \";} // Function to display the // elements of setvoid display(set<int> s){ for_each(s.begin(), s.end(), print);} // Driver code int main(){ // Empty set container set<int> s; // Insert elements in random order s.insert(10); s.insert(20); s.insert(30); s.insert(40); s.insert(50); // Invoking display() function display(s); return 0;}", "e": 30211, "s": 29717, "text": null }, { "code": null, "e": 30219, "s": 30211, "text": "Output:" }, { "code": null, "e": 30235, "s": 30219, "text": "10 20 30 40 50 " }, { "code": null, "e": 30243, "s": 30235, "text": "cpp-set" }, { "code": null, "e": 30247, "s": 30243, "text": "C++" }, { "code": null, "e": 30251, "s": 30247, "text": "CPP" }, { "code": null, "e": 30349, "s": 30251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30358, "s": 30349, "text": "Comments" }, { "code": null, "e": 30371, "s": 30358, "text": "Old Comments" }, { "code": null, "e": 30392, "s": 30371, "text": "Iterators in C++ STL" }, { "code": null, "e": 30420, "s": 30392, "text": "Operator Overloading in C++" }, { "code": null, "e": 30453, "s": 30420, "text": "Friend class and function in C++" }, { "code": null, "e": 30473, "s": 30453, "text": "Polymorphism in C++" }, { "code": null, "e": 30497, "s": 30473, "text": "Sorting a vector in C++" }, { "code": null, "e": 30521, "s": 30497, "text": "Inline Functions in C++" }, { "code": null, "e": 30557, "s": 30521, "text": "Convert string to char array in C++" }, { "code": null, "e": 30601, "s": 30557, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 30626, "s": 30601, "text": "std::string class in C++" } ]
Number of times a number can be replaced by the sum of its digits until it only contains one digit - GeeksforGeeks
16 Apr, 2021 Count the number of times a number can be replaced by the sum of its digits until it only contains one digit and number can be very large.Examples: Input : 10 Output : 1 1 + 0 = 1, so only one times an number can be replaced by its sum . Input : 991 Output : 3 9 + 9 + 1 = 19, 1 + 9 = 10, 1 + 0 = 1 hence 3 times the number can be replaced by its sum. We have discussed Finding sum of digits of a number until sum becomes single digit. The problem here is just extension of the above previous problem. Here, we just want to count number of times a number can be replaced by its sum until it only contains one digit. As number can be very much large so to avoid overflow, we input the number as string. So, to compute this we take one variable named as temporary_sum in which we repeatedly calculate the sum of digits of string and convert this temporary_sum into string again. This process repeats till the string length becomes 1 . To explain this in a more clear way consider number 991 9 + 9 + 1 = 19, Now 19 is a string 1 + 9 = 10, again 10 is a string 1 + 0 = 1 . again 1 is a string but here string length is 1 so, loop breaks . The number of sum operations is the final answer .Below is implementation of this approach . C++ Java Python3 C# PHP Javascript // C++ program to count number of times we// need to add digits to get a single digit.#include <bits/stdc++.h>using namespace std; int NumberofTimes(string str){ // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . int temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.length() > 1) { temporary_sum = 0; // computing sum of its digits for (int i = 0; i < str.length(); i++) temporary_sum += ( str[ i ] - '0' ) ; // converting temporary_sum into string // str again . str = to_string(temporary_sum) ; // increase the count count++; } return count;} // Driver program to test the above functionint main(){ string s = "991"; cout << NumberofTimes(s); return 0;} // Java program to count number of times we// need to add digits to get a single digit. public class GFG{ static int NumberofTimes(String str) { // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . int temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.length() > 1) { temporary_sum = 0; // computing sum of its digits for (int i = 0; i < str.length(); i++) temporary_sum += ( str.charAt(i) - '0' ) ; // converting temporary_sum into string // str again . str = temporary_sum + "" ; // increase the count count++; } return count; } // Driver program to test above functions public static void main(String[] args) { String s = "991"; System.out.println(NumberofTimes(s)); } }/* This code is contributed by Mr. Somesh Awasthi */ # Python 3 program to count number of times we# need to add digits to get a single digit.def NumberofTimes(s): # Here the count variable store # how many times we do sum of # digits and temporary_sum # always store the temporary sum # we get at each iteration . temporary_sum = 0 count = 0 # In this loop we always compute # the sum of digits in temporary_ # sum variable and convert it # into string str till its length # become 1 and increase the count # in each iteration. while (len(s) > 1): temporary_sum = 0 # computing sum of its digits for i in range(len(s)): temporary_sum += (ord(s[ i ]) - ord('0')) # converting temporary_sum into # string str again . s = str(temporary_sum) # increase the count count += 1 return count # Driver Codeif __name__ == "__main__": s = "991" print(NumberofTimes(s)) # This code is contributed by Ita_c // C# program to count number of// times we need to add digits to// get a single digit.using System; class GFG { // Function to count number of // times we need to add digits // to get a single digit static int NumberofTimes(String str) { // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . int temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.Length > 1) { temporary_sum = 0; // computing sum of its digits for (int i = 0; i < str.Length; i++) temporary_sum += (str[i] - '0'); // converting temporary_sum // into string str again . str = temporary_sum + "" ; // increase the count count++; } return count; } // Driver code public static void Main() { String s = "991"; Console.Write(NumberofTimes(s)); } } // This code is contributed by Nitin Mittal. <?php// PHP program to count number of times we// need to add digits to get a single digit. function NumberofTimes($str){ // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . $temporary_sum = 0; $count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (strlen($str) > 1) { $temporary_sum = 0; // computing sum of its digits for ($i = 0; $i < strlen($str); $i++) $temporary_sum += ($str[ $i ] - '0'); // converting temporary_sum into // string str again . $str = (string)($temporary_sum); // increase the count $count++; } return $count;} // Driver Code$s = "991";echo NumberofTimes($s); // This code is contributed// by Akanksha Rai?> <script> // Javascript program to// count number of times we// need to add digits to// get a single digit. function NumberofTimes(str){ // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . var temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.length > 1) { temporary_sum = 0; // computing sum of its digits for (i = 0; i < str.length; i++) temporary_sum += ( str.charAt(i) - '0' ) ; // converting temporary_sum into string // str again . str = temporary_sum + "" ; // increase the count count++; } return count;} // Driver program to test above functionsvar s = "991";document.write(NumberofTimes(s)); // This code contributed by Princi Singh </script> Output: 3 This article is contributed by Surya Priy. 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. nitin mittal ukasp Akanksha_Rai princi singh number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Modulo Operator (%) in C/C++ with Examples The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Modular multiplicative inverse Merge two sorted arrays Euclidean algorithms (Basic and Extended) Find minimum number of coins that make a given value Operators in C / C++ Program for factorial of a number
[ { "code": null, "e": 24719, "s": 24691, "text": "\n16 Apr, 2021" }, { "code": null, "e": 24869, "s": 24719, "text": "Count the number of times a number can be replaced by the sum of its digits until it only contains one digit and number can be very large.Examples: " }, { "code": null, "e": 25077, "s": 24869, "text": "Input : 10\nOutput : 1\n1 + 0 = 1, so only one times \nan number can be replaced by its sum .\n\nInput : 991\nOutput : 3\n9 + 9 + 1 = 19, 1 + 9 = 10, 1 + 0 = 1 \nhence 3 times the number can be replaced \nby its sum." }, { "code": null, "e": 25957, "s": 25079, "text": "We have discussed Finding sum of digits of a number until sum becomes single digit. The problem here is just extension of the above previous problem. Here, we just want to count number of times a number can be replaced by its sum until it only contains one digit. As number can be very much large so to avoid overflow, we input the number as string. So, to compute this we take one variable named as temporary_sum in which we repeatedly calculate the sum of digits of string and convert this temporary_sum into string again. This process repeats till the string length becomes 1 . To explain this in a more clear way consider number 991 9 + 9 + 1 = 19, Now 19 is a string 1 + 9 = 10, again 10 is a string 1 + 0 = 1 . again 1 is a string but here string length is 1 so, loop breaks . The number of sum operations is the final answer .Below is implementation of this approach . " }, { "code": null, "e": 25961, "s": 25957, "text": "C++" }, { "code": null, "e": 25966, "s": 25961, "text": "Java" }, { "code": null, "e": 25974, "s": 25966, "text": "Python3" }, { "code": null, "e": 25977, "s": 25974, "text": "C#" }, { "code": null, "e": 25981, "s": 25977, "text": "PHP" }, { "code": null, "e": 25992, "s": 25981, "text": "Javascript" }, { "code": "// C++ program to count number of times we// need to add digits to get a single digit.#include <bits/stdc++.h>using namespace std; int NumberofTimes(string str){ // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . int temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.length() > 1) { temporary_sum = 0; // computing sum of its digits for (int i = 0; i < str.length(); i++) temporary_sum += ( str[ i ] - '0' ) ; // converting temporary_sum into string // str again . str = to_string(temporary_sum) ; // increase the count count++; } return count;} // Driver program to test the above functionint main(){ string s = \"991\"; cout << NumberofTimes(s); return 0;}", "e": 27066, "s": 25992, "text": null }, { "code": "// Java program to count number of times we// need to add digits to get a single digit. public class GFG{ static int NumberofTimes(String str) { // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . int temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.length() > 1) { temporary_sum = 0; // computing sum of its digits for (int i = 0; i < str.length(); i++) temporary_sum += ( str.charAt(i) - '0' ) ; // converting temporary_sum into string // str again . str = temporary_sum + \"\" ; // increase the count count++; } return count; } // Driver program to test above functions public static void main(String[] args) { String s = \"991\"; System.out.println(NumberofTimes(s)); } }/* This code is contributed by Mr. Somesh Awasthi */", "e": 28365, "s": 27066, "text": null }, { "code": "# Python 3 program to count number of times we# need to add digits to get a single digit.def NumberofTimes(s): # Here the count variable store # how many times we do sum of # digits and temporary_sum # always store the temporary sum # we get at each iteration . temporary_sum = 0 count = 0 # In this loop we always compute # the sum of digits in temporary_ # sum variable and convert it # into string str till its length # become 1 and increase the count # in each iteration. while (len(s) > 1): temporary_sum = 0 # computing sum of its digits for i in range(len(s)): temporary_sum += (ord(s[ i ]) - ord('0')) # converting temporary_sum into # string str again . s = str(temporary_sum) # increase the count count += 1 return count # Driver Codeif __name__ == \"__main__\": s = \"991\" print(NumberofTimes(s)) # This code is contributed by Ita_c", "e": 29369, "s": 28365, "text": null }, { "code": "// C# program to count number of// times we need to add digits to// get a single digit.using System; class GFG { // Function to count number of // times we need to add digits // to get a single digit static int NumberofTimes(String str) { // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . int temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.Length > 1) { temporary_sum = 0; // computing sum of its digits for (int i = 0; i < str.Length; i++) temporary_sum += (str[i] - '0'); // converting temporary_sum // into string str again . str = temporary_sum + \"\" ; // increase the count count++; } return count; } // Driver code public static void Main() { String s = \"991\"; Console.Write(NumberofTimes(s)); } } // This code is contributed by Nitin Mittal.", "e": 30712, "s": 29369, "text": null }, { "code": "<?php// PHP program to count number of times we// need to add digits to get a single digit. function NumberofTimes($str){ // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . $temporary_sum = 0; $count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (strlen($str) > 1) { $temporary_sum = 0; // computing sum of its digits for ($i = 0; $i < strlen($str); $i++) $temporary_sum += ($str[ $i ] - '0'); // converting temporary_sum into // string str again . $str = (string)($temporary_sum); // increase the count $count++; } return $count;} // Driver Code$s = \"991\";echo NumberofTimes($s); // This code is contributed// by Akanksha Rai?>", "e": 31723, "s": 30712, "text": null }, { "code": "<script> // Javascript program to// count number of times we// need to add digits to// get a single digit. function NumberofTimes(str){ // Here the count variable store // how many times we do sum of // digits and temporary_sum // always store the temporary sum // we get at each iteration . var temporary_sum = 0, count = 0; // In this loop we always compute // the sum of digits in temporary_ // sum variable and convert it // into string str till its length // become 1 and increase the count // in each iteration. while (str.length > 1) { temporary_sum = 0; // computing sum of its digits for (i = 0; i < str.length; i++) temporary_sum += ( str.charAt(i) - '0' ) ; // converting temporary_sum into string // str again . str = temporary_sum + \"\" ; // increase the count count++; } return count;} // Driver program to test above functionsvar s = \"991\";document.write(NumberofTimes(s)); // This code contributed by Princi Singh </script>", "e": 32784, "s": 31723, "text": null }, { "code": null, "e": 32793, "s": 32784, "text": "Output: " }, { "code": null, "e": 32795, "s": 32793, "text": "3" }, { "code": null, "e": 33218, "s": 32795, "text": "This article is contributed by Surya Priy. 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. " }, { "code": null, "e": 33231, "s": 33218, "text": "nitin mittal" }, { "code": null, "e": 33237, "s": 33231, "text": "ukasp" }, { "code": null, "e": 33250, "s": 33237, "text": "Akanksha_Rai" }, { "code": null, "e": 33263, "s": 33250, "text": "princi singh" }, { "code": null, "e": 33277, "s": 33263, "text": "number-digits" }, { "code": null, "e": 33290, "s": 33277, "text": "Mathematical" }, { "code": null, "e": 33303, "s": 33290, "text": "Mathematical" }, { "code": null, "e": 33401, "s": 33303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33410, "s": 33401, "text": "Comments" }, { "code": null, "e": 33423, "s": 33410, "text": "Old Comments" }, { "code": null, "e": 33472, "s": 33423, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33515, "s": 33472, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33558, "s": 33515, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 33590, "s": 33558, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 33621, "s": 33590, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33645, "s": 33621, "text": "Merge two sorted arrays" }, { "code": null, "e": 33687, "s": 33645, "text": "Euclidean algorithms (Basic and Extended)" }, { "code": null, "e": 33740, "s": 33687, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 33761, "s": 33740, "text": "Operators in C / C++" } ]
How to insert blank row into dataframe in R ? - GeeksforGeeks
17 Dec, 2021 In this article, we will discuss how to insert blank rows in dataframe in R Programming Language. The nrow() method in R is used to return the number of rows in a dataframe. A new row can be inserted at the end of the dataframe using the indexing technique. The new row is assigned a vector NA, in order to insert blank entries. The changes are made to the original dataframe. Syntax: df [ nrow(df) + 1 , ] <- NA Example: R # declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # calculating total rowsrows <- nrow(data_frame) # inserting row at enddata_frame[rows+1,] <- NA print ("Modified Dataframe")print (data_frame) Output [1] "Original Dataframe" col1 col2 col3 1 1 a 8 2 2 b 9 3 3 c 10 4 4 d 11 [1] "Modified Dataframe" col1 col2 col3 1 1 a 8 2 2 b 9 3 3 c 10 4 4 d 11 5 NA <NA> NA A package in R programming language “berryFunctions” can be invoked in order to work with converting the lists to data.frames and arrays, fit multiple functions. Syntax: install.packages(“berryFunctions”) The method insertRows() in R language can be used to append rows at the dataframe at any specified position. This method can also insert multiple rows into the dataframe. The new row is declared in the form of a vector. In the case of a blank row insertion, the new row is equivalent to NA. The changes have to be saved to the original dataframe. Syntax: insertRows(df, r, new = NA) Parameter : df – A dataframe to append row to r – The position at which to insert the row new – The new row vector to insert Example: R library ("berryFunctions") # declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # inserting row at enddata_frame <- insertRows(data_frame, 2 , new = NA) print ("Modified DataFrame")print (data_frame) Output [1] "Original Dataframe" col1 col2 col3 1 1 a 8 2 2 b 9 3 3 c 10 4 4 d 11 [1] "Modified DataFrame" col1 col2 col3 1 1 a 8 2 NA <NA> NA 3 2 b 9 4 3 c 10 5 4 d 11 simmytarika5 singghakshay sweetyty Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Data Visualization in R How to Replace specific values in column in R DataFrame ? Loops in R (for, while, repeat) Control Statements in R Programming Logistic Regression in R Programming How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R
[ { "code": null, "e": 24834, "s": 24806, "text": "\n17 Dec, 2021" }, { "code": null, "e": 24932, "s": 24834, "text": "In this article, we will discuss how to insert blank rows in dataframe in R Programming Language." }, { "code": null, "e": 25212, "s": 24932, "text": "The nrow() method in R is used to return the number of rows in a dataframe. A new row can be inserted at the end of the dataframe using the indexing technique. The new row is assigned a vector NA, in order to insert blank entries. The changes are made to the original dataframe. " }, { "code": null, "e": 25220, "s": 25212, "text": "Syntax:" }, { "code": null, "e": 25248, "s": 25220, "text": "df [ nrow(df) + 1 , ] <- NA" }, { "code": null, "e": 25257, "s": 25248, "text": "Example:" }, { "code": null, "e": 25259, "s": 25257, "text": "R" }, { "code": "# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print (\"Original Dataframe\")print (data_frame) # calculating total rowsrows <- nrow(data_frame) # inserting row at enddata_frame[rows+1,] <- NA print (\"Modified Dataframe\")print (data_frame)", "e": 25603, "s": 25259, "text": null }, { "code": null, "e": 25610, "s": 25603, "text": "Output" }, { "code": null, "e": 25845, "s": 25610, "text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 8\n2 2 b 9\n3 3 c 10\n4 4 d 11\n[1] \"Modified Dataframe\"\n col1 col2 col3\n1 1 a 8\n2 2 b 9\n3 3 c 10\n4 4 d 11\n5 NA <NA> NA" }, { "code": null, "e": 26008, "s": 25845, "text": "A package in R programming language “berryFunctions” can be invoked in order to work with converting the lists to data.frames and arrays, fit multiple functions. " }, { "code": null, "e": 26016, "s": 26008, "text": "Syntax:" }, { "code": null, "e": 26051, "s": 26016, "text": "install.packages(“berryFunctions”)" }, { "code": null, "e": 26399, "s": 26051, "text": "The method insertRows() in R language can be used to append rows at the dataframe at any specified position. This method can also insert multiple rows into the dataframe. The new row is declared in the form of a vector. In the case of a blank row insertion, the new row is equivalent to NA. The changes have to be saved to the original dataframe. " }, { "code": null, "e": 26407, "s": 26399, "text": "Syntax:" }, { "code": null, "e": 26435, "s": 26407, "text": "insertRows(df, r, new = NA)" }, { "code": null, "e": 26448, "s": 26435, "text": "Parameter : " }, { "code": null, "e": 26482, "s": 26448, "text": "df – A dataframe to append row to" }, { "code": null, "e": 26526, "s": 26482, "text": "r – The position at which to insert the row" }, { "code": null, "e": 26561, "s": 26526, "text": "new – The new row vector to insert" }, { "code": null, "e": 26570, "s": 26561, "text": "Example:" }, { "code": null, "e": 26572, "s": 26570, "text": "R" }, { "code": "library (\"berryFunctions\") # declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4), col2 = letters[1:4], col3 = c(8:11)) print (\"Original Dataframe\")print (data_frame) # inserting row at enddata_frame <- insertRows(data_frame, 2 , new = NA) print (\"Modified DataFrame\")print (data_frame)", "e": 26919, "s": 26572, "text": null }, { "code": null, "e": 26926, "s": 26919, "text": "Output" }, { "code": null, "e": 27171, "s": 26926, "text": "[1] \"Original Dataframe\" \ncol1 col2 col3 \n1 1 a 8 \n2 2 b 9 \n3 3 c 10 \n4 4 d 11 \n[1] \"Modified DataFrame\" \ncol1 col2 col3 \n1 1 a 8 \n2 NA <NA> NA \n3 2 b 9 \n4 3 c 10 \n5 4 d 11" }, { "code": null, "e": 27184, "s": 27171, "text": "simmytarika5" }, { "code": null, "e": 27197, "s": 27184, "text": "singghakshay" }, { "code": null, "e": 27206, "s": 27197, "text": "sweetyty" }, { "code": null, "e": 27213, "s": 27206, "text": "Picked" }, { "code": null, "e": 27234, "s": 27213, "text": "R DataFrame-Programs" }, { "code": null, "e": 27246, "s": 27234, "text": "R-DataFrame" }, { "code": null, "e": 27257, "s": 27246, "text": "R Language" }, { "code": null, "e": 27268, "s": 27257, "text": "R Programs" }, { "code": null, "e": 27366, "s": 27268, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27375, "s": 27366, "text": "Comments" }, { "code": null, "e": 27388, "s": 27375, "text": "Old Comments" }, { "code": null, "e": 27412, "s": 27388, "text": "Data Visualization in R" }, { "code": null, "e": 27470, "s": 27412, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27502, "s": 27470, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 27538, "s": 27502, "text": "Control Statements in R Programming" }, { "code": null, "e": 27575, "s": 27538, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 27633, "s": 27575, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 27677, "s": 27633, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 27726, "s": 27677, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 27784, "s": 27726, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
How to use filter within controllers in AngularJS ?
29 Jan, 2020 Filters are used to format the value of an expression and display to the user. It can be used in HTML Previews, Controllers or Services, and directives. AngularJS has many built-in filters, but we can easily define our own filter. Built-in filters: AngularJS filter Filter: AngularJS currency Filter: AngularJS number Filter: AngularJS date Filter: AngularJS json Filter: AngularJS lowercase Filter AngularJS uppercase Filter: AngularJS limitTo Filter AngularJS orderBy Filter If a filter currency is injected by using the dependency currencyFilter. The injected argument is a function that takes the value to format as the first argument and filter parameters starting with the second argument. The following ways are used to implement the filter. Approach 1: Using filters in view templatesSyntax: By applying the Filters to expressions in view templates:{{ expression | filter }} {{ expression | filter }} Filters can be applied to the result of another filter. It is called “chaining”:{{ expression | filter1 | filter2 | ... }} {{ expression | filter1 | filter2 | ... }} Filters may have arguments:{{ expression | filter:argument1:argument2:... }} {{ expression | filter:argument1:argument2:... }} Program: <!DOCTYPE html><html><head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head><body> <div ng-app="app1" ng-controller="currencyCtrl"> <h1>Price: {{ price | currency }}</h1> </div> <script> var app = angular.module('app1', []); app.controller('currencyCtrl', function($scope) { $scope.price = 100; }); </script> <p> The currency filter formats a number to a currency format. </p> </body> </html> Output: Approach 2: The filter is used in directives, services, and controllers. To achieve this, inject a dependency with the name of filter into your directive/controller/service. Program: <script>var listedItems = [ { itemID: 001, itemName: "Laptop", stockLeft: 1 }, { itemID: 002, itemName: "Cell Phone", stockLeft: 3 }, { itemID: 003, itemName: "Earphones", stockLeft: 0 }, { itemID: 004, itemName: "Chargers", stockLeft: 5 }, { itemID: 005, itemName: "Headphones", stockLeft: 0 }, { itemID: 006, itemName: "USB Cables", stockLeft: 15}]; listedItems = listedItems.filter(function (item) { return (item.stockLeft > 0);}); // This will display the no of items are in stockprompt("", "There are " + listedItems.length + " items left in shop.");</script> Output: Approach 3: It is the modification of the second approach. Filters can also be added to AngularJS to format data values. There is $filter service which is used in our AngularJS controller. In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope.finalResult = $filter("filter")( $scope.objArray, $scope.searchObj); }; $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope.finalResult = $filter("filter")( $scope.objArray, $scope.searchObj); }; AngularJS has some built-in filters that can be used to reduce an array’s execution or array at some points based on some condition.$scope.formatDate = $filter("date")($scope.date, "yyyy-MM-dd"); $scope.finalResult = $filter('uppercase')($scope.name); $scope.formatDate = $filter("date")($scope.date, "yyyy-MM-dd"); $scope.finalResult = $filter('uppercase')($scope.name); Program: Filters are added to directives, like ng-repeat, by using the pipe symbol or character `|`, followed by a filter tag. <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script></head> <body> <div ng-app="app1" ng-controller="piprCtrl"> <p> Looping with obj object created for nameList array: </p> <ul> <li ng-repeat="obj in nameList | orderBy:'city'"> {{ obj.name + ', ' + obj.city }} </li> </ul> </div> <script> angular.module("app1", []).controller( "piprCtrl", function($scope) { $scope.nameList = [{ name: "Hardik", city: "Chandigarh" }, { name: "Shekhar", city: "Dehradun" }, { name: "Sanyam", city: "Chandigarh" }, { name: "Poojan", city: "Dehradun" }, { name: "Aman", city: "Muzaffarnagar" }, { name: "Shashank", city: "Roorkee" }, { name: "Shazi", city: "Lucknow" }, { name: "Harshit", city: "Dehradun" }, { name: "Abhishek", city: "Gangoh" }]; }); </script> </body> </html> Output: AngularJS-Misc Picked AngularJS Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jan, 2020" }, { "code": null, "e": 285, "s": 54, "text": "Filters are used to format the value of an expression and display to the user. It can be used in HTML Previews, Controllers or Services, and directives. AngularJS has many built-in filters, but we can easily define our own filter." }, { "code": null, "e": 303, "s": 285, "text": "Built-in filters:" }, { "code": null, "e": 328, "s": 303, "text": "AngularJS filter Filter:" }, { "code": null, "e": 355, "s": 328, "text": "AngularJS currency Filter:" }, { "code": null, "e": 380, "s": 355, "text": "AngularJS number Filter:" }, { "code": null, "e": 403, "s": 380, "text": "AngularJS date Filter:" }, { "code": null, "e": 426, "s": 403, "text": "AngularJS json Filter:" }, { "code": null, "e": 453, "s": 426, "text": "AngularJS lowercase Filter" }, { "code": null, "e": 481, "s": 453, "text": "AngularJS uppercase Filter:" }, { "code": null, "e": 506, "s": 481, "text": "AngularJS limitTo Filter" }, { "code": null, "e": 531, "s": 506, "text": "AngularJS orderBy Filter" }, { "code": null, "e": 803, "s": 531, "text": "If a filter currency is injected by using the dependency currencyFilter. The injected argument is a function that takes the value to format as the first argument and filter parameters starting with the second argument. The following ways are used to implement the filter." }, { "code": null, "e": 854, "s": 803, "text": "Approach 1: Using filters in view templatesSyntax:" }, { "code": null, "e": 938, "s": 854, "text": "By applying the Filters to expressions in view templates:{{ expression | filter }} " }, { "code": null, "e": 965, "s": 938, "text": "{{ expression | filter }} " }, { "code": null, "e": 1088, "s": 965, "text": "Filters can be applied to the result of another filter. It is called “chaining”:{{ expression | filter1 | filter2 | ... }}" }, { "code": null, "e": 1131, "s": 1088, "text": "{{ expression | filter1 | filter2 | ... }}" }, { "code": null, "e": 1208, "s": 1131, "text": "Filters may have arguments:{{ expression | filter:argument1:argument2:... }}" }, { "code": null, "e": 1258, "s": 1208, "text": "{{ expression | filter:argument1:argument2:... }}" }, { "code": null, "e": 1267, "s": 1258, "text": "Program:" }, { "code": "<!DOCTYPE html><html><head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head><body> <div ng-app=\"app1\" ng-controller=\"currencyCtrl\"> <h1>Price: {{ price | currency }}</h1> </div> <script> var app = angular.module('app1', []); app.controller('currencyCtrl', function($scope) { $scope.price = 100; }); </script> <p> The currency filter formats a number to a currency format. </p> </body> </html>", "e": 1797, "s": 1267, "text": null }, { "code": null, "e": 1805, "s": 1797, "text": "Output:" }, { "code": null, "e": 1979, "s": 1805, "text": "Approach 2: The filter is used in directives, services, and controllers. To achieve this, inject a dependency with the name of filter into your directive/controller/service." }, { "code": null, "e": 1988, "s": 1979, "text": "Program:" }, { "code": "<script>var listedItems = [ { itemID: 001, itemName: \"Laptop\", stockLeft: 1 }, { itemID: 002, itemName: \"Cell Phone\", stockLeft: 3 }, { itemID: 003, itemName: \"Earphones\", stockLeft: 0 }, { itemID: 004, itemName: \"Chargers\", stockLeft: 5 }, { itemID: 005, itemName: \"Headphones\", stockLeft: 0 }, { itemID: 006, itemName: \"USB Cables\", stockLeft: 15}]; listedItems = listedItems.filter(function (item) { return (item.stockLeft > 0);}); // This will display the no of items are in stockprompt(\"\", \"There are \" + listedItems.length + \" items left in shop.\");</script>", "e": 2584, "s": 1988, "text": null }, { "code": null, "e": 2592, "s": 2584, "text": "Output:" }, { "code": null, "e": 2910, "s": 2592, "text": "Approach 3: It is the modification of the second approach. Filters can also be added to AngularJS to format data values. There is $filter service which is used in our AngularJS controller. In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter." }, { "code": null, "e": 2918, "s": 2910, "text": "Syntax:" }, { "code": null, "e": 3108, "s": 2918, "text": "$filter(\"filter\")(array, expression, compare, propertyKey)\nfunction myCtrl($scope, $filter)\n{\n $scope.finalResult = $filter(\"filter\")(\n $scope.objArray, $scope.searchObj);\n};\n" }, { "code": null, "e": 3298, "s": 3108, "text": "$filter(\"filter\")(array, expression, compare, propertyKey)\nfunction myCtrl($scope, $filter)\n{\n $scope.finalResult = $filter(\"filter\")(\n $scope.objArray, $scope.searchObj);\n};\n" }, { "code": null, "e": 3551, "s": 3298, "text": "AngularJS has some built-in filters that can be used to reduce an array’s execution or array at some points based on some condition.$scope.formatDate = $filter(\"date\")($scope.date, \"yyyy-MM-dd\");\n$scope.finalResult = $filter('uppercase')($scope.name);\n" }, { "code": null, "e": 3672, "s": 3551, "text": "$scope.formatDate = $filter(\"date\")($scope.date, \"yyyy-MM-dd\");\n$scope.finalResult = $filter('uppercase')($scope.name);\n" }, { "code": null, "e": 3799, "s": 3672, "text": "Program: Filters are added to directives, like ng-repeat, by using the pipe symbol or character `|`, followed by a filter tag." }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script></head> <body> <div ng-app=\"app1\" ng-controller=\"piprCtrl\"> <p> Looping with obj object created for nameList array: </p> <ul> <li ng-repeat=\"obj in nameList | orderBy:'city'\"> {{ obj.name + ', ' + obj.city }} </li> </ul> </div> <script> angular.module(\"app1\", []).controller( \"piprCtrl\", function($scope) { $scope.nameList = [{ name: \"Hardik\", city: \"Chandigarh\" }, { name: \"Shekhar\", city: \"Dehradun\" }, { name: \"Sanyam\", city: \"Chandigarh\" }, { name: \"Poojan\", city: \"Dehradun\" }, { name: \"Aman\", city: \"Muzaffarnagar\" }, { name: \"Shashank\", city: \"Roorkee\" }, { name: \"Shazi\", city: \"Lucknow\" }, { name: \"Harshit\", city: \"Dehradun\" }, { name: \"Abhishek\", city: \"Gangoh\" }]; }); </script> </body> </html>", "e": 5151, "s": 3799, "text": null }, { "code": null, "e": 5159, "s": 5151, "text": "Output:" }, { "code": null, "e": 5174, "s": 5159, "text": "AngularJS-Misc" }, { "code": null, "e": 5181, "s": 5174, "text": "Picked" }, { "code": null, "e": 5191, "s": 5181, "text": "AngularJS" }, { "code": null, "e": 5210, "s": 5191, "text": "Technical Scripter" }, { "code": null, "e": 5227, "s": 5210, "text": "Web Technologies" }, { "code": null, "e": 5254, "s": 5227, "text": "Web technologies Questions" } ]
Express.js | app.render() Function
18 Jun, 2020 The app.render() function is used to rendered HTML of a view via the callback function. This function returns the html in the callback function. Syntax: app.render(view, [locals], callback) Parameters: view: It is the name of the HTML page which is to be rendered.locals: It is an optional parameter that which is an object containing local variables for the view parameter passed.callback: It is a function that is passed as a parameter. view: It is the name of the HTML page which is to be rendered. locals: It is an optional parameter that which is an object containing local variables for the view parameter passed. callback: It is a function that is passed as a parameter. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressCreate a email.ejs file in views folder with the following code:Filename: email.ejs<html><head> <title>Function Demo</title></head><body> <h3>Greetings from GeeksforGeeks</h3></body></html>Note: You may use any view engine, like in this case, we have used ejs.After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.jsFilename: index.jsvar express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); app.render('email', function (err, html) { if (err) console.log(err); console.log(html);}); app.listen(PORT, function(err){ if (err) console.log("Error in server setup"); console.log("Server listening on Port", PORT);}); You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing express module, you can check your express version in command prompt using the command.npm version express npm version express Create a email.ejs file in views folder with the following code:Filename: email.ejs<html><head> <title>Function Demo</title></head><body> <h3>Greetings from GeeksforGeeks</h3></body></html>Note: You may use any view engine, like in this case, we have used ejs. <html><head> <title>Function Demo</title></head><body> <h3>Greetings from GeeksforGeeks</h3></body></html> Note: You may use any view engine, like in this case, we have used ejs. After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.jsFilename: index.jsvar express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); app.render('email', function (err, html) { if (err) console.log(err); console.log(html);}); app.listen(PORT, function(err){ if (err) console.log("Error in server setup"); console.log("Server listening on Port", PORT);}); node index.js Filename: index.js var express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); app.render('email', function (err, html) { if (err) console.log(err); console.log(html);}); app.listen(PORT, function(err){ if (err) console.log("Error in server setup"); console.log("Server listening on Port", PORT);}); Steps to run the program: Make sure you have installed express and ejs module using following command:npm install express npm install ejsRun index.js file using below command:node index.jsOutput: Make sure you have installed express and ejs module using following command:npm install express npm install ejs npm install express npm install ejs Run index.js file using below command:node index.jsOutput: node index.js Output: Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Jun, 2020" }, { "code": null, "e": 199, "s": 54, "text": "The app.render() function is used to rendered HTML of a view via the callback function. This function returns the html in the callback function." }, { "code": null, "e": 207, "s": 199, "text": "Syntax:" }, { "code": null, "e": 244, "s": 207, "text": "app.render(view, [locals], callback)" }, { "code": null, "e": 256, "s": 244, "text": "Parameters:" }, { "code": null, "e": 493, "s": 256, "text": "view: It is the name of the HTML page which is to be rendered.locals: It is an optional parameter that which is an object containing local variables for the view parameter passed.callback: It is a function that is passed as a parameter." }, { "code": null, "e": 556, "s": 493, "text": "view: It is the name of the HTML page which is to be rendered." }, { "code": null, "e": 674, "s": 556, "text": "locals: It is an optional parameter that which is an object containing local variables for the view parameter passed." }, { "code": null, "e": 732, "s": 674, "text": "callback: It is a function that is passed as a parameter." }, { "code": null, "e": 764, "s": 732, "text": "Installation of express module:" }, { "code": null, "e": 1797, "s": 764, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressCreate a email.ejs file in views folder with the following code:Filename: email.ejs<html><head> <title>Function Demo</title></head><body> <h3>Greetings from GeeksforGeeks</h3></body></html>Note: You may use any view engine, like in this case, we have used ejs.After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.jsFilename: index.jsvar express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); app.render('email', function (err, html) { if (err) console.log(err); console.log(html);}); app.listen(PORT, function(err){ if (err) console.log(\"Error in server setup\"); console.log(\"Server listening on Port\", PORT);});" }, { "code": null, "e": 1918, "s": 1797, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 1938, "s": 1918, "text": "npm install express" }, { "code": null, "e": 2062, "s": 1938, "text": "After installing express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 2082, "s": 2062, "text": "npm version express" }, { "code": null, "e": 2349, "s": 2082, "text": "Create a email.ejs file in views folder with the following code:Filename: email.ejs<html><head> <title>Function Demo</title></head><body> <h3>Greetings from GeeksforGeeks</h3></body></html>Note: You may use any view engine, like in this case, we have used ejs." }, { "code": "<html><head> <title>Function Demo</title></head><body> <h3>Greetings from GeeksforGeeks</h3></body></html>", "e": 2462, "s": 2349, "text": null }, { "code": null, "e": 2534, "s": 2462, "text": "Note: You may use any view engine, like in this case, we have used ejs." }, { "code": null, "e": 3058, "s": 2534, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.jsFilename: index.jsvar express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); app.render('email', function (err, html) { if (err) console.log(err); console.log(html);}); app.listen(PORT, function(err){ if (err) console.log(\"Error in server setup\"); console.log(\"Server listening on Port\", PORT);});" }, { "code": null, "e": 3072, "s": 3058, "text": "node index.js" }, { "code": null, "e": 3091, "s": 3072, "text": "Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; // View engine setupapp.set('view engine', 'ejs'); app.render('email', function (err, html) { if (err) console.log(err); console.log(html);}); app.listen(PORT, function(err){ if (err) console.log(\"Error in server setup\"); console.log(\"Server listening on Port\", PORT);});", "e": 3450, "s": 3091, "text": null }, { "code": null, "e": 3476, "s": 3450, "text": "Steps to run the program:" }, { "code": null, "e": 3646, "s": 3476, "text": "Make sure you have installed express and ejs module using following command:npm install express\nnpm install ejsRun index.js file using below command:node index.jsOutput:" }, { "code": null, "e": 3758, "s": 3646, "text": "Make sure you have installed express and ejs module using following command:npm install express\nnpm install ejs" }, { "code": null, "e": 3794, "s": 3758, "text": "npm install express\nnpm install ejs" }, { "code": null, "e": 3853, "s": 3794, "text": "Run index.js file using below command:node index.jsOutput:" }, { "code": null, "e": 3867, "s": 3853, "text": "node index.js" }, { "code": null, "e": 3875, "s": 3867, "text": "Output:" }, { "code": null, "e": 3886, "s": 3875, "text": "Express.js" }, { "code": null, "e": 3894, "s": 3886, "text": "Node.js" }, { "code": null, "e": 3911, "s": 3894, "text": "Web Technologies" } ]
Python Tkinter – Entry Widget
01 Feb, 2021 Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.In Python3 Tkinter is come preinstalled But you can also install it by using the command: pip install tkinter Example: Now let’s create a simple window using Tkinter Python3 # creating a simple tkinter window# if you are using python2# use import Tkinter as tk import tkinter as tk root = tk.Tk()root.title("First Tkinter Window")root.mainloop() Output : The Entry Widget is a Tkinter Widget used to Enter or display a single line of text. Syntax : entry = tk.Entry(parent, options) Parameters: 1) Parent: The Parent window or frame in which the widget to display.2) Options: The various options provided by the entry widget are: bg : The normal background color displayed behind the label and indicator. bd : The size of the border around the indicator. Default is 2 pixels. font : The font used for the text. fg : The color used to render the text. justify : If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT. relief : With the default value, relief=FLAT. You may set this option to any of the other styles like : SUNKEN, RIGID, RAISED, GROOVE show : Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show=”*”. textvariable : In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class. Methods: The various methods provided by the entry widget are: get() : Returns the entry’s current text as a string. delete() : Deletes characters from the widget insert ( index, ‘name’) : Inserts string ‘name’ before the character at the given index. Example: Python3 # Program to make a simple# login screen import tkinter as tk root=tk.Tk() # setting the windows sizeroot.geometry("600x400") # declaring string variable# for storing name and passwordname_var=tk.StringVar()passw_var=tk.StringVar() # defining a function that will# get the name and password and# print them on the screendef submit(): name=name_var.get() password=passw_var.get() print("The name is : " + name) print("The password is : " + password) name_var.set("") passw_var.set("") # creating a label for# name using widget Labelname_label = tk.Label(root, text = 'Username', font=('calibre',10, 'bold')) # creating a entry for input# name using widget Entryname_entry = tk.Entry(root,textvariable = name_var, font=('calibre',10,'normal')) # creating a label for passwordpassw_label = tk.Label(root, text = 'Password', font = ('calibre',10,'bold')) # creating a entry for passwordpassw_entry=tk.Entry(root, textvariable = passw_var, font = ('calibre',10,'normal'), show = '*') # creating a button using the widget# Button that will call the submit functionsub_btn=tk.Button(root,text = 'Submit', command = submit) # placing the label and entry in# the required position using grid# methodname_label.grid(row=0,column=0)name_entry.grid(row=0,column=1)passw_label.grid(row=1,column=0)passw_entry.grid(row=1,column=1)sub_btn.grid(row=2,column=1) # performing an infinite loop# for the window to displayroot.mainloop() Output : jpschnyder jnaut2012 Python-gui Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Feb, 2021" }, { "code": null, "e": 420, "s": 54, "text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.In Python3 Tkinter is come preinstalled But you can also install it by using the command: " }, { "code": null, "e": 440, "s": 420, "text": "pip install tkinter" }, { "code": null, "e": 497, "s": 440, "text": "Example: Now let’s create a simple window using Tkinter " }, { "code": null, "e": 505, "s": 497, "text": "Python3" }, { "code": "# creating a simple tkinter window# if you are using python2# use import Tkinter as tk import tkinter as tk root = tk.Tk()root.title(\"First Tkinter Window\")root.mainloop()", "e": 679, "s": 505, "text": null }, { "code": null, "e": 689, "s": 679, "text": "Output : " }, { "code": null, "e": 778, "s": 691, "text": "The Entry Widget is a Tkinter Widget used to Enter or display a single line of text. " }, { "code": null, "e": 788, "s": 778, "text": "Syntax : " }, { "code": null, "e": 822, "s": 788, "text": "entry = tk.Entry(parent, options)" }, { "code": null, "e": 836, "s": 822, "text": "Parameters: " }, { "code": null, "e": 973, "s": 836, "text": "1) Parent: The Parent window or frame in which the widget to display.2) Options: The various options provided by the entry widget are: " }, { "code": null, "e": 1049, "s": 973, "text": "bg : The normal background color displayed behind the label and indicator. " }, { "code": null, "e": 1121, "s": 1049, "text": "bd : The size of the border around the indicator. Default is 2 pixels. " }, { "code": null, "e": 1157, "s": 1121, "text": "font : The font used for the text. " }, { "code": null, "e": 1198, "s": 1157, "text": "fg : The color used to render the text. " }, { "code": null, "e": 1318, "s": 1198, "text": "justify : If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT. " }, { "code": null, "e": 1453, "s": 1318, "text": "relief : With the default value, relief=FLAT. You may set this option to any of the other styles like : SUNKEN, RIGID, RAISED, GROOVE " }, { "code": null, "e": 1611, "s": 1453, "text": "show : Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show=”*”. " }, { "code": null, "e": 1763, "s": 1611, "text": "textvariable : In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class." }, { "code": null, "e": 1827, "s": 1763, "text": "Methods: The various methods provided by the entry widget are: " }, { "code": null, "e": 1882, "s": 1827, "text": "get() : Returns the entry’s current text as a string. " }, { "code": null, "e": 1929, "s": 1882, "text": "delete() : Deletes characters from the widget " }, { "code": null, "e": 2020, "s": 1929, "text": "insert ( index, ‘name’) : Inserts string ‘name’ before the character at the given index. " }, { "code": null, "e": 2031, "s": 2020, "text": "Example: " }, { "code": null, "e": 2039, "s": 2031, "text": "Python3" }, { "code": "# Program to make a simple# login screen import tkinter as tk root=tk.Tk() # setting the windows sizeroot.geometry(\"600x400\") # declaring string variable# for storing name and passwordname_var=tk.StringVar()passw_var=tk.StringVar() # defining a function that will# get the name and password and# print them on the screendef submit(): name=name_var.get() password=passw_var.get() print(\"The name is : \" + name) print(\"The password is : \" + password) name_var.set(\"\") passw_var.set(\"\") # creating a label for# name using widget Labelname_label = tk.Label(root, text = 'Username', font=('calibre',10, 'bold')) # creating a entry for input# name using widget Entryname_entry = tk.Entry(root,textvariable = name_var, font=('calibre',10,'normal')) # creating a label for passwordpassw_label = tk.Label(root, text = 'Password', font = ('calibre',10,'bold')) # creating a entry for passwordpassw_entry=tk.Entry(root, textvariable = passw_var, font = ('calibre',10,'normal'), show = '*') # creating a button using the widget# Button that will call the submit functionsub_btn=tk.Button(root,text = 'Submit', command = submit) # placing the label and entry in# the required position using grid# methodname_label.grid(row=0,column=0)name_entry.grid(row=0,column=1)passw_label.grid(row=1,column=0)passw_entry.grid(row=1,column=1)sub_btn.grid(row=2,column=1) # performing an infinite loop# for the window to displayroot.mainloop()", "e": 3506, "s": 2039, "text": null }, { "code": null, "e": 3517, "s": 3506, "text": "Output : " }, { "code": null, "e": 3532, "s": 3521, "text": "jpschnyder" }, { "code": null, "e": 3542, "s": 3532, "text": "jnaut2012" }, { "code": null, "e": 3553, "s": 3542, "text": "Python-gui" }, { "code": null, "e": 3568, "s": 3553, "text": "Python-tkinter" }, { "code": null, "e": 3575, "s": 3568, "text": "Python" } ]
Maximize array sum after K negations | Set 1
05 Jul, 2022 Given an array of size n and a number k. We must modify array K a number of times. Here modify array means in each operation we can replace any array element arr[i] by -arr[i]. We need to perform this operation in such a way that after K operations, the sum of the array must be maximum? Examples : Input : arr[] = {-2, 0, 5, -1, 2}, K = 4Output: 10Explanation:1. Replace (-2) by -(-2), array becomes {2, 0, 5, -1, 2}2. Replace (-1) by -(-1), array becomes {2, 0, 5, 1, 2}3. Replace (0) by -(0), array becomes {2, 0, 5, 1, 2}4. Replace (0) by -(0), array becomes {2, 0, 5, 1, 2} Input : arr[] = {9, 8, 8, 5}, K = 3Output: 20 Naive approach: This problem has a very simple solution, we just have to replace the minimum element arr[i] in the array by -arr[i] for the current operation. In this way, we can make sum of the array maximum after K operations. One interesting case is, that once the minimum element becomes 0, we don’t need to make any more changes. Implementation: C++ C Java Python3 C# PHP Javascript // C++ program to maximize array sum after// k operations.#include <bits/stdc++.h>using namespace std; // This function does k operations on array in a way that// maximize the array sum. index --> stores the index of// current minimum element for j'th operationint maximumSum(int arr[], int n, int k){ // Modify array K number of times for (int i = 1; i <= k; i++) { int min = INT_MAX; int index = -1; // Find minimum element in array for current // operation and modify it i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find 0 as minimum // element, so it will useless to replace 0 by -(0) // for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << maximumSum(arr, n, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C program to maximize array sum after// k operations.#include<stdio.h>#include<stdlib.h>#include <limits.h> // This function does k operations on array in a way that// maximize the array sum. index --> stores the index of// current minimum element for j'th operationint maximumSum(int arr[], int n, int k){ // Modify array K number of times for (int i = 1; i <= k; i++) { int min = INT_MAX; int index = -1; // Find minimum element in array for current // operation and modify it i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find 0 as minimum // element, so it will useless to replace 0 by -(0) // for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printf("%d",maximumSum(arr, n, k)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to maximize array// sum after k operations. class GFG { // This function does k operations on array in a way // that maximize the array sum. index --> stores the // index of current minimum element for j'th operation static int maximumSum(int arr[], int n, int k) { // Modify array K number of times for (int i = 1; i <= k; i++) { int min = +2147483647; int index = -1; // Find minimum element in array for current // operation and modify it i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find 0 as minimum // element, so it will useless to replace 0 by // -(0) for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver code public static void main(String arg[]) { int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; int n = arr.length; System.out.print(maximumSum(arr, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python3 program to maximize# array sum after k operations. # This function does k operations on array# in a way that maximize the array sum.# index --> stores the index of current# minimum element for j'th operation def maximumSum(arr, n, k): # Modify array K number of times for i in range(1, k + 1): min = +2147483647 index = -1 # Find minimum element in array for # current operation and modify it # i.e; arr[j] --> -arr[j] for j in range(n): if (arr[j] < min): min = arr[j] index = j # this the condition if we find 0 as # minimum element, so it will useless to # replace 0 by -(0) for remaining operations if (min == 0): break # Modify element of array arr[index] = -arr[index] # Calculate sum of array sum = 0 for i in range(n): sum += arr[i] return sum # Driver codearr = [-2, 0, 5, -1, 2]k = 4n = len(arr)print(maximumSum(arr, n, k)) # This code is contributed by Anant Agarwal. // C# program to maximize array// sum after k operations.using System; class GFG { // This function does k operations // on array in a way that maximize // the array sum. index --> stores // the index of current minimum // element for j'th operation static int maximumSum(int[] arr, int n, int k) { // Modify array K number of times for (int i = 1; i <= k; i++) { int min = +2147483647; int index = -1; // Find minimum element in array for // current operation and modify it // i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find // 0 as minimum element, so it // will useless to replace 0 by -(0) // for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver code public static void Main() { int[] arr = { -2, 0, 5, -1, 2 }; int k = 4; int n = arr.Length; Console.Write(maximumSum(arr, n, k)); }} // This code is contributed by Nitin Mittal. <?php// PHP program to maximize// array sum after k operations. // This function does k operations// on array in a way that maximize// the array sum. index --> stores// the index of current minimum// element for j'th operationfunction maximumSum($arr, $n, $k){ $INT_MAX = 0; // Modify array K // number of times for ($i = 1; $i <= $k; $i++) { $min = $INT_MAX; $index = -1; // Find minimum element in // array for current operation // and modify it i.e; // arr[j] --> -arr[j] for ($j = 0; $j < $n; $j++) { if ($arr[$j] < $min) { $min = $arr[$j]; $index = $j; } } // this the condition if we // find 0 as minimum element, so // it will useless to replace 0 // by -(0) for remaining operations if ($min == 0) break; // Modify element of array $arr[$index] = -$arr[$index]; } // Calculate sum of array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; return $sum;} // Driver Code$arr = array(-2, 0, 5, -1, 2);$k = 4;$n = sizeof($arr) / sizeof($arr[0]);echo maximumSum($arr, $n, $k); // This code is contributed// by nitin mittal.?> <script> // Javascript program to maximize array// sum after k operations. // This function does k operations// on array in a way that maximize// the array sum. index --> stores// the index of current minimum// element for j'th operationfunction maximumSum(arr, n, k){ // Modify array K number of times for(let i = 1; i <= k; i++) { let min = +2147483647; let index = -1; // Find minimum element in array for // current operation and modify it // i.e; arr[j] --> -arr[j] for(let j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // This the condition if we find 0 as // minimum element, so it will useless to // replace 0 by -(0) for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array let sum = 0; for(let i = 0; i < n; i++) sum += arr[i]; return sum;} // Driver codelet arr = [ -2, 0, 5, -1, 2 ];let k = 4;let n = arr.length; document.write(maximumSum(arr, n, k)); // This code is contributed by code_hunt </script> 10 Time Complexity: O(k*n) Auxiliary Space: O(1) Approach 2 (Using Sort): When there is a need to negate at most k elements. Follow the steps below to solve this problem: Sort the given array arr.Then for a given value of k, Iterate through the array till k remains greater than 0, If the value of the array at any index is less than 0 we will change its sign and decrement k by 1.If we find a 0 in the array we will immediately set k equal to 0 to maximize our result.In some cases, if we have all the values in an array greater than 0 we will change the sign of positive values, as our array is already sorted we will be changing signs of lower values present in the array which will eventually maximize our sum. Sort the given array arr. Then for a given value of k, Iterate through the array till k remains greater than 0, If the value of the array at any index is less than 0 we will change its sign and decrement k by 1. If we find a 0 in the array we will immediately set k equal to 0 to maximize our result. In some cases, if we have all the values in an array greater than 0 we will change the sign of positive values, as our array is already sorted we will be changing signs of lower values present in the array which will eventually maximize our sum. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ program to find maximum array sum after at most k// negations.#include <bits/stdc++.h> using namespace std; int sol(int arr[], int n, int k){ int sum = 0; int i = 0; // Sorting given array using in-built sort function sort(arr, arr + n); while (k > 0) { // If we find a 0 in our sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (int j = 0; j < n; j++) sum += arr[j]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sol(arr, n, 4) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C++ program to find maximum array sum after at most k// negations.#include <stdio.h>#include <stdlib.h> int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} int sol(int arr[], int n, int k){ int sum = 0; int i = 0; // Sorting given array using in-built sort function qsort(arr, n, sizeof(int), cmpfunc); while (k > 0) { // If we find a 0 in our sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (int j = 0; j < n; j++) sum += arr[j]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf("%d", sol(arr, n, 4)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to find maximum array sum// after at most k negations.import java.util.Arrays; public class GFG { static int sol(int arr[], int k) { // Sorting given array using in-built java sort // function Arrays.sort(arr); int sum = 0; int i = 0; while (k > 0) { // If we find a 0 in our sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (int j = 0; j < arr.length; j++) sum += arr[j]; return sum; } // Driver Code public static void main(String[] args) { int arr[] = { -2, 0, 5, -1, 2 }; System.out.println(sol(arr, 4)); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python3 program to find maximum array# sum after at most k negations def sol(arr, k): # Sorting given array using # in-built java sort function arr.sort() Sum = 0 i = 0 while (k > 0): # If we find a 0 in our # sorted array, we stop if (arr[i] >= 0): k = 0 else: arr[i] = (-1) * arr[i] k = k - 1 i += 1 # Calculating sum for j in range(len(arr)): Sum += arr[j] return Sum # Driver codearr = [-2, 0, 5, -1, 2] print(sol(arr, 4)) # This code is contributed by avanitrachhadiya2155 // C# program to find maximum array sum// after at most k negations.using System; class GFG{ static int sol(int []arr, int k){ // Sorting given array using // in-built java sort function Array.Sort(arr); int sum = 0; int i = 0; while (k > 0) { // If we find a 0 in our // sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for(int j = 0; j < arr.Length; j++) { sum += arr[j]; } return sum;} // Driver codepublic static void Main(string[] args){ int []arr = { -2, 0, 5, -1, 2 }; Console.Write(sol(arr, 4));}} // This code is contributed by rutvik_56 <script> // JavaScript program to find maximum array sum// after at most k negations. function sol(arr, k) { // Sorting given array using in-built // java sort function arr.sort(); let sum = 0; let i = 0; while (k > 0) { // If we find a 0 in our // sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (let j = 0; j < arr.length; j++) { sum += arr[j]; } return sum; } // Driver code let arr = [ -2, 0, 5, -1, 2 ]; document.write(sol(arr, 4)); // This code is contributed by souravghosh0416. </script> 10 Time Complexity: O(n*logn) Auxiliary Space: O(1) The above approach 2 is optimal when there is a need to negate at most k elements. To solve when there are exactly k negations the algorithm is given below. Sort the array in ascending order. Initialize i = 0.Increment i and multiply all negative elements by -1 till k becomes or a positive element is reached.Check if the end of the array has occurred. If true then go to (n-1)th element.If k ==0 or k is even, return the sum of all elements. Else multiply the absolute of minimum of ith or (i-1) th element by -1.Return sum of the array. Sort the array in ascending order. Initialize i = 0. Increment i and multiply all negative elements by -1 till k becomes or a positive element is reached. Check if the end of the array has occurred. If true then go to (n-1)th element. If k ==0 or k is even, return the sum of all elements. Else multiply the absolute of minimum of ith or (i-1) th element by -1. Return sum of the array. Below is the implementation of the above approach: C++ Java Python3 C# Javascript C // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate sum of the arraylong long int sumArray(long long int* arr, int n){ long long int sum = 0; // Iterate from 0 to n - 1 for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to maximize sumlong long int maximizeSum(long long int arr[], int n, int k){ sort(arr, arr + n); int i = 0; // Iterate from 0 to n - 1 for (i = 0; i < n; i++) { if (k && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) return sumArray(arr, n); if (i != 0 && abs(arr[i]) >= abs(arr[i - 1])) i--; arr[i] *= -1; return sumArray(arr, n);} // Driver Codeint main(){ int n = 5; int k = 4; long long int arr[5] = { -2, 0, 5, -1, 2 }; // Function Call cout << maximizeSum(arr, n, k) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program for the above approachimport java.util.*; class GFG { // Function to calculate sum of the array static int sumArray(int[] arr, int n) { int sum = 0; // Iterate from 0 to n - 1 for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Function to maximize sum static int maximizeSum(int arr[], int n, int k) { Arrays.sort(arr); int i = 0; // Iterate from 0 to n - 1 for (i = 0; i < n; i++) { if (k != 0 && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) return sumArray(arr, n); if (i != 0 && Math.abs(arr[i]) >= Math.abs(arr[i - 1])) i--; arr[i] *= -1; return sumArray(arr, n); } // Driver Code public static void main(String args[]) { int n = 5; int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; // Function Call System.out.print(maximizeSum(arr, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python3 program for the above approach # Function to calculate sum of the arraydef sumArray(arr, n): sum = 0 # Iterate from 0 to n - 1 for i in range(n): sum += arr[i] return sum # Function to maximize sumdef maximizeSum(arr, n, k): arr.sort() i = 0 # Iterate from 0 to n - 1 for i in range(n): if (k and arr[i] < 0): arr[i] *= -1 k -= 1 continue break if (i == n): i -= 1 if (k == 0 or k % 2 == 0): return sumArray(arr, n) if (i != 0 and abs(arr[i]) >= abs(arr[i - 1])): i -= 1 arr[i] *= -1 return sumArray(arr, n) # Driver Coden = 5k = 4arr = [ -2, 0, 5, -1, 2 ] # Function Callprint(maximizeSum(arr, n, k)) # This code is contributed by rohitsingh07052 // C# program for the above approachusing System; class GFG{ // Function to calculate sum of the arraystatic int sumArray( int[] arr, int n){ int sum = 0; // Iterate from 0 to n - 1 for(int i = 0; i < n; i++) { sum += arr[i]; } return sum;} // Function to maximize sumstatic int maximizeSum(int[] arr, int n, int k){ Array.Sort(arr); int i = 0; // Iterate from 0 to n - 1 for(i = 0; i < n; i++) { if (k != 0 && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) { return sumArray(arr, n); } if (i != 0 && Math.Abs(arr[i]) >= Math.Abs(arr[i - 1])) { i--; } arr[i] *= -1; return sumArray(arr, n);} // Driver Codestatic public void Main(){ int n = 5; int[] arr = { -2, 0, 5, -1, 2 }; int k = 4; // Function Call Console.Write(maximizeSum(arr, n, k));}} // This code is contributed by shubhamsingh10 <script>// Javascript program for the above approach // Function to calculate sum of the arrayfunction sumArray(arr,n){ let sum = 0; // Iterate from 0 to n - 1 for(let i = 0; i < n; i++) { sum += arr[i]; } return sum;} // Function to maximize sumfunction maximizeSum(arr,n,k){ (arr).sort(function(a,b){return a-b;}); let i = 0; // Iterate from 0 to n - 1 for(i = 0; i < n; i++) { if (k != 0 && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) { return sumArray(arr, n); } if (i != 0 && Math.abs(arr[i]) >= Math.abs(arr[i - 1])) { i--; } arr[i] *= -1; return sumArray(arr, n);} // Driver Codelet n = 5;let k = 4; let arr=[ -2, 0, 5, -1, 2 ]; // Function Calldocument.write(maximizeSum(arr, n, k)); // This code is contributed by ab2127</script> // C program for the above approach#include <stdio.h>#include<stdlib.h> // Function to calculate sum of the arraylong long int sumArray(long long int* arr, int n){ long long int sum = 0; // Iterate from 0 to n - 1 for (int i = 0; i < n; i++) sum += arr[i]; return sum;} void merge(long long int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of thesub-array of arr to be sorted */void mergeSort(long long int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} // Function to maximize sumlong long int maximizeSum(long long int arr[], int n, int k){ mergeSort(arr,0,n-1); int i = 0; // Iterate from 0 to n - 1 for (i = 0; i < n; i++) { if (k && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) return sumArray(arr, n); if (i != 0 && abs(arr[i]) >= abs(arr[i - 1])) i--; arr[i] *= -1; return sumArray(arr, n);} // Driver Codeint main(){ int n = 5; int k = 4; long long int arr[] = { -2, 0, 5, -1, 2 }; // Function Call printf("%lld",maximizeSum(arr,n,k)); return 0;} 10 Time Complexity: O(n*logn) Auxiliary Space: O(1) Maximize array sum after K negations | Set 2 This article is contributed by Shashank Mishra ( Gullu ). 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. nitin mittal nidhi_biet RitikGarg2 rutvik_56 avanitrachhadiya2155 pratham76 yashupadhyayece19 rjrachit code_hunt sanjoy_62 rohitsingh07052 souravghosh0416 ab2127 akashkumarsmet18 SHUBHAMSINGH10 harendrakumar123 adityakumar129 rexomkar hardikkoriintern Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2022" }, { "code": null, "e": 340, "s": 52, "text": "Given an array of size n and a number k. We must modify array K a number of times. Here modify array means in each operation we can replace any array element arr[i] by -arr[i]. We need to perform this operation in such a way that after K operations, the sum of the array must be maximum?" }, { "code": null, "e": 352, "s": 340, "text": "Examples : " }, { "code": null, "e": 632, "s": 352, "text": "Input : arr[] = {-2, 0, 5, -1, 2}, K = 4Output: 10Explanation:1. Replace (-2) by -(-2), array becomes {2, 0, 5, -1, 2}2. Replace (-1) by -(-1), array becomes {2, 0, 5, 1, 2}3. Replace (0) by -(0), array becomes {2, 0, 5, 1, 2}4. Replace (0) by -(0), array becomes {2, 0, 5, 1, 2}" }, { "code": null, "e": 678, "s": 632, "text": "Input : arr[] = {9, 8, 8, 5}, K = 3Output: 20" }, { "code": null, "e": 1014, "s": 678, "text": "Naive approach: This problem has a very simple solution, we just have to replace the minimum element arr[i] in the array by -arr[i] for the current operation. In this way, we can make sum of the array maximum after K operations. One interesting case is, that once the minimum element becomes 0, we don’t need to make any more changes. " }, { "code": null, "e": 1030, "s": 1014, "text": "Implementation:" }, { "code": null, "e": 1034, "s": 1030, "text": "C++" }, { "code": null, "e": 1036, "s": 1034, "text": "C" }, { "code": null, "e": 1041, "s": 1036, "text": "Java" }, { "code": null, "e": 1049, "s": 1041, "text": "Python3" }, { "code": null, "e": 1052, "s": 1049, "text": "C#" }, { "code": null, "e": 1056, "s": 1052, "text": "PHP" }, { "code": null, "e": 1067, "s": 1056, "text": "Javascript" }, { "code": "// C++ program to maximize array sum after// k operations.#include <bits/stdc++.h>using namespace std; // This function does k operations on array in a way that// maximize the array sum. index --> stores the index of// current minimum element for j'th operationint maximumSum(int arr[], int n, int k){ // Modify array K number of times for (int i = 1; i <= k; i++) { int min = INT_MAX; int index = -1; // Find minimum element in array for current // operation and modify it i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find 0 as minimum // element, so it will useless to replace 0 by -(0) // for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); cout << maximumSum(arr, n, k); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2346, "s": 1067, "text": null }, { "code": "// C program to maximize array sum after// k operations.#include<stdio.h>#include<stdlib.h>#include <limits.h> // This function does k operations on array in a way that// maximize the array sum. index --> stores the index of// current minimum element for j'th operationint maximumSum(int arr[], int n, int k){ // Modify array K number of times for (int i = 1; i <= k; i++) { int min = INT_MAX; int index = -1; // Find minimum element in array for current // operation and modify it i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find 0 as minimum // element, so it will useless to replace 0 by -(0) // for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\",maximumSum(arr, n, k)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 3638, "s": 2346, "text": null }, { "code": "// Java program to maximize array// sum after k operations. class GFG { // This function does k operations on array in a way // that maximize the array sum. index --> stores the // index of current minimum element for j'th operation static int maximumSum(int arr[], int n, int k) { // Modify array K number of times for (int i = 1; i <= k; i++) { int min = +2147483647; int index = -1; // Find minimum element in array for current // operation and modify it i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find 0 as minimum // element, so it will useless to replace 0 by // -(0) for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver code public static void main(String arg[]) { int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; int n = arr.length; System.out.print(maximumSum(arr, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 5059, "s": 3638, "text": null }, { "code": "# Python3 program to maximize# array sum after k operations. # This function does k operations on array# in a way that maximize the array sum.# index --> stores the index of current# minimum element for j'th operation def maximumSum(arr, n, k): # Modify array K number of times for i in range(1, k + 1): min = +2147483647 index = -1 # Find minimum element in array for # current operation and modify it # i.e; arr[j] --> -arr[j] for j in range(n): if (arr[j] < min): min = arr[j] index = j # this the condition if we find 0 as # minimum element, so it will useless to # replace 0 by -(0) for remaining operations if (min == 0): break # Modify element of array arr[index] = -arr[index] # Calculate sum of array sum = 0 for i in range(n): sum += arr[i] return sum # Driver codearr = [-2, 0, 5, -1, 2]k = 4n = len(arr)print(maximumSum(arr, n, k)) # This code is contributed by Anant Agarwal.", "e": 6119, "s": 5059, "text": null }, { "code": "// C# program to maximize array// sum after k operations.using System; class GFG { // This function does k operations // on array in a way that maximize // the array sum. index --> stores // the index of current minimum // element for j'th operation static int maximumSum(int[] arr, int n, int k) { // Modify array K number of times for (int i = 1; i <= k; i++) { int min = +2147483647; int index = -1; // Find minimum element in array for // current operation and modify it // i.e; arr[j] --> -arr[j] for (int j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // this the condition if we find // 0 as minimum element, so it // will useless to replace 0 by -(0) // for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Driver code public static void Main() { int[] arr = { -2, 0, 5, -1, 2 }; int k = 4; int n = arr.Length; Console.Write(maximumSum(arr, n, k)); }} // This code is contributed by Nitin Mittal.", "e": 7595, "s": 6119, "text": null }, { "code": "<?php// PHP program to maximize// array sum after k operations. // This function does k operations// on array in a way that maximize// the array sum. index --> stores// the index of current minimum// element for j'th operationfunction maximumSum($arr, $n, $k){ $INT_MAX = 0; // Modify array K // number of times for ($i = 1; $i <= $k; $i++) { $min = $INT_MAX; $index = -1; // Find minimum element in // array for current operation // and modify it i.e; // arr[j] --> -arr[j] for ($j = 0; $j < $n; $j++) { if ($arr[$j] < $min) { $min = $arr[$j]; $index = $j; } } // this the condition if we // find 0 as minimum element, so // it will useless to replace 0 // by -(0) for remaining operations if ($min == 0) break; // Modify element of array $arr[$index] = -$arr[$index]; } // Calculate sum of array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; return $sum;} // Driver Code$arr = array(-2, 0, 5, -1, 2);$k = 4;$n = sizeof($arr) / sizeof($arr[0]);echo maximumSum($arr, $n, $k); // This code is contributed// by nitin mittal.?>", "e": 8861, "s": 7595, "text": null }, { "code": "<script> // Javascript program to maximize array// sum after k operations. // This function does k operations// on array in a way that maximize// the array sum. index --> stores// the index of current minimum// element for j'th operationfunction maximumSum(arr, n, k){ // Modify array K number of times for(let i = 1; i <= k; i++) { let min = +2147483647; let index = -1; // Find minimum element in array for // current operation and modify it // i.e; arr[j] --> -arr[j] for(let j = 0; j < n; j++) { if (arr[j] < min) { min = arr[j]; index = j; } } // This the condition if we find 0 as // minimum element, so it will useless to // replace 0 by -(0) for remaining operations if (min == 0) break; // Modify element of array arr[index] = -arr[index]; } // Calculate sum of array let sum = 0; for(let i = 0; i < n; i++) sum += arr[i]; return sum;} // Driver codelet arr = [ -2, 0, 5, -1, 2 ];let k = 4;let n = arr.length; document.write(maximumSum(arr, n, k)); // This code is contributed by code_hunt </script>", "e": 10099, "s": 8861, "text": null }, { "code": null, "e": 10102, "s": 10099, "text": "10" }, { "code": null, "e": 10148, "s": 10102, "text": "Time Complexity: O(k*n) Auxiliary Space: O(1)" }, { "code": null, "e": 10225, "s": 10148, "text": "Approach 2 (Using Sort): When there is a need to negate at most k elements." }, { "code": null, "e": 10271, "s": 10225, "text": "Follow the steps below to solve this problem:" }, { "code": null, "e": 10815, "s": 10271, "text": "Sort the given array arr.Then for a given value of k, Iterate through the array till k remains greater than 0, If the value of the array at any index is less than 0 we will change its sign and decrement k by 1.If we find a 0 in the array we will immediately set k equal to 0 to maximize our result.In some cases, if we have all the values in an array greater than 0 we will change the sign of positive values, as our array is already sorted we will be changing signs of lower values present in the array which will eventually maximize our sum." }, { "code": null, "e": 10841, "s": 10815, "text": "Sort the given array arr." }, { "code": null, "e": 11027, "s": 10841, "text": "Then for a given value of k, Iterate through the array till k remains greater than 0, If the value of the array at any index is less than 0 we will change its sign and decrement k by 1." }, { "code": null, "e": 11116, "s": 11027, "text": "If we find a 0 in the array we will immediately set k equal to 0 to maximize our result." }, { "code": null, "e": 11362, "s": 11116, "text": "In some cases, if we have all the values in an array greater than 0 we will change the sign of positive values, as our array is already sorted we will be changing signs of lower values present in the array which will eventually maximize our sum." }, { "code": null, "e": 11413, "s": 11362, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 11417, "s": 11413, "text": "C++" }, { "code": null, "e": 11419, "s": 11417, "text": "C" }, { "code": null, "e": 11424, "s": 11419, "text": "Java" }, { "code": null, "e": 11432, "s": 11424, "text": "Python3" }, { "code": null, "e": 11435, "s": 11432, "text": "C#" }, { "code": null, "e": 11446, "s": 11435, "text": "Javascript" }, { "code": "// C++ program to find maximum array sum after at most k// negations.#include <bits/stdc++.h> using namespace std; int sol(int arr[], int n, int k){ int sum = 0; int i = 0; // Sorting given array using in-built sort function sort(arr, arr + n); while (k > 0) { // If we find a 0 in our sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (int j = 0; j < n; j++) sum += arr[j]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sol(arr, n, 4) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 12221, "s": 11446, "text": null }, { "code": "// C++ program to find maximum array sum after at most k// negations.#include <stdio.h>#include <stdlib.h> int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} int sol(int arr[], int n, int k){ int sum = 0; int i = 0; // Sorting given array using in-built sort function qsort(arr, n, sizeof(int), cmpfunc); while (k > 0) { // If we find a 0 in our sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (int j = 0; j < n; j++) sum += arr[j]; return sum;} // Driver codeint main(){ int arr[] = { -2, 0, 5, -1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"%d\", sol(arr, n, 4)); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 13080, "s": 12221, "text": null }, { "code": "// Java program to find maximum array sum// after at most k negations.import java.util.Arrays; public class GFG { static int sol(int arr[], int k) { // Sorting given array using in-built java sort // function Arrays.sort(arr); int sum = 0; int i = 0; while (k > 0) { // If we find a 0 in our sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (int j = 0; j < arr.length; j++) sum += arr[j]; return sum; } // Driver Code public static void main(String[] args) { int arr[] = { -2, 0, 5, -1, 2 }; System.out.println(sol(arr, 4)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 13960, "s": 13080, "text": null }, { "code": "# Python3 program to find maximum array# sum after at most k negations def sol(arr, k): # Sorting given array using # in-built java sort function arr.sort() Sum = 0 i = 0 while (k > 0): # If we find a 0 in our # sorted array, we stop if (arr[i] >= 0): k = 0 else: arr[i] = (-1) * arr[i] k = k - 1 i += 1 # Calculating sum for j in range(len(arr)): Sum += arr[j] return Sum # Driver codearr = [-2, 0, 5, -1, 2] print(sol(arr, 4)) # This code is contributed by avanitrachhadiya2155", "e": 14551, "s": 13960, "text": null }, { "code": "// C# program to find maximum array sum// after at most k negations.using System; class GFG{ static int sol(int []arr, int k){ // Sorting given array using // in-built java sort function Array.Sort(arr); int sum = 0; int i = 0; while (k > 0) { // If we find a 0 in our // sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for(int j = 0; j < arr.Length; j++) { sum += arr[j]; } return sum;} // Driver codepublic static void Main(string[] args){ int []arr = { -2, 0, 5, -1, 2 }; Console.Write(sol(arr, 4));}} // This code is contributed by rutvik_56", "e": 15336, "s": 14551, "text": null }, { "code": "<script> // JavaScript program to find maximum array sum// after at most k negations. function sol(arr, k) { // Sorting given array using in-built // java sort function arr.sort(); let sum = 0; let i = 0; while (k > 0) { // If we find a 0 in our // sorted array, we stop if (arr[i] >= 0) k = 0; else { arr[i] = (-1) * arr[i]; k = k - 1; } i++; } // Calculating sum for (let j = 0; j < arr.length; j++) { sum += arr[j]; } return sum; } // Driver code let arr = [ -2, 0, 5, -1, 2 ]; document.write(sol(arr, 4)); // This code is contributed by souravghosh0416. </script>", "e": 16193, "s": 15336, "text": null }, { "code": null, "e": 16196, "s": 16193, "text": "10" }, { "code": null, "e": 16245, "s": 16196, "text": "Time Complexity: O(n*logn) Auxiliary Space: O(1)" }, { "code": null, "e": 16402, "s": 16245, "text": "The above approach 2 is optimal when there is a need to negate at most k elements. To solve when there are exactly k negations the algorithm is given below." }, { "code": null, "e": 16785, "s": 16402, "text": "Sort the array in ascending order. Initialize i = 0.Increment i and multiply all negative elements by -1 till k becomes or a positive element is reached.Check if the end of the array has occurred. If true then go to (n-1)th element.If k ==0 or k is even, return the sum of all elements. Else multiply the absolute of minimum of ith or (i-1) th element by -1.Return sum of the array." }, { "code": null, "e": 16838, "s": 16785, "text": "Sort the array in ascending order. Initialize i = 0." }, { "code": null, "e": 16940, "s": 16838, "text": "Increment i and multiply all negative elements by -1 till k becomes or a positive element is reached." }, { "code": null, "e": 17020, "s": 16940, "text": "Check if the end of the array has occurred. If true then go to (n-1)th element." }, { "code": null, "e": 17147, "s": 17020, "text": "If k ==0 or k is even, return the sum of all elements. Else multiply the absolute of minimum of ith or (i-1) th element by -1." }, { "code": null, "e": 17172, "s": 17147, "text": "Return sum of the array." }, { "code": null, "e": 17223, "s": 17172, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 17227, "s": 17223, "text": "C++" }, { "code": null, "e": 17232, "s": 17227, "text": "Java" }, { "code": null, "e": 17240, "s": 17232, "text": "Python3" }, { "code": null, "e": 17243, "s": 17240, "text": "C#" }, { "code": null, "e": 17254, "s": 17243, "text": "Javascript" }, { "code": null, "e": 17256, "s": 17254, "text": "C" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate sum of the arraylong long int sumArray(long long int* arr, int n){ long long int sum = 0; // Iterate from 0 to n - 1 for (int i = 0; i < n; i++) sum += arr[i]; return sum;} // Function to maximize sumlong long int maximizeSum(long long int arr[], int n, int k){ sort(arr, arr + n); int i = 0; // Iterate from 0 to n - 1 for (i = 0; i < n; i++) { if (k && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) return sumArray(arr, n); if (i != 0 && abs(arr[i]) >= abs(arr[i - 1])) i--; arr[i] *= -1; return sumArray(arr, n);} // Driver Codeint main(){ int n = 5; int k = 4; long long int arr[5] = { -2, 0, 5, -1, 2 }; // Function Call cout << maximizeSum(arr, n, k) << endl; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 18296, "s": 17256, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { // Function to calculate sum of the array static int sumArray(int[] arr, int n) { int sum = 0; // Iterate from 0 to n - 1 for (int i = 0; i < n; i++) sum += arr[i]; return sum; } // Function to maximize sum static int maximizeSum(int arr[], int n, int k) { Arrays.sort(arr); int i = 0; // Iterate from 0 to n - 1 for (i = 0; i < n; i++) { if (k != 0 && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) return sumArray(arr, n); if (i != 0 && Math.abs(arr[i]) >= Math.abs(arr[i - 1])) i--; arr[i] *= -1; return sumArray(arr, n); } // Driver Code public static void main(String args[]) { int n = 5; int arr[] = { -2, 0, 5, -1, 2 }; int k = 4; // Function Call System.out.print(maximizeSum(arr, n, k)); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 19475, "s": 18296, "text": null }, { "code": "# Python3 program for the above approach # Function to calculate sum of the arraydef sumArray(arr, n): sum = 0 # Iterate from 0 to n - 1 for i in range(n): sum += arr[i] return sum # Function to maximize sumdef maximizeSum(arr, n, k): arr.sort() i = 0 # Iterate from 0 to n - 1 for i in range(n): if (k and arr[i] < 0): arr[i] *= -1 k -= 1 continue break if (i == n): i -= 1 if (k == 0 or k % 2 == 0): return sumArray(arr, n) if (i != 0 and abs(arr[i]) >= abs(arr[i - 1])): i -= 1 arr[i] *= -1 return sumArray(arr, n) # Driver Coden = 5k = 4arr = [ -2, 0, 5, -1, 2 ] # Function Callprint(maximizeSum(arr, n, k)) # This code is contributed by rohitsingh07052", "e": 20288, "s": 19475, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to calculate sum of the arraystatic int sumArray( int[] arr, int n){ int sum = 0; // Iterate from 0 to n - 1 for(int i = 0; i < n; i++) { sum += arr[i]; } return sum;} // Function to maximize sumstatic int maximizeSum(int[] arr, int n, int k){ Array.Sort(arr); int i = 0; // Iterate from 0 to n - 1 for(i = 0; i < n; i++) { if (k != 0 && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) { return sumArray(arr, n); } if (i != 0 && Math.Abs(arr[i]) >= Math.Abs(arr[i - 1])) { i--; } arr[i] *= -1; return sumArray(arr, n);} // Driver Codestatic public void Main(){ int n = 5; int[] arr = { -2, 0, 5, -1, 2 }; int k = 4; // Function Call Console.Write(maximizeSum(arr, n, k));}} // This code is contributed by shubhamsingh10", "e": 21337, "s": 20288, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to calculate sum of the arrayfunction sumArray(arr,n){ let sum = 0; // Iterate from 0 to n - 1 for(let i = 0; i < n; i++) { sum += arr[i]; } return sum;} // Function to maximize sumfunction maximizeSum(arr,n,k){ (arr).sort(function(a,b){return a-b;}); let i = 0; // Iterate from 0 to n - 1 for(i = 0; i < n; i++) { if (k != 0 && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) { return sumArray(arr, n); } if (i != 0 && Math.abs(arr[i]) >= Math.abs(arr[i - 1])) { i--; } arr[i] *= -1; return sumArray(arr, n);} // Driver Codelet n = 5;let k = 4; let arr=[ -2, 0, 5, -1, 2 ]; // Function Calldocument.write(maximizeSum(arr, n, k)); // This code is contributed by ab2127</script>", "e": 22310, "s": 21337, "text": null }, { "code": "// C program for the above approach#include <stdio.h>#include<stdlib.h> // Function to calculate sum of the arraylong long int sumArray(long long int* arr, int n){ long long int sum = 0; // Iterate from 0 to n - 1 for (int i = 0; i < n; i++) sum += arr[i]; return sum;} void merge(long long int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of thesub-array of arr to be sorted */void mergeSort(long long int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} // Function to maximize sumlong long int maximizeSum(long long int arr[], int n, int k){ mergeSort(arr,0,n-1); int i = 0; // Iterate from 0 to n - 1 for (i = 0; i < n; i++) { if (k && arr[i] < 0) { arr[i] *= -1; k--; continue; } break; } if (i == n) i--; if (k == 0 || k % 2 == 0) return sumArray(arr, n); if (i != 0 && abs(arr[i]) >= abs(arr[i - 1])) i--; arr[i] *= -1; return sumArray(arr, n);} // Driver Codeint main(){ int n = 5; int k = 4; long long int arr[] = { -2, 0, 5, -1, 2 }; // Function Call printf(\"%lld\",maximizeSum(arr,n,k)); return 0;}", "e": 24652, "s": 22310, "text": null }, { "code": null, "e": 24655, "s": 24652, "text": "10" }, { "code": null, "e": 24705, "s": 24655, "text": "Time Complexity: O(n*logn) Auxiliary Space: O(1)" }, { "code": null, "e": 24751, "s": 24705, "text": "Maximize array sum after K negations | Set 2 " }, { "code": null, "e": 25060, "s": 24751, "text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using 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": 25073, "s": 25060, "text": "nitin mittal" }, { "code": null, "e": 25084, "s": 25073, "text": "nidhi_biet" }, { "code": null, "e": 25095, "s": 25084, "text": "RitikGarg2" }, { "code": null, "e": 25105, "s": 25095, "text": "rutvik_56" }, { "code": null, "e": 25126, "s": 25105, "text": "avanitrachhadiya2155" }, { "code": null, "e": 25136, "s": 25126, "text": "pratham76" }, { "code": null, "e": 25154, "s": 25136, "text": "yashupadhyayece19" }, { "code": null, "e": 25163, "s": 25154, "text": "rjrachit" }, { "code": null, "e": 25173, "s": 25163, "text": "code_hunt" }, { "code": null, "e": 25183, "s": 25173, "text": "sanjoy_62" }, { "code": null, "e": 25199, "s": 25183, "text": "rohitsingh07052" }, { "code": null, "e": 25215, "s": 25199, "text": "souravghosh0416" }, { "code": null, "e": 25222, "s": 25215, "text": "ab2127" }, { "code": null, "e": 25239, "s": 25222, "text": "akashkumarsmet18" }, { "code": null, "e": 25254, "s": 25239, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 25271, "s": 25254, "text": "harendrakumar123" }, { "code": null, "e": 25286, "s": 25271, "text": "adityakumar129" }, { "code": null, "e": 25295, "s": 25286, "text": "rexomkar" }, { "code": null, "e": 25312, "s": 25295, "text": "hardikkoriintern" }, { "code": null, "e": 25319, "s": 25312, "text": "Arrays" }, { "code": null, "e": 25326, "s": 25319, "text": "Greedy" }, { "code": null, "e": 25333, "s": 25326, "text": "Arrays" }, { "code": null, "e": 25340, "s": 25333, "text": "Greedy" } ]
How to generate a simple popup using jQuery ?
27 Jan, 2021 The task is to generate a popup using jQuery. Popups are useful to splash important information to the visitors of a website. Approach: A simple pop can be made by using toggle() method of jQuery which toggles between hide() and show() function of jQuery i.e. it checks the visibility of the selector used. The hide() method is run when the selector is visible and show() is run when the selector is not visible. It displays the popup if the show popup button is clicked and hides the popup if the closed button is clicked. The selector used for toggling is ” .content ” which contains the close button and popup’s body. Initially to hide the popup on page reload we have used the display: none property on the .content class in style tag. Now when the user clicks on the show popup button the onclick event calls the togglePopup() which displays the popup and when the user clicks on the close button onclick event again calls the togglePopup() which hides the popup. $(selector).toggle(); HTML <!DOCTYPE html><html> <head> <!-- jQuery cdn link --> <script src= "https://code.jquery.com/jquery-3.5.1.min.js"> </script> <style type="text/css"> .content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 500px; height: 200px; text-align: center; background-color: #e8eae6; box-sizing: border-box; padding: 10px; z-index: 100; display: none; /*to hide popup initially*/ } .close-btn { position: absolute; right: 20px; top: 15px; background-color: black; color: white; border-radius: 50%; padding: 4px; } </style></head> <body> <button onclick="togglePopup()">show popup</button> <!-- div containing the popup --> <div class="content"> <div onclick="togglePopup()" class="close-btn"> × </div> <h3>Popup</h3> <p> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </p> </div> <script type="text/javascript"> // Function to show and hide the popup function togglePopup() { $(".content").toggle(); } </script></body> </html> CSS-Misc HTML-Misc jQuery-Misc Picked CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS 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 ? HTTP headers | Content-Type
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jan, 2021" }, { "code": null, "e": 178, "s": 52, "text": "The task is to generate a popup using jQuery. Popups are useful to splash important information to the visitors of a website." }, { "code": null, "e": 465, "s": 178, "text": "Approach: A simple pop can be made by using toggle() method of jQuery which toggles between hide() and show() function of jQuery i.e. it checks the visibility of the selector used. The hide() method is run when the selector is visible and show() is run when the selector is not visible." }, { "code": null, "e": 576, "s": 465, "text": "It displays the popup if the show popup button is clicked and hides the popup if the closed button is clicked." }, { "code": null, "e": 793, "s": 576, "text": "The selector used for toggling is ” .content ” which contains the close button and popup’s body. Initially to hide the popup on page reload we have used the display: none property on the .content class in style tag. " }, { "code": null, "e": 1022, "s": 793, "text": "Now when the user clicks on the show popup button the onclick event calls the togglePopup() which displays the popup and when the user clicks on the close button onclick event again calls the togglePopup() which hides the popup." }, { "code": null, "e": 1044, "s": 1022, "text": "$(selector).toggle();" }, { "code": null, "e": 1049, "s": 1044, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- jQuery cdn link --> <script src= \"https://code.jquery.com/jquery-3.5.1.min.js\"> </script> <style type=\"text/css\"> .content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 500px; height: 200px; text-align: center; background-color: #e8eae6; box-sizing: border-box; padding: 10px; z-index: 100; display: none; /*to hide popup initially*/ } .close-btn { position: absolute; right: 20px; top: 15px; background-color: black; color: white; border-radius: 50%; padding: 4px; } </style></head> <body> <button onclick=\"togglePopup()\">show popup</button> <!-- div containing the popup --> <div class=\"content\"> <div onclick=\"togglePopup()\" class=\"close-btn\"> × </div> <h3>Popup</h3> <p> jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development. </p> </div> <script type=\"text/javascript\"> // Function to show and hide the popup function togglePopup() { $(\".content\").toggle(); } </script></body> </html>", "e": 2816, "s": 1049, "text": null }, { "code": null, "e": 2825, "s": 2816, "text": "CSS-Misc" }, { "code": null, "e": 2835, "s": 2825, "text": "HTML-Misc" }, { "code": null, "e": 2847, "s": 2835, "text": "jQuery-Misc" }, { "code": null, "e": 2854, "s": 2847, "text": "Picked" }, { "code": null, "e": 2858, "s": 2854, "text": "CSS" }, { "code": null, "e": 2863, "s": 2858, "text": "HTML" }, { "code": null, "e": 2870, "s": 2863, "text": "JQuery" }, { "code": null, "e": 2887, "s": 2870, "text": "Web Technologies" }, { "code": null, "e": 2892, "s": 2887, "text": "HTML" }, { "code": null, "e": 2990, "s": 2892, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3029, "s": 2990, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3068, "s": 3029, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3107, "s": 3068, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3136, "s": 3107, "text": "Form validation using jQuery" }, { "code": null, "e": 3173, "s": 3136, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 3197, "s": 3173, "text": "REST API (Introduction)" }, { "code": null, "e": 3250, "s": 3197, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3310, "s": 3250, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3371, "s": 3310, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
std::set_difference in C++
28 Apr, 2022 The difference of two sets is formed by the elements that are present in the first set, but not in the second one. The elements copied by the function come always from the first range, in the same order. The elements in the both the ranges shall already be ordered. 1. Comparing elements using “<“: Syntax : Template : OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); Parameters : first1, last1 Input iterators to the initial and final positions of the first sorted sequence. The range used is [first1, last1), which contains all the elements between first1 and last1, including the element pointed by first1 but not the element pointed by last1. first2, last2 Input iterators to the initial and final positions of the second sorted sequence. The range used is [first2, last2). result Output iterator to the initial position of the range where the resulting sequence is stored. The pointed type shall support being assigned the value of an element from the first range. Return Type : An iterator to the end of the constructed range. CPP // CPP program to illustrate// std :: set_difference #include <bits/stdc++.h> int main(){ int first[] = { 5, 10, 15, 20, 25 }; int second[] = { 50, 40, 30, 20, 10 }; int n = sizeof(first) / sizeof(first[0]); std::vector<int> v2(5); std::vector<int>::iterator it, ls; std::sort(first, first + 5); std::sort(second, second + 5); // Print elements std::cout << "First array :"; for (int i = 0; i < n; i++) std::cout << " " << first[i]; std::cout << "\n"; // Print elements std::cout << "Second array :"; for (int i = 0; i < n; i++) std::cout << " " << second[i]; std::cout << "\n\n"; // using default comparison /* first array intersection second array */ ls = std::set_difference(first, first + 5, second, second + 5, v2.begin()); std::cout << "Using default comparison, \n"; std::cout << "The difference has " << (ls - v2.begin()) << " elements :"; for (it = v2.begin(); it < ls; ++it) std::cout << " " << *it; std::cout << "\n"; return 0;} Output: First array : 5 10 15 20 25 Second array : 10 20 30 40 50 Using default comparison, The difference has 3 elements : 5 15 25 2. By comparing using a pre-defined function: Template : OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); Parameters : first1, last1, first2, last2, result are same as above. comp Binary function that accepts two arguments of the types pointed by the input iterators, and returns a value convertible to bool. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Type : An iterator to the end of the constructed range. CPP // CPP program to illustrate// std :: set_difference #include <bits/stdc++.h> bool comp(int i, int j){ return (i < j);} int main(){ int first[] = { 50, 40, 30, 20, 10 }; int second[] = { 5, 10, 15, 20, 25 }; int n = sizeof(first) / sizeof(first[0]); std::vector<int> v1(5); std::sort(first, first + 5); std::sort(second, second + 5); // Print elements std::cout << "First array :"; for (int i = 0; i < n; i++) std::cout << " " << first[i]; std::cout << "\n"; // Print elements std::cout << "Second array :"; for (int i = 0; i < n; i++) std::cout << " " << second[i]; std::cout << "\n\n"; // using custom comparison, function as comp /* first array intersection second array */ ls = std::set_difference(second, second + 5, first, first + 5, v1.begin(), comp); std::cout << "Using custom comparison, \n"; std::cout << "The difference has " << (ls - v1.begin()) << " elements :"; for (it = v1.begin(); it < ls; ++it) std::cout << " " << *it; std::cout << "\n"; return 0;} Output: First array : 10 20 30 40 50 Second array : 5 10 15 20 25 Using custom comparison : The difference has 3 elements : 30 40 50 Possible Application : It is used to find the elements that are present only in first list and not in the second list. 1. It can be used to find the list of students that are attending only first classes. CPP // CPP program to demonstrate use of// std :: set_difference#include <iostream>#include <algorithm>#include <vector>#include <string> using namespace std; // Driver codeint main(){ string first[] = { "Sachin", "Rakesh", "Sandeep", "Serena" }; string second[] = { "Vaibhav", "Sandeep", "Rakesh", "Neha" }; int n = sizeof(first) / sizeof(first[0]); // Print students of first list cout << "Students in first class :"; for (int i = 0; i < n; i++) cout << " " << first[i]; cout << "\n"; // Print students of second list cout << "Students in second class :"; for (int i = 0; i < n; i++) cout << " " << second[i]; cout << "\n\n"; vector<string> v(10); vector<string>::iterator it, st; // Sorting both the list sort(first, first + n); sort(second, second + n); // Using default operator< it = set_difference(first, first + n, second, second + n, v.begin()); cout << "Students attending first class only are :\n"; for (st = v.begin(); st != it; ++st) cout << ' ' << *st; cout << '\n'; return 0;} OUTPUT : Students in first class : Sachin Rakesh Sandeep Serena Students in second class : Vaibhav Sandeep Rakesh Neha Students attending first classes only are : Sachin Serena 2. It can also be use to find the elements that are not present in first list only. Program is given above. This article is contributed by Sachin Bisht. 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 cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ std::string class in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library std::find in C++ List in C++ Standard Template Library (STL) Inline Functions in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2022" }, { "code": null, "e": 295, "s": 28, "text": "The difference of two sets is formed by the elements that are present in the first set, but not in the second one. The elements copied by the function come always from the first range, in the same order. The elements in the both the ranges shall already be ordered. " }, { "code": null, "e": 329, "s": 295, "text": "1. Comparing elements using “<“: " }, { "code": null, "e": 338, "s": 329, "text": "Syntax :" }, { "code": null, "e": 1225, "s": 338, "text": "Template :\nOutputIterator set_difference (InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2,\n OutputIterator result);\n\nParameters :\n\nfirst1, last1\nInput iterators to the initial and final positions of the first\nsorted sequence. The range used is [first1, last1), which contains\nall the elements between first1 and last1, including the element\npointed by first1 but not the element pointed by last1.\nfirst2, last2\nInput iterators to the initial and final positions of the second\nsorted sequence. The range used is [first2, last2).\n\nresult\nOutput iterator to the initial position of the range where the\nresulting sequence is stored.\nThe pointed type shall support being assigned the value of an\nelement from the first range.\n\nReturn Type :\nAn iterator to the end of the constructed range." }, { "code": null, "e": 1229, "s": 1225, "text": "CPP" }, { "code": "// CPP program to illustrate// std :: set_difference #include <bits/stdc++.h> int main(){ int first[] = { 5, 10, 15, 20, 25 }; int second[] = { 50, 40, 30, 20, 10 }; int n = sizeof(first) / sizeof(first[0]); std::vector<int> v2(5); std::vector<int>::iterator it, ls; std::sort(first, first + 5); std::sort(second, second + 5); // Print elements std::cout << \"First array :\"; for (int i = 0; i < n; i++) std::cout << \" \" << first[i]; std::cout << \"\\n\"; // Print elements std::cout << \"Second array :\"; for (int i = 0; i < n; i++) std::cout << \" \" << second[i]; std::cout << \"\\n\\n\"; // using default comparison /* first array intersection second array */ ls = std::set_difference(first, first + 5, second, second + 5, v2.begin()); std::cout << \"Using default comparison, \\n\"; std::cout << \"The difference has \" << (ls - v2.begin()) << \" elements :\"; for (it = v2.begin(); it < ls; ++it) std::cout << \" \" << *it; std::cout << \"\\n\"; return 0;}", "e": 2266, "s": 1229, "text": null }, { "code": null, "e": 2274, "s": 2266, "text": "Output:" }, { "code": null, "e": 2399, "s": 2274, "text": "First array : 5 10 15 20 25\nSecond array : 10 20 30 40 50\n\nUsing default comparison,\nThe difference has 3 elements : 5 15 25" }, { "code": null, "e": 2445, "s": 2399, "text": "2. By comparing using a pre-defined function:" }, { "code": null, "e": 3059, "s": 2445, "text": "Template :\nOutputIterator set_difference (InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2,\n OutputIterator result, Compare comp);\n\nParameters :\n\nfirst1, last1, first2, last2, result are same as above.\n\ncomp\nBinary function that accepts two arguments of the types pointed\nby the input iterators, and returns a value convertible to bool.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Type :\nAn iterator to the end of the constructed range." }, { "code": null, "e": 3063, "s": 3059, "text": "CPP" }, { "code": "// CPP program to illustrate// std :: set_difference #include <bits/stdc++.h> bool comp(int i, int j){ return (i < j);} int main(){ int first[] = { 50, 40, 30, 20, 10 }; int second[] = { 5, 10, 15, 20, 25 }; int n = sizeof(first) / sizeof(first[0]); std::vector<int> v1(5); std::sort(first, first + 5); std::sort(second, second + 5); // Print elements std::cout << \"First array :\"; for (int i = 0; i < n; i++) std::cout << \" \" << first[i]; std::cout << \"\\n\"; // Print elements std::cout << \"Second array :\"; for (int i = 0; i < n; i++) std::cout << \" \" << second[i]; std::cout << \"\\n\\n\"; // using custom comparison, function as comp /* first array intersection second array */ ls = std::set_difference(second, second + 5, first, first + 5, v1.begin(), comp); std::cout << \"Using custom comparison, \\n\"; std::cout << \"The difference has \" << (ls - v1.begin()) << \" elements :\"; for (it = v1.begin(); it < ls; ++it) std::cout << \" \" << *it; std::cout << \"\\n\"; return 0;}", "e": 4129, "s": 3063, "text": null }, { "code": null, "e": 4137, "s": 4129, "text": "Output:" }, { "code": null, "e": 4263, "s": 4137, "text": "First array : 10 20 30 40 50\nSecond array : 5 10 15 20 25\n\nUsing custom comparison :\nThe difference has 3 elements : 30 40 50" }, { "code": null, "e": 4469, "s": 4263, "text": "Possible Application : It is used to find the elements that are present only in first list and not in the second list. 1. It can be used to find the list of students that are attending only first classes. " }, { "code": null, "e": 4473, "s": 4469, "text": "CPP" }, { "code": "// CPP program to demonstrate use of// std :: set_difference#include <iostream>#include <algorithm>#include <vector>#include <string> using namespace std; // Driver codeint main(){ string first[] = { \"Sachin\", \"Rakesh\", \"Sandeep\", \"Serena\" }; string second[] = { \"Vaibhav\", \"Sandeep\", \"Rakesh\", \"Neha\" }; int n = sizeof(first) / sizeof(first[0]); // Print students of first list cout << \"Students in first class :\"; for (int i = 0; i < n; i++) cout << \" \" << first[i]; cout << \"\\n\"; // Print students of second list cout << \"Students in second class :\"; for (int i = 0; i < n; i++) cout << \" \" << second[i]; cout << \"\\n\\n\"; vector<string> v(10); vector<string>::iterator it, st; // Sorting both the list sort(first, first + n); sort(second, second + n); // Using default operator< it = set_difference(first, first + n, second, second + n, v.begin()); cout << \"Students attending first class only are :\\n\"; for (st = v.begin(); st != it; ++st) cout << ' ' << *st; cout << '\\n'; return 0;}", "e": 5555, "s": 4473, "text": null }, { "code": null, "e": 5564, "s": 5555, "text": "OUTPUT :" }, { "code": null, "e": 5734, "s": 5564, "text": "Students in first class : Sachin Rakesh Sandeep Serena\nStudents in second class : Vaibhav Sandeep Rakesh Neha\n\nStudents attending first classes only are :\n Sachin Serena" }, { "code": null, "e": 6263, "s": 5734, "text": "2. It can also be use to find the elements that are not present in first list only. Program is given above. This article is contributed by Sachin Bisht. 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": 6276, "s": 6263, "text": "simmytarika5" }, { "code": null, "e": 6298, "s": 6276, "text": "cpp-algorithm-library" }, { "code": null, "e": 6302, "s": 6298, "text": "STL" }, { "code": null, "e": 6306, "s": 6302, "text": "C++" }, { "code": null, "e": 6310, "s": 6306, "text": "STL" }, { "code": null, "e": 6314, "s": 6310, "text": "CPP" }, { "code": null, "e": 6412, "s": 6314, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6436, "s": 6412, "text": "Sorting a vector in C++" }, { "code": null, "e": 6456, "s": 6436, "text": "Polymorphism in C++" }, { "code": null, "e": 6481, "s": 6456, "text": "std::string class in C++" }, { "code": null, "e": 6514, "s": 6481, "text": "Friend class and function in C++" }, { "code": null, "e": 6558, "s": 6514, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 6603, "s": 6558, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6651, "s": 6603, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 6668, "s": 6651, "text": "std::find in C++" }, { "code": null, "e": 6712, "s": 6668, "text": "List in C++ Standard Template Library (STL)" } ]
enable and disable command in Linux
05 Nov, 2019 Enables and disables are the built-in shell commands. enable command is used to start the printers or classes whereas the disable command is used to stop the printers or classes. Syntax For enable Command: enable [-a] [-dnps] [-f filename][name ...] Syntax For disable Command: disable [-c] [-W] [ -r [ reason ] ] printer Options: -a : List all builtins with the message of whether it is enabled or not. -c : It will cancel the requests which are currently printing. -d : Delete a builtin loaded with `-f’. -W : Wait until the request currently being printed is finished before disabling printer. This option cannot be used with the -c option. If the printer is remote then the -W option will be silently ignored. -r reason : It assigns a reason for the disabling of the printer(s). printer : The name of the printer to be enabled or disabled. -n: Disable the names listed, otherwise names are enabled. Akanksha_Rai linux-command Linux-Shell-Commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Nov, 2019" }, { "code": null, "e": 207, "s": 28, "text": "Enables and disables are the built-in shell commands. enable command is used to start the printers or classes whereas the disable command is used to stop the printers or classes." }, { "code": null, "e": 234, "s": 207, "text": "Syntax For enable Command:" }, { "code": null, "e": 279, "s": 234, "text": "enable [-a] [-dnps] [-f filename][name ...]\n" }, { "code": null, "e": 307, "s": 279, "text": "Syntax For disable Command:" }, { "code": null, "e": 351, "s": 307, "text": "disable [-c] [-W] [ -r [ reason ] ] printer" }, { "code": null, "e": 360, "s": 351, "text": "Options:" }, { "code": null, "e": 433, "s": 360, "text": "-a : List all builtins with the message of whether it is enabled or not." }, { "code": null, "e": 496, "s": 433, "text": "-c : It will cancel the requests which are currently printing." }, { "code": null, "e": 536, "s": 496, "text": "-d : Delete a builtin loaded with `-f’." }, { "code": null, "e": 743, "s": 536, "text": "-W : Wait until the request currently being printed is finished before disabling printer. This option cannot be used with the -c option. If the printer is remote then the -W option will be silently ignored." }, { "code": null, "e": 812, "s": 743, "text": "-r reason : It assigns a reason for the disabling of the printer(s)." }, { "code": null, "e": 873, "s": 812, "text": "printer : The name of the printer to be enabled or disabled." }, { "code": null, "e": 932, "s": 873, "text": "-n: Disable the names listed, otherwise names are enabled." }, { "code": null, "e": 945, "s": 932, "text": "Akanksha_Rai" }, { "code": null, "e": 959, "s": 945, "text": "linux-command" }, { "code": null, "e": 980, "s": 959, "text": "Linux-Shell-Commands" }, { "code": null, "e": 991, "s": 980, "text": "Linux-Unix" } ]
Queries on Left and Right Circular shift on array
17 Jun, 2022 Given an array A of N integers. There are three types of commands: 1 x : Right Circular Shift the array x times. If an array is a[0], a[1], ...., a[n – 1], then after one right circular shift the array will become a[n – 1], a[0], a[1], ...., a[n – 2]. 2 y : Left Circular Shift the array y times. If an array is a[0], a[1], ...., a[n – 1], then after one left circular shift the array will become a[1], ...., a[n – 2], a[n – 1], a[0]. 3 l r : Print the sum of all integers in the subarray a[l...r] (l and r inclusive). Given Q queries, the task is to execute each query. Examples: Input : n = 5, arr[] = { 1, 2, 3, 4, 5 } query 1 = { 1, 3 } query 2 = { 3, 0, 2 } query 3 = { 2, 1 } query 4 = { 3, 1, 4 } Output : 12 11 Initial array arr[] = { 1, 2, 3, 4, 5 } After query 1, arr[] = { 3, 4, 5, 1, 2 }. After query 2, sum from index 0 to index 2 is 12, so output 12. After query 3, arr[] = { 4, 5, 1, 2, 3 }. After query 4, sum from index 1 to index 4 is 11, so output 11. Method 1 : (Brute Force)Implement three functions, rotateR(arr, k) which will right rotate array arr by k times, rotateL(arr, k) which will left rotate array arr by k times, sum(arr, l, r) which will output the sum of array arr from index l to index r. On the input of values 1, 2, and 3 call the appropriate function. Method 2 : (Efficient Approach)Initially, there are no rotations and we have many queries asking for the sum of integers present in a range of indexes. We can evaluate the prefix sum of all elements in the array, prefixsum[i] will denote the sum of all the integers up to ith index. Now, if we want to find sum of elements between two indexes i.e l and r, we compute it in constant time by just calculating prefixsum[r] – prefixsum[l – 1]. Now for rotations, if we are rotating the array for every query, that will be highly inefficient. We just need to track the net rotation. If the tracked number is negative, it means left rotation has dominated else right rotation has dominated. When we are tracking the net rotations, we need to do mod n. After every n rotation, the array will return to its original state. We need to observe it in such a way that every time we rotate the array, only its indexes are changing. If we need to answer any query of third type and we have l and r. We need to find what l and r were in the original order. We can easily find it out by adding the net rotations to the index and taking mod n. Every command can be executed in O(1) time. Below is C++ implementation of this approach: C++ Java Python3 C# Javascript // C++ Program to solve queries on Left and Right// Circular shift on array#include <bits/stdc++.h>using namespace std; // Function to solve query of type 1 x.void querytype1(int* toRotate, int times, int n){ // Decreasing the absolute rotation (*toRotate) = ((*toRotate) - times) % n;} // Function to solve query of type 2 y.void querytype2(int* toRotate, int times, int n){ // Increasing the absolute rotation. (*toRotate) = ((*toRotate) + times) % n;} // Function to solve queries of type 3 l r.void querytype3(int toRotate, int l, int r, int preSum[], int n){ // Finding absolute l and r. l = (l + toRotate + n) % n; r = (r + toRotate + n) % n; // if l is before r. if (l <= r) cout << (preSum[r + 1] - preSum[l]) << endl; // If r is before l. else cout << (preSum[n] + preSum[r + 1] - preSum[l]) << endl; } // Wrapper Function solve all queries.void wrapper(int a[], int n){ int preSum[n + 1]; preSum[0] = 0; // Finding Prefix sum for (int i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1]; int toRotate = 0; // Solving each query querytype1(&toRotate, 3, n); querytype3(toRotate, 0, 2, preSum, n); querytype2(&toRotate, 1, n); querytype3(toRotate, 1, 4, preSum, n);} // Driver Programint main(){ int a[] = { 1, 2, 3, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); wrapper(a, n); return 0;} // Java Program to solve queries on Left and Right// Circular shift on arrayclass GFG { // Function to solve query of type 1 x. static int querytype1(int toRotate, int times, int n) { // Decreasing the absolute rotation toRotate = (toRotate - times) % n; return toRotate; } // Function to solve query of type 2 y. static int querytype2(int toRotate, int times, int n) { // Increasing the absolute rotation. toRotate = (toRotate + times) % n; return toRotate; } // Function to solve queries of type 3 l r. static void querytype3(int toRotate, int l, int r, int preSum[], int n) { // Finding absolute l and r. l = (l + toRotate + n) % n; r = (r + toRotate + n) % n; // if l is before r. if (l <= r) System.out.println(preSum[r + 1] - preSum[l]); // If r is before l. else System.out.println(preSum[n] + preSum[r + 1] - preSum[l]); } // Wrapper Function solve all queries. static void wrapper(int a[], int n) { int preSum[] = new int[n + 1]; preSum[0] = 0; // Finding Prefix sum for (int i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1]; int toRotate = 0; // Solving each query toRotate = querytype1(toRotate, 3, n); querytype3(toRotate, 0, 2, preSum, n); toRotate = querytype2(toRotate, 1, n); querytype3(toRotate, 1, 4, preSum, n); } // Driver Program public static void main(String args[]) { int a[] = { 1, 2, 3, 4, 5 }; int n = a.length; wrapper(a, n); } } // This code is contributed by saurabh_jaiswal. # Python Program to solve queries on Left and Right# Circular shift on array # Function to solve query of type 1 x.def querytype1(toRotate, times, n): # Decreasing the absolute rotation toRotate = (toRotate - times) % n return toRotate # Function to solve query of type 2 y.def querytype2(toRotate, times, n): # Increasing the absolute rotation. toRotate = (toRotate + times) % n return toRotate # Function to solve queries of type 3 l r.def querytype3( toRotate, l, r, preSum, n): # Finding absolute l and r. l = (l + toRotate + n) % n r = (r + toRotate + n) % n # if l is before r. if (l <= r): print((preSum[r + 1] - preSum[l])) # If r is before l. else: print((preSum[n] + preSum[r + 1] - preSum[l])) # Wrapper Function solve all queries.def wrapper( a, n): preSum = [ 0 for i in range(n + 1)] # Finding Prefix sum for i in range(1,n+1): preSum[i] = preSum[i - 1] + a[i - 1] toRotate = 0 # Solving each query toRotate = querytype1(toRotate, 3, n) querytype3(toRotate, 0, 2, preSum, n) toRotate = querytype2(toRotate, 1, n) querytype3(toRotate, 1, 4, preSum, n); # Driver Programa = [ 1, 2, 3, 4, 5 ]n = len(a)wrapper(a, n) # This code is contributed by rohan07. // C# Program to solve queries on Left and Right// Circular shift on arrayusing System;class GFG{ // Function to solve query of type 1 x. static int querytype1(int toRotate, int times, int n) { // Decreasing the absolute rotation toRotate = (toRotate - times) % n; return toRotate; } // Function to solve query of type 2 y. static int querytype2(int toRotate, int times, int n) { // Increasing the absolute rotation. toRotate = (toRotate + times) % n; return toRotate; } // Function to solve queries of type 3 l r. static void querytype3(int toRotate, int l, int r, int[] preSum, int n) { // Finding absolute l and r. l = (l + toRotate + n) % n; r = (r + toRotate + n) % n; // if l is before r. if (l <= r) Console.WriteLine(preSum[r + 1] - preSum[l]); // If r is before l. else Console.WriteLine(preSum[n] + preSum[r + 1] - preSum[l]); } // Wrapper Function solve all queries. static void wrapper(int[] a, int n) { int[] preSum = new int[n + 1]; preSum[0] = 0; // Finding Prefix sum for (int i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1]; int toRotate = 0; // Solving each query toRotate = querytype1(toRotate, 3, n); querytype3(toRotate, 0, 2, preSum, n); toRotate = querytype2(toRotate, 1, n); querytype3(toRotate, 1, 4, preSum, n); } // Driver Program public static void Main() { int[] a = { 1, 2, 3, 4, 5 }; int n = a.Length; wrapper(a, n); } } // This code is contributed by _saurabh_jaiswal <script> // JavaScript Program to solve queries on Left and Right// Circular shift on array // Function to solve query of type 1 x.function querytype1(toRotate, times, n){ // Decreasing the absolute rotation toRotate = (toRotate - times) % n return toRotate} // Function to solve query of type 2 y.function querytype2(toRotate, times, n){ // Increasing the absolute rotation. toRotate = (toRotate + times) % n return toRotate} // Function to solve queries of type 3 l r.function querytype3( toRotate, l, r, preSum, n){ // Finding absolute l and r. l = (l + toRotate + n) % n r = (r + toRotate + n) % n // if l is before r. if (l <= r) document.write((preSum[r + 1] - preSum[l]),"</br>") // If r is before l. else document.write((preSum[n] + preSum[r + 1] - preSum[l]),"</br>")} // Wrapper Function solve all queries.function wrapper(a, n){ preSum = new Array(n+1).fill(0) // Finding Prefix sum for(let i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1] toRotate = 0 // Solving each query toRotate = querytype1(toRotate, 3, n) querytype3(toRotate, 0, 2, preSum, n) toRotate = querytype2(toRotate, 1, n) querytype3(toRotate, 1, 4, preSum, n);} // Driver Programlet a = [ 1, 2, 3, 4, 5 ]let n = a.lengthwrapper(a, n) // This code is contributed by rohan07.</script> Output: 12 11 Time Complexity: O(n). Auxiliary Space: O(1) patnaikbhawna rams2103 akshaysingh98088 siri1404 rohan07 shinjanpatra _saurabh_jaiswal codewithshinchan triangleofcoding array-range-queries rotation Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2022" }, { "code": null, "e": 122, "s": 54, "text": "Given an array A of N integers. There are three types of commands: " }, { "code": null, "e": 307, "s": 122, "text": "1 x : Right Circular Shift the array x times. If an array is a[0], a[1], ...., a[n – 1], then after one right circular shift the array will become a[n – 1], a[0], a[1], ...., a[n – 2]." }, { "code": null, "e": 490, "s": 307, "text": "2 y : Left Circular Shift the array y times. If an array is a[0], a[1], ...., a[n – 1], then after one left circular shift the array will become a[1], ...., a[n – 2], a[n – 1], a[0]." }, { "code": null, "e": 574, "s": 490, "text": "3 l r : Print the sum of all integers in the subarray a[l...r] (l and r inclusive)." }, { "code": null, "e": 626, "s": 574, "text": "Given Q queries, the task is to execute each query." }, { "code": null, "e": 638, "s": 626, "text": "Examples: " }, { "code": null, "e": 1101, "s": 638, "text": "Input : n = 5, arr[] = { 1, 2, 3, 4, 5 }\n query 1 = { 1, 3 }\n query 2 = { 3, 0, 2 }\n query 3 = { 2, 1 }\n query 4 = { 3, 1, 4 }\nOutput : 12\n 11\nInitial array arr[] = { 1, 2, 3, 4, 5 }\nAfter query 1, arr[] = { 3, 4, 5, 1, 2 }.\nAfter query 2, sum from index 0 to index \n 2 is 12, so output 12.\nAfter query 3, arr[] = { 4, 5, 1, 2, 3 }.\nAfter query 4, sum from index 1 to index \n 4 is 11, so output 11." }, { "code": null, "e": 1420, "s": 1101, "text": "Method 1 : (Brute Force)Implement three functions, rotateR(arr, k) which will right rotate array arr by k times, rotateL(arr, k) which will left rotate array arr by k times, sum(arr, l, r) which will output the sum of array arr from index l to index r. On the input of values 1, 2, and 3 call the appropriate function." }, { "code": null, "e": 2591, "s": 1420, "text": "Method 2 : (Efficient Approach)Initially, there are no rotations and we have many queries asking for the sum of integers present in a range of indexes. We can evaluate the prefix sum of all elements in the array, prefixsum[i] will denote the sum of all the integers up to ith index. Now, if we want to find sum of elements between two indexes i.e l and r, we compute it in constant time by just calculating prefixsum[r] – prefixsum[l – 1]. Now for rotations, if we are rotating the array for every query, that will be highly inefficient. We just need to track the net rotation. If the tracked number is negative, it means left rotation has dominated else right rotation has dominated. When we are tracking the net rotations, we need to do mod n. After every n rotation, the array will return to its original state. We need to observe it in such a way that every time we rotate the array, only its indexes are changing. If we need to answer any query of third type and we have l and r. We need to find what l and r were in the original order. We can easily find it out by adding the net rotations to the index and taking mod n. Every command can be executed in O(1) time." }, { "code": null, "e": 2639, "s": 2591, "text": "Below is C++ implementation of this approach: " }, { "code": null, "e": 2643, "s": 2639, "text": "C++" }, { "code": null, "e": 2648, "s": 2643, "text": "Java" }, { "code": null, "e": 2656, "s": 2648, "text": "Python3" }, { "code": null, "e": 2659, "s": 2656, "text": "C#" }, { "code": null, "e": 2670, "s": 2659, "text": "Javascript" }, { "code": "// C++ Program to solve queries on Left and Right// Circular shift on array#include <bits/stdc++.h>using namespace std; // Function to solve query of type 1 x.void querytype1(int* toRotate, int times, int n){ // Decreasing the absolute rotation (*toRotate) = ((*toRotate) - times) % n;} // Function to solve query of type 2 y.void querytype2(int* toRotate, int times, int n){ // Increasing the absolute rotation. (*toRotate) = ((*toRotate) + times) % n;} // Function to solve queries of type 3 l r.void querytype3(int toRotate, int l, int r, int preSum[], int n){ // Finding absolute l and r. l = (l + toRotate + n) % n; r = (r + toRotate + n) % n; // if l is before r. if (l <= r) cout << (preSum[r + 1] - preSum[l]) << endl; // If r is before l. else cout << (preSum[n] + preSum[r + 1] - preSum[l]) << endl; } // Wrapper Function solve all queries.void wrapper(int a[], int n){ int preSum[n + 1]; preSum[0] = 0; // Finding Prefix sum for (int i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1]; int toRotate = 0; // Solving each query querytype1(&toRotate, 3, n); querytype3(toRotate, 0, 2, preSum, n); querytype2(&toRotate, 1, n); querytype3(toRotate, 1, 4, preSum, n);} // Driver Programint main(){ int a[] = { 1, 2, 3, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); wrapper(a, n); return 0;}", "e": 4107, "s": 2670, "text": null }, { "code": "// Java Program to solve queries on Left and Right// Circular shift on arrayclass GFG { // Function to solve query of type 1 x. static int querytype1(int toRotate, int times, int n) { // Decreasing the absolute rotation toRotate = (toRotate - times) % n; return toRotate; } // Function to solve query of type 2 y. static int querytype2(int toRotate, int times, int n) { // Increasing the absolute rotation. toRotate = (toRotate + times) % n; return toRotate; } // Function to solve queries of type 3 l r. static void querytype3(int toRotate, int l, int r, int preSum[], int n) { // Finding absolute l and r. l = (l + toRotate + n) % n; r = (r + toRotate + n) % n; // if l is before r. if (l <= r) System.out.println(preSum[r + 1] - preSum[l]); // If r is before l. else System.out.println(preSum[n] + preSum[r + 1] - preSum[l]); } // Wrapper Function solve all queries. static void wrapper(int a[], int n) { int preSum[] = new int[n + 1]; preSum[0] = 0; // Finding Prefix sum for (int i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1]; int toRotate = 0; // Solving each query toRotate = querytype1(toRotate, 3, n); querytype3(toRotate, 0, 2, preSum, n); toRotate = querytype2(toRotate, 1, n); querytype3(toRotate, 1, 4, preSum, n); } // Driver Program public static void main(String args[]) { int a[] = { 1, 2, 3, 4, 5 }; int n = a.length; wrapper(a, n); } } // This code is contributed by saurabh_jaiswal.", "e": 5669, "s": 4107, "text": null }, { "code": "# Python Program to solve queries on Left and Right# Circular shift on array # Function to solve query of type 1 x.def querytype1(toRotate, times, n): # Decreasing the absolute rotation toRotate = (toRotate - times) % n return toRotate # Function to solve query of type 2 y.def querytype2(toRotate, times, n): # Increasing the absolute rotation. toRotate = (toRotate + times) % n return toRotate # Function to solve queries of type 3 l r.def querytype3( toRotate, l, r, preSum, n): # Finding absolute l and r. l = (l + toRotate + n) % n r = (r + toRotate + n) % n # if l is before r. if (l <= r): print((preSum[r + 1] - preSum[l])) # If r is before l. else: print((preSum[n] + preSum[r + 1] - preSum[l])) # Wrapper Function solve all queries.def wrapper( a, n): preSum = [ 0 for i in range(n + 1)] # Finding Prefix sum for i in range(1,n+1): preSum[i] = preSum[i - 1] + a[i - 1] toRotate = 0 # Solving each query toRotate = querytype1(toRotate, 3, n) querytype3(toRotate, 0, 2, preSum, n) toRotate = querytype2(toRotate, 1, n) querytype3(toRotate, 1, 4, preSum, n); # Driver Programa = [ 1, 2, 3, 4, 5 ]n = len(a)wrapper(a, n) # This code is contributed by rohan07.", "e": 6942, "s": 5669, "text": null }, { "code": "// C# Program to solve queries on Left and Right// Circular shift on arrayusing System;class GFG{ // Function to solve query of type 1 x. static int querytype1(int toRotate, int times, int n) { // Decreasing the absolute rotation toRotate = (toRotate - times) % n; return toRotate; } // Function to solve query of type 2 y. static int querytype2(int toRotate, int times, int n) { // Increasing the absolute rotation. toRotate = (toRotate + times) % n; return toRotate; } // Function to solve queries of type 3 l r. static void querytype3(int toRotate, int l, int r, int[] preSum, int n) { // Finding absolute l and r. l = (l + toRotate + n) % n; r = (r + toRotate + n) % n; // if l is before r. if (l <= r) Console.WriteLine(preSum[r + 1] - preSum[l]); // If r is before l. else Console.WriteLine(preSum[n] + preSum[r + 1] - preSum[l]); } // Wrapper Function solve all queries. static void wrapper(int[] a, int n) { int[] preSum = new int[n + 1]; preSum[0] = 0; // Finding Prefix sum for (int i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1]; int toRotate = 0; // Solving each query toRotate = querytype1(toRotate, 3, n); querytype3(toRotate, 0, 2, preSum, n); toRotate = querytype2(toRotate, 1, n); querytype3(toRotate, 1, 4, preSum, n); } // Driver Program public static void Main() { int[] a = { 1, 2, 3, 4, 5 }; int n = a.Length; wrapper(a, n); } } // This code is contributed by _saurabh_jaiswal", "e": 8499, "s": 6942, "text": null }, { "code": "<script> // JavaScript Program to solve queries on Left and Right// Circular shift on array // Function to solve query of type 1 x.function querytype1(toRotate, times, n){ // Decreasing the absolute rotation toRotate = (toRotate - times) % n return toRotate} // Function to solve query of type 2 y.function querytype2(toRotate, times, n){ // Increasing the absolute rotation. toRotate = (toRotate + times) % n return toRotate} // Function to solve queries of type 3 l r.function querytype3( toRotate, l, r, preSum, n){ // Finding absolute l and r. l = (l + toRotate + n) % n r = (r + toRotate + n) % n // if l is before r. if (l <= r) document.write((preSum[r + 1] - preSum[l]),\"</br>\") // If r is before l. else document.write((preSum[n] + preSum[r + 1] - preSum[l]),\"</br>\")} // Wrapper Function solve all queries.function wrapper(a, n){ preSum = new Array(n+1).fill(0) // Finding Prefix sum for(let i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1] toRotate = 0 // Solving each query toRotate = querytype1(toRotate, 3, n) querytype3(toRotate, 0, 2, preSum, n) toRotate = querytype2(toRotate, 1, n) querytype3(toRotate, 1, 4, preSum, n);} // Driver Programlet a = [ 1, 2, 3, 4, 5 ]let n = a.lengthwrapper(a, n) // This code is contributed by rohan07.</script>", "e": 9863, "s": 8499, "text": null }, { "code": null, "e": 9872, "s": 9863, "text": "Output: " }, { "code": null, "e": 9878, "s": 9872, "text": "12\n11" }, { "code": null, "e": 9901, "s": 9878, "text": "Time Complexity: O(n)." }, { "code": null, "e": 9924, "s": 9901, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 9938, "s": 9924, "text": "patnaikbhawna" }, { "code": null, "e": 9947, "s": 9938, "text": "rams2103" }, { "code": null, "e": 9964, "s": 9947, "text": "akshaysingh98088" }, { "code": null, "e": 9973, "s": 9964, "text": "siri1404" }, { "code": null, "e": 9981, "s": 9973, "text": "rohan07" }, { "code": null, "e": 9994, "s": 9981, "text": "shinjanpatra" }, { "code": null, "e": 10011, "s": 9994, "text": "_saurabh_jaiswal" }, { "code": null, "e": 10028, "s": 10011, "text": "codewithshinchan" }, { "code": null, "e": 10045, "s": 10028, "text": "triangleofcoding" }, { "code": null, "e": 10065, "s": 10045, "text": "array-range-queries" }, { "code": null, "e": 10074, "s": 10065, "text": "rotation" }, { "code": null, "e": 10081, "s": 10074, "text": "Arrays" }, { "code": null, "e": 10088, "s": 10081, "text": "Arrays" } ]
Sleeping Barber problem in Process Synchronization
14 Aug, 2019 Prerequisite – Inter Process CommunicationProblem : The analogy is based upon a hypothetical barber shop with one barber. There is a barber shop which has one barber, one barber chair, and n chairs for waiting for customers if there are any to sit on the chair. If there is no customer, then the barber sleeps in his own chair. When a customer arrives, he has to wake up the barber. If there are many customers and the barber is cutting a customer’s hair, then the remaining customers either wait if there are empty chairs in the waiting room or they leave if no chairs are empty. Solution : The solution to this problem includes three semaphores.First is for the customer which counts the number of customers present in the waiting room (customer in the barber chair is not included because he is not waiting). Second, the barber 0 or 1 is used to tell whether the barber is idle or is working, And the third mutex is used to provide the mutual exclusion which is required for the process to execute. In the solution, the customer has the record of the number of customers waiting in the waiting room if the number of customers is equal to the number of chairs in the waiting room then the upcoming customer leaves the barbershop. When the barber shows up in the morning, he executes the procedure barber, causing him to block on the semaphore customers because it is initially 0. Then the barber goes to sleep until the first customer comes up. When a customer arrives, he executes customer procedure the customer acquires the mutex for entering the critical region, if another customer enters thereafter, the second one will not be able to anything until the first one has released the mutex. The customer then checks the chairs in the waiting room if waiting customers are less then the number of chairs then he sits otherwise he leaves and releases the mutex. If the chair is available then customer sits in the waiting room and increments the variable waiting value and also increases the customer’s semaphore this wakes up the barber if he is sleeping. At this point, customer and barber are both awake and the barber is ready to give that person a haircut. When the haircut is over, the customer exits the procedure and if there are no customers in waiting room barber sleeps. Algorithm for Sleeping Barber problem: Semaphore Customers = 0;Semaphore Barber = 0;Mutex Seats = 1;int FreeSeats = N; Barber { while(true) { /* waits for a customer (sleeps). */ down(Customers); /* mutex to protect the number of available seats.*/ down(Seats); /* a chair gets free.*/ FreeSeats++; /* bring customer for haircut.*/ up(Barber); /* release the mutex on the chair.*/ up(Seats); /* barber is cutting hair.*/ }} Customer { while(true) { /* protects seats so only 1 customer tries to sit in a chair if that's the case.*/ down(Seats); //This line should not be here. if(FreeSeats > 0) { /* sitting down.*/ FreeSeats--; /* notify the barber. */ up(Customers); /* release the lock */ up(Seats); /* wait in the waiting room if barber is busy. */ down(Barber); // customer is having hair cut } else { /* release the lock */ up(Seats); // customer leaves } }} Kumar Shubham 10 Process Synchronization GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Aug, 2019" }, { "code": null, "e": 316, "s": 54, "text": "Prerequisite – Inter Process CommunicationProblem : The analogy is based upon a hypothetical barber shop with one barber. There is a barber shop which has one barber, one barber chair, and n chairs for waiting for customers if there are any to sit on the chair." }, { "code": null, "e": 382, "s": 316, "text": "If there is no customer, then the barber sleeps in his own chair." }, { "code": null, "e": 437, "s": 382, "text": "When a customer arrives, he has to wake up the barber." }, { "code": null, "e": 635, "s": 437, "text": "If there are many customers and the barber is cutting a customer’s hair, then the remaining customers either wait if there are empty chairs in the waiting room or they leave if no chairs are empty." }, { "code": null, "e": 1286, "s": 635, "text": "Solution : The solution to this problem includes three semaphores.First is for the customer which counts the number of customers present in the waiting room (customer in the barber chair is not included because he is not waiting). Second, the barber 0 or 1 is used to tell whether the barber is idle or is working, And the third mutex is used to provide the mutual exclusion which is required for the process to execute. In the solution, the customer has the record of the number of customers waiting in the waiting room if the number of customers is equal to the number of chairs in the waiting room then the upcoming customer leaves the barbershop." }, { "code": null, "e": 1501, "s": 1286, "text": "When the barber shows up in the morning, he executes the procedure barber, causing him to block on the semaphore customers because it is initially 0. Then the barber goes to sleep until the first customer comes up." }, { "code": null, "e": 1919, "s": 1501, "text": "When a customer arrives, he executes customer procedure the customer acquires the mutex for entering the critical region, if another customer enters thereafter, the second one will not be able to anything until the first one has released the mutex. The customer then checks the chairs in the waiting room if waiting customers are less then the number of chairs then he sits otherwise he leaves and releases the mutex." }, { "code": null, "e": 2114, "s": 1919, "text": "If the chair is available then customer sits in the waiting room and increments the variable waiting value and also increases the customer’s semaphore this wakes up the barber if he is sleeping." }, { "code": null, "e": 2339, "s": 2114, "text": "At this point, customer and barber are both awake and the barber is ready to give that person a haircut. When the haircut is over, the customer exits the procedure and if there are no customers in waiting room barber sleeps." }, { "code": null, "e": 2378, "s": 2339, "text": "Algorithm for Sleeping Barber problem:" }, { "code": "Semaphore Customers = 0;Semaphore Barber = 0;Mutex Seats = 1;int FreeSeats = N; Barber { while(true) { /* waits for a customer (sleeps). */ down(Customers); /* mutex to protect the number of available seats.*/ down(Seats); /* a chair gets free.*/ FreeSeats++; /* bring customer for haircut.*/ up(Barber); /* release the mutex on the chair.*/ up(Seats); /* barber is cutting hair.*/ }} Customer { while(true) { /* protects seats so only 1 customer tries to sit in a chair if that's the case.*/ down(Seats); //This line should not be here. if(FreeSeats > 0) { /* sitting down.*/ FreeSeats--; /* notify the barber. */ up(Customers); /* release the lock */ up(Seats); /* wait in the waiting room if barber is busy. */ down(Barber); // customer is having hair cut } else { /* release the lock */ up(Seats); // customer leaves } }}", "e": 3726, "s": 2378, "text": null }, { "code": null, "e": 3743, "s": 3726, "text": "Kumar Shubham 10" }, { "code": null, "e": 3767, "s": 3743, "text": "Process Synchronization" }, { "code": null, "e": 3775, "s": 3767, "text": "GATE CS" }, { "code": null, "e": 3793, "s": 3775, "text": "Operating Systems" }, { "code": null, "e": 3811, "s": 3793, "text": "Operating Systems" } ]
How to detect HTTP or HTTPS then force redirect to HTTPS in JavaScript ?
12 Dec, 2021 HTTPS stands for Hypertext Transfer Protocol Secure. As its name implies, it creates a secure, encrypted connection between the user’s browser and the server they are trying to access. Since it is an encrypted connection, it prevents malicious hackers from stealing data that is transmitted from the user’s browser to the server. Having a site in HTTPS also tells users that they can trust your site. If you have a site in HTTP as well as the same version in HTTPS, you can automatically redirect the user to the HTTPS site.To implement this redirect, we will use JavaScript code. Specifically, we will use the window.location.protocol property to identify the protocol and then use window.location.href property to redirect the browser. The window.location is a property of the Window object. It is often used for redirects. The window.location returns a Location object, which contains a number of useful properties: protocol: This is the protocol (http: or https:) of the current URL of the browser window. href: This is the full URL of the current browser window. It is writable. Note: Since window.location.href is writable, we will set a new URL to it and therefore reload the browser with the new URL. Example: javascript if (window.location.protocol == 'http:') { console.log("you are accessing us via " + "an insecure protocol (HTTP). " + "Redirecting you to HTTPS."); window.location.href = window.location.href.replace( 'http:', 'https:');}else (window.location.protocol == "https:") { console.log("you are accessing us via" + " our secure HTTPS protocol."); } Output: // On HTTP sites, you will be redirected to the HTTPS version. Disadvantages: There are some downsides with setting an HTTPS redirect from the browser side. These downsides include: If there is a malicious hacker in the middle of your connection (Man in the Middle Attack), they can prevent the redirect from occurring. During the initial load of HTTP, there may be cookies that have been previously set that can now be read by the hacker. Therefore, we recommend redirecting users via HTTPS on the server-side instead of in JavaScript. We have added an example below on how to do this redirect using NodeJS, which is a server written in Javascript. Using NodeJS on the server, the code is similar but not exactly the same. We will use req.protocol instead. Example (app.js): javascript app.get('/', function(req, res, next) { if (req.protocol == 'http') { res.redirect('https://' + req.get('host') + req.originalUrl); }}); Output: // On HTTP sites, you will be redirected to the HTTPS version. Note: The req.protocol does not include the colon (eg: http or https) whereas window.location.protocol does (eg: http: and https:). sagar0719kumar JavaScript-Misc Picked JavaScript Node.js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Dec, 2021" }, { "code": null, "e": 949, "s": 28, "text": "HTTPS stands for Hypertext Transfer Protocol Secure. As its name implies, it creates a secure, encrypted connection between the user’s browser and the server they are trying to access. Since it is an encrypted connection, it prevents malicious hackers from stealing data that is transmitted from the user’s browser to the server. Having a site in HTTPS also tells users that they can trust your site. If you have a site in HTTP as well as the same version in HTTPS, you can automatically redirect the user to the HTTPS site.To implement this redirect, we will use JavaScript code. Specifically, we will use the window.location.protocol property to identify the protocol and then use window.location.href property to redirect the browser. The window.location is a property of the Window object. It is often used for redirects. The window.location returns a Location object, which contains a number of useful properties: " }, { "code": null, "e": 1040, "s": 949, "text": "protocol: This is the protocol (http: or https:) of the current URL of the browser window." }, { "code": null, "e": 1114, "s": 1040, "text": "href: This is the full URL of the current browser window. It is writable." }, { "code": null, "e": 1240, "s": 1114, "text": "Note: Since window.location.href is writable, we will set a new URL to it and therefore reload the browser with the new URL. " }, { "code": null, "e": 1251, "s": 1240, "text": "Example: " }, { "code": null, "e": 1262, "s": 1251, "text": "javascript" }, { "code": "if (window.location.protocol == 'http:') { console.log(\"you are accessing us via \" + \"an insecure protocol (HTTP). \" + \"Redirecting you to HTTPS.\"); window.location.href = window.location.href.replace( 'http:', 'https:');}else (window.location.protocol == \"https:\") { console.log(\"you are accessing us via\" + \" our secure HTTPS protocol.\"); }", "e": 1689, "s": 1262, "text": null }, { "code": null, "e": 1699, "s": 1689, "text": "Output: " }, { "code": null, "e": 1762, "s": 1699, "text": "// On HTTP sites, you will be redirected to the HTTPS version." }, { "code": null, "e": 1883, "s": 1762, "text": "Disadvantages: There are some downsides with setting an HTTPS redirect from the browser side. These downsides include: " }, { "code": null, "e": 2021, "s": 1883, "text": "If there is a malicious hacker in the middle of your connection (Man in the Middle Attack), they can prevent the redirect from occurring." }, { "code": null, "e": 2141, "s": 2021, "text": "During the initial load of HTTP, there may be cookies that have been previously set that can now be read by the hacker." }, { "code": null, "e": 2461, "s": 2141, "text": "Therefore, we recommend redirecting users via HTTPS on the server-side instead of in JavaScript. We have added an example below on how to do this redirect using NodeJS, which is a server written in Javascript. Using NodeJS on the server, the code is similar but not exactly the same. We will use req.protocol instead. " }, { "code": null, "e": 2480, "s": 2461, "text": "Example (app.js): " }, { "code": null, "e": 2491, "s": 2480, "text": "javascript" }, { "code": "app.get('/', function(req, res, next) { if (req.protocol == 'http') { res.redirect('https://' + req.get('host') + req.originalUrl); }});", "e": 2648, "s": 2491, "text": null }, { "code": null, "e": 2658, "s": 2648, "text": "Output: " }, { "code": null, "e": 2721, "s": 2658, "text": "// On HTTP sites, you will be redirected to the HTTPS version." }, { "code": null, "e": 2854, "s": 2721, "text": "Note: The req.protocol does not include the colon (eg: http or https) whereas window.location.protocol does (eg: http: and https:). " }, { "code": null, "e": 2869, "s": 2854, "text": "sagar0719kumar" }, { "code": null, "e": 2885, "s": 2869, "text": "JavaScript-Misc" }, { "code": null, "e": 2892, "s": 2885, "text": "Picked" }, { "code": null, "e": 2903, "s": 2892, "text": "JavaScript" }, { "code": null, "e": 2911, "s": 2903, "text": "Node.js" }, { "code": null, "e": 2928, "s": 2911, "text": "Web Technologies" }, { "code": null, "e": 2955, "s": 2928, "text": "Web technologies Questions" } ]
Why we should use set.seed in R?
The use of set.seed is to make sure that we get the same results for randomization. If we randomly select some observations for any task in R or in any statistical software it results in different values all the time and this happens because of randomization. If we want to keep the values that are produced at first random selection then we can do this by storing them in an object after randomization or we can fix the randomization procedure so that we get the same results all the time. Randomization without set.seed > sample(1:10) [1] 4 10 5 3 1 6 9 2 8 7 > sample(1:10) [1] 1 4 2 5 8 3 7 9 6 10 > sample(1:10) [1] 6 3 9 5 10 2 7 1 8 4 Here we created a sample of size 10 three times and in all these samples the values are different. Randomization with set.seed > set.seed(99) > sample(1:10) [1] 6 2 10 7 4 5 3 1 8 9 > set.seed(99) > sample(1:10) [1] 6 2 10 7 4 5 3 1 8 9 > set.seed(99) > sample(1:10) [1] 6 2 10 7 4 5 3 1 8 9 Since we used the same set.seed in all the three samples hence we obtained the same sample values.
[ { "code": null, "e": 1553, "s": 1062, "text": "The use of set.seed is to make sure that we get the same results for randomization. If we\nrandomly select some observations for any task in R or in any statistical software it\nresults in different values all the time and this happens because of randomization. If we\nwant to keep the values that are produced at first random selection then we can do this by\nstoring them in an object after randomization or we can fix the randomization procedure\nso that we get the same results all the time." }, { "code": null, "e": 1584, "s": 1553, "text": "Randomization without set.seed" }, { "code": null, "e": 1704, "s": 1584, "text": "> sample(1:10)\n[1] 4 10 5 3 1 6 9 2 8 7\n> sample(1:10)\n[1] 1 4 2 5 8 3 7 9 6 10\n> sample(1:10)\n[1] 6 3 9 5 10 2 7 1 8 4" }, { "code": null, "e": 1803, "s": 1704, "text": "Here we created a sample of size 10 three times and in all these samples the values are\ndifferent." }, { "code": null, "e": 1831, "s": 1803, "text": "Randomization with set.seed" }, { "code": null, "e": 1996, "s": 1831, "text": "> set.seed(99)\n> sample(1:10)\n[1] 6 2 10 7 4 5 3 1 8 9\n> set.seed(99)\n> sample(1:10)\n[1] 6 2 10 7 4 5 3 1 8 9\n> set.seed(99)\n> sample(1:10)\n[1] 6 2 10 7 4 5 3 1 8 9" }, { "code": null, "e": 2095, "s": 1996, "text": "Since we used the same set.seed in all the three samples hence we obtained the same\nsample values." } ]
How to order an alphanumeric column in MySQL?
To order an alphanumeric column with values like “100X, “2Z”, etc. use the ORDER BY. Let us first create a table − mysql> create table DemoTable -> ( -> StudentId varchar(100) -> ); Query OK, 0 rows affected (0.52 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('2X'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values('100Y'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('100X'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('2Z'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('2Y'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('100Z'); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-----------+ | StudentId | +-----------+ | 2X | | 100Y | | 100X | | 2Z | | 2Y | | 100Z | +-----------+ 6 rows in set (0.00 sec) Here is the query to order by an alphanumeric column in MySQL − mysql>select *from DemoTable order by (StudentId+0), right(StudentId, 1); This will produce the following output − +-----------+ | StudentId | +-----------+ | 2X | | 2Y | | 2Z | | 100X | | 100Y | | 100Z | +-----------+ 6 rows in set, 6 warnings (0.00 sec)
[ { "code": null, "e": 1177, "s": 1062, "text": "To order an alphanumeric column with values like “100X, “2Z”, etc. use the ORDER BY. Let us first create a table −" }, { "code": null, "e": 1281, "s": 1177, "text": "mysql> create table DemoTable\n-> (\n-> StudentId varchar(100)\n-> );\nQuery OK, 0 rows affected (0.52 sec)" }, { "code": null, "e": 1337, "s": 1281, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1822, "s": 1337, "text": "mysql> insert into DemoTable values('2X');\nQuery OK, 1 row affected (0.21 sec)\n\nmysql> insert into DemoTable values('100Y');\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable values('100X');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DemoTable values('2Z');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('2Y');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into DemoTable values('100Z');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1882, "s": 1822, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1913, "s": 1882, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1954, "s": 1913, "text": "This will produce the following output −" }, { "code": null, "e": 2119, "s": 1954, "text": "+-----------+\n| StudentId |\n+-----------+\n| 2X |\n| 100Y |\n| 100X |\n| 2Z |\n| 2Y |\n| 100Z |\n+-----------+\n6 rows in set (0.00 sec)" }, { "code": null, "e": 2183, "s": 2119, "text": "Here is the query to order by an alphanumeric column in MySQL −" }, { "code": null, "e": 2257, "s": 2183, "text": "mysql>select *from DemoTable order by (StudentId+0), right(StudentId, 1);" }, { "code": null, "e": 2298, "s": 2257, "text": "This will produce the following output −" }, { "code": null, "e": 2475, "s": 2298, "text": "+-----------+\n| StudentId |\n+-----------+\n| 2X |\n| 2Y |\n| 2Z |\n| 100X |\n| 100Y |\n| 100Z |\n+-----------+\n6 rows in set, 6 warnings (0.00 sec)" } ]
Bootstrap Collapsible button
The collapsible button is used in Bootstrap to create a collapsible that can be shown or hidden on click. You can try to run the following code to create a collapsible button: Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <h2>Contact Us</h2> <p>Click for more info...</p> <button type = "button" class = "btn btn-info" data-toggle = "collapse" data-target = "#demo">More</button> <div id="demo" class="collapse"> You can also contact us on 9199****** for more information on our products. </div> </div> </body> </html>
[ { "code": null, "e": 1168, "s": 1062, "text": "The collapsible button is used in Bootstrap to create a collapsible that can be shown or hidden on click." }, { "code": null, "e": 1238, "s": 1168, "text": "You can try to run the following code to create a collapsible button:" }, { "code": null, "e": 1248, "s": 1238, "text": "Live Demo" }, { "code": null, "e": 1928, "s": 1248, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h2>Contact Us</h2>\n <p>Click for more info...</p>\n <button type = \"button\" class = \"btn btn-info\" data-toggle = \"collapse\" data-target = \"#demo\">More</button>\n <div id=\"demo\" class=\"collapse\">\n You can also contact us on 9199****** for more information on our products.\n </div>\n </div>\n </body>\n</html>" } ]
Python Program For Finding The Length Of Loop In Linked List - GeeksforGeeks
21 Jan, 2022 Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Approach: It is known that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable say (ptr). Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.Algorithm: Find the common point in the loop by using the Floyd’s Cycle detection algorithmStore the pointer in a temporary variable and keep a count = 0Traverse the linked list until the same node is reached again and increase the count while moving to next node.Print the count as length of loop Find the common point in the loop by using the Floyd’s Cycle detection algorithm Store the pointer in a temporary variable and keep a count = 0 Traverse the linked list until the same node is reached again and increase the count while moving to next node. Print the count as length of loop Python3 # Python program to detect a loop and# find the length of the loop# Node defining classclass Node: # Function to make a node def __init__(self, val): self.val = val self.next = None # Linked List defining and loop# length finding classclass LinkedList: # Function to initialize the # head of the linked list def __init__(self): self.head = None # Function to insert a new # node at the end def AddNode(self, val): if self.head is None: self.head = Node(val) else: curr = self.head while(curr.next): curr = curr.next curr.next = Node(val) # Function to create a loop in the # Linked List. This function creates # a loop by connecting the last node # to n^th node of the linked list, # (counting first node as 1) def CreateLoop(self, n): # LoopNode is the connecting node to # the last node of linked list LoopNode = self.head for _ in range(1, n): LoopNode = LoopNode.next # end is the last node of the # Linked List end = self.head while(end.next): end = end.next # Creating the loop end.next = LoopNode # Function to detect the loop and return # the length of the loop if the returned # value is zero, which means that either # the linked list is empty or the linked # list doesn't have any loop def detectLoop(self): # If linked list is empty then there # is no loop, so return 0 if self.head is None: return 0 # Using Floyd’s Cycle-Finding # Algorithm/ Slow-Fast Pointer Method slow = self.head fast = self.head # To show that both slow and fast # are at start of the Linked List flag = 0 while(slow and slow.next and fast and fast.next and fast.next.next): if slow == fast and flag != 0: # Means loop is confirmed in the # Linked List. Now slow and fast # are both at the same node which # is part of the loop count = 1 slow = slow.next while(slow != fast): slow = slow.next count += 1 return count slow = slow.next fast = fast.next.next flag = 1 return 0 # No loop # Setting up the code# Making a Linked List and# adding the nodesmyLL = LinkedList()myLL.AddNode(1)myLL.AddNode(2)myLL.AddNode(3)myLL.AddNode(4)myLL.AddNode(5) # Creating a loop in the linked List# Loop is created by connecting the# last node of linked list to n^th node# 1<= n <= len(LinkedList)myLL.CreateLoop(2) # Checking for Loop in the Linked List# and printing the length of the looploopLength = myLL.detectLoop()if myLL.head is None: print("Linked list is empty")else: print(str(loopLength))# This code is contributed by _Ashutosh Output: 4 Complexity Analysis: Time complexity:O(n). Only one traversal of the linked list is needed. Auxiliary Space:O(1). As no extra space is required. Please refer complete article on Find length of loop in linked list for more details! sumitgumber28 Adobe Linked Lists Qualcomm Linked List Python Python Programs Adobe Qualcomm Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Swap nodes in a linked list without swapping data Given a linked list which is sorted, how will you insert in sorted way Delete a node in a Doubly Linked List Circular Linked List | Set 2 (Traversal) Circular Singly Linked List | Insertion 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": 24854, "s": 24826, "text": "\n21 Jan, 2022" }, { "code": null, "e": 25152, "s": 24854, "text": "Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0." }, { "code": null, "e": 25675, "s": 25152, "text": "Approach: It is known that Floyd’s Cycle detection algorithm terminates when fast and slow pointers meet at a common point. It is also known that this common point is one of the loop nodes. Store the address of this common point in a pointer variable say (ptr). Then initialize a counter with 1 and start from the common point and keeps on visiting the next node and increasing the counter till the common pointer is reached again. At that point, the value of the counter will be equal to the length of the loop.Algorithm:" }, { "code": null, "e": 25962, "s": 25675, "text": "Find the common point in the loop by using the Floyd’s Cycle detection algorithmStore the pointer in a temporary variable and keep a count = 0Traverse the linked list until the same node is reached again and increase the count while moving to next node.Print the count as length of loop" }, { "code": null, "e": 26043, "s": 25962, "text": "Find the common point in the loop by using the Floyd’s Cycle detection algorithm" }, { "code": null, "e": 26106, "s": 26043, "text": "Store the pointer in a temporary variable and keep a count = 0" }, { "code": null, "e": 26218, "s": 26106, "text": "Traverse the linked list until the same node is reached again and increase the count while moving to next node." }, { "code": null, "e": 26252, "s": 26218, "text": "Print the count as length of loop" }, { "code": null, "e": 26260, "s": 26252, "text": "Python3" }, { "code": "# Python program to detect a loop and# find the length of the loop# Node defining classclass Node: # Function to make a node def __init__(self, val): self.val = val self.next = None # Linked List defining and loop# length finding classclass LinkedList: # Function to initialize the # head of the linked list def __init__(self): self.head = None # Function to insert a new # node at the end def AddNode(self, val): if self.head is None: self.head = Node(val) else: curr = self.head while(curr.next): curr = curr.next curr.next = Node(val) # Function to create a loop in the # Linked List. This function creates # a loop by connecting the last node # to n^th node of the linked list, # (counting first node as 1) def CreateLoop(self, n): # LoopNode is the connecting node to # the last node of linked list LoopNode = self.head for _ in range(1, n): LoopNode = LoopNode.next # end is the last node of the # Linked List end = self.head while(end.next): end = end.next # Creating the loop end.next = LoopNode # Function to detect the loop and return # the length of the loop if the returned # value is zero, which means that either # the linked list is empty or the linked # list doesn't have any loop def detectLoop(self): # If linked list is empty then there # is no loop, so return 0 if self.head is None: return 0 # Using Floyd’s Cycle-Finding # Algorithm/ Slow-Fast Pointer Method slow = self.head fast = self.head # To show that both slow and fast # are at start of the Linked List flag = 0 while(slow and slow.next and fast and fast.next and fast.next.next): if slow == fast and flag != 0: # Means loop is confirmed in the # Linked List. Now slow and fast # are both at the same node which # is part of the loop count = 1 slow = slow.next while(slow != fast): slow = slow.next count += 1 return count slow = slow.next fast = fast.next.next flag = 1 return 0 # No loop # Setting up the code# Making a Linked List and# adding the nodesmyLL = LinkedList()myLL.AddNode(1)myLL.AddNode(2)myLL.AddNode(3)myLL.AddNode(4)myLL.AddNode(5) # Creating a loop in the linked List# Loop is created by connecting the# last node of linked list to n^th node# 1<= n <= len(LinkedList)myLL.CreateLoop(2) # Checking for Loop in the Linked List# and printing the length of the looploopLength = myLL.detectLoop()if myLL.head is None: print(\"Linked list is empty\")else: print(str(loopLength))# This code is contributed by _Ashutosh", "e": 29381, "s": 26260, "text": null }, { "code": null, "e": 29389, "s": 29381, "text": "Output:" }, { "code": null, "e": 29391, "s": 29389, "text": "4" }, { "code": null, "e": 29412, "s": 29391, "text": "Complexity Analysis:" }, { "code": null, "e": 29483, "s": 29412, "text": "Time complexity:O(n). Only one traversal of the linked list is needed." }, { "code": null, "e": 29536, "s": 29483, "text": "Auxiliary Space:O(1). As no extra space is required." }, { "code": null, "e": 29623, "s": 29536, "text": "Please refer complete article on Find length of loop in linked list for more details! " }, { "code": null, "e": 29637, "s": 29623, "text": "sumitgumber28" }, { "code": null, "e": 29643, "s": 29637, "text": "Adobe" }, { "code": null, "e": 29656, "s": 29643, "text": "Linked Lists" }, { "code": null, "e": 29665, "s": 29656, "text": "Qualcomm" }, { "code": null, "e": 29677, "s": 29665, "text": "Linked List" }, { "code": null, "e": 29684, "s": 29677, "text": "Python" }, { "code": null, "e": 29700, "s": 29684, "text": "Python Programs" }, { "code": null, "e": 29706, "s": 29700, "text": "Adobe" }, { "code": null, "e": 29715, "s": 29706, "text": "Qualcomm" }, { "code": null, "e": 29727, "s": 29715, "text": "Linked List" }, { "code": null, "e": 29825, "s": 29727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29834, "s": 29825, "text": "Comments" }, { "code": null, "e": 29847, "s": 29834, "text": "Old Comments" }, { "code": null, "e": 29897, "s": 29847, "text": "Swap nodes in a linked list without swapping data" }, { "code": null, "e": 29968, "s": 29897, "text": "Given a linked list which is sorted, how will you insert in sorted way" }, { "code": null, "e": 30006, "s": 29968, "text": "Delete a node in a Doubly Linked List" }, { "code": null, "e": 30047, "s": 30006, "text": "Circular Linked List | Set 2 (Traversal)" }, { "code": null, "e": 30087, "s": 30047, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 30115, "s": 30087, "text": "Read JSON file using Python" }, { "code": null, "e": 30165, "s": 30115, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 30187, "s": 30165, "text": "Python map() function" } ]
Convert a list into tuple of lists in Python
Converting one data container into another in python is a frequent requirement. In this article we will take a list and convert into a tuple where each element of the tuple is also a list. We can apply the tuple function straight to the list. But we have to also put a for loop in place so that each element is enclosed in a []. Live Demo listA = ["Mon",2,"Tue",3] # Given list print("Given list A: ", listA) # Use zip res = tuple([i] for i in listA) # Result print("The tuple is : ",res) Running the above code gives us the following result − Given list A: ['Mon', 2, 'Tue', 3] The tuple is : (['Mon'], [2], ['Tue'], [3]) We can also use zip and map in a similar approach as in the above. The map function will apply the list function to each element in the list. Finally the tuple function converts the result into a tuple whose each element is a list. Live Demo listA = ["Mon",2,"Tue",3] # Given list print("Given list A: ", listA) # Use zip res = tuple(map(list, zip(listA))) # Result print("The tuple is : ",res) Running the above code gives us the following result − Given list A: ['Mon', 2, 'Tue', 3] The tuple is : (['Mon'], [2], ['Tue'], [3])
[ { "code": null, "e": 1251, "s": 1062, "text": "Converting one data container into another in python is a frequent requirement. In this article we will take a list and convert into a tuple where each element of the tuple is also a list." }, { "code": null, "e": 1391, "s": 1251, "text": "We can apply the tuple function straight to the list. But we have to also put a for loop in place so that each element is enclosed in a []." }, { "code": null, "e": 1402, "s": 1391, "text": " Live Demo" }, { "code": null, "e": 1552, "s": 1402, "text": "listA = [\"Mon\",2,\"Tue\",3]\n# Given list\nprint(\"Given list A: \", listA)\n# Use zip\nres = tuple([i] for i in listA)\n# Result\nprint(\"The tuple is : \",res)" }, { "code": null, "e": 1607, "s": 1552, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1686, "s": 1607, "text": "Given list A: ['Mon', 2, 'Tue', 3]\nThe tuple is : (['Mon'], [2], ['Tue'], [3])" }, { "code": null, "e": 1918, "s": 1686, "text": "We can also use zip and map in a similar approach as in the above. The map function will apply the list function to each element in the list. Finally the tuple function converts the result into a tuple whose each element is a list." }, { "code": null, "e": 1929, "s": 1918, "text": " Live Demo" }, { "code": null, "e": 2082, "s": 1929, "text": "listA = [\"Mon\",2,\"Tue\",3]\n# Given list\nprint(\"Given list A: \", listA)\n# Use zip\nres = tuple(map(list, zip(listA)))\n# Result\nprint(\"The tuple is : \",res)" }, { "code": null, "e": 2137, "s": 2082, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2216, "s": 2137, "text": "Given list A: ['Mon', 2, 'Tue', 3]\nThe tuple is : (['Mon'], [2], ['Tue'], [3])" } ]
Bootstrap 5 Spinners - GeeksforGeeks
18 Nov, 2021 In this article, we will implement spinners in the website using Bootstrap & will also see the implementation of different types of spinners through the example. The spinners are used to specify the loading state of a component or webpage. Bootstrap facilitates the various classes for creating different styles of spinners by modifying the appearance, size, and placement. Syntax: For spinner-border: <div class="spinner-border" role="status"></div> For spinner-grow: <div class="spinner-grow" role="status"></div> Approach: We will use a div element for spinners & declare the bootstrap classes called spinner-border and spinner-grow, inside the div section in order to use the spinners. The spinner-border class is used for rotating spinner and the spinner-grow is used for growing spinners. They are used for showing that some content is loading. Example 1: This example illustrates the spinner-border in Bootstrap. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"></head> <body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <h4 class="text-info text-center"> Bootstrap Spinner Border </h4> <div class="d-flex justify-content-center"> <div class="spinner-border text-secondary" role="status"> </div> <span>Please Wait </span> </div></body> </html> Output: spinner-border Example 2: This example describes the spinner-grow in Bootstrap. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"></head> <body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <h4 class="text-info text-center"> Bootstrap Spinner Grow </h4> <div class="d-flex justify-content-center"> <span> <h5>Processing</h5> </span> <div class="spinner-grow text-primary" role="status"> </div> </div></body> </html> Output: spinner-grow Now we will learn how to align the spinners in the webpage according to our needs. We can add margin to the spinners in Bootstrap using the margin utilities class in Bootstrap. Here is an example given below: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"></head> <body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <h4 class="text-info text-center"> Adding margin to Bootstrap Spinners </h4> <div class="spinner-border m-5" role="status"> </div></body> </html> Adding margin to Bootstrap spinners We can place the spinner at different positions like the center, end or start using the text placement or flex box classes. Below given is the example in which we have used flexbox and text placement classes: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"></head> <body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <h4 class="text-info text-center"> Spinner Placement using Bootstrap classes </h4> <h4 class=" text-center"> Using the Text Placement Classes </h4> <div class="text-center"> <div class="spinner-border m-5 " role="status"> </div> </div> <h4 class="text-center"> Using the Flex Box Classes </h4> <div class="d-flex justify-content-center"> <div class="spinner-border" role="status"> </div> </div></body> </html> Placing the Spinners using the Bootstrap Classes We can also adjust the size of the spinners according to our needs using the Bootstrap classes or by using the inline CSS styling. We can add the .spinner-border-sm and .spinner-grow-sm classes to make smaller spinners that can fit inside different components. Here is an example: HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"></head> <body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <div class="text-center"> <h3>Making smaller Spinners using the Bootstrap Classes</h3> <div class="spinner-border spinner-border-sm" role="status"> <span class="visually-hidden">Loading...</span> </div> <div class="spinner-grow spinner-grow-sm" role="status"> <span class="visually-hidden">Loading...</span> </div> </div></body> </html> Decreasing the Size of Bootstrap Spinners We can also increase or decrease size of spinners using the inline CSS styling by defining the width and height attributes. Here is an example where we increased the size of the spinner using the inline CSS styling: HTML <!DOCTYPE html><html><head><title>Page Title</title></head><body><h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> </body></html>a<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"></head> <body> <h1 class="text-success text-center"> GeeksforGeeks </h1> <div class="text-center"> <h3>Increasing the size of Spinners using inline CSS</h3> <div class="spinner-border" style="width: 4rem; height: 4rem;" role="status"> <span class="visually-hidden">Loading...</span> </div> <div class="spinner-grow" style="width: 4rem; height: 4rem;" role="status"> <span class="visually-hidden">Loading...</span> </div> </div></body> </html> Increasing the size of Bootstrap Spinners using inline CSS Supported Browsers: Google Chrome Microsoft Edge Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. saikatmohanta43434 sumitgumber28 surinderdawra388 Bootstrap-Questions HTML-Questions Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25227, "s": 25199, "text": "\n18 Nov, 2021" }, { "code": null, "e": 25601, "s": 25227, "text": "In this article, we will implement spinners in the website using Bootstrap & will also see the implementation of different types of spinners through the example. The spinners are used to specify the loading state of a component or webpage. Bootstrap facilitates the various classes for creating different styles of spinners by modifying the appearance, size, and placement." }, { "code": null, "e": 25609, "s": 25601, "text": "Syntax:" }, { "code": null, "e": 25629, "s": 25609, "text": "For spinner-border:" }, { "code": null, "e": 25678, "s": 25629, "text": "<div class=\"spinner-border\" role=\"status\"></div>" }, { "code": null, "e": 25696, "s": 25678, "text": "For spinner-grow:" }, { "code": null, "e": 25743, "s": 25696, "text": "<div class=\"spinner-grow\" role=\"status\"></div>" }, { "code": null, "e": 26078, "s": 25743, "text": "Approach: We will use a div element for spinners & declare the bootstrap classes called spinner-border and spinner-grow, inside the div section in order to use the spinners. The spinner-border class is used for rotating spinner and the spinner-grow is used for growing spinners. They are used for showing that some content is loading." }, { "code": null, "e": 26147, "s": 26078, "text": "Example 1: This example illustrates the spinner-border in Bootstrap." }, { "code": null, "e": 26152, "s": 26147, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\"></head> <body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <h4 class=\"text-info text-center\"> Bootstrap Spinner Border </h4> <div class=\"d-flex justify-content-center\"> <div class=\"spinner-border text-secondary\" role=\"status\"> </div> <span>Please Wait </span> </div></body> </html>", "e": 26762, "s": 26152, "text": null }, { "code": null, "e": 26770, "s": 26762, "text": "Output:" }, { "code": null, "e": 26785, "s": 26770, "text": "spinner-border" }, { "code": null, "e": 26851, "s": 26785, "text": "Example 2: This example describes the spinner-grow in Bootstrap. " }, { "code": null, "e": 26856, "s": 26851, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\"></head> <body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <h4 class=\"text-info text-center\"> Bootstrap Spinner Grow </h4> <div class=\"d-flex justify-content-center\"> <span> <h5>Processing</h5> </span> <div class=\"spinner-grow text-primary\" role=\"status\"> </div> </div></body> </html>", "e": 27477, "s": 26856, "text": null }, { "code": null, "e": 27485, "s": 27477, "text": "Output:" }, { "code": null, "e": 27498, "s": 27485, "text": "spinner-grow" }, { "code": null, "e": 27581, "s": 27498, "text": "Now we will learn how to align the spinners in the webpage according to our needs." }, { "code": null, "e": 27707, "s": 27581, "text": "We can add margin to the spinners in Bootstrap using the margin utilities class in Bootstrap. Here is an example given below:" }, { "code": null, "e": 27712, "s": 27707, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\"></head> <body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <h4 class=\"text-info text-center\"> Adding margin to Bootstrap Spinners </h4> <div class=\"spinner-border m-5\" role=\"status\"> </div></body> </html>", "e": 28183, "s": 27712, "text": null }, { "code": null, "e": 28219, "s": 28183, "text": "Adding margin to Bootstrap spinners" }, { "code": null, "e": 28429, "s": 28219, "text": "We can place the spinner at different positions like the center, end or start using the text placement or flex box classes. Below given is the example in which we have used flexbox and text placement classes: " }, { "code": null, "e": 28434, "s": 28429, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\"></head> <body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <h4 class=\"text-info text-center\"> Spinner Placement using Bootstrap classes </h4> <h4 class=\" text-center\"> Using the Text Placement Classes </h4> <div class=\"text-center\"> <div class=\"spinner-border m-5 \" role=\"status\"> </div> </div> <h4 class=\"text-center\"> Using the Flex Box Classes </h4> <div class=\"d-flex justify-content-center\"> <div class=\"spinner-border\" role=\"status\"> </div> </div></body> </html>", "e": 29228, "s": 28434, "text": null }, { "code": null, "e": 29277, "s": 29228, "text": "Placing the Spinners using the Bootstrap Classes" }, { "code": null, "e": 29408, "s": 29277, "text": "We can also adjust the size of the spinners according to our needs using the Bootstrap classes or by using the inline CSS styling." }, { "code": null, "e": 29558, "s": 29408, "text": "We can add the .spinner-border-sm and .spinner-grow-sm classes to make smaller spinners that can fit inside different components. Here is an example:" }, { "code": null, "e": 29563, "s": 29558, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\"></head> <body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <div class=\"text-center\"> <h3>Making smaller Spinners using the Bootstrap Classes</h3> <div class=\"spinner-border spinner-border-sm\" role=\"status\"> <span class=\"visually-hidden\">Loading...</span> </div> <div class=\"spinner-grow spinner-grow-sm\" role=\"status\"> <span class=\"visually-hidden\">Loading...</span> </div> </div></body> </html>", "e": 30276, "s": 29563, "text": null }, { "code": null, "e": 30318, "s": 30276, "text": "Decreasing the Size of Bootstrap Spinners" }, { "code": null, "e": 30534, "s": 30318, "text": "We can also increase or decrease size of spinners using the inline CSS styling by defining the width and height attributes. Here is an example where we increased the size of the spinner using the inline CSS styling:" }, { "code": null, "e": 30539, "s": 30534, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head><title>Page Title</title></head><body><h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> </body></html>a<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\"></head> <body> <h1 class=\"text-success text-center\"> GeeksforGeeks </h1> <div class=\"text-center\"> <h3>Increasing the size of Spinners using inline CSS</h3> <div class=\"spinner-border\" style=\"width: 4rem; height: 4rem;\" role=\"status\"> <span class=\"visually-hidden\">Loading...</span> </div> <div class=\"spinner-grow\" style=\"width: 4rem; height: 4rem;\" role=\"status\"> <span class=\"visually-hidden\">Loading...</span> </div> </div></body> </html>", "e": 31452, "s": 30539, "text": null }, { "code": null, "e": 31511, "s": 31452, "text": "Increasing the size of Bootstrap Spinners using inline CSS" }, { "code": null, "e": 31531, "s": 31511, "text": "Supported Browsers:" }, { "code": null, "e": 31545, "s": 31531, "text": "Google Chrome" }, { "code": null, "e": 31560, "s": 31545, "text": "Microsoft Edge" }, { "code": null, "e": 31568, "s": 31560, "text": "Firefox" }, { "code": null, "e": 31574, "s": 31568, "text": "Opera" }, { "code": null, "e": 31581, "s": 31574, "text": "Safari" }, { "code": null, "e": 31718, "s": 31581, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 31737, "s": 31718, "text": "saikatmohanta43434" }, { "code": null, "e": 31751, "s": 31737, "text": "sumitgumber28" }, { "code": null, "e": 31768, "s": 31751, "text": "surinderdawra388" }, { "code": null, "e": 31788, "s": 31768, "text": "Bootstrap-Questions" }, { "code": null, "e": 31803, "s": 31788, "text": "HTML-Questions" }, { "code": null, "e": 31813, "s": 31803, "text": "Bootstrap" }, { "code": null, "e": 31818, "s": 31813, "text": "HTML" }, { "code": null, "e": 31835, "s": 31818, "text": "Web Technologies" }, { "code": null, "e": 31840, "s": 31835, "text": "HTML" }, { "code": null, "e": 31938, "s": 31840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31947, "s": 31938, "text": "Comments" }, { "code": null, "e": 31960, "s": 31947, "text": "Old Comments" }, { "code": null, "e": 32001, "s": 31960, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 32064, "s": 32001, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 32097, "s": 32064, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 32123, "s": 32097, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 32172, "s": 32123, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 32234, "s": 32172, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32284, "s": 32234, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32344, "s": 32284, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32392, "s": 32344, "text": "How to update Node.js and NPM to next version ?" } ]
Heap Data Structure - GeeksQuiz
07 Nov, 2019 BUILD-HEAP(A) heapsize := size(A); for i := floor(heapsize/2) downto 1 do HEAPIFY(A, i); end for END 9 / | \ / | \ 5 6 8 / | / | 3 1 9 / | \ / | \ 7 6 8 / | \ / | \ 3 1 5 9 / | \ / | \ 7 6 8 / | \ / / | \ / 3 1 5 2 10 / | \ / | \ 7 9 8 / | \ / | / | \ / | 3 1 5 2 6 10 / | \ / | \ 7 9 8 / | \ / | \ / | \ / | \ 3 1 5 2 6 4 25 / \ / \ 14 16 / \ / \ / \ / \ 13 10 8 12 12 / \ / \ 14 16 / \ / / \ / 13 10 8 16 / \ / \ 14 12 / \ / / \ / 13 10 8 8 / \ / \ 14 12 / \ / \ 13 10 14 / \ / \ 8 12 / \ / \ 13 10 14 / \ / \ 13 12 / \ / \ 8 10 12 / \ / \ 8 7 / \ / \ / \ / \ 2 3 4 5 Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies SQL Query to Convert VARCHAR to INT How to Update Multiple Columns in Single Update Statement in SQL? Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File Insert Image in a Jupyter Notebook How to Replace Values in a List in Python?
[ { "code": null, "e": 27530, "s": 27502, "text": "\n07 Nov, 2019" }, { "code": null, "e": 27656, "s": 27530, "text": "BUILD-HEAP(A) \n heapsize := size(A); \n for i := floor(heapsize/2) downto 1 \n do HEAPIFY(A, i); \n end for \nEND" }, { "code": null, "e": 27930, "s": 27656, "text": " 9\n / | \\\n / | \\\n 5 6 8\n / |\n / |\n 3 1\n" }, { "code": null, "e": 28244, "s": 27930, "text": " 9\n / | \\\n / | \\\n 7 6 8\n / | \\\n / | \\\n 3 1 5 \n" }, { "code": null, "e": 28575, "s": 28244, "text": " 9\n / | \\\n / | \\\n 7 6 8\n / | \\ /\n / | \\ /\n 3 1 5 2\n" }, { "code": null, "e": 28846, "s": 28575, "text": " 10\n / | \\\n / | \\\n 7 9 8\n / | \\ / |\n / | \\ / |\n 3 1 5 2 6\n" }, { "code": null, "e": 29129, "s": 28846, "text": " 10\n / | \\\n / | \\\n 7 9 8\n / | \\ / | \\\n / | \\ / | \\\n 3 1 5 2 6 4\n" }, { "code": null, "e": 29273, "s": 29129, "text": " 25\n / \\\n / \\\n 14 16\n / \\ / \\\n / \\ / \\\n13 10 8 12" }, { "code": null, "e": 29382, "s": 29273, "text": " 12\n / \\\n / \\\n 14 16\n / \\ /\n / \\ /\n13 10 8" }, { "code": null, "e": 29495, "s": 29382, "text": " 16\n / \\\n / \\\n 14 12\n / \\ /\n / \\ /\n13 10 8" }, { "code": null, "e": 29583, "s": 29495, "text": " 8\n / \\\n / \\\n 14 12\n / \\\n / \\\n 13 10" }, { "code": null, "e": 29772, "s": 29583, "text": " 14\n / \\\n / \\\n 8 12\n / \\\n / \\\n 13 10\n 14\n / \\\n / \\\n 13 12\n / \\\n / \\\n 8 10" }, { "code": null, "e": 29887, "s": 29772, "text": " 12\n / \\\n / \\\n 8 7\n / \\ / \\\n / \\ / \\\n2 3 4 5" }, { "code": null, "e": 29985, "s": 29887, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29994, "s": 29985, "text": "Comments" }, { "code": null, "e": 30007, "s": 29994, "text": "Old Comments" }, { "code": null, "e": 30060, "s": 30007, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 30096, "s": 30060, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 30162, "s": 30096, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 30223, "s": 30162, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30261, "s": 30223, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 30323, "s": 30261, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 30403, "s": 30323, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 30444, "s": 30403, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30479, "s": 30444, "text": "Insert Image in a Jupyter Notebook" } ]
Python | Pandas Timestamp.toordinal - GeeksforGeeks
27 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.toordinal() function return proleptic Gregorian ordinal. January 1 of year 1 is day 1. Function return the ordinal value for the given Timestamp object. Syntax :Timestamp.toordinal() Parameters : None Return : ordinal Example #1: Use Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object. # return ordinalts.toordinal() Output : As we can see in the output, the Timestamp.toordinal() function has returned the Gregorian ordinal for the given Timestamp. Example #2: Use Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object. # return ordinalts.toordinal() Output : As we can see in the output, the Timestamp.toordinal() function has returned the Gregorian ordinal for the given Timestamp. Python Pandas-Timestamp Python-pandas 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 Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists sum() function in Python
[ { "code": null, "e": 24643, "s": 24615, "text": "\n27 Jan, 2019" }, { "code": null, "e": 24857, "s": 24643, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25027, "s": 24857, "text": "Pandas Timestamp.toordinal() function return proleptic Gregorian ordinal. January 1 of year 1 is day 1. Function return the ordinal value for the given Timestamp object." }, { "code": null, "e": 25057, "s": 25027, "text": "Syntax :Timestamp.toordinal()" }, { "code": null, "e": 25075, "s": 25057, "text": "Parameters : None" }, { "code": null, "e": 25092, "s": 25075, "text": "Return : ordinal" }, { "code": null, "e": 25203, "s": 25092, "text": "Example #1: Use Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)", "e": 25432, "s": 25203, "text": null }, { "code": null, "e": 25441, "s": 25432, "text": "Output :" }, { "code": null, "e": 25556, "s": 25441, "text": "Now we will use the Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object." }, { "code": "# return ordinalts.toordinal()", "e": 25587, "s": 25556, "text": null }, { "code": null, "e": 25596, "s": 25587, "text": "Output :" }, { "code": null, "e": 25720, "s": 25596, "text": "As we can see in the output, the Timestamp.toordinal() function has returned the Gregorian ordinal for the given Timestamp." }, { "code": null, "e": 25831, "s": 25720, "text": "Example #2: Use Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 26059, "s": 25831, "text": null }, { "code": null, "e": 26068, "s": 26059, "text": "Output :" }, { "code": null, "e": 26183, "s": 26068, "text": "Now we will use the Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object." }, { "code": "# return ordinalts.toordinal()", "e": 26214, "s": 26183, "text": null }, { "code": null, "e": 26223, "s": 26214, "text": "Output :" }, { "code": null, "e": 26347, "s": 26223, "text": "As we can see in the output, the Timestamp.toordinal() function has returned the Gregorian ordinal for the given Timestamp." }, { "code": null, "e": 26371, "s": 26347, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 26385, "s": 26371, "text": "Python-pandas" }, { "code": null, "e": 26392, "s": 26385, "text": "Python" }, { "code": null, "e": 26490, "s": 26392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26499, "s": 26490, "text": "Comments" }, { "code": null, "e": 26512, "s": 26499, "text": "Old Comments" }, { "code": null, "e": 26530, "s": 26512, "text": "Python Dictionary" }, { "code": null, "e": 26565, "s": 26530, "text": "Read a file line by line in Python" }, { "code": null, "e": 26587, "s": 26565, "text": "Enumerate() in Python" }, { "code": null, "e": 26619, "s": 26587, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26649, "s": 26619, "text": "Iterate over a list in Python" }, { "code": null, "e": 26691, "s": 26649, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26734, "s": 26691, "text": "Python program to convert a list to string" }, { "code": null, "e": 26778, "s": 26734, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26815, "s": 26778, "text": "Create a Pandas DataFrame from Lists" } ]
How to record a video in Selenium webdriver?
We can record a video with Selenium. There is no default technique in Selenium to record videos. The videos can be captured in the below processes− ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar files need to be downloaded and saved within the project folder. ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar files need to be downloaded and saved within the project folder. Next, add the above two jars to the project Build path. Right-click on project−> Click on Properties−> Choose Java Build Path−> Click on the Libraries tab−> Click on Add External Jars−> Browser and select the ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar−> Click on Apply−> Click OK. Next, add the above two jars to the project Build path. Right-click on project−> Click on Properties−> Choose Java Build Path−> Click on the Libraries tab−> Click on Add External Jars−> Browser and select the ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar−> Click on Apply−> Click OK. Have a folder to hold the videos within the project. Have a folder to hold the videos within the project. @BeforeMethod public void bmethod(Method m){ // format of the date and time defined DateFormat d = new SimpleDateFormat("yy−mm−dd HH−mm−ss"); // get the current date Date dt = new Date(); try { // video capture file name recorder = new ATUTestRecorder(System.getProperty("userdir") + "\\TestVideos\\" , m.getName() + "_" + d.format(dt), false); } catch (Exception e){ Log.error("Error capturing videos"); } //begin recording try { recorder.start(); } catch (Exception e){ Log.error("Error in beginning videos"); } } @AfterMethod public void amethod(iTestResult result) { try { recorder.stop(); } catch (Exception e){ Log.error("Error in stopping videos"); } } For a Maven project, the pom.xml should have the setting −
[ { "code": null, "e": 1210, "s": 1062, "text": "We can record a video with Selenium. There is no default technique in Selenium to record videos. The videos can be captured in the below processes−" }, { "code": null, "e": 1331, "s": 1210, "text": "ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar files need to be downloaded and saved within the project folder." }, { "code": null, "e": 1452, "s": 1331, "text": "ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar files need to be downloaded and saved within the project folder." }, { "code": null, "e": 1746, "s": 1452, "text": "Next, add the above two jars to the project Build path. Right-click on project−> Click on Properties−> Choose Java Build Path−> Click on the Libraries tab−> Click on Add External Jars−> Browser and select the ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar−> Click on Apply−> Click OK." }, { "code": null, "e": 2040, "s": 1746, "text": "Next, add the above two jars to the project Build path. Right-click on project−> Click on Properties−> Choose Java Build Path−> Click on the Libraries tab−> Click on Add External Jars−> Browser and select the ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar−> Click on Apply−> Click OK." }, { "code": null, "e": 2093, "s": 2040, "text": "Have a folder to hold the videos within the project." }, { "code": null, "e": 2146, "s": 2093, "text": "Have a folder to hold the videos within the project." }, { "code": null, "e": 2737, "s": 2146, "text": "@BeforeMethod\npublic void bmethod(Method m){\n // format of the date and time defined\n DateFormat d = new SimpleDateFormat(\"yy−mm−dd HH−mm−ss\");\n // get the current date\n Date dt = new Date();\n try {\n // video capture file name\n recorder = new ATUTestRecorder(System.getProperty(\"userdir\") + \"\\\\TestVideos\\\\\" , m.getName() + \"_\" + d.format(dt), false);\n }\n catch (Exception e){\n Log.error(\"Error capturing videos\");\n }\n //begin recording\n try {\n recorder.start();\n }\n catch (Exception e){\n Log.error(\"Error in beginning videos\");\n }\n}" }, { "code": null, "e": 2905, "s": 2737, "text": "@AfterMethod\npublic void amethod(iTestResult result) {\n try {\n recorder.stop();\n }\n catch (Exception e){\n Log.error(\"Error in stopping videos\");\n }\n}" }, { "code": null, "e": 2964, "s": 2905, "text": "For a Maven project, the pom.xml should have the setting −" } ]
How to key in values in input text box with Javascript executor in Selenium with python?
We can key in values inside an input text box with a Javascript executor in Selenium. Javascript is a language used for scripting and runs on the client side (on the browser). Selenium gives default methods to work with Javascript. javaScript = "document.getElementsByClassName('gsc-input')[0].value = 'T' ") driver.execute_script(javaScript) There are couple of methods by which Javascript can be executed within browser − Javascript execution at document root level.In this process, we shall identify the element with locators (class or id) and then perform the required action on it. Then execute_script() method is called and the Javascript is passed as a string to it. Javascript execution at document root level. In this process, we shall identify the element with locators (class or id) and then perform the required action on it. Then execute_script() method is called and the Javascript is passed as a string to it. Syntax − javas = "document.getElementsByName('user-search')[0].click();" driver.execute_script(javas) Please note, we have used getElementsByName('user-search')[0]. The functions like getElementsByName and getElementsById return an array of matching elements. So for locating the first element, the index[0] is used. However if we are using getElementById function, we need not use the index since only one matching element is referred there. Finally, for execution the web driver will put the Javascript statement in the browser and then perform the necessary action like clicking the required element. This Javascript does not mingle with the Javascript present in the webpage. Javascript execution at element level.In this process, we shall identify the element with the help of web driver methods like find_element_by_xpath or find_element_by_id and so on. Then execute the necessary action on it like clicking the element. Finally, the method execute_script() is called. This method has the Javascript statement and the identified webelement as arguments. Javascript execution at element level. In this process, we shall identify the element with the help of web driver methods like find_element_by_xpath or find_element_by_id and so on. Then execute the necessary action on it like clicking the element. Finally, the method execute_script() is called. This method has the Javascript statement and the identified webelement as arguments. Syntax − userN= driver.find_element_by_id("user-search']") driver.execute_script("arguments[0].click();", userN) Code Implementation with Javascript key in values in text box. from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke #actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/about/about_careers.htm") #to refresh the browser driver.refresh() # inputting values in the text box with help of Javascript executor javaScript = "document.getElementsByClassName('gsc-input')[0].value = 'TestNG' " driver.execute_script(javaScript) #to close the browser driver.quit()
[ { "code": null, "e": 1294, "s": 1062, "text": "We can key in values inside an input text box with a Javascript executor in Selenium. Javascript is a language used for scripting and runs on the client side (on the browser). Selenium gives default methods to work with Javascript." }, { "code": null, "e": 1405, "s": 1294, "text": "javaScript = \"document.getElementsByClassName('gsc-input')[0].value = 'T' \")\ndriver.execute_script(javaScript)" }, { "code": null, "e": 1486, "s": 1405, "text": "There are couple of methods by which Javascript can be executed within browser −" }, { "code": null, "e": 1736, "s": 1486, "text": "Javascript execution at document root level.In this process, we shall identify the element with locators (class or id) and then perform the required action on it. Then execute_script() method is called and the Javascript is passed as a string to it." }, { "code": null, "e": 1781, "s": 1736, "text": "Javascript execution at document root level." }, { "code": null, "e": 1987, "s": 1781, "text": "In this process, we shall identify the element with locators (class or id) and then perform the required action on it. Then execute_script() method is called and the Javascript is passed as a string to it." }, { "code": null, "e": 1996, "s": 1987, "text": "Syntax −" }, { "code": null, "e": 2089, "s": 1996, "text": "javas = \"document.getElementsByName('user-search')[0].click();\"\ndriver.execute_script(javas)" }, { "code": null, "e": 2430, "s": 2089, "text": "Please note, we have used getElementsByName('user-search')[0]. The functions like getElementsByName and getElementsById return an array of matching elements. So for locating the first element, the index[0] is used. However if we are using getElementById function, we need not use the index since only one matching element is referred there." }, { "code": null, "e": 2667, "s": 2430, "text": "Finally, for execution the web driver will put the Javascript statement in the browser and then perform the necessary action like clicking the required element. This Javascript does not mingle with the Javascript present in the webpage." }, { "code": null, "e": 3048, "s": 2667, "text": "Javascript execution at element level.In this process, we shall identify the element with the help of web driver methods like find_element_by_xpath or find_element_by_id and so on. Then execute the necessary action on it like clicking the element. Finally, the method execute_script() is called. This method has the Javascript statement and the identified webelement as arguments." }, { "code": null, "e": 3087, "s": 3048, "text": "Javascript execution at element level." }, { "code": null, "e": 3430, "s": 3087, "text": "In this process, we shall identify the element with the help of web driver methods like find_element_by_xpath or find_element_by_id and so on. Then execute the necessary action on it like clicking the element. Finally, the method execute_script() is called. This method has the Javascript statement and the identified webelement as arguments." }, { "code": null, "e": 3439, "s": 3430, "text": "Syntax −" }, { "code": null, "e": 3543, "s": 3439, "text": "userN= driver.find_element_by_id(\"user-search']\")\ndriver.execute_script(\"arguments[0].click();\", userN)" }, { "code": null, "e": 3606, "s": 3543, "text": "Code Implementation with Javascript key in values in text box." }, { "code": null, "e": 4254, "s": 3606, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke #actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#to refresh the browser\ndriver.refresh()\n# inputting values in the text box with help of Javascript executor\njavaScript = \"document.getElementsByClassName('gsc-input')[0].value = 'TestNG' \"\ndriver.execute_script(javaScript)\n#to close the browser\ndriver.quit()" } ]
Extract Author's information from Geeksforgeeks article using Python - GeeksforGeeks
25 Aug, 2021 In this article, we are going to write a python script to extract author information from GeeksforGeeks article. bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal. pip install requests Approach: Import module Make requests instance and pass into URL Initialize the article Title Pass URL into a getdata() Scrape the data with the help of requests and Beautiful Soup Find the required details and filter them. Stepwise execution of scripts: Step 1: Import all dependence Python # import moduleimport requestsfrom bs4 import BeautifulSoup Step 2: Create a URL get function Python3 # link for extract html data# Making a GET request def getdata(url): r=requests.get(url) return r.text Step 3: Now merge the Article name into URL and pass the URL into the getdata() function and Convert that data into HTML code Python3 # input article by geekarticle = "optparse-module-in-python" # urlurl = "https://www.geeksforgeeks.org/"+article # pass the url# into getdata functionhtmldata=getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # display html codeprint(soup) Output: Step 4: Traverse the author’s name from the HTML document. Python # traverse author namefor i in soup.find('div', class_="author_handle"): Author = i.get_text()print(Author) Output: kumar_satyam Step 5: Now create a URL with author-name and get HTML code. Python3 # now get author information# with author nameprofile ='https://auth.geeksforgeeks.org/user/'+Author+'/profile' # pass the url# into getdata functionhtmldata=getdata(profile)soup = BeautifulSoup(htmldata, 'html.parser') Step 6: Traverse the author’s information. Python3 # traverse information of authorname = soup.find( 'div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold medText').get_text() author_info = []for item in soup.find_all('div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold'): author_info.append(item.get_text()) print("Author name :")print(name)print("Author information :")print(author_info) Output: Author name : Satyam Kumar Author information : [‘LNMI patna’, ‘\nhttps://www.linkedin.com/in/satyam-kumar-174273101/’] Complete code: Python3 # import moduleimport requestsfrom bs4 import BeautifulSoup # link for extract html data# Making a GET request def getdata(url): r = requests.get(url) return r.text # input article by geekarticle = "optparse-module-in-python" # urlurl = "https://www.geeksforgeeks.org/"+article # pass the url# into getdata functionhtmldata = getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # traverse author namefor i in soup.find('div', class_="author_handle"): Author = i.get_text() # now get author information# with author nameprofile = 'https://auth.geeksforgeeks.org/user/'+Author+'/profile' # pass the url# into getdata functionhtmldata = getdata(profile)soup = BeautifulSoup(htmldata, 'html.parser') # traverse information of authorname = soup.find( 'div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold medText').get_text() author_info = []for item in soup.find_all('div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold'): author_info.append(item.get_text()) print("Author name :", name)print("Author information :")print(author_info) Output: Author name : Satyam Kumar Author information : [‘LNMI patna’, ‘\nhttps://www.linkedin.com/in/satyam-kumar-174273101/’] rajeev0719singh simranarora5sos Python web-scraping-exercises python-utility Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24780, "s": 24752, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24893, "s": 24780, "text": "In this article, we are going to write a python script to extract author information from GeeksforGeeks article." }, { "code": null, "e": 25086, "s": 24893, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 25102, "s": 25086, "text": "pip install bs4" }, { "code": null, "e": 25286, "s": 25102, "text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 25307, "s": 25286, "text": "pip install requests" }, { "code": null, "e": 25317, "s": 25307, "text": "Approach:" }, { "code": null, "e": 25331, "s": 25317, "text": "Import module" }, { "code": null, "e": 25372, "s": 25331, "text": "Make requests instance and pass into URL" }, { "code": null, "e": 25401, "s": 25372, "text": "Initialize the article Title" }, { "code": null, "e": 25427, "s": 25401, "text": "Pass URL into a getdata()" }, { "code": null, "e": 25488, "s": 25427, "text": "Scrape the data with the help of requests and Beautiful Soup" }, { "code": null, "e": 25531, "s": 25488, "text": "Find the required details and filter them." }, { "code": null, "e": 25562, "s": 25531, "text": "Stepwise execution of scripts:" }, { "code": null, "e": 25592, "s": 25562, "text": "Step 1: Import all dependence" }, { "code": null, "e": 25599, "s": 25592, "text": "Python" }, { "code": "# import moduleimport requestsfrom bs4 import BeautifulSoup", "e": 25659, "s": 25599, "text": null }, { "code": null, "e": 25695, "s": 25659, "text": " Step 2: Create a URL get function " }, { "code": null, "e": 25703, "s": 25695, "text": "Python3" }, { "code": "# link for extract html data# Making a GET request def getdata(url): r=requests.get(url) return r.text", "e": 25816, "s": 25703, "text": null }, { "code": null, "e": 25943, "s": 25816, "text": "Step 3: Now merge the Article name into URL and pass the URL into the getdata() function and Convert that data into HTML code " }, { "code": null, "e": 25951, "s": 25943, "text": "Python3" }, { "code": "# input article by geekarticle = \"optparse-module-in-python\" # urlurl = \"https://www.geeksforgeeks.org/\"+article # pass the url# into getdata functionhtmldata=getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # display html codeprint(soup)", "e": 26199, "s": 25951, "text": null }, { "code": null, "e": 26208, "s": 26199, "text": "Output: " }, { "code": null, "e": 26268, "s": 26208, "text": "Step 4: Traverse the author’s name from the HTML document. " }, { "code": null, "e": 26275, "s": 26268, "text": "Python" }, { "code": "# traverse author namefor i in soup.find('div', class_=\"author_handle\"): Author = i.get_text()print(Author)", "e": 26386, "s": 26275, "text": null }, { "code": null, "e": 26395, "s": 26386, "text": "Output: " }, { "code": null, "e": 26408, "s": 26395, "text": "kumar_satyam" }, { "code": null, "e": 26470, "s": 26408, "text": "Step 5: Now create a URL with author-name and get HTML code. " }, { "code": null, "e": 26478, "s": 26470, "text": "Python3" }, { "code": "# now get author information# with author nameprofile ='https://auth.geeksforgeeks.org/user/'+Author+'/profile' # pass the url# into getdata functionhtmldata=getdata(profile)soup = BeautifulSoup(htmldata, 'html.parser')", "e": 26698, "s": 26478, "text": null }, { "code": null, "e": 26741, "s": 26698, "text": "Step 6: Traverse the author’s information." }, { "code": null, "e": 26749, "s": 26741, "text": "Python3" }, { "code": "# traverse information of authorname = soup.find( 'div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold medText').get_text() author_info = []for item in soup.find_all('div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold'): author_info.append(item.get_text()) print(\"Author name :\")print(name)print(\"Author information :\")print(author_info)", "e": 27134, "s": 26749, "text": null }, { "code": null, "e": 27142, "s": 27134, "text": "Output:" }, { "code": null, "e": 27265, "s": 27142, "text": "Author name : Satyam Kumar Author information : [‘LNMI patna’, ‘\\nhttps://www.linkedin.com/in/satyam-kumar-174273101/’] " }, { "code": null, "e": 27280, "s": 27265, "text": "Complete code:" }, { "code": null, "e": 27288, "s": 27280, "text": "Python3" }, { "code": "# import moduleimport requestsfrom bs4 import BeautifulSoup # link for extract html data# Making a GET request def getdata(url): r = requests.get(url) return r.text # input article by geekarticle = \"optparse-module-in-python\" # urlurl = \"https://www.geeksforgeeks.org/\"+article # pass the url# into getdata functionhtmldata = getdata(url)soup = BeautifulSoup(htmldata, 'html.parser') # traverse author namefor i in soup.find('div', class_=\"author_handle\"): Author = i.get_text() # now get author information# with author nameprofile = 'https://auth.geeksforgeeks.org/user/'+Author+'/profile' # pass the url# into getdata functionhtmldata = getdata(profile)soup = BeautifulSoup(htmldata, 'html.parser') # traverse information of authorname = soup.find( 'div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold medText').get_text() author_info = []for item in soup.find_all('div', class_='mdl-cell mdl-cell--9-col mdl-cell--12-col-phone textBold'): author_info.append(item.get_text()) print(\"Author name :\", name)print(\"Author information :\")print(author_info)", "e": 28382, "s": 27288, "text": null }, { "code": null, "e": 28390, "s": 28382, "text": "Output:" }, { "code": null, "e": 28513, "s": 28390, "text": "Author name : Satyam Kumar Author information : [‘LNMI patna’, ‘\\nhttps://www.linkedin.com/in/satyam-kumar-174273101/’] " }, { "code": null, "e": 28529, "s": 28513, "text": "rajeev0719singh" }, { "code": null, "e": 28545, "s": 28529, "text": "simranarora5sos" }, { "code": null, "e": 28575, "s": 28545, "text": "Python web-scraping-exercises" }, { "code": null, "e": 28590, "s": 28575, "text": "python-utility" }, { "code": null, "e": 28603, "s": 28590, "text": "Web-scraping" }, { "code": null, "e": 28610, "s": 28603, "text": "Python" }, { "code": null, "e": 28708, "s": 28610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28726, "s": 28708, "text": "Python Dictionary" }, { "code": null, "e": 28761, "s": 28726, "text": "Read a file line by line in Python" }, { "code": null, "e": 28783, "s": 28761, "text": "Enumerate() in Python" }, { "code": null, "e": 28815, "s": 28783, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28845, "s": 28815, "text": "Iterate over a list in Python" }, { "code": null, "e": 28887, "s": 28845, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28913, "s": 28887, "text": "Python String | replace()" }, { "code": null, "e": 28950, "s": 28913, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28993, "s": 28950, "text": "Python program to convert a list to string" } ]
Finding LCM of more than two (or array) numbers without using GCD in C++
We have an array A, we have to find the LCM of all elements without using the GCD operation. If the array is like {4, 6, 12, 24, 30}, then the LCM will be 120. The LCM can be calculated easily for two numbers. We have to follow this algorithm to get the LCM. getLCM(a, b) − begin if a > b, then m := a, otherwise m := b while true do if m is divisible by both a and b, then return m m := m + 1 done end Use this function to get LCM of first two numbers of array, then result of LCM will be used to find LCM of next element, thus we can get the result Live Demo #include <iostream> using namespace std; int getLCM(int a, int b){ int m; m = (a > b) ? a : b; while(true){ if(m % a == 0 && m % b == 0) return m; m++; } } int getLCMArray(int arr[], int n){ int lcm = getLCM(arr[0], arr[1]); for(int i = 2; i < n; i++){ lcm = getLCM(lcm, arr[i]); } return lcm; } int main() { int arr[] = {4, 6, 12, 24, 30}; int n = sizeof(arr)/sizeof(arr[0]); cout << "LCM of array elements: " << getLCMArray(arr, n); } LCM of array elements: 120
[ { "code": null, "e": 1222, "s": 1062, "text": "We have an array A, we have to find the LCM of all elements without using the GCD operation. If the array is like {4, 6, 12, 24, 30}, then the LCM will be 120." }, { "code": null, "e": 1321, "s": 1222, "text": "The LCM can be calculated easily for two numbers. We have to follow this algorithm to get the LCM." }, { "code": null, "e": 1336, "s": 1321, "text": "getLCM(a, b) −" }, { "code": null, "e": 1498, "s": 1336, "text": "begin\n if a > b, then m := a, otherwise m := b\n while true do\n if m is divisible by both a and b, then return m\n m := m + 1\n done\nend" }, { "code": null, "e": 1646, "s": 1498, "text": "Use this function to get LCM of first two numbers of array, then result of LCM will be used to find LCM of next element, thus we can get the result" }, { "code": null, "e": 1657, "s": 1646, "text": " Live Demo" }, { "code": null, "e": 2151, "s": 1657, "text": "#include <iostream>\nusing namespace std;\nint getLCM(int a, int b){\n int m;\n m = (a > b) ? a : b;\n while(true){\n if(m % a == 0 && m % b == 0)\n return m;\n m++;\n }\n}\nint getLCMArray(int arr[], int n){\n int lcm = getLCM(arr[0], arr[1]);\n for(int i = 2; i < n; i++){\n lcm = getLCM(lcm, arr[i]);\n }\n return lcm;\n}\nint main() {\n int arr[] = {4, 6, 12, 24, 30};\n int n = sizeof(arr)/sizeof(arr[0]);\n cout << \"LCM of array elements: \" << getLCMArray(arr, n);\n}" }, { "code": null, "e": 2178, "s": 2151, "text": "LCM of array elements: 120" } ]
Python | Pandas Dataframe.pop()
30 Dec, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop doesn’t require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly. Syntax: DataFrame.pop(item)Parameters: item: Column name to be popped in stringReturn type: Popped column in form of Pandas Series To download the CSV used in code, click here.Example #1: In this example, a column have been popped and returned by the function. The new data frame is then compared with the old one. Python3 import pandas as pd# importing pandas package data = pd.read_csv("nba.csv")# making data frame from csv file popped_col = data.pop("Team")# storing data in new var data# display Output: In the output images, the data frames are compared before and after using .pop(). As shown in second image, Team column has been popped out.Dataframe before using .pop() Dataframe after using .pop() Example #2: Popping and pushing in other data frame In this example, a copy of data frame is made and the popped column is inserted at the end of the other data frame. Python3 import pandas as pd# importing pandas package data = pd.read_csv("nba.csv")# making data frame from csv file new = data.copy()# creating independent copy of data frame popped_col = data.pop("Name")# storing data in new var new["New Col"]= popped_col# creating new col and passing popped col new# display Output: As shown in the output image, the new data frame is having the New col at the end which is nothing but the Name column which was popped out earlier. sumitgumber28 Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2021" }, { "code": null, "e": 540, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop doesn’t require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly. " }, { "code": null, "e": 671, "s": 540, "text": "Syntax: DataFrame.pop(item)Parameters: item: Column name to be popped in stringReturn type: Popped column in form of Pandas Series" }, { "code": null, "e": 856, "s": 671, "text": "To download the CSV used in code, click here.Example #1: In this example, a column have been popped and returned by the function. The new data frame is then compared with the old one. " }, { "code": null, "e": 864, "s": 856, "text": "Python3" }, { "code": "import pandas as pd# importing pandas package data = pd.read_csv(\"nba.csv\")# making data frame from csv file popped_col = data.pop(\"Team\")# storing data in new var data# display", "e": 1042, "s": 864, "text": null }, { "code": null, "e": 1222, "s": 1042, "text": "Output: In the output images, the data frames are compared before and after using .pop(). As shown in second image, Team column has been popped out.Dataframe before using .pop() " }, { "code": null, "e": 1253, "s": 1222, "text": "Dataframe after using .pop() " }, { "code": null, "e": 1424, "s": 1253, "text": " Example #2: Popping and pushing in other data frame In this example, a copy of data frame is made and the popped column is inserted at the end of the other data frame. " }, { "code": null, "e": 1432, "s": 1424, "text": "Python3" }, { "code": "import pandas as pd# importing pandas package data = pd.read_csv(\"nba.csv\")# making data frame from csv file new = data.copy()# creating independent copy of data frame popped_col = data.pop(\"Name\")# storing data in new var new[\"New Col\"]= popped_col# creating new col and passing popped col new# display", "e": 1736, "s": 1432, "text": null }, { "code": null, "e": 1895, "s": 1736, "text": "Output: As shown in the output image, the new data frame is having the New col at the end which is nothing but the Name column which was popped out earlier. " }, { "code": null, "e": 1911, "s": 1897, "text": "sumitgumber28" }, { "code": null, "e": 1935, "s": 1911, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1967, "s": 1935, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 1981, "s": 1967, "text": "Python-pandas" }, { "code": null, "e": 1988, "s": 1981, "text": "Python" }, { "code": null, "e": 2086, "s": 1988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2104, "s": 2086, "text": "Python Dictionary" }, { "code": null, "e": 2146, "s": 2104, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2168, "s": 2146, "text": "Enumerate() in Python" }, { "code": null, "e": 2203, "s": 2168, "text": "Read a file line by line in Python" }, { "code": null, "e": 2229, "s": 2203, "text": "Python String | replace()" }, { "code": null, "e": 2261, "s": 2229, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2290, "s": 2261, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2317, "s": 2290, "text": "Python Classes and Objects" }, { "code": null, "e": 2347, "s": 2317, "text": "Iterate over a list in Python" } ]
JavaScript | Adding minutes to Date object
23 May, 2019 Given a date and the task is to add minutes to it. To add minutes to the date object in javascript, some methods are used which are listed below: JavaScript getMinutes() Method: This method returns the Minutes (from 0 to 59) of the provided date and time.Syntax:Date.getMinutes() Return value: It returns a number, from 0 to 59, representing the minutes. Syntax: Date.getMinutes() Return value: It returns a number, from 0 to 59, representing the minutes. JavaScript setMinutes() Method: This method set the minutes of a date object. This method can also be used to set the seconds and milliseconds.Syntax:Date.setMinutes(min, sec, millisec) Parameters:min: It is required parameter. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed.sec: It is optional parameter. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed.millisec: It is optional parameter. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed.Note: All the previous three parameters accept values apart from their range and these values adjust like:min = -1, it means the last minute of the previous hour and same for the other parameters.If min value passed to 60, it means the first minute of the next hour and same for the other parameters.Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970. JavaScript setMinutes() Method: This method set the minutes of a date object. This method can also be used to set the seconds and milliseconds. Syntax: Date.setMinutes(min, sec, millisec) Parameters: min: It is required parameter. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed. sec: It is optional parameter. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed. millisec: It is optional parameter. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed. Note: All the previous three parameters accept values apart from their range and these values adjust like: min = -1, it means the last minute of the previous hour and same for the other parameters. If min value passed to 60, it means the first minute of the next hour and same for the other parameters. Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970. JavaScript getTime() method: This method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime() Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970. Syntax: Date.getTime() Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970. JavaScript setTime() method: This method set the date and time by adding/subtracting a defined number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec) Parameters: It contains single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970.Return value: It returns, representing the number of milliseconds between the date object and midnight January 1 1970.Example 1: This example added 4 minutes to the var today by using setTime() and getTime() method.<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size:15px; font-weight:bold;"> </p> <button onclick = "gfg_Run()"> addMinutes </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addMins = function(m) { this.setTime(this.getTime() + (m*60*1000)); return this; } function gfg_Run() { var a = new Date(); a.addMins(4); el_down.innerHTML = a; } </script> </body> </html>Output:Before clicking on the button:After clicking on the button:Example 2: This example adds 6 minutes to the var today by using setMinutes() and getMinutes() method.<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> addMinutes </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addMinutes= function(m) { this.setMinutes(this.getMinutes() + m); return this; } function gfg_Run() { var a = new Date(); a.addMinutes(6); el_down.innerHTML = a; } </script> </body> </html> Output:Before clicking on the button:After clicking on the button:My Personal Notes arrow_drop_upSave Syntax: Date.setTime(millisec) Parameters: It contains single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970. Return value: It returns, representing the number of milliseconds between the date object and midnight January 1 1970. Example 1: This example added 4 minutes to the var today by using setTime() and getTime() method. <!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size:15px; font-weight:bold;"> </p> <button onclick = "gfg_Run()"> addMinutes </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addMins = function(m) { this.setTime(this.getTime() + (m*60*1000)); return this; } function gfg_Run() { var a = new Date(); a.addMins(4); el_down.innerHTML = a; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example adds 6 minutes to the var today by using setMinutes() and getMinutes() method. <!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> addMinutes </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var today = new Date(); el_up.innerHTML = "Date = " + today; Date.prototype.addMinutes= function(m) { this.setMinutes(this.getMinutes() + m); return this; } function gfg_Run() { var a = new Date(); a.addMinutes(6); el_down.innerHTML = a; } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: javascript-date JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2019" }, { "code": null, "e": 174, "s": 28, "text": "Given a date and the task is to add minutes to it. To add minutes to the date object in javascript, some methods are used which are listed below:" }, { "code": null, "e": 383, "s": 174, "text": "JavaScript getMinutes() Method: This method returns the Minutes (from 0 to 59) of the provided date and time.Syntax:Date.getMinutes()\nReturn value: It returns a number, from 0 to 59, representing the minutes." }, { "code": null, "e": 391, "s": 383, "text": "Syntax:" }, { "code": null, "e": 410, "s": 391, "text": "Date.getMinutes()\n" }, { "code": null, "e": 485, "s": 410, "text": "Return value: It returns a number, from 0 to 59, representing the minutes." }, { "code": null, "e": 1528, "s": 485, "text": "JavaScript setMinutes() Method: This method set the minutes of a date object. This method can also be used to set the seconds and milliseconds.Syntax:Date.setMinutes(min, sec, millisec)\nParameters:min: It is required parameter. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed.sec: It is optional parameter. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed.millisec: It is optional parameter. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed.Note: All the previous three parameters accept values apart from their range and these values adjust like:min = -1, it means the last minute of the previous hour and same for the other parameters.If min value passed to 60, it means the first minute of the next hour and same for the other parameters.Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 1672, "s": 1528, "text": "JavaScript setMinutes() Method: This method set the minutes of a date object. This method can also be used to set the seconds and milliseconds." }, { "code": null, "e": 1680, "s": 1672, "text": "Syntax:" }, { "code": null, "e": 1717, "s": 1680, "text": "Date.setMinutes(min, sec, millisec)\n" }, { "code": null, "e": 1729, "s": 1717, "text": "Parameters:" }, { "code": null, "e": 1867, "s": 1729, "text": "min: It is required parameter. It specifies the integer representing the minutes. Values expected are 0-59, but other values are allowed." }, { "code": null, "e": 2005, "s": 1867, "text": "sec: It is optional parameter. It specifies the integer representing the seconds. Values expected are 0-59, but other values are allowed." }, { "code": null, "e": 2154, "s": 2005, "text": "millisec: It is optional parameter. It specifies the integer representing the milliseconds. Values expected are 0-999, but other values are allowed." }, { "code": null, "e": 2261, "s": 2154, "text": "Note: All the previous three parameters accept values apart from their range and these values adjust like:" }, { "code": null, "e": 2352, "s": 2261, "text": "min = -1, it means the last minute of the previous hour and same for the other parameters." }, { "code": null, "e": 2457, "s": 2352, "text": "If min value passed to 60, it means the first minute of the next hour and same for the other parameters." }, { "code": null, "e": 2581, "s": 2457, "text": "Return value: It returns a number, denoting the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 2846, "s": 2581, "text": "JavaScript getTime() method: This method returns the number of milliseconds between midnight of January 1, 1970, and the specified date.Syntax:Date.getTime()\nReturn value: It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 2854, "s": 2846, "text": "Syntax:" }, { "code": null, "e": 2870, "s": 2854, "text": "Date.getTime()\n" }, { "code": null, "e": 2977, "s": 2870, "text": "Return value: It returns a number, representing the number of milliseconds since midnight January 1, 1970." }, { "code": null, "e": 6143, "s": 2977, "text": "JavaScript setTime() method: This method set the date and time by adding/subtracting a defined number of milliseconds to/from midnight January 1, 1970.Syntax:Date.setTime(millisec)\nParameters: It contains single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970.Return value: It returns, representing the number of milliseconds between the date object and midnight January 1 1970.Example 1: This example added 4 minutes to the var today by using setTime() and getTime() method.<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size:15px; font-weight:bold;\"> </p> <button onclick = \"gfg_Run()\"> addMinutes </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addMins = function(m) { this.setTime(this.getTime() + (m*60*1000)); return this; } function gfg_Run() { var a = new Date(); a.addMins(4); el_down.innerHTML = a; } </script> </body> </html>Output:Before clicking on the button:After clicking on the button:Example 2: This example adds 6 minutes to the var today by using setMinutes() and getMinutes() method.<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> addMinutes </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addMinutes= function(m) { this.setMinutes(this.getMinutes() + m); return this; } function gfg_Run() { var a = new Date(); a.addMinutes(6); el_down.innerHTML = a; } </script> </body> </html> Output:Before clicking on the button:After clicking on the button:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 6151, "s": 6143, "text": "Syntax:" }, { "code": null, "e": 6175, "s": 6151, "text": "Date.setTime(millisec)\n" }, { "code": null, "e": 6334, "s": 6175, "text": "Parameters: It contains single parameter millisec which is required. It specifies the number of milliseconds to be added/subtracted, midnight January 1, 1970." }, { "code": null, "e": 6453, "s": 6334, "text": "Return value: It returns, representing the number of milliseconds between the date object and midnight January 1 1970." }, { "code": null, "e": 6551, "s": 6453, "text": "Example 1: This example added 4 minutes to the var today by using setTime() and getTime() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size:15px; font-weight:bold;\"> </p> <button onclick = \"gfg_Run()\"> addMinutes </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addMins = function(m) { this.setTime(this.getTime() + (m*60*1000)); return this; } function gfg_Run() { var a = new Date(); a.addMins(4); el_down.innerHTML = a; } </script> </body> </html>", "e": 7741, "s": 6551, "text": null }, { "code": null, "e": 7749, "s": 7741, "text": "Output:" }, { "code": null, "e": 7780, "s": 7749, "text": "Before clicking on the button:" }, { "code": null, "e": 7810, "s": 7780, "text": "After clicking on the button:" }, { "code": null, "e": 7913, "s": 7810, "text": "Example 2: This example adds 6 minutes to the var today by using setMinutes() and getMinutes() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JavaScript | Adding Minutes to Date object. </title> </head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> addMinutes </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var today = new Date(); el_up.innerHTML = \"Date = \" + today; Date.prototype.addMinutes= function(m) { this.setMinutes(this.getMinutes() + m); return this; } function gfg_Run() { var a = new Date(); a.addMinutes(6); el_down.innerHTML = a; } </script> </body> </html> ", "e": 9067, "s": 7913, "text": null }, { "code": null, "e": 9075, "s": 9067, "text": "Output:" }, { "code": null, "e": 9106, "s": 9075, "text": "Before clicking on the button:" }, { "code": null, "e": 9136, "s": 9106, "text": "After clicking on the button:" }, { "code": null, "e": 9152, "s": 9136, "text": "javascript-date" }, { "code": null, "e": 9163, "s": 9152, "text": "JavaScript" }, { "code": null, "e": 9180, "s": 9163, "text": "Web Technologies" }, { "code": null, "e": 9207, "s": 9180, "text": "Web technologies Questions" }, { "code": null, "e": 9305, "s": 9207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9366, "s": 9305, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 9438, "s": 9366, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 9478, "s": 9438, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 9530, "s": 9478, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 9571, "s": 9530, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 9633, "s": 9571, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 9666, "s": 9633, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 9727, "s": 9666, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 9777, "s": 9727, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Frequency Reuse
16 May, 2020 Frequency Reuse is the scheme in which allocation and reuse of channels throughout a coverage region is done. Each cellular base station is allocated a group of radio channels or Frequency sub-bands to be used within a small geographic area known as a cell. The shape of the cell is Hexagonal. The process of selecting and allocating the frequency sub-bands for all of the cellular base station within a system is called Frequency reuse or Frequency Planning. Silent Features of using Frequency Reuse: Frequency reuse improve the spectral efficiency and signal Quality (QoS). Frequency reuse classical scheme proposed for GSM systems offers a protection against interference. The number of times a frequency can be reused is depend on the tolerance capacity of the radio channel from the nearby transmitter that is using the same frequencies. In Frequency Reuse scheme, total bandwidth is divided into different sub-bands that are used by cells. Frequency reuse scheme allow WiMax system operators to reuse the same frequencies at different cell sites. Cell with the same letter uses the same set of channels group or frequencies sub-band. To find the total number of channel allocated to a cell: S = Total number of duplex channels available to usek = Channels allocated to each cell (k<S)N = Total number of cells or Cluster Size Then Total number of channels (S) will be, S = kN Frequency Reuse Factor = 1/N In the above diagram cluster size is 7 (A,B,C,D,E,F,G) thus frequency reuse factor is 1/7. N is the number of cells which collectively use the complete set of available frequencies is called a Cluster. The value of N is calculated by the following formula: N = I2 + I*J + J2 Where I,J = 0,1,2,3...Hence, possible values of N are 1,3,4,7,9,12,13,16,19 and so on. If a Cluster is replicated or repeated M times within the cellular system, then Capacity, C, will be, C = MkN = MS In Frequency reuse there are several cells that use the same set of frequencies. These cells are called Co-Channel Cells. These Co-Channel cells results in interference. So to avoid the Interference cells that use the same set of channels or frequencies are separated from one another by a larger distance. The distance between any two Co-Channels can be calculated by the following formula: D = R * (3 * N)1/2 Where,R = Radius of a cellN = Number of cells in a given cluster Below is the Python code for visualizing the Frequency Reuse concept #!/usr/bin/python from math import * # import everything from Tkinter modulefrom tkinter import * # Base class for Hexagon shapeclass Hexagon(object): def __init__(self, parent, x, y, length, color, tags): self.parent = parent self.x = x self.y = y self.length = length self.color = color self.size = None self.tags = tags self.draw_hex() # draw one hexagon def draw_hex(self): start_x = self.x start_y = self.y angle = 60 coords = [] for i in range(6): end_x = start_x + self.length * cos(radians(angle * i)) end_y = start_y + self.length * sin(radians(angle * i)) coords.append([start_x, start_y]) start_x = end_x start_y = end_y self.parent.create_polygon(coords[0][0], coords[0][1], coords[1][0], coords[1][1], coords[2][0], coords[2][1], coords[3][0], coords[3][1], coords[4][0], coords[4][1], coords[5][0], coords[5][1], fill=self.color, outline="black", tags=self.tags) # class holds frequency reuse logic and related methodsclass FrequencyReuse(Tk): CANVAS_WIDTH = 800 CANVAS_HEIGHT = 650 TOP_LEFT = (20, 20) BOTTOM_LEFT = (790, 560) TOP_RIGHT = (780, 20) BOTTOM_RIGHT = (780, 560) def __init__(self, cluster_size, columns=16, rows=10, edge_len=30): Tk.__init__(self) self.textbox = None self.curr_angle = 330 self.first_click = True self.reset = False self.edge_len = edge_len self.cluster_size = cluster_size self.reuse_list = [] self.all_selected = False self.curr_count = 0 self.hexagons = [] self.co_cell_endp = [] self.reuse_xy = [] self.canvas = Canvas(self, width=self.CANVAS_WIDTH, height=self.CANVAS_HEIGHT, bg="#4dd0e1") self.canvas.bind("<Button-1>", self.call_back) self.canvas.focus_set() self.canvas.bind('<Shift-R>', self.resets) self.canvas.pack() self.title("Frequency reuse and co-channel selection") self.create_grid(16, 10) self.create_textbox() self.cluster_reuse_calc() # show lines joining all co-channel cells def show_lines(self): # center(x,y) of first hexagon approx_center = self.co_cell_endp[0] self.line_ids = [] for k in range(1, len(self.co_cell_endp)): end_xx = (self.co_cell_endp[k])[0] end_yy = (self.co_cell_endp[k])[1] # move i^th steps l_id = self.canvas.create_line(approx_center[0], approx_center[1], end_xx, end_yy) if j == 0: self.line_ids.append(l_id) dist = 0 elif i >= j and j != 0: self.line_ids.append(l_id) dist = j # rotate counter-clockwise and move j^th step l_id = self.canvas.create_line( end_xx, end_yy, end_xx + self.center_dist * dist * cos(radians(self.curr_angle - 60)), end_yy + self.center_dist * dist * sin(radians(self.curr_angle - 60))) self.line_ids.append(l_id) self.curr_angle -= 60 def create_textbox(self): txt = Text(self.canvas, width=80, height=1, font=("Helvatica", 12), padx=10, pady=10) txt.tag_configure("center", justify="center") txt.insert("1.0", "Select a Hexagon") txt.tag_add("center", "1.0", "end") self.canvas.create_window((0, 600), anchor='w', window=txt) txt.config(state=DISABLED) self.textbox = txt def resets(self, event): if event.char == 'R': self.reset_grid() # clear hexagonal grid for new i/p def reset_grid(self, button_reset=False): self.first_click = True self.curr_angle = 330 self.curr_count = 0 self.co_cell_endp = [] self.reuse_list = [] for i in self.hexagons: self.canvas.itemconfigure(i.tags, fill=i.color) try: self.line_ids except AttributeError: pass else: for i in self.line_ids: self.canvas.after(0, self.canvas.delete, i) self.line_ids = [] if button_reset: self.write_text("Select a Hexagon") # create a grid of Hexagons def create_grid(self, cols, rows): size = self.edge_len for c in range(cols): if c % 2 == 0: offset = 0 else: offset = size * sqrt(3) / 2 for r in range(rows): x = c * (self.edge_len * 1.5) + 50 y = (r * (self.edge_len * sqrt(3))) + offset + 15 hx = Hexagon(self.canvas, x, y, self.edge_len, "#fafafa", "{},{}".format(r, c)) self.hexagons.append(hx) # calculate reuse distance, center distance and radius of the hexagon def cluster_reuse_calc(self): self.hex_radius = sqrt(3) / 2 * self.edge_len self.center_dist = sqrt(3) * self.hex_radius self.reuse_dist = self.hex_radius * sqrt(3 * self.cluster_size) def write_text(self, text): self.textbox.config(state=NORMAL) self.textbox.delete('1.0', END) self.textbox.insert('1.0', text, "center") self.textbox.config(state=DISABLED) #check if the co-channels are within visible canvas def is_within_bound(self, coords): if self.TOP_LEFT[0] < coords[0] < self.BOTTOM_RIGHT[0] \ and self.TOP_RIGHT[1] < coords[1] < self.BOTTOM_RIGHT[1]: return True return False #gets called when user selects a hexagon #This function applies frequency reuse logic in order to #figure out the positions of the co-channels def call_back(self, evt): selected_hex_id = self.canvas.find_closest(evt.x, evt.y)[0] hexagon = self.hexagons[int(selected_hex_id - 1)] s_x, s_y = hexagon.x, hexagon.y approx_center = (s_x + 15, s_y + 25) if self.first_click: self.first_click = False self.write_text( """Now, select another hexagon such that it should be a co-cell of the original hexagon.""" ) self.co_cell_endp.append(approx_center) self.canvas.itemconfigure(hexagon.tags, fill="green") for _ in range(6): end_xx = approx_center[0] + self.center_dist * i * cos( radians(self.curr_angle)) end_yy = approx_center[1] + self.center_dist * i * sin( radians(self.curr_angle)) reuse_x = end_xx + (self.center_dist * j) * cos( radians(self.curr_angle - 60)) reuse_y = end_yy + (self.center_dist * j) * sin( radians(self.curr_angle - 60)) if not self.is_within_bound((reuse_x, reuse_y)): self.write_text( """co-cells are exceeding canvas boundary. Select cell in the center""" ) self.reset_grid() break if j == 0: self.reuse_list.append( self.canvas.find_closest(end_xx, end_yy)[0]) elif i >= j and j != 0: self.reuse_list.append( self.canvas.find_closest(reuse_x, reuse_y)[0]) self.co_cell_endp.append((end_xx, end_yy)) self.curr_angle -= 60 else: curr = self.canvas.find_closest(s_x, s_y)[0] if curr in self.reuse_list: self.canvas.itemconfigure(hexagon.tags, fill="green") self.write_text("Correct! Cell {} is a co-cell.".format( hexagon.tags)) if self.curr_count == len(self.reuse_list) - 1: self.write_text("Great! Press Shift-R to restart") self.show_lines() self.curr_count += 1 else: self.write_text("Incorrect! Cell {} is not a co-cell.".format( hexagon.tags)) self.canvas.itemconfigure(hexagon.tags, fill="red") if __name__ == '__main__': print( """Enter i & j values. common (i,j) values are: (1,0), (1,1), (2,0), (2,1), (3,0), (2,2)""" ) i = int(input("Enter i: ")) j = int(input("Enter j: ")) if i == 0 and j == 0: raise ValueError("i & j both cannot be zero") elif j > i: raise ValueError("value of j cannot be greater than i") else: N = (i**2 + i * j + j**2) print("N is {}".format(N)) freqreuse = FrequencyReuse(cluster_size=N) freqreuse.mainloop() INPUT: Enter i & j values i: 2 j: 1 OUTPUT: AdiK Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) GSM in Wireless Communication Data encryption standard (DES) | Set 1 Wireless Application Protocol
[ { "code": null, "e": 54, "s": 26, "text": "\n16 May, 2020" }, { "code": null, "e": 514, "s": 54, "text": "Frequency Reuse is the scheme in which allocation and reuse of channels throughout a coverage region is done. Each cellular base station is allocated a group of radio channels or Frequency sub-bands to be used within a small geographic area known as a cell. The shape of the cell is Hexagonal. The process of selecting and allocating the frequency sub-bands for all of the cellular base station within a system is called Frequency reuse or Frequency Planning." }, { "code": null, "e": 556, "s": 514, "text": "Silent Features of using Frequency Reuse:" }, { "code": null, "e": 630, "s": 556, "text": "Frequency reuse improve the spectral efficiency and signal Quality (QoS)." }, { "code": null, "e": 730, "s": 630, "text": "Frequency reuse classical scheme proposed for GSM systems offers a protection against interference." }, { "code": null, "e": 897, "s": 730, "text": "The number of times a frequency can be reused is depend on the tolerance capacity of the radio channel from the nearby transmitter that is using the same frequencies." }, { "code": null, "e": 1000, "s": 897, "text": "In Frequency Reuse scheme, total bandwidth is divided into different sub-bands that are used by cells." }, { "code": null, "e": 1107, "s": 1000, "text": "Frequency reuse scheme allow WiMax system operators to reuse the same frequencies at different cell sites." }, { "code": null, "e": 1194, "s": 1107, "text": "Cell with the same letter uses the same set of channels group or frequencies sub-band." }, { "code": null, "e": 1251, "s": 1194, "text": "To find the total number of channel allocated to a cell:" }, { "code": null, "e": 1386, "s": 1251, "text": "S = Total number of duplex channels available to usek = Channels allocated to each cell (k<S)N = Total number of cells or Cluster Size" }, { "code": null, "e": 1429, "s": 1386, "text": "Then Total number of channels (S) will be," }, { "code": null, "e": 1467, "s": 1429, "text": "S = kN \n\nFrequency Reuse Factor = 1/N" }, { "code": null, "e": 1558, "s": 1467, "text": "In the above diagram cluster size is 7 (A,B,C,D,E,F,G) thus frequency reuse factor is 1/7." }, { "code": null, "e": 1724, "s": 1558, "text": "N is the number of cells which collectively use the complete set of available frequencies is called a Cluster. The value of N is calculated by the following formula:" }, { "code": null, "e": 1743, "s": 1724, "text": "N = I2 + I*J + J2 " }, { "code": null, "e": 1830, "s": 1743, "text": "Where I,J = 0,1,2,3...Hence, possible values of N are 1,3,4,7,9,12,13,16,19 and so on." }, { "code": null, "e": 1932, "s": 1830, "text": "If a Cluster is replicated or repeated M times within the cellular system, then Capacity, C, will be," }, { "code": null, "e": 1945, "s": 1932, "text": "C = MkN = MS" }, { "code": null, "e": 2337, "s": 1945, "text": "In Frequency reuse there are several cells that use the same set of frequencies. These cells are called Co-Channel Cells. These Co-Channel cells results in interference. So to avoid the Interference cells that use the same set of channels or frequencies are separated from one another by a larger distance. The distance between any two Co-Channels can be calculated by the following formula:" }, { "code": null, "e": 2357, "s": 2337, "text": " D = R * (3 * N)1/2" }, { "code": null, "e": 2422, "s": 2357, "text": "Where,R = Radius of a cellN = Number of cells in a given cluster" }, { "code": null, "e": 2491, "s": 2422, "text": "Below is the Python code for visualizing the Frequency Reuse concept" }, { "code": "#!/usr/bin/python from math import * # import everything from Tkinter modulefrom tkinter import * # Base class for Hexagon shapeclass Hexagon(object): def __init__(self, parent, x, y, length, color, tags): self.parent = parent self.x = x self.y = y self.length = length self.color = color self.size = None self.tags = tags self.draw_hex() # draw one hexagon def draw_hex(self): start_x = self.x start_y = self.y angle = 60 coords = [] for i in range(6): end_x = start_x + self.length * cos(radians(angle * i)) end_y = start_y + self.length * sin(radians(angle * i)) coords.append([start_x, start_y]) start_x = end_x start_y = end_y self.parent.create_polygon(coords[0][0], coords[0][1], coords[1][0], coords[1][1], coords[2][0], coords[2][1], coords[3][0], coords[3][1], coords[4][0], coords[4][1], coords[5][0], coords[5][1], fill=self.color, outline=\"black\", tags=self.tags) # class holds frequency reuse logic and related methodsclass FrequencyReuse(Tk): CANVAS_WIDTH = 800 CANVAS_HEIGHT = 650 TOP_LEFT = (20, 20) BOTTOM_LEFT = (790, 560) TOP_RIGHT = (780, 20) BOTTOM_RIGHT = (780, 560) def __init__(self, cluster_size, columns=16, rows=10, edge_len=30): Tk.__init__(self) self.textbox = None self.curr_angle = 330 self.first_click = True self.reset = False self.edge_len = edge_len self.cluster_size = cluster_size self.reuse_list = [] self.all_selected = False self.curr_count = 0 self.hexagons = [] self.co_cell_endp = [] self.reuse_xy = [] self.canvas = Canvas(self, width=self.CANVAS_WIDTH, height=self.CANVAS_HEIGHT, bg=\"#4dd0e1\") self.canvas.bind(\"<Button-1>\", self.call_back) self.canvas.focus_set() self.canvas.bind('<Shift-R>', self.resets) self.canvas.pack() self.title(\"Frequency reuse and co-channel selection\") self.create_grid(16, 10) self.create_textbox() self.cluster_reuse_calc() # show lines joining all co-channel cells def show_lines(self): # center(x,y) of first hexagon approx_center = self.co_cell_endp[0] self.line_ids = [] for k in range(1, len(self.co_cell_endp)): end_xx = (self.co_cell_endp[k])[0] end_yy = (self.co_cell_endp[k])[1] # move i^th steps l_id = self.canvas.create_line(approx_center[0], approx_center[1], end_xx, end_yy) if j == 0: self.line_ids.append(l_id) dist = 0 elif i >= j and j != 0: self.line_ids.append(l_id) dist = j # rotate counter-clockwise and move j^th step l_id = self.canvas.create_line( end_xx, end_yy, end_xx + self.center_dist * dist * cos(radians(self.curr_angle - 60)), end_yy + self.center_dist * dist * sin(radians(self.curr_angle - 60))) self.line_ids.append(l_id) self.curr_angle -= 60 def create_textbox(self): txt = Text(self.canvas, width=80, height=1, font=(\"Helvatica\", 12), padx=10, pady=10) txt.tag_configure(\"center\", justify=\"center\") txt.insert(\"1.0\", \"Select a Hexagon\") txt.tag_add(\"center\", \"1.0\", \"end\") self.canvas.create_window((0, 600), anchor='w', window=txt) txt.config(state=DISABLED) self.textbox = txt def resets(self, event): if event.char == 'R': self.reset_grid() # clear hexagonal grid for new i/p def reset_grid(self, button_reset=False): self.first_click = True self.curr_angle = 330 self.curr_count = 0 self.co_cell_endp = [] self.reuse_list = [] for i in self.hexagons: self.canvas.itemconfigure(i.tags, fill=i.color) try: self.line_ids except AttributeError: pass else: for i in self.line_ids: self.canvas.after(0, self.canvas.delete, i) self.line_ids = [] if button_reset: self.write_text(\"Select a Hexagon\") # create a grid of Hexagons def create_grid(self, cols, rows): size = self.edge_len for c in range(cols): if c % 2 == 0: offset = 0 else: offset = size * sqrt(3) / 2 for r in range(rows): x = c * (self.edge_len * 1.5) + 50 y = (r * (self.edge_len * sqrt(3))) + offset + 15 hx = Hexagon(self.canvas, x, y, self.edge_len, \"#fafafa\", \"{},{}\".format(r, c)) self.hexagons.append(hx) # calculate reuse distance, center distance and radius of the hexagon def cluster_reuse_calc(self): self.hex_radius = sqrt(3) / 2 * self.edge_len self.center_dist = sqrt(3) * self.hex_radius self.reuse_dist = self.hex_radius * sqrt(3 * self.cluster_size) def write_text(self, text): self.textbox.config(state=NORMAL) self.textbox.delete('1.0', END) self.textbox.insert('1.0', text, \"center\") self.textbox.config(state=DISABLED) #check if the co-channels are within visible canvas def is_within_bound(self, coords): if self.TOP_LEFT[0] < coords[0] < self.BOTTOM_RIGHT[0] \\ and self.TOP_RIGHT[1] < coords[1] < self.BOTTOM_RIGHT[1]: return True return False #gets called when user selects a hexagon #This function applies frequency reuse logic in order to #figure out the positions of the co-channels def call_back(self, evt): selected_hex_id = self.canvas.find_closest(evt.x, evt.y)[0] hexagon = self.hexagons[int(selected_hex_id - 1)] s_x, s_y = hexagon.x, hexagon.y approx_center = (s_x + 15, s_y + 25) if self.first_click: self.first_click = False self.write_text( \"\"\"Now, select another hexagon such that it should be a co-cell of the original hexagon.\"\"\" ) self.co_cell_endp.append(approx_center) self.canvas.itemconfigure(hexagon.tags, fill=\"green\") for _ in range(6): end_xx = approx_center[0] + self.center_dist * i * cos( radians(self.curr_angle)) end_yy = approx_center[1] + self.center_dist * i * sin( radians(self.curr_angle)) reuse_x = end_xx + (self.center_dist * j) * cos( radians(self.curr_angle - 60)) reuse_y = end_yy + (self.center_dist * j) * sin( radians(self.curr_angle - 60)) if not self.is_within_bound((reuse_x, reuse_y)): self.write_text( \"\"\"co-cells are exceeding canvas boundary. Select cell in the center\"\"\" ) self.reset_grid() break if j == 0: self.reuse_list.append( self.canvas.find_closest(end_xx, end_yy)[0]) elif i >= j and j != 0: self.reuse_list.append( self.canvas.find_closest(reuse_x, reuse_y)[0]) self.co_cell_endp.append((end_xx, end_yy)) self.curr_angle -= 60 else: curr = self.canvas.find_closest(s_x, s_y)[0] if curr in self.reuse_list: self.canvas.itemconfigure(hexagon.tags, fill=\"green\") self.write_text(\"Correct! Cell {} is a co-cell.\".format( hexagon.tags)) if self.curr_count == len(self.reuse_list) - 1: self.write_text(\"Great! Press Shift-R to restart\") self.show_lines() self.curr_count += 1 else: self.write_text(\"Incorrect! Cell {} is not a co-cell.\".format( hexagon.tags)) self.canvas.itemconfigure(hexagon.tags, fill=\"red\") if __name__ == '__main__': print( \"\"\"Enter i & j values. common (i,j) values are: (1,0), (1,1), (2,0), (2,1), (3,0), (2,2)\"\"\" ) i = int(input(\"Enter i: \")) j = int(input(\"Enter j: \")) if i == 0 and j == 0: raise ValueError(\"i & j both cannot be zero\") elif j > i: raise ValueError(\"value of j cannot be greater than i\") else: N = (i**2 + i * j + j**2) print(\"N is {}\".format(N)) freqreuse = FrequencyReuse(cluster_size=N) freqreuse.mainloop()", "e": 11878, "s": 2491, "text": null }, { "code": null, "e": 11915, "s": 11878, "text": "INPUT:\nEnter i & j values\ni: 2\nj: 1\n" }, { "code": null, "e": 11923, "s": 11915, "text": "OUTPUT:" }, { "code": null, "e": 11928, "s": 11923, "text": "AdiK" }, { "code": null, "e": 11946, "s": 11928, "text": "Computer Networks" }, { "code": null, "e": 11964, "s": 11946, "text": "Computer Networks" }, { "code": null, "e": 12062, "s": 11964, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12094, "s": 12062, "text": "Differences between TCP and UDP" }, { "code": null, "e": 12120, "s": 12094, "text": "Types of Network Topology" }, { "code": null, "e": 12150, "s": 12120, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 12188, "s": 12150, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 12217, "s": 12188, "text": "Socket Programming in Python" }, { "code": null, "e": 12251, "s": 12217, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 12277, "s": 12251, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 12307, "s": 12277, "text": "GSM in Wireless Communication" }, { "code": null, "e": 12346, "s": 12307, "text": "Data encryption standard (DES) | Set 1" } ]
Convert Infix To Prefix Notation
23 Jun, 2022 While we use infix expressions in our day to day lives. Computers have trouble understanding this format because they need to keep in mind rules of operator precedence and also brackets. Prefix and Postfix expressions are easier for a computer to understand and evaluate. Given two operands and and an operator , the infix notation implies that O will be placed in between a and b i.e . When the operator is placed after both operands i.e , it is called postfix notation. And when the operator is placed before the operands i.e , the expression in prefix notation.Given any infix expression, we can obtain the equivalent prefix and postfix format. Examples: Input : A * B + C / D Output : + * A B/ C D Input : (A - B/C) * (A/K-L) Output : *-A/BC-/AKL To convert an infix to postfix expression refer to this article Stack | Set 2 (Infix to Postfix). We use the same to convert Infix to Prefix. Step 1: Reverse the infix expression i.e A+B*C will become C*B+A. Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘. Step 2: Obtain the “nearly” postfix expression of the modified expression i.e CB*A+. Step 3: Reverse the postfix expression. Hence in our example prefix is +A*BC. Note that for Step 2, we don’t use the postfix algorithm as it is. There is a minor change in the algorithm. As per https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/ , we have to pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. But here, we have to pop all the operators from the stack which are greater in precedence than that of the scanned operator. Only in the case of “^” operator, we pop operators from the stack which are greater than or equal to in precedence. Below is the C++ implementation of the algorithm. C++ Java C# // CPP program to convert infix to prefix#include <bits/stdc++.h>using namespace std; bool isOperator(char c){ return (!isalpha(c) && !isdigit(c));} int getPriority(char C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} string infixToPostfix(string infix){ infix = '(' + infix + ')'; int l = infix.size(); stack<char> char_stack; string output; for (int i = 0; i < l; i++) { // If the scanned character is an // operand, add it to output. if (isalpha(infix[i]) || isdigit(infix[i])) output += infix[i]; // If the scanned character is an // ‘(‘, push it to the stack. else if (infix[i] == '(') char_stack.push('('); // If the scanned character is an // ‘)’, pop and output from the stack // until an ‘(‘ is encountered. else if (infix[i] == ')') { while (char_stack.top() != '(') { output += char_stack.top(); char_stack.pop(); } // Remove '(' from the stack char_stack.pop(); } // Operator found else { if (isOperator(char_stack.top())) { if(infix[i] == '^') { while (getPriority(infix[i]) <= getPriority(char_stack.top())) { output += char_stack.top(); char_stack.pop(); } } else { while (getPriority(infix[i]) < getPriority(char_stack.top())) { output += char_stack.top(); char_stack.pop(); } } // Push current Operator on stack char_stack.push(infix[i]); } } } while(!char_stack.empty()){ output += char_stack.top(); char_stack.pop(); } return output;} string infixToPrefix(string infix){ /* Reverse String * Replace ( with ) and vice versa * Get Postfix * Reverse Postfix * */ int l = infix.size(); // Reverse infix reverse(infix.begin(), infix.end()); // Replace ( with ) and vice versa for (int i = 0; i < l; i++) { if (infix[i] == '(') { infix[i] = ')'; } else if (infix[i] == ')') { infix[i] = '('; } } string prefix = infixToPostfix(infix); // Reverse postfix reverse(prefix.begin(), prefix.end()); return prefix;} // Driver codeint main(){ string s = ("x+y*z/w+u"); cout << infixToPrefix(s) << std::endl; return 0;} // JAVA program to convert infix to prefiximport java.util.*; class GFG{ static boolean isalpha(char c) { if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { return true; } return false; } static boolean isdigit(char c) { if (c >= '0' && c <= '9') { return true; } return false; } static boolean isOperator(char c) { return (!isalpha(c) && !isdigit(c)); } static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Reverse the letters of the word static String reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start < end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.valueOf(str); } static String infixToPostfix(char[] infix1) { System.out.println(infix1); String infix = '(' + String.valueOf(infix1) + ')'; int l = infix.length(); Stack<Character> char_stack = new Stack<>(); String output=""; for (int i = 0; i < l; i++) { // If the scanned character is an // operand, add it to output. if (isalpha(infix.charAt(i)) || isdigit(infix.charAt(i))) output += infix.charAt(i); // If the scanned character is an // ‘(‘, push it to the stack. else if (infix.charAt(i) == '(') char_stack.add('('); // If the scanned character is an // ‘)’, pop and output from the stack // until an ‘(‘ is encountered. else if (infix.charAt(i) == ')') { while (char_stack.peek() != '(') { output += char_stack.peek(); char_stack.pop(); } // Remove '(' from the stack char_stack.pop(); } // Operator found else { if (isOperator(char_stack.peek())) { while ((getPriority(infix.charAt(i)) < getPriority(char_stack.peek())) || (getPriority(infix.charAt(i)) <= getPriority(char_stack.peek()) && infix.charAt(i) == '^')) { output += char_stack.peek(); char_stack.pop(); } // Push current Operator on stack char_stack.add(infix.charAt(i)); } } } while(!char_stack.empty()){ output += char_stack.pop(); } return output; } static String infixToPrefix(char[] infix) { /* * Reverse String Replace ( with ) and vice versa Get Postfix Reverse Postfix * */ int l = infix.length; // Reverse infix String infix1 = reverse(infix, 0, l - 1); infix = infix1.toCharArray(); // Replace ( with ) and vice versa for (int i = 0; i < l; i++) { if (infix[i] == '(') { infix[i] = ')'; i++; } else if (infix[i] == ')') { infix[i] = '('; i++; } } String prefix = infixToPostfix(infix); // Reverse postfix prefix = reverse(prefix.toCharArray(), 0, l-1); return prefix; } // Driver code public static void main(String[] args) { String s = ("x+y*z/w+u"); System.out.print(infixToPrefix(s.toCharArray())); }} // This code is contributed by Rajput-Ji // C# program to convert infix to prefixusing System;using System.Collections.Generic; public class GFG { static bool isalpha(char c) { if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { return true; } return false; } static bool isdigit(char c) { if (c >= '0' && c <= '9') { return true; } return false; } static bool isOperator(char c) { return (!isalpha(c) && !isdigit(c)); } static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Reverse the letters of the word static String reverse(char []str, int start, int end) { // Temporary variable to store character char temp; while (start < end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.Join("",str); } static String infixToPostfix(char[] infix1) { String infix = '(' + String.Join("",infix1) + ')'; int l = infix.Length; Stack<char> char_stack = new Stack<char>(); String output = ""; for (int i = 0; i < l; i++) { // If the scanned character is an // operand, add it to output. if (isalpha(infix[i]) || isdigit(infix[i])) output += infix[i]; // If the scanned character is an // ‘(‘, push it to the stack. else if (infix[i] == '(') char_stack.Push('('); // If the scanned character is an // ‘)’, pop and output from the stack // until an ‘(‘ is encountered. else if (infix[i] == ')') { while (char_stack.Peek() != '(') { output += char_stack.Peek(); char_stack.Pop(); } // Remove '(' from the stack char_stack.Pop(); } // Operator found else { if (isOperator(char_stack.Peek())) { while ((getPriority(infix[i]) < getPriority(char_stack.Peek())) || (getPriority(infix[i]) <= getPriority(char_stack.Peek()) && infix[i] == '^')) { output += char_stack.Peek(); char_stack.Pop(); } // Push current Operator on stack char_stack.Push(infix[i]); } } } while (char_stack.Count!=0) { output += char_stack.Pop(); } return output; } static String infixToPrefix(char[] infix) { /* * Reverse String Replace ( with ) and // vice versa Get Postfix Reverse Postfix * */ int l = infix.Length; // Reverse infix String infix1 = reverse(infix, 0, l - 1); infix = infix1.ToCharArray(); // Replace ( with ) and vice versa for (int i = 0; i < l; i++) { if (infix[i] == '(') { infix[i] = ')'; i++; } else if (infix[i] == ')') { infix[i] = '('; i++; } } String prefix = infixToPostfix(infix); // Reverse postfix prefix = reverse(prefix.ToCharArray(), 0, l - 1); return prefix; } // Driver code public static void Main(String[] args) { String s = ("x+y*z/w+u"); Console.Write(infixToPrefix(s.ToCharArray())); }} // This code is contributed by gauravrajput1 ++x/*yzwu Time Complexity: Stack operations like push() and pop() are performed in constant time. Since we scan all the characters in the expression once the complexity is linear in time i.e . zen716 sandravsnair Rajput-Ji jiaxuantw i_m_inevitable 202051112 shitalpatil94612 GauravRajput1 rohitkavitake3012 expression-evaluation Stack Strings Strings Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 702, "s": 54, "text": "While we use infix expressions in our day to day lives. Computers have trouble understanding this format because they need to keep in mind rules of operator precedence and also brackets. Prefix and Postfix expressions are easier for a computer to understand and evaluate. Given two operands and and an operator , the infix notation implies that O will be placed in between a and b i.e . When the operator is placed after both operands i.e , it is called postfix notation. And when the operator is placed before the operands i.e , the expression in prefix notation.Given any infix expression, we can obtain the equivalent prefix and postfix format." }, { "code": null, "e": 713, "s": 702, "text": "Examples: " }, { "code": null, "e": 808, "s": 713, "text": "Input : A * B + C / D\nOutput : + * A B/ C D \n\nInput : (A - B/C) * (A/K-L)\nOutput : *-A/BC-/AKL" }, { "code": null, "e": 950, "s": 808, "text": "To convert an infix to postfix expression refer to this article Stack | Set 2 (Infix to Postfix). We use the same to convert Infix to Prefix." }, { "code": null, "e": 1088, "s": 950, "text": "Step 1: Reverse the infix expression i.e A+B*C will become C*B+A. Note while reversing each ‘(‘ will become ‘)’ and each ‘)’ becomes ‘(‘." }, { "code": null, "e": 1173, "s": 1088, "text": "Step 2: Obtain the “nearly” postfix expression of the modified expression i.e CB*A+." }, { "code": null, "e": 1251, "s": 1173, "text": "Step 3: Reverse the postfix expression. Hence in our example prefix is +A*BC." }, { "code": null, "e": 1802, "s": 1251, "text": "Note that for Step 2, we don’t use the postfix algorithm as it is. There is a minor change in the algorithm. As per https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/ , we have to pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. But here, we have to pop all the operators from the stack which are greater in precedence than that of the scanned operator. Only in the case of “^” operator, we pop operators from the stack which are greater than or equal to in precedence." }, { "code": null, "e": 1853, "s": 1802, "text": "Below is the C++ implementation of the algorithm. " }, { "code": null, "e": 1857, "s": 1853, "text": "C++" }, { "code": null, "e": 1862, "s": 1857, "text": "Java" }, { "code": null, "e": 1865, "s": 1862, "text": "C#" }, { "code": "// CPP program to convert infix to prefix#include <bits/stdc++.h>using namespace std; bool isOperator(char c){ return (!isalpha(c) && !isdigit(c));} int getPriority(char C){ if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0;} string infixToPostfix(string infix){ infix = '(' + infix + ')'; int l = infix.size(); stack<char> char_stack; string output; for (int i = 0; i < l; i++) { // If the scanned character is an // operand, add it to output. if (isalpha(infix[i]) || isdigit(infix[i])) output += infix[i]; // If the scanned character is an // ‘(‘, push it to the stack. else if (infix[i] == '(') char_stack.push('('); // If the scanned character is an // ‘)’, pop and output from the stack // until an ‘(‘ is encountered. else if (infix[i] == ')') { while (char_stack.top() != '(') { output += char_stack.top(); char_stack.pop(); } // Remove '(' from the stack char_stack.pop(); } // Operator found else { if (isOperator(char_stack.top())) { if(infix[i] == '^') { while (getPriority(infix[i]) <= getPriority(char_stack.top())) { output += char_stack.top(); char_stack.pop(); } } else { while (getPriority(infix[i]) < getPriority(char_stack.top())) { output += char_stack.top(); char_stack.pop(); } } // Push current Operator on stack char_stack.push(infix[i]); } } } while(!char_stack.empty()){ output += char_stack.top(); char_stack.pop(); } return output;} string infixToPrefix(string infix){ /* Reverse String * Replace ( with ) and vice versa * Get Postfix * Reverse Postfix * */ int l = infix.size(); // Reverse infix reverse(infix.begin(), infix.end()); // Replace ( with ) and vice versa for (int i = 0; i < l; i++) { if (infix[i] == '(') { infix[i] = ')'; } else if (infix[i] == ')') { infix[i] = '('; } } string prefix = infixToPostfix(infix); // Reverse postfix reverse(prefix.begin(), prefix.end()); return prefix;} // Driver codeint main(){ string s = (\"x+y*z/w+u\"); cout << infixToPrefix(s) << std::endl; return 0;}", "e": 4682, "s": 1865, "text": null }, { "code": "// JAVA program to convert infix to prefiximport java.util.*; class GFG{ static boolean isalpha(char c) { if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { return true; } return false; } static boolean isdigit(char c) { if (c >= '0' && c <= '9') { return true; } return false; } static boolean isOperator(char c) { return (!isalpha(c) && !isdigit(c)); } static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Reverse the letters of the word static String reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start < end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.valueOf(str); } static String infixToPostfix(char[] infix1) { System.out.println(infix1); String infix = '(' + String.valueOf(infix1) + ')'; int l = infix.length(); Stack<Character> char_stack = new Stack<>(); String output=\"\"; for (int i = 0; i < l; i++) { // If the scanned character is an // operand, add it to output. if (isalpha(infix.charAt(i)) || isdigit(infix.charAt(i))) output += infix.charAt(i); // If the scanned character is an // ‘(‘, push it to the stack. else if (infix.charAt(i) == '(') char_stack.add('('); // If the scanned character is an // ‘)’, pop and output from the stack // until an ‘(‘ is encountered. else if (infix.charAt(i) == ')') { while (char_stack.peek() != '(') { output += char_stack.peek(); char_stack.pop(); } // Remove '(' from the stack char_stack.pop(); } // Operator found else { if (isOperator(char_stack.peek())) { while ((getPriority(infix.charAt(i)) < getPriority(char_stack.peek())) || (getPriority(infix.charAt(i)) <= getPriority(char_stack.peek()) && infix.charAt(i) == '^')) { output += char_stack.peek(); char_stack.pop(); } // Push current Operator on stack char_stack.add(infix.charAt(i)); } } } while(!char_stack.empty()){ output += char_stack.pop(); } return output; } static String infixToPrefix(char[] infix) { /* * Reverse String Replace ( with ) and vice versa Get Postfix Reverse Postfix * */ int l = infix.length; // Reverse infix String infix1 = reverse(infix, 0, l - 1); infix = infix1.toCharArray(); // Replace ( with ) and vice versa for (int i = 0; i < l; i++) { if (infix[i] == '(') { infix[i] = ')'; i++; } else if (infix[i] == ')') { infix[i] = '('; i++; } } String prefix = infixToPostfix(infix); // Reverse postfix prefix = reverse(prefix.toCharArray(), 0, l-1); return prefix; } // Driver code public static void main(String[] args) { String s = (\"x+y*z/w+u\"); System.out.print(infixToPrefix(s.toCharArray())); }} // This code is contributed by Rajput-Ji", "e": 8039, "s": 4682, "text": null }, { "code": "// C# program to convert infix to prefixusing System;using System.Collections.Generic; public class GFG { static bool isalpha(char c) { if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { return true; } return false; } static bool isdigit(char c) { if (c >= '0' && c <= '9') { return true; } return false; } static bool isOperator(char c) { return (!isalpha(c) && !isdigit(c)); } static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } // Reverse the letters of the word static String reverse(char []str, int start, int end) { // Temporary variable to store character char temp; while (start < end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } return String.Join(\"\",str); } static String infixToPostfix(char[] infix1) { String infix = '(' + String.Join(\"\",infix1) + ')'; int l = infix.Length; Stack<char> char_stack = new Stack<char>(); String output = \"\"; for (int i = 0; i < l; i++) { // If the scanned character is an // operand, add it to output. if (isalpha(infix[i]) || isdigit(infix[i])) output += infix[i]; // If the scanned character is an // ‘(‘, push it to the stack. else if (infix[i] == '(') char_stack.Push('('); // If the scanned character is an // ‘)’, pop and output from the stack // until an ‘(‘ is encountered. else if (infix[i] == ')') { while (char_stack.Peek() != '(') { output += char_stack.Peek(); char_stack.Pop(); } // Remove '(' from the stack char_stack.Pop(); } // Operator found else { if (isOperator(char_stack.Peek())) { while ((getPriority(infix[i]) < getPriority(char_stack.Peek())) || (getPriority(infix[i]) <= getPriority(char_stack.Peek()) && infix[i] == '^')) { output += char_stack.Peek(); char_stack.Pop(); } // Push current Operator on stack char_stack.Push(infix[i]); } } } while (char_stack.Count!=0) { output += char_stack.Pop(); } return output; } static String infixToPrefix(char[] infix) { /* * Reverse String Replace ( with ) and // vice versa Get Postfix Reverse Postfix * */ int l = infix.Length; // Reverse infix String infix1 = reverse(infix, 0, l - 1); infix = infix1.ToCharArray(); // Replace ( with ) and vice versa for (int i = 0; i < l; i++) { if (infix[i] == '(') { infix[i] = ')'; i++; } else if (infix[i] == ')') { infix[i] = '('; i++; } } String prefix = infixToPostfix(infix); // Reverse postfix prefix = reverse(prefix.ToCharArray(), 0, l - 1); return prefix; } // Driver code public static void Main(String[] args) { String s = (\"x+y*z/w+u\"); Console.Write(infixToPrefix(s.ToCharArray())); }} // This code is contributed by gauravrajput1", "e": 11236, "s": 8039, "text": null }, { "code": null, "e": 11247, "s": 11236, "text": "++x/*yzwu\n" }, { "code": null, "e": 11430, "s": 11247, "text": "Time Complexity: Stack operations like push() and pop() are performed in constant time. Since we scan all the characters in the expression once the complexity is linear in time i.e ." }, { "code": null, "e": 11437, "s": 11430, "text": "zen716" }, { "code": null, "e": 11450, "s": 11437, "text": "sandravsnair" }, { "code": null, "e": 11460, "s": 11450, "text": "Rajput-Ji" }, { "code": null, "e": 11470, "s": 11460, "text": "jiaxuantw" }, { "code": null, "e": 11485, "s": 11470, "text": "i_m_inevitable" }, { "code": null, "e": 11495, "s": 11485, "text": "202051112" }, { "code": null, "e": 11512, "s": 11495, "text": "shitalpatil94612" }, { "code": null, "e": 11526, "s": 11512, "text": "GauravRajput1" }, { "code": null, "e": 11544, "s": 11526, "text": "rohitkavitake3012" }, { "code": null, "e": 11566, "s": 11544, "text": "expression-evaluation" }, { "code": null, "e": 11572, "s": 11566, "text": "Stack" }, { "code": null, "e": 11580, "s": 11572, "text": "Strings" }, { "code": null, "e": 11588, "s": 11580, "text": "Strings" }, { "code": null, "e": 11594, "s": 11588, "text": "Stack" } ]
Harmonic Progression
06 Jul, 2022 A sequence of numbers is called a Harmonic progression if the reciprocal of the terms are in AP. In simple terms, a, b, c, d, e, f are in HP if 1/a, 1/b, 1/c, 1/d, 1/e, 1/f are in AP. For example, 1/a, 1/(a+d), 1/(a+2d), and so on are in HP because a, a + d, a + 2d are in AP. Fact about Harmonic Progression : In order to solve a problem on Harmonic Progression, one should make the corresponding AP series and then solve the problem.As the nth term of an A.P is given by an = a + (n-1)d, So the nth term of an H.P is given by 1/ [a + (n -1) d].For two numbers, if A, G and H are respectively the arithmetic, geometric and harmonic means, then A ≥ G ≥ HA H = G2, i.e., A, G, H are in GPIf we need to find three numbers in a H.P. then they should be assumed as 1/a–d, 1/a, 1/a+dMajority of the questions of H.P. are solved by first converting them into A.P In order to solve a problem on Harmonic Progression, one should make the corresponding AP series and then solve the problem. As the nth term of an A.P is given by an = a + (n-1)d, So the nth term of an H.P is given by 1/ [a + (n -1) d]. For two numbers, if A, G and H are respectively the arithmetic, geometric and harmonic means, then A ≥ G ≥ HA H = G2, i.e., A, G, H are in GP A ≥ G ≥ H A H = G2, i.e., A, G, H are in GP If we need to find three numbers in a H.P. then they should be assumed as 1/a–d, 1/a, 1/a+d Majority of the questions of H.P. are solved by first converting them into A.P Formula of Harmonic Progression: How we check whether a series is harmonic progression or not? The idea is to reciprocal the given array or series. After reciprocal, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible. So as we know if the reciprocal of the terms are in AP then given a sequence of series is in H.P. Let’s take a series 1/5, 1/10, 1/15, 1/20, 1/25 and check whether it is a harmonic progression or not. Below is the implementation: C++ Java Python3 C# PHP Javascript // CPP program to check if a given // array can form harmonic progression#include<bits/stdc++.h>using namespace std; bool checkIsHP(vector<double> &arr){ int n = arr.size(); if (n == 1) { return true; } // Find reciprocal of arr[] vector<int> rec; for (int i = 0; i < n; i++) { rec.push_back((1 / arr[i])); } // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements sort(rec.begin(), rec.end()); int d = (rec[1]) - (rec[0]); for (int i = 2; i < n; i++) { if (rec[i] - rec[i - 1] != d) { return false; } } return true;} // Driver Codeint main(){ // series to check whether it is in H.P vector<double> arr = {1 / 5, 1 / 10, 1 / 15, 1 / 20, 1 / 25}; // Checking a series is in H.P or not if (checkIsHP(arr)) { cout << "Yes" << std::endl; } else { cout << "No" <<endl; } return 0;} // This code is contributed by mits // Java program to check if a given// array can form harmonic progressionimport java.util.*; class GFG{static boolean checkIsHP(double []arr){ int n = arr.length; if (n == 1) return true; // Find reciprocal of arr[] ArrayList<Integer> rec = new ArrayList<Integer>(); for (int i = 0; i < n; i++) rec.add((int)(1 / arr[i])); // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements Collections.sort(rec); int d = (int)rec.get(1) - (int)rec.get(0); for (int i = 2; i < n; i++) if (rec.get(i) - rec.get(i - 1) != d) return false; return true;} // Driver codepublic static void main(String[] args){ // series to check whether it is in H.P double arr[] = { 1/5, 1/10, 1/15, 1/20, 1/25 }; // Checking a series is in H.P or not if (checkIsHP(arr)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by mits # Python3 program to check if a given# array can form harmonic progression def checkIsHP(arr): n = len(arr) if (n == 1): return True # Find reciprocal of arr[] rec = [] for i in range(0, len(arr)): a = 1 / arr[i] rec.append(a) return(rec) # After finding reciprocal, check if the # reciprocal is in A. P. # To check for A.P., first Sort the # reciprocal array, then check difference # between consecutive elements rec.sort() d = rec[1] - rec[0] for i in range(2, n): if (rec[i] - rec[i-1] != d): return False return True # Driver codeif __name__=='__main__': # series to check whether it is in H.P arr = [ 1/5, 1/10, 1/15, 1/20, 1/25 ] # Checking a series is in H.P or not if (checkIsHP(arr)): print("Yes") else: print("No") // C# program to check if a given// array can form harmonic progressionusing System;using System.Collections;class GFG{static bool checkIsHP(double[] arr){ int n = arr.Length; if (n == 1) return true; // Find reciprocal of arr[] ArrayList rec = new ArrayList(); for (int i = 0; i < n; i++) rec.Add((int)(1 / arr[i])); // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements rec.Sort(); int d = (int)rec[1] - (int)rec[0]; for (int i = 2; i < n; i++) if ((int)rec[i] - (int)rec[i - 1] != d) return false; return true;} // Driver codepublic static void Main(){ // series to check whether it is in H.P double[] arr = { 1/5, 1/10, 1/15, 1/20, 1/25 }; // Checking a series is in H.P or not if (checkIsHP(arr)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by mits <?php// PHP program to check if a given// array can form harmonic progression function checkIsHP($arr){ $n = count($arr); if ($n == 1) return true; // Find reciprocal of arr[] $rec = array(); for ($i=0;$i<count($arr);$i++) { $a = 1 / $arr[$i]; array_push($rec,$a); } return ($rec); // After finding reciprocal, check if the // reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements sort($rec); $d = $rec[1] - $rec[0]; for ($i=2;$i<$n;$i++) if ($rec[$i] - $rec[$i-1] != $d) return false; return true;} // Driver code // series to check whether it is in H.P $arr = array( 1/5, 1/10, 1/15, 1/20, 1/25 ); // Checking a series is in H.P or not if (checkIsHP($arr)) print("Yes"); else print("No"); // This code is contributed by mits?> <script> // JavaScript program to check if a given // array can form harmonic progression function checkIsHP(arr){ let n = arr.length; if (n == 1) { return true; } // Find reciprocal of arr[] let rec = []; for (let i = 0; i < n; i++) { rec.push((1 / arr[i])); } // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements rec.sort((a,b) => a - b); let d = (rec[1]) - (rec[0]); for (let i = 2; i < n; i++) { if (rec[i] - rec[i - 1] != d) { return false; } } return true;} // Driver Code // series to check whether it is in H.P let arr = [1 / 5, 1 / 10, 1 / 15, 1 / 20, 1 / 25]; // Checking a series is in H.P or not if (checkIsHP(arr)) { document.write("Yes"); } else { document.write("No"); } </script> Output: Yes Time Complexity: O(n Log n). Auxiliary Space: O(n)Basic Program related to Harmonic Progression Harmonic progression Sum Program to find the Nth Harmonic Number Sum of series (n/1) + (n/2) + (n/3) + (n/4) +.......+ (n/n) Check if the given number is Ore number or not Expected Number of Trials until Success Recent Articles on Harmonic Progression! Mithun Kumar nidhi_biet rishavmahato348 subham348 harmonic progression series Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 331, "s": 52, "text": "A sequence of numbers is called a Harmonic progression if the reciprocal of the terms are in AP. In simple terms, a, b, c, d, e, f are in HP if 1/a, 1/b, 1/c, 1/d, 1/e, 1/f are in AP. For example, 1/a, 1/(a+d), 1/(a+2d), and so on are in HP because a, a + d, a + 2d are in AP. " }, { "code": null, "e": 367, "s": 331, "text": "Fact about Harmonic Progression : " }, { "code": null, "e": 913, "s": 367, "text": "In order to solve a problem on Harmonic Progression, one should make the corresponding AP series and then solve the problem.As the nth term of an A.P is given by an = a + (n-1)d, So the nth term of an H.P is given by 1/ [a + (n -1) d].For two numbers, if A, G and H are respectively the arithmetic, geometric and harmonic means, then A ≥ G ≥ HA H = G2, i.e., A, G, H are in GPIf we need to find three numbers in a H.P. then they should be assumed as 1/a–d, 1/a, 1/a+dMajority of the questions of H.P. are solved by first converting them into A.P" }, { "code": null, "e": 1038, "s": 913, "text": "In order to solve a problem on Harmonic Progression, one should make the corresponding AP series and then solve the problem." }, { "code": null, "e": 1150, "s": 1038, "text": "As the nth term of an A.P is given by an = a + (n-1)d, So the nth term of an H.P is given by 1/ [a + (n -1) d]." }, { "code": null, "e": 1292, "s": 1150, "text": "For two numbers, if A, G and H are respectively the arithmetic, geometric and harmonic means, then A ≥ G ≥ HA H = G2, i.e., A, G, H are in GP" }, { "code": null, "e": 1302, "s": 1292, "text": "A ≥ G ≥ H" }, { "code": null, "e": 1336, "s": 1302, "text": "A H = G2, i.e., A, G, H are in GP" }, { "code": null, "e": 1428, "s": 1336, "text": "If we need to find three numbers in a H.P. then they should be assumed as 1/a–d, 1/a, 1/a+d" }, { "code": null, "e": 1507, "s": 1428, "text": "Majority of the questions of H.P. are solved by first converting them into A.P" }, { "code": null, "e": 1542, "s": 1507, "text": "Formula of Harmonic Progression: " }, { "code": null, "e": 2039, "s": 1542, "text": "How we check whether a series is harmonic progression or not? The idea is to reciprocal the given array or series. After reciprocal, check if differences between consecutive elements are same or not. If all differences are same, Arithmetic Progression is possible. So as we know if the reciprocal of the terms are in AP then given a sequence of series is in H.P. Let’s take a series 1/5, 1/10, 1/15, 1/20, 1/25 and check whether it is a harmonic progression or not. Below is the implementation: " }, { "code": null, "e": 2043, "s": 2039, "text": "C++" }, { "code": null, "e": 2048, "s": 2043, "text": "Java" }, { "code": null, "e": 2056, "s": 2048, "text": "Python3" }, { "code": null, "e": 2059, "s": 2056, "text": "C#" }, { "code": null, "e": 2063, "s": 2059, "text": "PHP" }, { "code": null, "e": 2074, "s": 2063, "text": "Javascript" }, { "code": "// CPP program to check if a given // array can form harmonic progression#include<bits/stdc++.h>using namespace std; bool checkIsHP(vector<double> &arr){ int n = arr.size(); if (n == 1) { return true; } // Find reciprocal of arr[] vector<int> rec; for (int i = 0; i < n; i++) { rec.push_back((1 / arr[i])); } // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements sort(rec.begin(), rec.end()); int d = (rec[1]) - (rec[0]); for (int i = 2; i < n; i++) { if (rec[i] - rec[i - 1] != d) { return false; } } return true;} // Driver Codeint main(){ // series to check whether it is in H.P vector<double> arr = {1 / 5, 1 / 10, 1 / 15, 1 / 20, 1 / 25}; // Checking a series is in H.P or not if (checkIsHP(arr)) { cout << \"Yes\" << std::endl; } else { cout << \"No\" <<endl; } return 0;} // This code is contributed by mits", "e": 3196, "s": 2074, "text": null }, { "code": "// Java program to check if a given// array can form harmonic progressionimport java.util.*; class GFG{static boolean checkIsHP(double []arr){ int n = arr.length; if (n == 1) return true; // Find reciprocal of arr[] ArrayList<Integer> rec = new ArrayList<Integer>(); for (int i = 0; i < n; i++) rec.add((int)(1 / arr[i])); // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements Collections.sort(rec); int d = (int)rec.get(1) - (int)rec.get(0); for (int i = 2; i < n; i++) if (rec.get(i) - rec.get(i - 1) != d) return false; return true;} // Driver codepublic static void main(String[] args){ // series to check whether it is in H.P double arr[] = { 1/5, 1/10, 1/15, 1/20, 1/25 }; // Checking a series is in H.P or not if (checkIsHP(arr)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by mits", "e": 4321, "s": 3196, "text": null }, { "code": "# Python3 program to check if a given# array can form harmonic progression def checkIsHP(arr): n = len(arr) if (n == 1): return True # Find reciprocal of arr[] rec = [] for i in range(0, len(arr)): a = 1 / arr[i] rec.append(a) return(rec) # After finding reciprocal, check if the # reciprocal is in A. P. # To check for A.P., first Sort the # reciprocal array, then check difference # between consecutive elements rec.sort() d = rec[1] - rec[0] for i in range(2, n): if (rec[i] - rec[i-1] != d): return False return True # Driver codeif __name__=='__main__': # series to check whether it is in H.P arr = [ 1/5, 1/10, 1/15, 1/20, 1/25 ] # Checking a series is in H.P or not if (checkIsHP(arr)): print(\"Yes\") else: print(\"No\")", "e": 5181, "s": 4321, "text": null }, { "code": "// C# program to check if a given// array can form harmonic progressionusing System;using System.Collections;class GFG{static bool checkIsHP(double[] arr){ int n = arr.Length; if (n == 1) return true; // Find reciprocal of arr[] ArrayList rec = new ArrayList(); for (int i = 0; i < n; i++) rec.Add((int)(1 / arr[i])); // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements rec.Sort(); int d = (int)rec[1] - (int)rec[0]; for (int i = 2; i < n; i++) if ((int)rec[i] - (int)rec[i - 1] != d) return false; return true;} // Driver codepublic static void Main(){ // series to check whether it is in H.P double[] arr = { 1/5, 1/10, 1/15, 1/20, 1/25 }; // Checking a series is in H.P or not if (checkIsHP(arr)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by mits", "e": 6267, "s": 5181, "text": null }, { "code": "<?php// PHP program to check if a given// array can form harmonic progression function checkIsHP($arr){ $n = count($arr); if ($n == 1) return true; // Find reciprocal of arr[] $rec = array(); for ($i=0;$i<count($arr);$i++) { $a = 1 / $arr[$i]; array_push($rec,$a); } return ($rec); // After finding reciprocal, check if the // reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements sort($rec); $d = $rec[1] - $rec[0]; for ($i=2;$i<$n;$i++) if ($rec[$i] - $rec[$i-1] != $d) return false; return true;} // Driver code // series to check whether it is in H.P $arr = array( 1/5, 1/10, 1/15, 1/20, 1/25 ); // Checking a series is in H.P or not if (checkIsHP($arr)) print(\"Yes\"); else print(\"No\"); // This code is contributed by mits?>", "e": 7218, "s": 6267, "text": null }, { "code": "<script> // JavaScript program to check if a given // array can form harmonic progression function checkIsHP(arr){ let n = arr.length; if (n == 1) { return true; } // Find reciprocal of arr[] let rec = []; for (let i = 0; i < n; i++) { rec.push((1 / arr[i])); } // return (rec); // After finding reciprocal, check if // the reciprocal is in A. P. // To check for A.P., first Sort the // reciprocal array, then check difference // between consecutive elements rec.sort((a,b) => a - b); let d = (rec[1]) - (rec[0]); for (let i = 2; i < n; i++) { if (rec[i] - rec[i - 1] != d) { return false; } } return true;} // Driver Code // series to check whether it is in H.P let arr = [1 / 5, 1 / 10, 1 / 15, 1 / 20, 1 / 25]; // Checking a series is in H.P or not if (checkIsHP(arr)) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>", "e": 8223, "s": 7218, "text": null }, { "code": null, "e": 8233, "s": 8223, "text": "Output: " }, { "code": null, "e": 8237, "s": 8233, "text": "Yes" }, { "code": null, "e": 8267, "s": 8237, "text": "Time Complexity: O(n Log n). " }, { "code": null, "e": 8336, "s": 8267, "text": "Auxiliary Space: O(n)Basic Program related to Harmonic Progression " }, { "code": null, "e": 8361, "s": 8336, "text": "Harmonic progression Sum" }, { "code": null, "e": 8401, "s": 8361, "text": "Program to find the Nth Harmonic Number" }, { "code": null, "e": 8461, "s": 8401, "text": "Sum of series (n/1) + (n/2) + (n/3) + (n/4) +.......+ (n/n)" }, { "code": null, "e": 8508, "s": 8461, "text": "Check if the given number is Ore number or not" }, { "code": null, "e": 8548, "s": 8508, "text": "Expected Number of Trials until Success" }, { "code": null, "e": 8590, "s": 8548, "text": "Recent Articles on Harmonic Progression! " }, { "code": null, "e": 8603, "s": 8590, "text": "Mithun Kumar" }, { "code": null, "e": 8614, "s": 8603, "text": "nidhi_biet" }, { "code": null, "e": 8630, "s": 8614, "text": "rishavmahato348" }, { "code": null, "e": 8640, "s": 8630, "text": "subham348" }, { "code": null, "e": 8661, "s": 8640, "text": "harmonic progression" }, { "code": null, "e": 8668, "s": 8661, "text": "series" }, { "code": null, "e": 8681, "s": 8668, "text": "Mathematical" }, { "code": null, "e": 8700, "s": 8681, "text": "School Programming" }, { "code": null, "e": 8713, "s": 8700, "text": "Mathematical" }, { "code": null, "e": 8720, "s": 8713, "text": "series" }, { "code": null, "e": 8818, "s": 8720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8842, "s": 8818, "text": "Merge two sorted arrays" }, { "code": null, "e": 8863, "s": 8842, "text": "Operators in C / C++" }, { "code": null, "e": 8885, "s": 8863, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 8899, "s": 8885, "text": "Prime Numbers" }, { "code": null, "e": 8941, "s": 8899, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 8959, "s": 8941, "text": "Python Dictionary" }, { "code": null, "e": 8984, "s": 8959, "text": "Reverse a string in Java" }, { "code": null, "e": 9000, "s": 8984, "text": "Arrays in C/C++" }, { "code": null, "e": 9023, "s": 9000, "text": "Introduction To PYTHON" } ]
Taking multiple inputs from user in Python
08 Jul, 2022 The developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. Using split() method Using List comprehension Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it in taking multiple inputs. Syntax : input().split(separator, maxsplit) Example : Python3 # Python program showing how to# multiple input using split # taking two inputs at a timex, y = input("Enter two values: ").split()print("Number of boys: ", x)print("Number of girls: ", y)print() # taking three inputs at a timex, y, z = input("Enter three values: ").split()print("Total number of students: ", x)print("Number of boys is : ", y)print("Number of girls is : ", z)print() # taking two inputs at a timea, b = input("Enter two values: ").split()print("First number is {} and second number is {}".format(a, b))print() # taking multiple inputs at a time # and type casting using list() functionx = list(map(int, input("Enter multiple values: ").split()))print("List of students: ", x) Output: Using List comprehension : List comprehension is an elegant way to define and create list in Python. We can create lists just like mathematical statements in one line only. It is also used in getting multiple inputs from a user. Example: Python3 # Python program showing# how to take multiple input# using List comprehension # taking two input at a timex, y = [int(x) for x in input("Enter two values: ").split()]print("First Number is: ", x)print("Second Number is: ", y)print() # taking three input at a timex, y, z = [int(x) for x in input("Enter three values: ").split()]print("First Number is: ", x)print("Second Number is: ", y)print("Third Number is: ", z)print() # taking two inputs at a timex, y = [int(x) for x in input("Enter two values: ").split()]print("First number is {} and second number is {}".format(x, y))print() # taking multiple inputs at a time x = [int(x) for x in input("Enter multiple values: ").split()]print("Number of list is: ", x) Output : Note: The above examples take input separated by spaces. In case we wish to take input separated by comma (, ), we can use the following: Python3 # taking multiple inputs at a time separated by commax = [int(x) for x in input("Enter multiple value: ").split(",")]print("Number of list is: ", x) Please see https://ide.geeksforgeeks.org/BHf0Cxr4mx for a sample run. rakeshsshankala eramitkrgupta punamsingh628700 tyunsworth python-input-output Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 279, "s": 52, "text": "The developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. " }, { "code": null, "e": 300, "s": 279, "text": "Using split() method" }, { "code": null, "e": 325, "s": 300, "text": "Using List comprehension" }, { "code": null, "e": 638, "s": 325, "text": "Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it in taking multiple inputs." }, { "code": null, "e": 648, "s": 638, "text": "Syntax : " }, { "code": null, "e": 683, "s": 648, "text": "input().split(separator, maxsplit)" }, { "code": null, "e": 694, "s": 683, "text": "Example : " }, { "code": null, "e": 702, "s": 694, "text": "Python3" }, { "code": "# Python program showing how to# multiple input using split # taking two inputs at a timex, y = input(\"Enter two values: \").split()print(\"Number of boys: \", x)print(\"Number of girls: \", y)print() # taking three inputs at a timex, y, z = input(\"Enter three values: \").split()print(\"Total number of students: \", x)print(\"Number of boys is : \", y)print(\"Number of girls is : \", z)print() # taking two inputs at a timea, b = input(\"Enter two values: \").split()print(\"First number is {} and second number is {}\".format(a, b))print() # taking multiple inputs at a time # and type casting using list() functionx = list(map(int, input(\"Enter multiple values: \").split()))print(\"List of students: \", x)", "e": 1400, "s": 702, "text": null }, { "code": null, "e": 1410, "s": 1400, "text": "Output: " }, { "code": null, "e": 1640, "s": 1410, "text": "Using List comprehension : List comprehension is an elegant way to define and create list in Python. We can create lists just like mathematical statements in one line only. It is also used in getting multiple inputs from a user. " }, { "code": null, "e": 1650, "s": 1640, "text": "Example: " }, { "code": null, "e": 1658, "s": 1650, "text": "Python3" }, { "code": "# Python program showing# how to take multiple input# using List comprehension # taking two input at a timex, y = [int(x) for x in input(\"Enter two values: \").split()]print(\"First Number is: \", x)print(\"Second Number is: \", y)print() # taking three input at a timex, y, z = [int(x) for x in input(\"Enter three values: \").split()]print(\"First Number is: \", x)print(\"Second Number is: \", y)print(\"Third Number is: \", z)print() # taking two inputs at a timex, y = [int(x) for x in input(\"Enter two values: \").split()]print(\"First number is {} and second number is {}\".format(x, y))print() # taking multiple inputs at a time x = [int(x) for x in input(\"Enter multiple values: \").split()]print(\"Number of list is: \", x) ", "e": 2378, "s": 1658, "text": null }, { "code": null, "e": 2389, "s": 2378, "text": "Output : " }, { "code": null, "e": 2528, "s": 2389, "text": "Note: The above examples take input separated by spaces. In case we wish to take input separated by comma (, ), we can use the following: " }, { "code": null, "e": 2536, "s": 2528, "text": "Python3" }, { "code": "# taking multiple inputs at a time separated by commax = [int(x) for x in input(\"Enter multiple value: \").split(\",\")]print(\"Number of list is: \", x) ", "e": 2686, "s": 2536, "text": null }, { "code": null, "e": 2757, "s": 2686, "text": "Please see https://ide.geeksforgeeks.org/BHf0Cxr4mx for a sample run. " }, { "code": null, "e": 2773, "s": 2757, "text": "rakeshsshankala" }, { "code": null, "e": 2787, "s": 2773, "text": "eramitkrgupta" }, { "code": null, "e": 2804, "s": 2787, "text": "punamsingh628700" }, { "code": null, "e": 2815, "s": 2804, "text": "tyunsworth" }, { "code": null, "e": 2835, "s": 2815, "text": "python-input-output" }, { "code": null, "e": 2842, "s": 2835, "text": "Python" } ]
Python | Positional Index
13 Sep, 2021 This article talks about building an inverted index for an information retrieval (IR) system. However, in a real-life IR system, we not only encounter single-word queries (such as “dog”, “computer”, or “alex”) but also phrasal queries (such as “winter is coming”, “new york”, or “where is kevin”). To handle such queries, using an inverted index is not sufficient. To understand the motivation better, consider that a user queries “saint mary school”. Now, the inverted index will provide us a list of documents containing the terms “saint”, “mary” and “school” independently. What we actually require, however, are documents where the entire phrase “saint mary school” appears verbatim. In order to successfully answer such queries, we require an index of documents that also stores the positions of terms. Postings List In the case of the inverted index, a postings list is a list of documents where the term appears. It is typically sorted by the document ID and stored in the form of a linked list. The above figure shows a sample postings list for the term “hello”. It indicates that “hello” appears in documents with docIDs 3, 5, 10, 23 and 27. It also specifies the document frequency 5 (highlighted in green). Given is a sample Python data format containing a dictionary and linked lists to store the postings list. {"hello" : [5, [3, 5, 10, 23, 27] ] } In the case of the positional index, the positions at which the term appears in a particular document is also stored along with the docID. The above figure shows the same postings list implemented for a positional index. The blue boxes indicate the position of the term “hello” in the corresponding documents. For instance, “hello” appears in document 5 at three positions: 120, 125, and 278. Also, the frequency of the term is stored for each document. Given is a sample Python data format for the same. {"hello" : [5, [ {3 : [3, [120, 125, 278]]}, {5 : [1, [28] ] }, {10 : [2, [132, 182]]}, {23 : [3, [0, 12, 28]]}, {27 : [1, [2]]} ] } One can also omit the term frequency in the individual documents for the sake of simplicity (as done in the sample code). The data format then looks as follows. {"hello" : [5, {3 : [120, 125, 278]}, {5 : [28]}, {10 : [132, 182]}, {23 : [0, 12, 28]}, {27 : [2]} ] } Steps to build a Positional Index Fetch the document. Remove stop words, stem the resulting words. If the word is already present in the dictionary, add the document and the corresponding positions it appears in. Else, create a new entry. Also update the frequency of the word for each document, as well as the no. of documents it appears in. Code In order to implement a positional index, we make use of a sample dataset called “20 Newsgroups”. Python3 # importing librariesimport numpy as npimport osimport nltkfrom nltk.stem import PorterStemmerfrom nltk.tokenize import TweetTokenizerfrom natsort import natsortedimport string def read_file(filename): with open(filename, 'r', encoding ="ascii", errors ="surrogateescape") as f: stuff = f.read() f.close() # Remove header and footer. stuff = remove_header_footer(stuff) return stuff def remove_header_footer(final_string): new_final_string = "" tokens = final_string.split('\n\n') # Remove tokens[0] and tokens[-1] for token in tokens[1:-1]: new_final_string += token+" " return new_final_string def preprocessing(final_string): # Tokenize. tokenizer = TweetTokenizer() token_list = tokenizer.tokenize(final_string) # Remove punctuations. table = str.maketrans('', '', '\t') token_list = [word.translate(table) for word in token_list] punctuations = (string.punctuation).replace("'", "") trans_table = str.maketrans('', '', punctuations) stripped_words = [word.translate(trans_table) for word in token_list] token_list = [str for str in stripped_words if str] # Change to lowercase. token_list =[word.lower() for word in token_list] return token_list # In this example, we create the positional index for only 1 folder.folder_names = ["comp.graphics"] # Initialize the stemmer.stemmer = PorterStemmer() # Initialize the file no.fileno = 0 # Initialize the dictionary.pos_index = {} # Initialize the file mapping (fileno -> file name).file_map = {} for folder_name in folder_names: # Open files. file_names = natsorted(os.listdir("20_newsgroups/" + folder_name)) # For every file. for file_name in file_names: # Read file contents. stuff = read_file("20_newsgroups/" + folder_name + "/" + file_name) # This is the list of words in order of the text. # We need to preserve the order because we require positions. # 'preprocessing' function does some basic punctuation removal, # stopword removal etc. final_token_list = preprocessing(stuff) # For position and term in the tokens. for pos, term in enumerate(final_token_list): # First stem the term. term = stemmer.stem(term) # If term already exists in the positional index dictionary. if term in pos_index: # Increment total freq by 1. pos_index[term][0] = pos_index[term][0] + 1 # Check if the term has existed in that DocID before. if fileno in pos_index[term][1]: pos_index[term][1][fileno].append(pos) else: pos_index[term][1][fileno] = [pos] # If term does not exist in the positional index dictionary # (first encounter). else: # Initialize the list. pos_index[term] = [] # The total frequency is 1. pos_index[term].append(1) # The postings list is initially empty. pos_index[term].append({}) # Add doc ID to postings list. pos_index[term][1][fileno] = [pos] # Map the file no. to the file name. file_map[fileno] = "20_newsgroups/" + folder_name + "/" + file_name # Increment the file no. counter for document ID mapping fileno += 1 # Sample positional index to test the code.sample_pos_idx = pos_index["andrew"]print("Positional Index")print(sample_pos_idx) file_list = sample_pos_idx[1]print("Filename, [Positions]")for fileno, positions in file_list.items(): print(file_map[fileno], positions) Output: Positional Index [10, {215: [2081], 539: [66], 591: [879], 616: [462, 473], 680: [135], 691: [2081], 714: [4], 809: [333], 979: [0]}] Filename, [Positions] 20_newsgroups/comp.graphics/38376 [2081] 20_newsgroups/comp.graphics/38701 [66] 20_newsgroups/comp.graphics/38753 [879] 20_newsgroups/comp.graphics/38778 [462, 473] 20_newsgroups/comp.graphics/38842 [135] 20_newsgroups/comp.graphics/38853 [2081] 20_newsgroups/comp.graphics/38876 [4] 20_newsgroups/comp.graphics/38971 [333] 20_newsgroups/comp.graphics/39663 [0] Akanksha_Rai nnr223442 Advanced Computer Subject Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Sep, 2021" }, { "code": null, "e": 394, "s": 28, "text": "This article talks about building an inverted index for an information retrieval (IR) system. However, in a real-life IR system, we not only encounter single-word queries (such as “dog”, “computer”, or “alex”) but also phrasal queries (such as “winter is coming”, “new york”, or “where is kevin”). To handle such queries, using an inverted index is not sufficient. " }, { "code": null, "e": 837, "s": 394, "text": "To understand the motivation better, consider that a user queries “saint mary school”. Now, the inverted index will provide us a list of documents containing the terms “saint”, “mary” and “school” independently. What we actually require, however, are documents where the entire phrase “saint mary school” appears verbatim. In order to successfully answer such queries, we require an index of documents that also stores the positions of terms." }, { "code": null, "e": 1032, "s": 837, "text": "Postings List In the case of the inverted index, a postings list is a list of documents where the term appears. It is typically sorted by the document ID and stored in the form of a linked list." }, { "code": null, "e": 1353, "s": 1032, "text": "The above figure shows a sample postings list for the term “hello”. It indicates that “hello” appears in documents with docIDs 3, 5, 10, 23 and 27. It also specifies the document frequency 5 (highlighted in green). Given is a sample Python data format containing a dictionary and linked lists to store the postings list." }, { "code": null, "e": 1391, "s": 1353, "text": "{\"hello\" : [5, [3, 5, 10, 23, 27] ] }" }, { "code": null, "e": 1530, "s": 1391, "text": "In the case of the positional index, the positions at which the term appears in a particular document is also stored along with the docID." }, { "code": null, "e": 1896, "s": 1530, "text": "The above figure shows the same postings list implemented for a positional index. The blue boxes indicate the position of the term “hello” in the corresponding documents. For instance, “hello” appears in document 5 at three positions: 120, 125, and 278. Also, the frequency of the term is stored for each document. Given is a sample Python data format for the same." }, { "code": null, "e": 2029, "s": 1896, "text": "{\"hello\" : [5, [ {3 : [3, [120, 125, 278]]}, {5 : [1, [28] ] }, {10 : [2, [132, 182]]}, {23 : [3, [0, 12, 28]]}, {27 : [1, [2]]} ] }" }, { "code": null, "e": 2190, "s": 2029, "text": "One can also omit the term frequency in the individual documents for the sake of simplicity (as done in the sample code). The data format then looks as follows." }, { "code": null, "e": 2294, "s": 2190, "text": "{\"hello\" : [5, {3 : [120, 125, 278]}, {5 : [28]}, {10 : [132, 182]}, {23 : [0, 12, 28]}, {27 : [2]} ] }" }, { "code": null, "e": 2329, "s": 2294, "text": "Steps to build a Positional Index " }, { "code": null, "e": 2349, "s": 2329, "text": "Fetch the document." }, { "code": null, "e": 2394, "s": 2349, "text": "Remove stop words, stem the resulting words." }, { "code": null, "e": 2534, "s": 2394, "text": "If the word is already present in the dictionary, add the document and the corresponding positions it appears in. Else, create a new entry." }, { "code": null, "e": 2638, "s": 2534, "text": "Also update the frequency of the word for each document, as well as the no. of documents it appears in." }, { "code": null, "e": 2741, "s": 2638, "text": "Code In order to implement a positional index, we make use of a sample dataset called “20 Newsgroups”." }, { "code": null, "e": 2749, "s": 2741, "text": "Python3" }, { "code": "# importing librariesimport numpy as npimport osimport nltkfrom nltk.stem import PorterStemmerfrom nltk.tokenize import TweetTokenizerfrom natsort import natsortedimport string def read_file(filename): with open(filename, 'r', encoding =\"ascii\", errors =\"surrogateescape\") as f: stuff = f.read() f.close() # Remove header and footer. stuff = remove_header_footer(stuff) return stuff def remove_header_footer(final_string): new_final_string = \"\" tokens = final_string.split('\\n\\n') # Remove tokens[0] and tokens[-1] for token in tokens[1:-1]: new_final_string += token+\" \" return new_final_string def preprocessing(final_string): # Tokenize. tokenizer = TweetTokenizer() token_list = tokenizer.tokenize(final_string) # Remove punctuations. table = str.maketrans('', '', '\\t') token_list = [word.translate(table) for word in token_list] punctuations = (string.punctuation).replace(\"'\", \"\") trans_table = str.maketrans('', '', punctuations) stripped_words = [word.translate(trans_table) for word in token_list] token_list = [str for str in stripped_words if str] # Change to lowercase. token_list =[word.lower() for word in token_list] return token_list # In this example, we create the positional index for only 1 folder.folder_names = [\"comp.graphics\"] # Initialize the stemmer.stemmer = PorterStemmer() # Initialize the file no.fileno = 0 # Initialize the dictionary.pos_index = {} # Initialize the file mapping (fileno -> file name).file_map = {} for folder_name in folder_names: # Open files. file_names = natsorted(os.listdir(\"20_newsgroups/\" + folder_name)) # For every file. for file_name in file_names: # Read file contents. stuff = read_file(\"20_newsgroups/\" + folder_name + \"/\" + file_name) # This is the list of words in order of the text. # We need to preserve the order because we require positions. # 'preprocessing' function does some basic punctuation removal, # stopword removal etc. final_token_list = preprocessing(stuff) # For position and term in the tokens. for pos, term in enumerate(final_token_list): # First stem the term. term = stemmer.stem(term) # If term already exists in the positional index dictionary. if term in pos_index: # Increment total freq by 1. pos_index[term][0] = pos_index[term][0] + 1 # Check if the term has existed in that DocID before. if fileno in pos_index[term][1]: pos_index[term][1][fileno].append(pos) else: pos_index[term][1][fileno] = [pos] # If term does not exist in the positional index dictionary # (first encounter). else: # Initialize the list. pos_index[term] = [] # The total frequency is 1. pos_index[term].append(1) # The postings list is initially empty. pos_index[term].append({}) # Add doc ID to postings list. pos_index[term][1][fileno] = [pos] # Map the file no. to the file name. file_map[fileno] = \"20_newsgroups/\" + folder_name + \"/\" + file_name # Increment the file no. counter for document ID mapping fileno += 1 # Sample positional index to test the code.sample_pos_idx = pos_index[\"andrew\"]print(\"Positional Index\")print(sample_pos_idx) file_list = sample_pos_idx[1]print(\"Filename, [Positions]\")for fileno, positions in file_list.items(): print(file_map[fileno], positions)", "e": 6746, "s": 2749, "text": null }, { "code": null, "e": 6754, "s": 6746, "text": "Output:" }, { "code": null, "e": 7272, "s": 6754, "text": "Positional Index\n[10, {215: [2081], 539: [66], 591: [879], 616: [462, 473], 680: [135], 691: [2081], 714: [4], 809: [333], 979: [0]}]\nFilename, [Positions]\n20_newsgroups/comp.graphics/38376 [2081]\n20_newsgroups/comp.graphics/38701 [66]\n20_newsgroups/comp.graphics/38753 [879]\n20_newsgroups/comp.graphics/38778 [462, 473]\n20_newsgroups/comp.graphics/38842 [135]\n20_newsgroups/comp.graphics/38853 [2081]\n20_newsgroups/comp.graphics/38876 [4]\n20_newsgroups/comp.graphics/38971 [333]\n20_newsgroups/comp.graphics/39663 [0]" }, { "code": null, "e": 7287, "s": 7274, "text": "Akanksha_Rai" }, { "code": null, "e": 7297, "s": 7287, "text": "nnr223442" }, { "code": null, "e": 7323, "s": 7297, "text": "Advanced Computer Subject" }, { "code": null, "e": 7330, "s": 7323, "text": "Python" }, { "code": null, "e": 7346, "s": 7330, "text": "Python Programs" } ]
Binary Search (bisect) in Python
Here we will see the bisect in Python. The bisect is used for binary search. The binary search technique is used to find elements in sorted list. The bisect is one library function. We will see three different task using bisect in Python. The bisect.bisect_left(a, x, lo = 0, hi = len(a)) this function is used to return the left most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist. from bisect import bisect_left def BinSearch(a, x): i = bisect_left(a, x) if i != len(a) and a[i] == x: return i else: return -1 a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96] x = int(4) pos = BinSearch(a, x) if pos == -1: print(x, "is absent") else: print("First occurrence of", x, "is at position", pos) First occurrence of 4 is at position 2 Using the bisect_left option, we can get the greater value, which is smaller than the x (key). from bisect import bisect_left def BinSearch(a, x): i = bisect_left(a, x) if i : return i-1 else: return -1 a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96] x = int(8) pos = BinSearch(a, x) if pos == -1: print(x, "is absent") else: print("Larger value, smaller than", x, "is at position", pos) Larger value, smaller than 8 is at position 4 The bisect.bisect_right(a, x, lo = 0, hi = len(a)) this function is used to return the right most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist. from bisect import bisect_right def BinSearch(a, x): i = bisect_right(a, x) if i != len(a) + 1 and a[i-1] == x: return i-1 else: return -1 a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96] x = int(36) pos = BinSearch(a, x) if pos == -1: print(x, "is absent") else: print("Right most occurrence of", x, "is at position", pos) Right most occurrence of 36 is at position 9
[ { "code": null, "e": 1369, "s": 1187, "text": "Here we will see the bisect in Python. The bisect is used for binary search. The binary search technique is used to find elements in sorted list. The bisect is one library function." }, { "code": null, "e": 1426, "s": 1369, "text": "We will see three different task using bisect in Python." }, { "code": null, "e": 1649, "s": 1426, "text": "The bisect.bisect_left(a, x, lo = 0, hi = len(a)) this function is used to return the left most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist." }, { "code": null, "e": 1986, "s": 1649, "text": "from bisect import bisect_left\ndef BinSearch(a, x):\n i = bisect_left(a, x)\n if i != len(a) and a[i] == x:\n return i\n else:\n return -1\na = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]\nx = int(4)\npos = BinSearch(a, x)\nif pos == -1:\n print(x, \"is absent\")\nelse:\n print(\"First occurrence of\", x, \"is at position\", pos)" }, { "code": null, "e": 2025, "s": 1986, "text": "First occurrence of 4 is at position 2" }, { "code": null, "e": 2120, "s": 2025, "text": "Using the bisect_left option, we can get the greater value, which is smaller than the x (key)." }, { "code": null, "e": 2443, "s": 2120, "text": "from bisect import bisect_left\ndef BinSearch(a, x):\n i = bisect_left(a, x)\n if i :\n return i-1\n else:\n return -1\na = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]\nx = int(8)\npos = BinSearch(a, x)\nif pos == -1:\n print(x, \"is absent\")\nelse:\n print(\"Larger value, smaller than\", x, \"is at position\", pos)" }, { "code": null, "e": 2489, "s": 2443, "text": "Larger value, smaller than 8 is at position 4" }, { "code": null, "e": 2714, "s": 2489, "text": "The bisect.bisect_right(a, x, lo = 0, hi = len(a)) this function is used to return the right most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist." }, { "code": null, "e": 3067, "s": 2714, "text": "from bisect import bisect_right\ndef BinSearch(a, x):\n i = bisect_right(a, x)\n if i != len(a) + 1 and a[i-1] == x:\n return i-1\n else:\n return -1\na = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]\nx = int(36)\npos = BinSearch(a, x)\nif pos == -1:\n print(x, \"is absent\")\nelse:\n print(\"Right most occurrence of\", x, \"is at position\", pos)" }, { "code": null, "e": 3112, "s": 3067, "text": "Right most occurrence of 36 is at position 9" } ]
jQuery - children( [selector]) Method
The children( [selector] ) method gets a set of elements containing all of the unique immediate children of each of the matched set of elements. Here is the simple syntax to use this method − selector.children( [selector] ) Here is the description of all the parameters used by this method − selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected. selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected. Following is a simple example a simple showing the usage of this method − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"> </script> <script> $(document).ready(function(){ $("div").children(".selected").addClass("blue"); }); </script> <style> .blue { color:blue; } </style> </head> <body> <div> <span>Hello</span> <p class = "selected">Hello Again</p> <div class = "selected">And Again</div> <p class = "biggest">And One Last Time</p> </div> </body> </html> This would apply blue color to all children with a class "selected" of each div, as shown below − Hello Again And One Last Time <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"> </script> <script> $(document).ready(function(){ $("div").children(".selected").addClass("blue"); }); </script> <style> .blue { color:blue; } </style> </head> <body> <div> <span>Hello</span> <p class = "blue">Hello Again</p> <div class = "blue">And Again</div> <p class = "biggest">And One Last Time</p> </div> </body> </html> This will produce following result − Hello Again And One Last Time
[ { "code": null, "e": 2934, "s": 2789, "text": "The children( [selector] ) method gets a set of elements containing all of the unique immediate children of each of the matched set of elements." }, { "code": null, "e": 2981, "s": 2934, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 3014, "s": 2981, "text": "selector.children( [selector] )\n" }, { "code": null, "e": 3082, "s": 3014, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 3208, "s": 3082, "text": "selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected." }, { "code": null, "e": 3334, "s": 3208, "text": "selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected." }, { "code": null, "e": 3408, "s": 3334, "text": "Following is a simple example a simple showing the usage of this method −" }, { "code": null, "e": 4046, "s": 3408, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://www.tutorialspoint.com/jquery/jquery-3.6.0.js\">\n </script>\n\t\t\n <script>\n $(document).ready(function(){\n $(\"div\").children(\".selected\").addClass(\"blue\");\n });\n </script>\n\t\t\n <style>\n .blue { color:blue; }\n </style>\n </head>\n\t\n <body>\n <div>\n <span>Hello</span>\n <p class = \"selected\">Hello Again</p>\n <div class = \"selected\">And Again</div>\n <p class = \"biggest\">And One Last Time</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4144, "s": 4046, "text": "This would apply blue color to all children with a class \"selected\" of each div, as shown below −" }, { "code": null, "e": 4156, "s": 4144, "text": "Hello Again" }, { "code": null, "e": 4174, "s": 4156, "text": "And One Last Time" }, { "code": null, "e": 4804, "s": 4174, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://www.tutorialspoint.com/jquery/jquery-3.6.0.js\">\n </script>\n\t\t\n <script>\n $(document).ready(function(){\n $(\"div\").children(\".selected\").addClass(\"blue\");\n });\n </script>\n\t\t\n <style>\n .blue { color:blue; }\n </style>\n </head>\n\t\n <body>\n <div>\n <span>Hello</span>\n <p class = \"blue\">Hello Again</p>\n <div class = \"blue\">And Again</div>\n <p class = \"biggest\">And One Last Time</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 4841, "s": 4804, "text": "This will produce following result −" }, { "code": null, "e": 4853, "s": 4841, "text": "Hello Again" } ]
How to call an API continuously from server side itself in Node.js/Express.js ?
06 Oct, 2021 Calling an API endpoint is the core functionality of modern internet technology. Usually, we call API from the browser. Sometimes we need to call API endpoint from the server itself to fetch data, load dependencies, etc. There are many ways to call API from NodeJS server itself, depending on the abstraction level that you want to use. The simplest way to call an API from NodeJS server is using the Axios library. Project Setup: Create a NodeJS project and initialize it using the following command. mkdir Project && cd Project npm init -y Module Installation: Install the required modules i.e. ExpressJS and Axios using the following command. npm i express axios Now create a JS file in the root folder of your project and name it index.js 1. Make an HTTP GET request: Write the following code on your index.js file. index.js const express = require('express')const axios = require('axios') const app = express() // Post ID trackervar num = 0 setInterval(() => { // Increment post tracker num++ console.log('Wait for 2 second...') // Make GET Request on every 2 second axios.get(`https://jsonplaceholder.typicode.com/posts/${num}`) // Print data .then(response => { const { id, title } = response.data console.log(`Post ${id}: ${title}\n`) }) // Print error message if occur .catch(error => console.log( 'Error to fetch data\n'))}, 2000) Explanation: In the above example, NodeJS call an API in 2-second intervals to fetch data. If the promise is resolved, then the block will be executed and print data. If a promise rejects, catch block will be executed and print an Error message. Run the server using the following command: node index.js Output: 2. Make an HTTP POST request: Write down the following code in the index.js file. index.js const express = require('express')const axios = require('axios') const app = express() // Dummy databaseconst posts = [ { title: 'Headline 1', id: 1, body: `sint suscipit perspiciatis velit dolorum rerum ipsa laboriosam odio`, userId: 1 }, { title: 'Headline 2', id: 2, body: "fugit voluptas sed molestias voluptatem provident", userId: 1 }, { title: 'Headline 3', id: 3, body: "voluptate et itaque vero tempora molestiae", userId: 1 }] // Loop over the postsposts.forEach(post => { // Post data to API endpoint axios.post('https://jsonplaceholder.typicode.com/posts/', { body: post, }) // Print response .then(response => { const { id, title } = response.data.body console.log(`Post ${id}: ${title}`) }) // Print error message if occur .catch(error => console.log(error))}) Explanation: In the above example, we have created dummy user data. NodeJS makes a POST request to send these data to the API endpoint and print either the response’s data or the error message. Run the server using the following command: node index.js Output: Node.js-Methods NodeJS-Questions Picked Node.js 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": "\n06 Oct, 2021" }, { "code": null, "e": 249, "s": 28, "text": "Calling an API endpoint is the core functionality of modern internet technology. Usually, we call API from the browser. Sometimes we need to call API endpoint from the server itself to fetch data, load dependencies, etc." }, { "code": null, "e": 445, "s": 249, "text": "There are many ways to call API from NodeJS server itself, depending on the abstraction level that you want to use. The simplest way to call an API from NodeJS server is using the Axios library. " }, { "code": null, "e": 531, "s": 445, "text": "Project Setup: Create a NodeJS project and initialize it using the following command." }, { "code": null, "e": 571, "s": 531, "text": "mkdir Project && cd Project\nnpm init -y" }, { "code": null, "e": 675, "s": 571, "text": "Module Installation: Install the required modules i.e. ExpressJS and Axios using the following command." }, { "code": null, "e": 695, "s": 675, "text": "npm i express axios" }, { "code": null, "e": 772, "s": 695, "text": "Now create a JS file in the root folder of your project and name it index.js" }, { "code": null, "e": 849, "s": 772, "text": "1. Make an HTTP GET request: Write the following code on your index.js file." }, { "code": null, "e": 858, "s": 849, "text": "index.js" }, { "code": "const express = require('express')const axios = require('axios') const app = express() // Post ID trackervar num = 0 setInterval(() => { // Increment post tracker num++ console.log('Wait for 2 second...') // Make GET Request on every 2 second axios.get(`https://jsonplaceholder.typicode.com/posts/${num}`) // Print data .then(response => { const { id, title } = response.data console.log(`Post ${id}: ${title}\\n`) }) // Print error message if occur .catch(error => console.log( 'Error to fetch data\\n'))}, 2000)", "e": 1443, "s": 858, "text": null }, { "code": null, "e": 1691, "s": 1443, "text": "Explanation: In the above example, NodeJS call an API in 2-second intervals to fetch data. If the promise is resolved, then the block will be executed and print data. If a promise rejects, catch block will be executed and print an Error message. " }, { "code": null, "e": 1735, "s": 1691, "text": "Run the server using the following command:" }, { "code": null, "e": 1750, "s": 1735, "text": "node index.js " }, { "code": null, "e": 1758, "s": 1750, "text": "Output:" }, { "code": null, "e": 1840, "s": 1758, "text": "2. Make an HTTP POST request: Write down the following code in the index.js file." }, { "code": null, "e": 1849, "s": 1840, "text": "index.js" }, { "code": "const express = require('express')const axios = require('axios') const app = express() // Dummy databaseconst posts = [ { title: 'Headline 1', id: 1, body: `sint suscipit perspiciatis velit dolorum rerum ipsa laboriosam odio`, userId: 1 }, { title: 'Headline 2', id: 2, body: \"fugit voluptas sed molestias voluptatem provident\", userId: 1 }, { title: 'Headline 3', id: 3, body: \"voluptate et itaque vero tempora molestiae\", userId: 1 }] // Loop over the postsposts.forEach(post => { // Post data to API endpoint axios.post('https://jsonplaceholder.typicode.com/posts/', { body: post, }) // Print response .then(response => { const { id, title } = response.data.body console.log(`Post ${id}: ${title}`) }) // Print error message if occur .catch(error => console.log(error))})", "e": 2773, "s": 1849, "text": null }, { "code": null, "e": 2967, "s": 2773, "text": "Explanation: In the above example, we have created dummy user data. NodeJS makes a POST request to send these data to the API endpoint and print either the response’s data or the error message." }, { "code": null, "e": 3011, "s": 2967, "text": "Run the server using the following command:" }, { "code": null, "e": 3026, "s": 3011, "text": "node index.js " }, { "code": null, "e": 3034, "s": 3026, "text": "Output:" }, { "code": null, "e": 3050, "s": 3034, "text": "Node.js-Methods" }, { "code": null, "e": 3067, "s": 3050, "text": "NodeJS-Questions" }, { "code": null, "e": 3074, "s": 3067, "text": "Picked" }, { "code": null, "e": 3082, "s": 3074, "text": "Node.js" }, { "code": null, "e": 3099, "s": 3082, "text": "Web Technologies" } ]
What is Register Renaming?
Register renaming is a standard approach for eliminating false data dependencies, such as WAR and WAW dependencies, between register data. It was first suggested by Tjaden and Flynn in 1970. They intended to use register renaming for a definite set of instructions that compare more or less to the class of load instructions, although it does not use the phrase ‘renaming’. Keller (1975) introduced the designation ‘register renaming’ and interpreted it for all suitable instructions. Register Renaming presumes the three-operand instruction format. To illustrate this precondition, let us consider a two-operand instruction, say ad r1, r2 with the interpretation r1←(r1)+(r2) In the two instruction format, the result is written back in place of one of the source operands, in the example in the place of r1. However, for the renaming of the destination, a register different from that containing a source operand (r1) has to be used, say r11. Thus, after renaming we get r11←(r1)+(r2) This means that the renaming of two-operand instruction always ends up as three-operand instruction. As a consequence, two-operand instructions can only be renamed using an internal two to three operand conversion. Register renaming can be implemented either statistically or dynamically as shown in the figure. Static Implementation − In a static implementation, register renaming is carried out during compilation. This technique was first introduced in parallel optimizing compilers for pipelined processors, and later in superscalar processors. Dynamic Implementation − When register renaming is implemented dynamically, renaming takes place during execution. This requires extra circuitry in terms of supplementary register space, additional data path, and logic. The dynamic renaming has been utilized in advanced superscalar processors because the early 1990s. The renaming was introduced in two stages. In the first stage, the renaming was only partially implemented. Here, renaming is confined to one or a few particular data types. For instance, the Power1, Power2, PowerPC 601 and Nx586 processors employ partial renaming. In both stages, IBM was the first vendor to introduce renaming, initially in its Power-line with the Power1 (RS/6000) and later in the high-end processors of its ES/9000 family. IBM continued to implement full renaming in the power-based PowerPC-line except for the first model, the PowerPC 601. All vendors of significant superscalar processors have introduced renaming in their most recent models, except DEC in its α-line and Sun in the UltraSparc.
[ { "code": null, "e": 1378, "s": 1187, "text": "Register renaming is a standard approach for eliminating false data dependencies, such as WAR and WAW dependencies, between register data. It was first suggested by Tjaden and Flynn in 1970." }, { "code": null, "e": 1672, "s": 1378, "text": "They intended to use register renaming for a definite set of instructions that compare more or less to the class of load instructions, although it does not use the phrase ‘renaming’. Keller (1975) introduced the designation ‘register renaming’ and interpreted it for all suitable instructions." }, { "code": null, "e": 1817, "s": 1672, "text": "Register Renaming presumes the three-operand instruction format. To illustrate this precondition, let us consider a two-operand instruction, say" }, { "code": null, "e": 1827, "s": 1817, "text": "ad r1, r2" }, { "code": null, "e": 1851, "s": 1827, "text": "with the interpretation" }, { "code": null, "e": 1865, "s": 1851, "text": "r1←(r1)+(r2)\n" }, { "code": null, "e": 2161, "s": 1865, "text": "In the two instruction format, the result is written back in place of one of the source operands, in the example in the place of r1. However, for the renaming of the destination, a register different from that containing a source operand (r1) has to be used, say r11. Thus, after renaming we get" }, { "code": null, "e": 2175, "s": 2161, "text": "r11←(r1)+(r2)" }, { "code": null, "e": 2390, "s": 2175, "text": "This means that the renaming of two-operand instruction always ends up as three-operand instruction. As a consequence, two-operand instructions can only be renamed using an internal two to three operand conversion." }, { "code": null, "e": 2487, "s": 2390, "text": "Register renaming can be implemented either statistically or dynamically as shown in the figure." }, { "code": null, "e": 2724, "s": 2487, "text": "Static Implementation − In a static implementation, register renaming is carried out during compilation. This technique was first introduced in parallel optimizing compilers for pipelined processors, and later in superscalar processors." }, { "code": null, "e": 3043, "s": 2724, "text": "Dynamic Implementation − When register renaming is implemented dynamically, renaming takes place during execution. This requires extra circuitry in terms of supplementary register space, additional data path, and logic. The dynamic renaming has been utilized in advanced superscalar processors because the early 1990s." }, { "code": null, "e": 3309, "s": 3043, "text": "The renaming was introduced in two stages. In the first stage, the renaming was only partially implemented. Here, renaming is confined to one or a few particular data types. For instance, the Power1, Power2, PowerPC 601 and Nx586 processors employ partial renaming." }, { "code": null, "e": 3761, "s": 3309, "text": "In both stages, IBM was the first vendor to introduce renaming, initially in its Power-line with the Power1 (RS/6000) and later in the high-end processors of its ES/9000 family. IBM continued to implement full renaming in the power-based PowerPC-line except for the first model, the PowerPC 601. All vendors of significant superscalar processors have introduced renaming in their most recent models, except DEC in its α-line and Sun in the UltraSparc." } ]
ReactJS | Icons
22 Jun, 2020 A built-in library of icons is provided by React, by using it we can include any number of icons in our project. We just have to import module in our app.js file by mentioning library name and icon name which we want to add. Prerequisites: Basics of ReactJS NodeJS:Installation of Node.js on WindowsInstallation of Node.js on Linux Installation of Node.js on Windows Installation of Node.js on Linux Already created ReactJS app Below all the steps are described order wise how to add icons and design them in React. Step 1: Before moving further, firstly you have to install react icons library, by running following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder. npm install react-icons --save Step 2: After installing icons library, now open your app.js file which is preset inside your project directory’s, under src folder and delete code preset inside it. Step 3: Now open react-icons library by visiting the below link. This is inbuilt library of react-icons which is provided by react. After opening react-icons, now from menu select category and name of icon you want to add. After clicking, on right hand side you will see many icons and there names. In category I am selecting Game icons, and from right hand side I am selecting GiPoliceBadge you can choose any other if you want. https://react-icons.github.io/react-icons/icons?name=gi Step 4: Now in your app.js file, add this code: import { IconName } from "react-icons/"; app.js: javascript import React, { Component } from "react"; // gi is sort name of game icon.import { GiPoliceBadge } from "react-icons/gi"; // The GiPoliceBadge is icon name.class App extends Component { render() { return ( <div> <GiPoliceBadge /> </div> ); }}export default App; Output: To see output run below command. npm start Now, after npm started successfully , open browser and type below url to see output. http://localhost:3000/ app.js: To change color of Icons and size, see below code. javascript import React, { Component } from "react"; // gi is sort name of game icon.import { GiPoliceBadge } from "react-icons/gi"; // The GiPoliceBadge is icon name.class App extends Component { render() { return ( <div> <GiPoliceBadge size="100px" color="green"/> </div> ); }}export default App; Output: app.js: To add multiple icons, see below javascript import React, { Component } from "react"; // gi is sort name of game icon.import { GiPoliceBadge } from "react-icons/gi";import { MdAndroid } from "react-icons/md";import { GoBroadcast } from "react-icons/go";import { FaAmazon } from "react-icons/fa";// The GiPoliceBadge is icon name.class App extends Component { render() { return ( <div> <GiPoliceBadge size="50px" color="green"/> <MdAndroid size="50px" color="yellow" /> <GoBroadcast size="50px" color="purple"/> <FaAmazon size="50px" color="black" /> </div> ); }}export default App; Output: react-js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 253, "s": 28, "text": "A built-in library of icons is provided by React, by using it we can include any number of icons in our project. We just have to import module in our app.js file by mentioning library name and icon name which we want to add." }, { "code": null, "e": 270, "s": 253, "text": "Prerequisites: " }, { "code": null, "e": 288, "s": 270, "text": "Basics of ReactJS" }, { "code": null, "e": 362, "s": 288, "text": "NodeJS:Installation of Node.js on WindowsInstallation of Node.js on Linux" }, { "code": null, "e": 397, "s": 362, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 430, "s": 397, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 458, "s": 430, "text": "Already created ReactJS app" }, { "code": null, "e": 546, "s": 458, "text": "Below all the steps are described order wise how to add icons and design them in React." }, { "code": null, "e": 818, "s": 546, "text": "Step 1: Before moving further, firstly you have to install react icons library, by running following command in your project directory, with the help of terminal in your src folder or you can also run this command in Visual Studio Code’s terminal in your project folder. " }, { "code": null, "e": 850, "s": 818, "text": "npm install react-icons --save\n" }, { "code": null, "e": 1018, "s": 850, "text": "Step 2: After installing icons library, now open your app.js file which is preset inside your project directory’s, under src folder and delete code preset inside it. " }, { "code": null, "e": 1448, "s": 1018, "text": "Step 3: Now open react-icons library by visiting the below link. This is inbuilt library of react-icons which is provided by react. After opening react-icons, now from menu select category and name of icon you want to add. After clicking, on right hand side you will see many icons and there names. In category I am selecting Game icons, and from right hand side I am selecting GiPoliceBadge you can choose any other if you want." }, { "code": null, "e": 1504, "s": 1448, "text": "https://react-icons.github.io/react-icons/icons?name=gi" }, { "code": null, "e": 1554, "s": 1504, "text": "Step 4: Now in your app.js file, add this code: " }, { "code": null, "e": 1596, "s": 1554, "text": "import { IconName } from \"react-icons/\";\n" }, { "code": null, "e": 1604, "s": 1596, "text": "app.js:" }, { "code": null, "e": 1615, "s": 1604, "text": "javascript" }, { "code": "import React, { Component } from \"react\"; // gi is sort name of game icon.import { GiPoliceBadge } from \"react-icons/gi\"; // The GiPoliceBadge is icon name.class App extends Component { render() { return ( <div> <GiPoliceBadge /> </div> ); }}export default App;", "e": 1937, "s": 1615, "text": null }, { "code": null, "e": 1946, "s": 1937, "text": "Output: " }, { "code": null, "e": 1981, "s": 1946, "text": "To see output run below command. " }, { "code": null, "e": 1991, "s": 1981, "text": "npm start" }, { "code": null, "e": 2076, "s": 1991, "text": "Now, after npm started successfully , open browser and type below url to see output." }, { "code": null, "e": 2099, "s": 2076, "text": "http://localhost:3000/" }, { "code": null, "e": 2158, "s": 2099, "text": "app.js: To change color of Icons and size, see below code." }, { "code": null, "e": 2169, "s": 2158, "text": "javascript" }, { "code": "import React, { Component } from \"react\"; // gi is sort name of game icon.import { GiPoliceBadge } from \"react-icons/gi\"; // The GiPoliceBadge is icon name.class App extends Component { render() { return ( <div> <GiPoliceBadge size=\"100px\" color=\"green\"/> </div> ); }}export default App;", "e": 2517, "s": 2169, "text": null }, { "code": null, "e": 2525, "s": 2517, "text": "Output:" }, { "code": null, "e": 2566, "s": 2525, "text": "app.js: To add multiple icons, see below" }, { "code": null, "e": 2577, "s": 2566, "text": "javascript" }, { "code": "import React, { Component } from \"react\"; // gi is sort name of game icon.import { GiPoliceBadge } from \"react-icons/gi\";import { MdAndroid } from \"react-icons/md\";import { GoBroadcast } from \"react-icons/go\";import { FaAmazon } from \"react-icons/fa\";// The GiPoliceBadge is icon name.class App extends Component { render() { return ( <div> <GiPoliceBadge size=\"50px\" color=\"green\"/> <MdAndroid size=\"50px\" color=\"yellow\" /> <GoBroadcast size=\"50px\" color=\"purple\"/> <FaAmazon size=\"50px\" color=\"black\" /> </div> ); }}export default App;", "e": 3220, "s": 2577, "text": null }, { "code": null, "e": 3228, "s": 3220, "text": "Output:" }, { "code": null, "e": 3237, "s": 3228, "text": "react-js" }, { "code": null, "e": 3248, "s": 3237, "text": "JavaScript" }, { "code": null, "e": 3265, "s": 3248, "text": "Web Technologies" }, { "code": null, "e": 3363, "s": 3265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3424, "s": 3363, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3496, "s": 3424, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3536, "s": 3496, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3578, "s": 3536, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3619, "s": 3578, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3652, "s": 3619, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3714, "s": 3652, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3775, "s": 3714, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3825, "s": 3775, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
List in C++ Standard Template Library (STL)
06 Jul, 2022 Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list. Below is the program to show the working of some functions of List: CPP // CPP program to show the implementation of List#include <iostream>#include <iterator>#include <list>using namespace std; // function for printing the elements in a listvoid showlist(list<int> g){ list<int>::iterator it; for (it = g.begin(); it != g.end(); ++it) cout << '\t' << *it; cout << '\n';} // Driver Codeint main(){ list<int> gqlist1, gqlist2; for (int i = 0; i < 10; ++i) { gqlist1.push_back(i * 2); gqlist2.push_front(i * 3); } cout << "\nList 1 (gqlist1) is : "; showlist(gqlist1); cout << "\nList 2 (gqlist2) is : "; showlist(gqlist2); cout << "\ngqlist1.front() : " << gqlist1.front(); cout << "\ngqlist1.back() : " << gqlist1.back(); cout << "\ngqlist1.pop_front() : "; gqlist1.pop_front(); showlist(gqlist1); cout << "\ngqlist2.pop_back() : "; gqlist2.pop_back(); showlist(gqlist2); cout << "\ngqlist1.reverse() : "; gqlist1.reverse(); showlist(gqlist1); cout << "\ngqlist2.sort(): "; gqlist2.sort(); showlist(gqlist2); return 0;} List 1 (gqlist1) is : 0 2 4 6 8 10 12 14 16 18 List 2 (gqlist2) is : 27 24 21 18 15 12 9 6 3 0 gqlist1.front() : 0 gqlist1.back() : 18 gqlist1.pop_front() : 2 4 6 8 10 12 14 16 18 gqlist2.pop_back() : 27 24 21 18 15 12 9 6 3 gqlist1.reverse() : 18 16 14 12 10 8 6 4 2 gqlist2.sort(): 3 6 9 12 15 18 21 24 27 Functions Definition Recent Articles on C++ list Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. anshikajain26 cpp-containers-library cpp-list STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vector in C++ STL Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Sorting a vector in C++ 2D Vector In C++ With User Defined Size Virtual Function in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 446, "s": 52, "text": "Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list. Below is the program to show the working of some functions of List: " }, { "code": null, "e": 450, "s": 446, "text": "CPP" }, { "code": "// CPP program to show the implementation of List#include <iostream>#include <iterator>#include <list>using namespace std; // function for printing the elements in a listvoid showlist(list<int> g){ list<int>::iterator it; for (it = g.begin(); it != g.end(); ++it) cout << '\\t' << *it; cout << '\\n';} // Driver Codeint main(){ list<int> gqlist1, gqlist2; for (int i = 0; i < 10; ++i) { gqlist1.push_back(i * 2); gqlist2.push_front(i * 3); } cout << \"\\nList 1 (gqlist1) is : \"; showlist(gqlist1); cout << \"\\nList 2 (gqlist2) is : \"; showlist(gqlist2); cout << \"\\ngqlist1.front() : \" << gqlist1.front(); cout << \"\\ngqlist1.back() : \" << gqlist1.back(); cout << \"\\ngqlist1.pop_front() : \"; gqlist1.pop_front(); showlist(gqlist1); cout << \"\\ngqlist2.pop_back() : \"; gqlist2.pop_back(); showlist(gqlist2); cout << \"\\ngqlist1.reverse() : \"; gqlist1.reverse(); showlist(gqlist1); cout << \"\\ngqlist2.sort(): \"; gqlist2.sort(); showlist(gqlist2); return 0;}", "e": 1514, "s": 450, "text": null }, { "code": null, "e": 2001, "s": 1514, "text": "List 1 (gqlist1) is : 0 2 4 6 8 10 12 14 16 18\n\nList 2 (gqlist2) is : 27 24 21 18 15 12 9 6 3 0\n\ngqlist1.front() : 0\ngqlist1.back() : 18\ngqlist1.pop_front() : 2 4 6 8 10 12 14 16 18\n\ngqlist2.pop_back() : 27 24 21 18 15 12 9 6 3\n\ngqlist1.reverse() : 18 16 14 12 10 8 6 4 2\n\ngqlist2.sort(): 3 6 9 12 15 18 21 24 27" }, { "code": null, "e": 2011, "s": 2001, "text": "Functions" }, { "code": null, "e": 2022, "s": 2011, "text": "Definition" }, { "code": null, "e": 2050, "s": 2022, "text": "Recent Articles on C++ list" }, { "code": null, "e": 2175, "s": 2050, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2189, "s": 2175, "text": "anshikajain26" }, { "code": null, "e": 2212, "s": 2189, "text": "cpp-containers-library" }, { "code": null, "e": 2221, "s": 2212, "text": "cpp-list" }, { "code": null, "e": 2225, "s": 2221, "text": "STL" }, { "code": null, "e": 2229, "s": 2225, "text": "C++" }, { "code": null, "e": 2233, "s": 2229, "text": "STL" }, { "code": null, "e": 2237, "s": 2233, "text": "CPP" }, { "code": null, "e": 2335, "s": 2237, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2353, "s": 2335, "text": "Vector in C++ STL" }, { "code": null, "e": 2399, "s": 2353, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2422, "s": 2399, "text": "std::sort() in C++ STL" }, { "code": null, "e": 2449, "s": 2422, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 2483, "s": 2449, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 2508, "s": 2483, "text": "unordered_map in C++ STL" }, { "code": null, "e": 2525, "s": 2508, "text": "Substring in C++" }, { "code": null, "e": 2549, "s": 2525, "text": "Sorting a vector in C++" }, { "code": null, "e": 2589, "s": 2549, "text": "2D Vector In C++ With User Defined Size" } ]
Python | Pandas Series.asfreq()
27 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.asfreq() function is used to convert TimeSeries to specified frequency. The function also provide filling method to pad/backfill missing values. Syntax: Series.asfreq(freq, method=None, how=None, normalize=False, fill_value=None) Parameter :freq : DateOffset object, or stringmethod : {‘backfill’/’bfill’, ‘pad’/’ffill’}, default Nonehow : For PeriodIndex only, see PeriodIndex.asfreqnormalize : Whether to reset output index to midnightfill_value : Value to use for missing values Returns : converted : same type as caller Example #1: Use Series.asfreq() function to change the frequency of the given series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Indexindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : 2010-12-31 08:45:00 8 2011-01-31 08:45:00 18 2011-02-28 08:45:00 65 2011-03-31 08:45:00 18 2011-04-30 08:45:00 32 2011-05-31 08:45:00 10 2011-06-30 08:45:00 5 2011-07-31 08:45:00 32 2011-08-31 08:45:00 NaN Freq: M, dtype: float64 Now we will use Series.asfreq() function to change the frequency of the given series object to quarterly. # change to quarterly frequencyresult = sr.asfreq(freq = 'Q') # Print the resultprint(result) Output : 2010-12-31 08:45:00 8 2011-03-31 08:45:00 18 2011-06-30 08:45:00 5 Freq: Q-DEC, dtype: float64 As we can see in the output, the Series.asfreq() function has successfully changed the frequency of the given series object. Example #2 : Use Series.asfreq() function to change the yearly frequency of the given series object to the batches of 3 years. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr) Output : 2010-12-31 08:45:00 11.0 2011-12-31 08:45:00 21.0 2012-12-31 08:45:00 8.0 2013-12-31 08:45:00 18.0 2014-12-31 08:45:00 65.0 2015-12-31 08:45:00 18.0 2016-12-31 08:45:00 32.0 2017-12-31 08:45:00 10.0 2018-12-31 08:45:00 5.0 2019-12-31 08:45:00 32.0 2020-12-31 08:45:00 NaN Freq: A-DEC, dtype: float64 Now we will use Series.asfreq() function to change the yearly frequency of the given series object to the batches of 3 years. # apply year batch frequencyresult = sr.asfreq(freq = '3Y') # Print the resultprint(result) Output : 2010-12-31 08:45:00 11.0 2013-12-31 08:45:00 18.0 2016-12-31 08:45:00 32.0 2019-12-31 08:45:00 32.0 Freq: 3A-DEC, dtype: float64 As we can see in the output, the Series.asfreq() function has successfully changed the frequency of the given series object. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 444, "s": 285, "text": "Pandas Series.asfreq() function is used to convert TimeSeries to specified frequency. The function also provide filling method to pad/backfill missing values." }, { "code": null, "e": 529, "s": 444, "text": "Syntax: Series.asfreq(freq, method=None, how=None, normalize=False, fill_value=None)" }, { "code": null, "e": 781, "s": 529, "text": "Parameter :freq : DateOffset object, or stringmethod : {‘backfill’/’bfill’, ‘pad’/’ffill’}, default Nonehow : For PeriodIndex only, see PeriodIndex.asfreqnormalize : Whether to reset output index to midnightfill_value : Value to use for missing values" }, { "code": null, "e": 823, "s": 781, "text": "Returns : converted : same type as caller" }, { "code": null, "e": 916, "s": 823, "text": "Example #1: Use Series.asfreq() function to change the frequency of the given series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Indexindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='M') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 1193, "s": 916, "text": null }, { "code": null, "e": 1202, "s": 1193, "text": "Output :" }, { "code": null, "e": 1460, "s": 1202, "text": "2010-12-31 08:45:00 8\n2011-01-31 08:45:00 18\n2011-02-28 08:45:00 65\n2011-03-31 08:45:00 18\n2011-04-30 08:45:00 32\n2011-05-31 08:45:00 10\n2011-06-30 08:45:00 5\n2011-07-31 08:45:00 32\n2011-08-31 08:45:00 NaN\nFreq: M, dtype: float64" }, { "code": null, "e": 1566, "s": 1460, "text": "Now we will use Series.asfreq() function to change the frequency of the given series object to quarterly." }, { "code": "# change to quarterly frequencyresult = sr.asfreq(freq = 'Q') # Print the resultprint(result)", "e": 1661, "s": 1566, "text": null }, { "code": null, "e": 1670, "s": 1661, "text": "Output :" }, { "code": null, "e": 1776, "s": 1670, "text": "2010-12-31 08:45:00 8\n2011-03-31 08:45:00 18\n2011-06-30 08:45:00 5\nFreq: Q-DEC, dtype: float64" }, { "code": null, "e": 2028, "s": 1776, "text": "As we can see in the output, the Series.asfreq() function has successfully changed the frequency of the given series object. Example #2 : Use Series.asfreq() function to change the yearly frequency of the given series object to the batches of 3 years." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Index# apply yearly frequencyindex_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') # set the indexsr.index = index_ # Print the seriesprint(sr)", "e": 2329, "s": 2028, "text": null }, { "code": null, "e": 2338, "s": 2329, "text": "Output :" }, { "code": null, "e": 2674, "s": 2338, "text": "2010-12-31 08:45:00 11.0\n2011-12-31 08:45:00 21.0\n2012-12-31 08:45:00 8.0\n2013-12-31 08:45:00 18.0\n2014-12-31 08:45:00 65.0\n2015-12-31 08:45:00 18.0\n2016-12-31 08:45:00 32.0\n2017-12-31 08:45:00 10.0\n2018-12-31 08:45:00 5.0\n2019-12-31 08:45:00 32.0\n2020-12-31 08:45:00 NaN\nFreq: A-DEC, dtype: float64" }, { "code": null, "e": 2800, "s": 2674, "text": "Now we will use Series.asfreq() function to change the yearly frequency of the given series object to the batches of 3 years." }, { "code": "# apply year batch frequencyresult = sr.asfreq(freq = '3Y') # Print the resultprint(result)", "e": 2893, "s": 2800, "text": null }, { "code": null, "e": 2902, "s": 2893, "text": "Output :" }, { "code": null, "e": 3043, "s": 2902, "text": "2010-12-31 08:45:00 11.0\n2013-12-31 08:45:00 18.0\n2016-12-31 08:45:00 32.0\n2019-12-31 08:45:00 32.0\nFreq: 3A-DEC, dtype: float64" }, { "code": null, "e": 3168, "s": 3043, "text": "As we can see in the output, the Series.asfreq() function has successfully changed the frequency of the given series object." }, { "code": null, "e": 3189, "s": 3168, "text": "Python pandas-series" }, { "code": null, "e": 3218, "s": 3189, "text": "Python pandas-series-methods" }, { "code": null, "e": 3232, "s": 3218, "text": "Python-pandas" }, { "code": null, "e": 3239, "s": 3232, "text": "Python" } ]
Test Case Prioritization in Software Testing
11 Aug, 2020 As the name suggests, test case prioritization refers to prioritizing test cases in test suite on basis of different factors. Factors could be code coverage, risk/critical modules, functionality, features, etc. Why should test cases be prioritized?As the size of software increases, test suite also grows bigger and also requires more efforts to maintain test suite. In order to detect bugs in software as early as possible, it is important to prioritize test cases so that important test cases can be executed first. Types of Test Case Prioritization : General Prioritization :In this type of prioritization, test cases that will be useful for the subsequent modified versions of product are prioritized. It does not require any information regarding modifications made in the product. Version – Specific Prioritization :Test cases can also be prioritized such that they are useful on specific version of product. This type of prioritization requires knowledge about changes that have been introduced in product. Prioritization Techniques : 1. Coverage – based Test Case Prioritization :This type of prioritization is based on code coverage i.e. test cases are prioritized on basis of their code coverage. Total Statement Coverage Prioritization –In this technique, total number of statements covered by test case is used as factor to prioritize test cases. For example, test case covering 10 statements will be given higher priority than test case covering 5 statements. Additional Statement Coverage Prioritization –This technique involves iteratively selecting test case with maximum statement coverage, then selecting test case which covers statements that were left uncovered by previous test case. This process is repeated till all statements have been covered. Total Branch Coverage Prioritization –Using total branch coverage as factor for ordering test cases, prioritization can be achieved. Here, branch coverage refers to coverage of each possible outcome of condition. Additional Branch Coverage Prioritization –Similar to additional statement coverage technique, it first selects text case with maximum branch coverage and then iteratively selects test case which covers branch outcomes that were left uncovered by previous test case. Total Fault-Exposing-Potential Prioritization –Fault-exposing-potential (FEP) refers to ability of test case to expose fault. Statement and Branch Coverage Techniques do not take into account fact that some bugs can be more easily detected than others and also that some test cases have more potential to detect bugs than others. FEP depends on :Whether test cases cover faulty statements or not.Probability that faulty statement will cause test case to fail. Whether test cases cover faulty statements or not.Probability that faulty statement will cause test case to fail. Whether test cases cover faulty statements or not. Probability that faulty statement will cause test case to fail. 2. Risk – based Prioritization :This technique uses risk analysis to identify potential problem areas which if failed, could lead to bad consequences. Therefore, test cases are prioritized keeping in mind potential problem areas. In risk analysis, following steps are performed : List potential problems. Assigning probability of occurrence for each problem. Calculating severity of impact for each problem. After performing above steps, risk analysis table is formed to present results. The table consists of columns like Problem ID, Potential problem identified, Severity of Impact, Risk exposure, etc. 3. Prioritization using Relevant Slice :In this type of prioritization, slicing technique is used – when program is modified, all existing regression test cases are executed in order to make sure that program yields same result as before, except where it has been modified. For this purpose, we try to find part of program which has been affected by modification, and then prioritization of test cases is performed for this affected part. There are 3 parts to slicing technique : Execution slice –The statements executed under test case form execution slice. Dynamic slice –Statements executed under test case that might impact program output. Relevant Slice –Statements that are executed under test case and don’t have any impact on the program output but may impact output of test case. 4. Requirements – based Prioritization :Some requirements are more important than others or are more critical in nature, hence test cases for such requirements should be prioritized first. The following factors can be considered while prioritizing test cases based on requirements : Customer assigned priority –The customer assigns weight to requirements according to his need or understanding of requirements of product. Developer perceived implementation complexity –Priority is assigned by developer on basis of efforts or time that would be required to implement that requirement. Requirement volatility –This factor determines frequency of change of requirement. Fault proneness of requirements –Priority is assigned based on how error-prone requirement has been in previous versions of software. Metric for measuring Effectiveness of Prioritized Test Suite :For measuring how effective prioritized test suite is, we can use metric called APFD (Average Percentage of Faults Detected). The formula for APFD is given by : APFD = 1 - ( (TF1 + TF2 + ....... + TFm) / nm ) + 1 / 2n where, TFi = position of first Test case in Test suite T that exposes Fault i m = total number of Faults exposed under T n = total number of Test cases in T AFPD value can range from 0 to 100. The higher APFD value, faster faults detection rate. So simply put, APFD indicates of how quickly test suite can identify faults or bugs in software. If test suite can detect faults quickly, then it is considered to be more effective and reliable. Software Testing Computer Networks Software Engineering Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Types of Software Testing Differences between Black Box Testing vs White Box Testing Functional vs Non Functional Requirements Software Engineering | COCOMO Model Differences between Verification and Validation
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2020" }, { "code": null, "e": 263, "s": 52, "text": "As the name suggests, test case prioritization refers to prioritizing test cases in test suite on basis of different factors. Factors could be code coverage, risk/critical modules, functionality, features, etc." }, { "code": null, "e": 570, "s": 263, "text": "Why should test cases be prioritized?As the size of software increases, test suite also grows bigger and also requires more efforts to maintain test suite. In order to detect bugs in software as early as possible, it is important to prioritize test cases so that important test cases can be executed first." }, { "code": null, "e": 606, "s": 570, "text": "Types of Test Case Prioritization :" }, { "code": null, "e": 839, "s": 606, "text": "General Prioritization :In this type of prioritization, test cases that will be useful for the subsequent modified versions of product are prioritized. It does not require any information regarding modifications made in the product." }, { "code": null, "e": 1066, "s": 839, "text": "Version – Specific Prioritization :Test cases can also be prioritized such that they are useful on specific version of product. This type of prioritization requires knowledge about changes that have been introduced in product." }, { "code": null, "e": 1094, "s": 1066, "text": "Prioritization Techniques :" }, { "code": null, "e": 1259, "s": 1094, "text": "1. Coverage – based Test Case Prioritization :This type of prioritization is based on code coverage i.e. test cases are prioritized on basis of their code coverage." }, { "code": null, "e": 1525, "s": 1259, "text": "Total Statement Coverage Prioritization –In this technique, total number of statements covered by test case is used as factor to prioritize test cases. For example, test case covering 10 statements will be given higher priority than test case covering 5 statements." }, { "code": null, "e": 1821, "s": 1525, "text": "Additional Statement Coverage Prioritization –This technique involves iteratively selecting test case with maximum statement coverage, then selecting test case which covers statements that were left uncovered by previous test case. This process is repeated till all statements have been covered." }, { "code": null, "e": 2034, "s": 1821, "text": "Total Branch Coverage Prioritization –Using total branch coverage as factor for ordering test cases, prioritization can be achieved. Here, branch coverage refers to coverage of each possible outcome of condition." }, { "code": null, "e": 2301, "s": 2034, "text": "Additional Branch Coverage Prioritization –Similar to additional statement coverage technique, it first selects text case with maximum branch coverage and then iteratively selects test case which covers branch outcomes that were left uncovered by previous test case." }, { "code": null, "e": 2761, "s": 2301, "text": "Total Fault-Exposing-Potential Prioritization –Fault-exposing-potential (FEP) refers to ability of test case to expose fault. Statement and Branch Coverage Techniques do not take into account fact that some bugs can be more easily detected than others and also that some test cases have more potential to detect bugs than others. FEP depends on :Whether test cases cover faulty statements or not.Probability that faulty statement will cause test case to fail." }, { "code": null, "e": 2875, "s": 2761, "text": "Whether test cases cover faulty statements or not.Probability that faulty statement will cause test case to fail." }, { "code": null, "e": 2926, "s": 2875, "text": "Whether test cases cover faulty statements or not." }, { "code": null, "e": 2990, "s": 2926, "text": "Probability that faulty statement will cause test case to fail." }, { "code": null, "e": 3270, "s": 2990, "text": "2. Risk – based Prioritization :This technique uses risk analysis to identify potential problem areas which if failed, could lead to bad consequences. Therefore, test cases are prioritized keeping in mind potential problem areas. In risk analysis, following steps are performed :" }, { "code": null, "e": 3295, "s": 3270, "text": "List potential problems." }, { "code": null, "e": 3349, "s": 3295, "text": "Assigning probability of occurrence for each problem." }, { "code": null, "e": 3398, "s": 3349, "text": "Calculating severity of impact for each problem." }, { "code": null, "e": 3595, "s": 3398, "text": "After performing above steps, risk analysis table is formed to present results. The table consists of columns like Problem ID, Potential problem identified, Severity of Impact, Risk exposure, etc." }, { "code": null, "e": 4075, "s": 3595, "text": "3. Prioritization using Relevant Slice :In this type of prioritization, slicing technique is used – when program is modified, all existing regression test cases are executed in order to make sure that program yields same result as before, except where it has been modified. For this purpose, we try to find part of program which has been affected by modification, and then prioritization of test cases is performed for this affected part. There are 3 parts to slicing technique :" }, { "code": null, "e": 4154, "s": 4075, "text": "Execution slice –The statements executed under test case form execution slice." }, { "code": null, "e": 4239, "s": 4154, "text": "Dynamic slice –Statements executed under test case that might impact program output." }, { "code": null, "e": 4384, "s": 4239, "text": "Relevant Slice –Statements that are executed under test case and don’t have any impact on the program output but may impact output of test case." }, { "code": null, "e": 4667, "s": 4384, "text": "4. Requirements – based Prioritization :Some requirements are more important than others or are more critical in nature, hence test cases for such requirements should be prioritized first. The following factors can be considered while prioritizing test cases based on requirements :" }, { "code": null, "e": 4806, "s": 4667, "text": "Customer assigned priority –The customer assigns weight to requirements according to his need or understanding of requirements of product." }, { "code": null, "e": 4969, "s": 4806, "text": "Developer perceived implementation complexity –Priority is assigned by developer on basis of efforts or time that would be required to implement that requirement." }, { "code": null, "e": 5052, "s": 4969, "text": "Requirement volatility –This factor determines frequency of change of requirement." }, { "code": null, "e": 5186, "s": 5052, "text": "Fault proneness of requirements –Priority is assigned based on how error-prone requirement has been in previous versions of software." }, { "code": null, "e": 5409, "s": 5186, "text": "Metric for measuring Effectiveness of Prioritized Test Suite :For measuring how effective prioritized test suite is, we can use metric called APFD (Average Percentage of Faults Detected). The formula for APFD is given by :" }, { "code": null, "e": 5626, "s": 5409, "text": "APFD = 1 - ( (TF1 + TF2 + ....... + TFm) / nm ) + 1 / 2n\n\nwhere, \nTFi = position of first Test case in Test suite T that exposes Fault i\nm = total number of Faults exposed under T\nn = total number of Test cases in T " }, { "code": null, "e": 5910, "s": 5626, "text": "AFPD value can range from 0 to 100. The higher APFD value, faster faults detection rate. So simply put, APFD indicates of how quickly test suite can identify faults or bugs in software. If test suite can detect faults quickly, then it is considered to be more effective and reliable." }, { "code": null, "e": 5927, "s": 5910, "text": "Software Testing" }, { "code": null, "e": 5945, "s": 5927, "text": "Computer Networks" }, { "code": null, "e": 5966, "s": 5945, "text": "Software Engineering" }, { "code": null, "e": 5984, "s": 5966, "text": "Computer Networks" }, { "code": null, "e": 6082, "s": 5984, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6112, "s": 6082, "text": "Wireless Application Protocol" }, { "code": null, "e": 6142, "s": 6112, "text": "GSM in Wireless Communication" }, { "code": null, "e": 6168, "s": 6142, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 6208, "s": 6168, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 6243, "s": 6208, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 6269, "s": 6243, "text": "Types of Software Testing" }, { "code": null, "e": 6328, "s": 6269, "text": "Differences between Black Box Testing vs White Box Testing" }, { "code": null, "e": 6370, "s": 6328, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 6406, "s": 6370, "text": "Software Engineering | COCOMO Model" } ]
Stack of Pair in C++ STL with Examples
25 Mar, 2020 Stack in STL Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only. Pair in STL The pair container is a simple container defined in header consisting of two data elements or objects. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second). Stack of pair in STL: Stack of pair can be very efficient in designing complex data structures. Syntax: stack<pair<datatype, datatype>> stack_of_pair; Below is an example to show the Stack of Pairs: // CPP program to demonstrate// the working of STL stack of pairs #include <bits/stdc++.h>using namespace std; // Print the current pairvoid printPair(pair<int, int> p){ cout << "(" << p.first << ", " << p.second << ") ";} // Print the Stack of Pairsvoid Showstack(stack<pair<int, int> > s){ while (!s.empty()) { printPair(s.top()); s.pop(); } cout << '\n';} // Driver codeint main(){ stack<pair<int, int> > s; s.push({ 10, 20 }); s.push({ 15, 5 }); s.push({ 1, 5 }); s.push({ 5, 10 }); s.push({ 7, 9 }); cout << "Stack of Pairs: "; Showstack(s); cout << "\nSize of Stack of Pairs: " << s.size(); cout << "\nTop of Stack of Pairs: "; printPair(s.top()); cout << "\n\nRemoving the top pair\n"; s.pop(); cout << "Current Stack of Pairs: "; Showstack(s); return 0;} Stack of Pairs: (7, 9) (5, 10) (1, 5) (15, 5) (10, 20) Size of Stack of Pairs: 5 Top of Stack of Pairs: (7, 9) Removing the top pair Current Stack of Pairs: (5, 10) (1, 5) (15, 5) (10, 20) Below are the images to show the working of Stack of Pairs: cpp-pair STL C++ Programs Data Structures Stack Data Structures Stack STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ cout in C++ Program to implement Singly Linked List in C++ using class Dynamic _Cast in C++ DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews What is Hashing | A Complete Tutorial Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Mar, 2020" }, { "code": null, "e": 243, "s": 52, "text": "Stack in STL Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end and (top) an element is removed from that end only." }, { "code": null, "e": 476, "s": 243, "text": "Pair in STL The pair container is a simple container defined in header consisting of two data elements or objects. The first element is referenced as ‘first’ and the second element as ‘second’ and the order is fixed (first, second)." }, { "code": null, "e": 572, "s": 476, "text": "Stack of pair in STL: Stack of pair can be very efficient in designing complex data structures." }, { "code": null, "e": 580, "s": 572, "text": "Syntax:" }, { "code": null, "e": 628, "s": 580, "text": "stack<pair<datatype, datatype>> stack_of_pair;\n" }, { "code": null, "e": 676, "s": 628, "text": "Below is an example to show the Stack of Pairs:" }, { "code": "// CPP program to demonstrate// the working of STL stack of pairs #include <bits/stdc++.h>using namespace std; // Print the current pairvoid printPair(pair<int, int> p){ cout << \"(\" << p.first << \", \" << p.second << \") \";} // Print the Stack of Pairsvoid Showstack(stack<pair<int, int> > s){ while (!s.empty()) { printPair(s.top()); s.pop(); } cout << '\\n';} // Driver codeint main(){ stack<pair<int, int> > s; s.push({ 10, 20 }); s.push({ 15, 5 }); s.push({ 1, 5 }); s.push({ 5, 10 }); s.push({ 7, 9 }); cout << \"Stack of Pairs: \"; Showstack(s); cout << \"\\nSize of Stack of Pairs: \" << s.size(); cout << \"\\nTop of Stack of Pairs: \"; printPair(s.top()); cout << \"\\n\\nRemoving the top pair\\n\"; s.pop(); cout << \"Current Stack of Pairs: \"; Showstack(s); return 0;}", "e": 1557, "s": 676, "text": null }, { "code": null, "e": 1751, "s": 1557, "text": "Stack of Pairs: (7, 9) (5, 10) (1, 5) (15, 5) (10, 20) \n\nSize of Stack of Pairs: 5\nTop of Stack of Pairs: (7, 9) \n\nRemoving the top pair\nCurrent Stack of Pairs: (5, 10) (1, 5) (15, 5) (10, 20)\n" }, { "code": null, "e": 1811, "s": 1751, "text": "Below are the images to show the working of Stack of Pairs:" }, { "code": null, "e": 1820, "s": 1811, "text": "cpp-pair" }, { "code": null, "e": 1824, "s": 1820, "text": "STL" }, { "code": null, "e": 1837, "s": 1824, "text": "C++ Programs" }, { "code": null, "e": 1853, "s": 1837, "text": "Data Structures" }, { "code": null, "e": 1859, "s": 1853, "text": "Stack" }, { "code": null, "e": 1875, "s": 1859, "text": "Data Structures" }, { "code": null, "e": 1881, "s": 1875, "text": "Stack" }, { "code": null, "e": 1885, "s": 1881, "text": "STL" }, { "code": null, "e": 1983, "s": 1885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2024, "s": 1983, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 2045, "s": 2024, "text": "Const keyword in C++" }, { "code": null, "e": 2057, "s": 2045, "text": "cout in C++" }, { "code": null, "e": 2116, "s": 2057, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 2137, "s": 2116, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 2162, "s": 2137, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 2211, "s": 2162, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 2255, "s": 2211, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 2293, "s": 2255, "text": "What is Hashing | A Complete Tutorial" } ]
Optional get() method in Java with examples
30 Jul, 2019 The get() method of java.util.Optional class in Java is used to get the value of this Optional instance. If there is no value present in this Optional instance, then this method throws NullPointerException. Syntax: public T get() Parameters: This method do not accept any parameter. Return value: This method returns the value of this instance of the Optional class. Exception: This method throws NoSuchElementExcpetion if there is no value present in this Optional instance. Below programs illustrate get() method:Program 1: // Java program to demonstrate// Optional.get() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println("Optional: " + op); // get the value System.out.println("Value of this Optional: " + op.get()); }} Optional: Optional[9455] Value of this Optional: 9455 Program 2: // Java program to demonstrate// Optional.get() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // get the value System.out.println("Value of " + "this Optional: " + op.get()); } catch (Exception e) { System.out.println(e); } }} Optional: Optional.empty java.util.NoSuchElementException: No value present Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#get– Java - util package Java-Functions Java-Optional Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jul, 2019" }, { "code": null, "e": 235, "s": 28, "text": "The get() method of java.util.Optional class in Java is used to get the value of this Optional instance. If there is no value present in this Optional instance, then this method throws NullPointerException." }, { "code": null, "e": 243, "s": 235, "text": "Syntax:" }, { "code": null, "e": 259, "s": 243, "text": "public T get()\n" }, { "code": null, "e": 312, "s": 259, "text": "Parameters: This method do not accept any parameter." }, { "code": null, "e": 396, "s": 312, "text": "Return value: This method returns the value of this instance of the Optional class." }, { "code": null, "e": 505, "s": 396, "text": "Exception: This method throws NoSuchElementExcpetion if there is no value present in this Optional instance." }, { "code": null, "e": 555, "s": 505, "text": "Below programs illustrate get() method:Program 1:" }, { "code": "// Java program to demonstrate// Optional.get() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println(\"Optional: \" + op); // get the value System.out.println(\"Value of this Optional: \" + op.get()); }}", "e": 1010, "s": 555, "text": null }, { "code": null, "e": 1065, "s": 1010, "text": "Optional: Optional[9455]\nValue of this Optional: 9455\n" }, { "code": null, "e": 1076, "s": 1065, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Optional.get() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println(\"Optional: \" + op); try { // get the value System.out.println(\"Value of \" + \"this Optional: \" + op.get()); } catch (Exception e) { System.out.println(e); } }}", "e": 1673, "s": 1076, "text": null }, { "code": null, "e": 1750, "s": 1673, "text": "Optional: Optional.empty\njava.util.NoSuchElementException: No value present\n" }, { "code": null, "e": 1832, "s": 1750, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#get–" }, { "code": null, "e": 1852, "s": 1832, "text": "Java - util package" }, { "code": null, "e": 1867, "s": 1852, "text": "Java-Functions" }, { "code": null, "e": 1881, "s": 1867, "text": "Java-Optional" }, { "code": null, "e": 1886, "s": 1881, "text": "Java" }, { "code": null, "e": 1891, "s": 1886, "text": "Java" }, { "code": null, "e": 1989, "s": 1891, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2040, "s": 1989, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2071, "s": 2040, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2090, "s": 2071, "text": "Interfaces in Java" }, { "code": null, "e": 2120, "s": 2090, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2138, "s": 2120, "text": "ArrayList in Java" }, { "code": null, "e": 2153, "s": 2138, "text": "Stream In Java" }, { "code": null, "e": 2173, "s": 2153, "text": "Collections in Java" }, { "code": null, "e": 2205, "s": 2173, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2229, "s": 2205, "text": "Singleton Class in Java" } ]
How to generate a drop down list of timezone using PHP ?
11 Oct, 2019 The timezone_identifiers_list() function is used to generate a dropdown list of timezone with PHP. This function is used to return an indexed array containing all the timezone identifiers. The datetimezone object is sent as a parameter to the timezone_identifiers_list() function and it returns an indexed array on success or False on failure. This function is an alias of DateTimeZone::listIdentifiers() function.The timezone_identifiers_list() function uses its timezone constants and country to display a list of timezone independently.Such that the possible values for timezone constants are: 1 = AFRICA | 2 = AMERICA | 4 = ANTARCTICA | 8 = ARCTIC | 16 = ASIA | 32 = ATLANTIC | 64 = AUSTRALIA | 128 = EUROPE | 256 = INDIAN | 512 = PACIFIC | 1024 = UTC | 2047 = ALL | 4095 = ALL_WITH_BC | 4096 = PER_COUNTRY Syntax: array timezone_identifiers_list( int $datetimezone, string $country ) Example 1: This example illustrates how to select the timezone listed in dropdown using timezone identifiers. <?php function select_Timezone($selected = '') { // Create a list of timezone $OptionsArray = timezone_identifiers_list(); $select= '<select name="SelectContacts"> <option disabled selected> Please Select Timezone </option>'; while (list ($key, $row) = each ($OptionsArray) ){ $select .='<option value="'.$key.'"'; $select .= ($key == $selected ? : ''); $select .= '>'.$row.'</option>'; } $select.='</select>'; return $select;} echo select_Timezone() . '<br>'; ?> Output: Example 2: This example illustrates how to select the timezone listed in dropdown using timezone identifiers. <?php // Create a timezone identifiers$timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL); echo "<select>"; echo "<option disabled selected> Please Select Timezone </option>"; $n = 425;for($i = 0; $i < $n; $i++) { // Print the timezone identifiers echo "<option value='" . $timezone_identifiers[$i] . "'>" . $timezone_identifiers[$i] . "</option>";} echo "</select>"; ?> Output: Example 3: This example illustrates the dropdown with list of TimeZone using DateTimeZone::listIdentifiers (DateTimeZone::ALL) along with range() function. <?php $timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL); $Africa = range(0, 51);$America = range(52, 198);$Asia = range(211, 292);$tz_stamp = time(); echo "<center><select style='padding:20px; font-family: Courier New, Courier, monospace; width: 450px;border:2px solid #a09; outline: none;'>"; echo "<option style='color:#FFF;font-family:Cambria; background-color:#a09;'><h3>Africa</h3> </option>"; foreach($Africa as $x) { $tzone[$x] = date_default_timezone_set( $timezone_identifiers[$x]); echo "<option>" . $timezone_identifiers[$x] . ' @ ' . date('P', $tz_stamp);"</option>";} echo "<option style='color:#FFF;font-family:Cambria; background-color:#a09;font-size:15px;'> <h3>America</h3></option>"; foreach($America as $x) { $tzone[$x] = date_default_timezone_set( $timezone_identifiers[$x]); echo "<option>" . $timezone_identifiers[$x] . ' @ ' . date('P', $tz_stamp);"</option>";} echo "<option style='color:#FFF;font-family:Cambria; background-color:#a09;font-size:15px;'> <h3>Asia</h3></option>"; foreach($Asia as $x) { $tzone[$x] = date_default_timezone_set( $timezone_identifiers[$x]); echo "<option>" . $timezone_identifiers[$x] . ' @ ' . date('P', $tz_stamp);"</option>";} echo "</select></center>";?> Output: Reference: https://www.php.net/manual/en/function.timezone-identifiers-list.php Picked PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 625, "s": 28, "text": "The timezone_identifiers_list() function is used to generate a dropdown list of timezone with PHP. This function is used to return an indexed array containing all the timezone identifiers. The datetimezone object is sent as a parameter to the timezone_identifiers_list() function and it returns an indexed array on success or False on failure. This function is an alias of DateTimeZone::listIdentifiers() function.The timezone_identifiers_list() function uses its timezone constants and country to display a list of timezone independently.Such that the possible values for timezone constants are:" }, { "code": null, "e": 839, "s": 625, "text": "1 = AFRICA | 2 = AMERICA | 4 = ANTARCTICA | 8 = ARCTIC | 16 = ASIA | 32 = ATLANTIC | 64 = AUSTRALIA | 128 = EUROPE | 256 = INDIAN | 512 = PACIFIC | 1024 = UTC | 2047 = ALL | 4095 = ALL_WITH_BC | 4096 = PER_COUNTRY" }, { "code": null, "e": 847, "s": 839, "text": "Syntax:" }, { "code": null, "e": 917, "s": 847, "text": "array timezone_identifiers_list( int $datetimezone, string $country )" }, { "code": null, "e": 1027, "s": 917, "text": "Example 1: This example illustrates how to select the timezone listed in dropdown using timezone identifiers." }, { "code": "<?php function select_Timezone($selected = '') { // Create a list of timezone $OptionsArray = timezone_identifiers_list(); $select= '<select name=\"SelectContacts\"> <option disabled selected> Please Select Timezone </option>'; while (list ($key, $row) = each ($OptionsArray) ){ $select .='<option value=\"'.$key.'\"'; $select .= ($key == $selected ? : ''); $select .= '>'.$row.'</option>'; } $select.='</select>'; return $select;} echo select_Timezone() . '<br>'; ?>", "e": 1648, "s": 1027, "text": null }, { "code": null, "e": 1656, "s": 1648, "text": "Output:" }, { "code": null, "e": 1766, "s": 1656, "text": "Example 2: This example illustrates how to select the timezone listed in dropdown using timezone identifiers." }, { "code": "<?php // Create a timezone identifiers$timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL); echo \"<select>\"; echo \"<option disabled selected> Please Select Timezone </option>\"; $n = 425;for($i = 0; $i < $n; $i++) { // Print the timezone identifiers echo \"<option value='\" . $timezone_identifiers[$i] . \"'>\" . $timezone_identifiers[$i] . \"</option>\";} echo \"</select>\"; ?>", "e": 2201, "s": 1766, "text": null }, { "code": null, "e": 2209, "s": 2201, "text": "Output:" }, { "code": null, "e": 2365, "s": 2209, "text": "Example 3: This example illustrates the dropdown with list of TimeZone using DateTimeZone::listIdentifiers (DateTimeZone::ALL) along with range() function." }, { "code": "<?php $timezone_identifiers = DateTimeZone::listIdentifiers(DateTimeZone::ALL); $Africa = range(0, 51);$America = range(52, 198);$Asia = range(211, 292);$tz_stamp = time(); echo \"<center><select style='padding:20px; font-family: Courier New, Courier, monospace; width: 450px;border:2px solid #a09; outline: none;'>\"; echo \"<option style='color:#FFF;font-family:Cambria; background-color:#a09;'><h3>Africa</h3> </option>\"; foreach($Africa as $x) { $tzone[$x] = date_default_timezone_set( $timezone_identifiers[$x]); echo \"<option>\" . $timezone_identifiers[$x] . ' @ ' . date('P', $tz_stamp);\"</option>\";} echo \"<option style='color:#FFF;font-family:Cambria; background-color:#a09;font-size:15px;'> <h3>America</h3></option>\"; foreach($America as $x) { $tzone[$x] = date_default_timezone_set( $timezone_identifiers[$x]); echo \"<option>\" . $timezone_identifiers[$x] . ' @ ' . date('P', $tz_stamp);\"</option>\";} echo \"<option style='color:#FFF;font-family:Cambria; background-color:#a09;font-size:15px;'> <h3>Asia</h3></option>\"; foreach($Asia as $x) { $tzone[$x] = date_default_timezone_set( $timezone_identifiers[$x]); echo \"<option>\" . $timezone_identifiers[$x] . ' @ ' . date('P', $tz_stamp);\"</option>\";} echo \"</select></center>\";?>", "e": 3814, "s": 2365, "text": null }, { "code": null, "e": 3822, "s": 3814, "text": "Output:" }, { "code": null, "e": 3902, "s": 3822, "text": "Reference: https://www.php.net/manual/en/function.timezone-identifiers-list.php" }, { "code": null, "e": 3909, "s": 3902, "text": "Picked" }, { "code": null, "e": 3913, "s": 3909, "text": "PHP" }, { "code": null, "e": 3930, "s": 3913, "text": "Web Technologies" }, { "code": null, "e": 3957, "s": 3930, "text": "Web technologies Questions" }, { "code": null, "e": 3961, "s": 3957, "text": "PHP" }, { "code": null, "e": 4059, "s": 3961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4109, "s": 4059, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 4149, "s": 4109, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 4210, "s": 4149, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4260, "s": 4210, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 4305, "s": 4260, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 4338, "s": 4305, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4400, "s": 4338, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4461, "s": 4400, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4511, "s": 4461, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sorting without comparison of elements
06 May, 2021 Given an array with integer elements in small range, sort the array. We need to write a non-comparison based sorting algorithm with following assumptions about input. All the entries in the array are integers.The difference between the maximum value and the minimum value in the array is less than or equal to 10^6. All the entries in the array are integers. The difference between the maximum value and the minimum value in the array is less than or equal to 10^6. Input : arr[] = {10, 30, 20, 4} Output : 4 10 20 30 Input : arr[] = {10, 30, 1, 20, 4} Output : 1 4 10 20 30 We are not allowed to use comparison based sorting algorithms like QuickSort, MergeSort, etc.Since elements are small, we use array elements as index. We store element counts in a count array. Once we have count array, we traverse the count array and print every present element its count times. C++ Java Python3 C# Javascript // C++ program to sort an array without comparison// operator.#include <bits/stdc++.h>using namespace std; int sortArr(int arr[], int n, int min, int max){ // Count of elements in given range int m = max - min + 1; // Count frequencies of all elements vector<int> c(m, 0); for (int i=0; i<n; i++) c[arr[i] - min]++; // Traverse through range. For every // element, print it its count times. for (int i=0; i<m; i++) for (int j=0; j < c[i]; j++) cout << (i + min) << " ";} // Driver Codeint main(){ int arr[] = {10, 10, 1, 4, 4, 100, 0}; int min = 0, max = 100; int n = sizeof(arr)/sizeof(arr[0]); sortArr(arr, n, min, max); return 0;} // Java program to sort an array without comparison// operator.import java.util.*; // Represents node of a doubly linked listclass Node{ static void sortArr(int arr[], int n, int min, int max) { // Count of elements in given range int m = max - min + 1; // Count frequencies of all elements int[] c = new int[m]; for (int i = 0; i < n; i++) { c[arr[i] - min]++; } // Traverse through range. For every // element, print it its count times. for (int i = 0; i < m; i++) { for (int j = 0; j < c[i]; j++) { System.out.print((i + min) + " "); } } } // Driver Code public static void main(String[] args) { int arr[] = {10, 10, 1, 4, 4, 100, 0}; int min = 0, max = 100; int n = arr.length; sortArr(arr, n, min, max); }} // This code is contributed by Princi Singh # Python3 program to sort an array without comparison# operator. def sortArr(arr, n, min_no, max_no): # Count of elements in given range m = max_no - min_no + 1 # Count frequencies of all elements c = [0] * m for i in range(n): c[arr[i] - min_no] += 1 # Traverse through range. For every # element, print it its count times. for i in range(m): for j in range((c[i])): print((i + min_no), end=" ") # Driver Codearr = [10, 10, 1, 4, 4, 100, 0]min_no,max_no = 0,100n = len(arr)sortArr(arr, n, min_no, max_no) # This code is contributed by Rajput-Ji# Improved by Rutvik J // C# program to sort an array// without comparison operator.using System; class GFG{ // Represents node of a doubly linked list static void sortArr(int []arr, int n, int min, int max) { // Count of elements in given range int m = max - min + 1; // Count frequencies of all elements int[] c = new int[m]; for (int i = 0; i < n; i++) { c[arr[i] - min]++; } // Traverse through range. For every // element, print it its count times. for (int i = 0; i < m; i++) { for (int j = 0; j < c[i]; j++) { Console.Write((i + min) + " "); } } } // Driver Code static public void Main () { int []arr = {10, 10, 1, 4, 4, 100, 0}; int min = 0, max = 100; int n = arr.Length; sortArr(arr, n, min, max); }} // This code is contributed by ajit. <script> // Javascript program to sort an array // without comparison operator. // Represents node of a doubly linked list function sortArr(arr, n, min, max) { // Count of elements in given range let m = max - min + 1; // Count frequencies of all elements let c = new Array(m); c.fill(0); for (let i = 0; i < n; i++) { c[arr[i] - min]++; } // Traverse through range. For every // element, print it its count times. for (let i = 0; i < m; i++) { for (let j = 0; j < c[i]; j++) { document.write((i + min) + " "); } } } let arr = [10, 10, 1, 4, 4, 100, 0]; let min = 0, max = 100; let n = arr.length; sortArr(arr, n, min, max); </script> 0 1 4 4 10 10 100 What is time complexity? Time complexity of above algorithm is O(n + (max-min)) Is above algorithm stable? The above implementation is not stable as we do not care about order of same elements while sorting. How to make above algorithm stable? The stable version of above algorithm is called Counting Sort. In counting sort, we store sums of all smaller or equal values in c[i] so that c[i] store actual position of i in sorted array. After filling c[], we traverse input array again, place every element at its position and decrement count. What are non-comparison based standard algorithms? Counting Sort, Radix Sort and Bucket Sort. princi singh jit_t Rajput-Ji nidhi_biet yashkhorja4 orion77 tanmaymishra2 divyeshrabadiya07 counting-sort frequency-counting Analysis Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 May, 2021" }, { "code": null, "e": 220, "s": 52, "text": "Given an array with integer elements in small range, sort the array. We need to write a non-comparison based sorting algorithm with following assumptions about input. " }, { "code": null, "e": 369, "s": 220, "text": "All the entries in the array are integers.The difference between the maximum value and the minimum value in the array is less than or equal to 10^6." }, { "code": null, "e": 412, "s": 369, "text": "All the entries in the array are integers." }, { "code": null, "e": 519, "s": 412, "text": "The difference between the maximum value and the minimum value in the array is less than or equal to 10^6." }, { "code": null, "e": 629, "s": 519, "text": "Input : arr[] = {10, 30, 20, 4}\nOutput : 4 10 20 30\n\nInput : arr[] = {10, 30, 1, 20, 4}\nOutput : 1 4 10 20 30" }, { "code": null, "e": 927, "s": 629, "text": "We are not allowed to use comparison based sorting algorithms like QuickSort, MergeSort, etc.Since elements are small, we use array elements as index. We store element counts in a count array. Once we have count array, we traverse the count array and print every present element its count times. " }, { "code": null, "e": 931, "s": 927, "text": "C++" }, { "code": null, "e": 936, "s": 931, "text": "Java" }, { "code": null, "e": 944, "s": 936, "text": "Python3" }, { "code": null, "e": 947, "s": 944, "text": "C#" }, { "code": null, "e": 958, "s": 947, "text": "Javascript" }, { "code": "// C++ program to sort an array without comparison// operator.#include <bits/stdc++.h>using namespace std; int sortArr(int arr[], int n, int min, int max){ // Count of elements in given range int m = max - min + 1; // Count frequencies of all elements vector<int> c(m, 0); for (int i=0; i<n; i++) c[arr[i] - min]++; // Traverse through range. For every // element, print it its count times. for (int i=0; i<m; i++) for (int j=0; j < c[i]; j++) cout << (i + min) << \" \";} // Driver Codeint main(){ int arr[] = {10, 10, 1, 4, 4, 100, 0}; int min = 0, max = 100; int n = sizeof(arr)/sizeof(arr[0]); sortArr(arr, n, min, max); return 0;}", "e": 1661, "s": 958, "text": null }, { "code": "// Java program to sort an array without comparison// operator.import java.util.*; // Represents node of a doubly linked listclass Node{ static void sortArr(int arr[], int n, int min, int max) { // Count of elements in given range int m = max - min + 1; // Count frequencies of all elements int[] c = new int[m]; for (int i = 0; i < n; i++) { c[arr[i] - min]++; } // Traverse through range. For every // element, print it its count times. for (int i = 0; i < m; i++) { for (int j = 0; j < c[i]; j++) { System.out.print((i + min) + \" \"); } } } // Driver Code public static void main(String[] args) { int arr[] = {10, 10, 1, 4, 4, 100, 0}; int min = 0, max = 100; int n = arr.length; sortArr(arr, n, min, max); }} // This code is contributed by Princi Singh", "e": 2615, "s": 1661, "text": null }, { "code": "# Python3 program to sort an array without comparison# operator. def sortArr(arr, n, min_no, max_no): # Count of elements in given range m = max_no - min_no + 1 # Count frequencies of all elements c = [0] * m for i in range(n): c[arr[i] - min_no] += 1 # Traverse through range. For every # element, print it its count times. for i in range(m): for j in range((c[i])): print((i + min_no), end=\" \") # Driver Codearr = [10, 10, 1, 4, 4, 100, 0]min_no,max_no = 0,100n = len(arr)sortArr(arr, n, min_no, max_no) # This code is contributed by Rajput-Ji# Improved by Rutvik J", "e": 3238, "s": 2615, "text": null }, { "code": "// C# program to sort an array// without comparison operator.using System; class GFG{ // Represents node of a doubly linked list static void sortArr(int []arr, int n, int min, int max) { // Count of elements in given range int m = max - min + 1; // Count frequencies of all elements int[] c = new int[m]; for (int i = 0; i < n; i++) { c[arr[i] - min]++; } // Traverse through range. For every // element, print it its count times. for (int i = 0; i < m; i++) { for (int j = 0; j < c[i]; j++) { Console.Write((i + min) + \" \"); } } } // Driver Code static public void Main () { int []arr = {10, 10, 1, 4, 4, 100, 0}; int min = 0, max = 100; int n = arr.Length; sortArr(arr, n, min, max); }} // This code is contributed by ajit.", "e": 4190, "s": 3238, "text": null }, { "code": "<script> // Javascript program to sort an array // without comparison operator. // Represents node of a doubly linked list function sortArr(arr, n, min, max) { // Count of elements in given range let m = max - min + 1; // Count frequencies of all elements let c = new Array(m); c.fill(0); for (let i = 0; i < n; i++) { c[arr[i] - min]++; } // Traverse through range. For every // element, print it its count times. for (let i = 0; i < m; i++) { for (let j = 0; j < c[i]; j++) { document.write((i + min) + \" \"); } } } let arr = [10, 10, 1, 4, 4, 100, 0]; let min = 0, max = 100; let n = arr.length; sortArr(arr, n, min, max); </script>", "e": 5024, "s": 4190, "text": null }, { "code": null, "e": 5042, "s": 5024, "text": "0 1 4 4 10 10 100" }, { "code": null, "e": 5122, "s": 5042, "text": "What is time complexity? Time complexity of above algorithm is O(n + (max-min))" }, { "code": null, "e": 5250, "s": 5122, "text": "Is above algorithm stable? The above implementation is not stable as we do not care about order of same elements while sorting." }, { "code": null, "e": 5584, "s": 5250, "text": "How to make above algorithm stable? The stable version of above algorithm is called Counting Sort. In counting sort, we store sums of all smaller or equal values in c[i] so that c[i] store actual position of i in sorted array. After filling c[], we traverse input array again, place every element at its position and decrement count." }, { "code": null, "e": 5678, "s": 5584, "text": "What are non-comparison based standard algorithms? Counting Sort, Radix Sort and Bucket Sort." }, { "code": null, "e": 5691, "s": 5678, "text": "princi singh" }, { "code": null, "e": 5697, "s": 5691, "text": "jit_t" }, { "code": null, "e": 5707, "s": 5697, "text": "Rajput-Ji" }, { "code": null, "e": 5718, "s": 5707, "text": "nidhi_biet" }, { "code": null, "e": 5730, "s": 5718, "text": "yashkhorja4" }, { "code": null, "e": 5738, "s": 5730, "text": "orion77" }, { "code": null, "e": 5752, "s": 5738, "text": "tanmaymishra2" }, { "code": null, "e": 5770, "s": 5752, "text": "divyeshrabadiya07" }, { "code": null, "e": 5784, "s": 5770, "text": "counting-sort" }, { "code": null, "e": 5803, "s": 5784, "text": "frequency-counting" }, { "code": null, "e": 5812, "s": 5803, "text": "Analysis" }, { "code": null, "e": 5820, "s": 5812, "text": "Sorting" }, { "code": null, "e": 5828, "s": 5820, "text": "Sorting" } ]
What are the various timing features of Node.js ?
20 May, 2020 The timer modules in Node.js consists of functions that help to control the timings of code execution. It includes setTimeout(), setImmediate(), and setInterval() methods. 1. setTimeout() Method: The setTimeout() method is used to schedule code execution after a designated amount of milliseconds. The specified function will be executed once. We can use the clearTimeout() method to prevent the function from running. The setTimeout() method returns the ID that can be used in clearTimeout() method. Syntax: setTimeout(callback, delay, args ) Parameters: callback: This parameter holds the function that to be executed. delay: This parameter holds the number of milliseconds to wait before calling the callback function. args: This parameter holds the optional parameter. Example: let str = 'GeeksforGeeks!'; setTimeout(function () { return console.log(str);}, 5000); // This console log is executed right awayconsole.log('Executing setTimeout() method'); Output: Executing setTimeout() method GeeksforGeeks! Notice that the console is executing first. The trick to realizing is that the code is only guaranteed to execute after at least that length of time has passed. 2. setImmediate() Method: The setImmediate() method is used to execute code at the end of the current event loop cycle. Any function passed as the setImmediate() argument is a callback that can be executed in the next iteration of the event loop. Syntax: setImmediate(callback, args) Parameters: callback: This parameter holds the function to call at the end of this turn of the Node.js Event Loop. args: This parameter holds the optional arguments for the function. Example: setTimeout(function () { console.log('setTimeout() function running');}, 5000); // An intervalsetInterval(function () { console.log('setInterval() function running');}, 5000); // An immediate, its callback will be // executed before those defined abovesetImmediate(function () { console.log('setImmediate() function running');}); // IO callbacks and code in the normal// event loop runs before the timersconsole.log('Simple statement in the event loop'); Output: Simple statement in the event loop setImmediate() function running setTimeout() function running setInterval() function running setInterval() function running setInterval() function running setInterval() function running . . . Notice, how even though setImmediate function is defined after setTimeout and setInterval functions, it runs ahead of them. 3. setInterval() Method: The setInterval() method is used to call a function at specified intervals (in milliseconds). It is used to execute the function only once after a specified period.We can use the clearInterval() method to prevent the function from running. The setInterval() method returns the ID which can be used in clearInterval() method. Syntax: setInterval(callback, delay, args) Parameters: callback: This parameter holds the function that to be called when the timer elapse. delay: This parameter holds the number of milliseconds to wait before calling the vallback function. args: This parameter holds the optional arguments for the function. Example: setInterval(function() { console.log('Welcome to GeeksforGeeks');}, 5000); Output: Welcome to GeeksforGeeks Welcome to GeeksforGeeks ..... It will print output multiple times with a time interval of 5 seconds. Node.js-Misc Picked Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 54, "s": 26, "text": "\n20 May, 2020" }, { "code": null, "e": 226, "s": 54, "text": "The timer modules in Node.js consists of functions that help to control the timings of code execution. It includes setTimeout(), setImmediate(), and setInterval() methods." }, { "code": null, "e": 555, "s": 226, "text": "1. setTimeout() Method: The setTimeout() method is used to schedule code execution after a designated amount of milliseconds. The specified function will be executed once. We can use the clearTimeout() method to prevent the function from running. The setTimeout() method returns the ID that can be used in clearTimeout() method." }, { "code": null, "e": 563, "s": 555, "text": "Syntax:" }, { "code": null, "e": 598, "s": 563, "text": "setTimeout(callback, delay, args )" }, { "code": null, "e": 610, "s": 598, "text": "Parameters:" }, { "code": null, "e": 675, "s": 610, "text": "callback: This parameter holds the function that to be executed." }, { "code": null, "e": 776, "s": 675, "text": "delay: This parameter holds the number of milliseconds to wait before calling the callback function." }, { "code": null, "e": 827, "s": 776, "text": "args: This parameter holds the optional parameter." }, { "code": null, "e": 836, "s": 827, "text": "Example:" }, { "code": "let str = 'GeeksforGeeks!'; setTimeout(function () { return console.log(str);}, 5000); // This console log is executed right awayconsole.log('Executing setTimeout() method');", "e": 1016, "s": 836, "text": null }, { "code": null, "e": 1024, "s": 1016, "text": "Output:" }, { "code": null, "e": 1069, "s": 1024, "text": "Executing setTimeout() method\nGeeksforGeeks!" }, { "code": null, "e": 1230, "s": 1069, "text": "Notice that the console is executing first. The trick to realizing is that the code is only guaranteed to execute after at least that length of time has passed." }, { "code": null, "e": 1477, "s": 1230, "text": "2. setImmediate() Method: The setImmediate() method is used to execute code at the end of the current event loop cycle. Any function passed as the setImmediate() argument is a callback that can be executed in the next iteration of the event loop." }, { "code": null, "e": 1485, "s": 1477, "text": "Syntax:" }, { "code": null, "e": 1514, "s": 1485, "text": "setImmediate(callback, args)" }, { "code": null, "e": 1526, "s": 1514, "text": "Parameters:" }, { "code": null, "e": 1629, "s": 1526, "text": "callback: This parameter holds the function to call at the end of this turn of the Node.js Event Loop." }, { "code": null, "e": 1697, "s": 1629, "text": "args: This parameter holds the optional arguments for the function." }, { "code": null, "e": 1706, "s": 1697, "text": "Example:" }, { "code": "setTimeout(function () { console.log('setTimeout() function running');}, 5000); // An intervalsetInterval(function () { console.log('setInterval() function running');}, 5000); // An immediate, its callback will be // executed before those defined abovesetImmediate(function () { console.log('setImmediate() function running');}); // IO callbacks and code in the normal// event loop runs before the timersconsole.log('Simple statement in the event loop');", "e": 2173, "s": 1706, "text": null }, { "code": null, "e": 2181, "s": 2173, "text": "Output:" }, { "code": null, "e": 2408, "s": 2181, "text": "Simple statement in the event loop\nsetImmediate() function running\nsetTimeout() function running\nsetInterval() function running\nsetInterval() function running\nsetInterval() function running\nsetInterval() function running\n. . ." }, { "code": null, "e": 2532, "s": 2408, "text": "Notice, how even though setImmediate function is defined after setTimeout and setInterval functions, it runs ahead of them." }, { "code": null, "e": 2882, "s": 2532, "text": "3. setInterval() Method: The setInterval() method is used to call a function at specified intervals (in milliseconds). It is used to execute the function only once after a specified period.We can use the clearInterval() method to prevent the function from running. The setInterval() method returns the ID which can be used in clearInterval() method." }, { "code": null, "e": 2890, "s": 2882, "text": "Syntax:" }, { "code": null, "e": 2925, "s": 2890, "text": "setInterval(callback, delay, args)" }, { "code": null, "e": 2937, "s": 2925, "text": "Parameters:" }, { "code": null, "e": 3022, "s": 2937, "text": "callback: This parameter holds the function that to be called when the timer elapse." }, { "code": null, "e": 3123, "s": 3022, "text": "delay: This parameter holds the number of milliseconds to wait before calling the vallback function." }, { "code": null, "e": 3191, "s": 3123, "text": "args: This parameter holds the optional arguments for the function." }, { "code": null, "e": 3200, "s": 3191, "text": "Example:" }, { "code": "setInterval(function() { console.log('Welcome to GeeksforGeeks');}, 5000);", "e": 3278, "s": 3200, "text": null }, { "code": null, "e": 3286, "s": 3278, "text": "Output:" }, { "code": null, "e": 3342, "s": 3286, "text": "Welcome to GeeksforGeeks\nWelcome to GeeksforGeeks\n....." }, { "code": null, "e": 3413, "s": 3342, "text": "It will print output multiple times with a time interval of 5 seconds." }, { "code": null, "e": 3426, "s": 3413, "text": "Node.js-Misc" }, { "code": null, "e": 3433, "s": 3426, "text": "Picked" }, { "code": null, "e": 3441, "s": 3433, "text": "Node.js" }, { "code": null, "e": 3458, "s": 3441, "text": "Web Technologies" }, { "code": null, "e": 3485, "s": 3458, "text": "Web technologies Questions" }, { "code": null, "e": 3501, "s": 3485, "text": "Write From Home" }, { "code": null, "e": 3599, "s": 3501, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3629, "s": 3599, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 3686, "s": 3629, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 3740, "s": 3686, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 3780, "s": 3740, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 3812, "s": 3780, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 3874, "s": 3812, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3935, "s": 3874, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3985, "s": 3935, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4028, "s": 3985, "text": "How to fetch data from an API in ReactJS ?" } ]
One bit memory cell (or Basic Bistable element)
22 Aug, 2019 One Bit memory cell is also called Basic Bistable element. It has two cross-coupled inverters, 2 outputs Q and Q’. It is called “Bistable” as the basic bistable element circuit has two stable states logic 0 and logic 1. The following diagram shows the Basic Bistable element: (A) when A=0, (i) In inverter1, Q = A'= B= 1 (ii)In inverter2, Q' = B' = A = 0 (B) when A=1, (i) In inverter1, Q = A'= B= 0 (ii)In inverter2, Q' = B' = A = 1 Some key points: The 2 outputs are always complementary.The circuit has 2 stable states. when Q=1, it is Set state. when Q=0, it is Reset state.The circuit can store 1-bit of digital information and so it is called one-bit memory cell.The one-bit information stored in the circuit is locked or latched in the circuit. This circuit is also called Latch. The 2 outputs are always complementary. The circuit has 2 stable states. when Q=1, it is Set state. when Q=0, it is Reset state. The circuit can store 1-bit of digital information and so it is called one-bit memory cell. The one-bit information stored in the circuit is locked or latched in the circuit. This circuit is also called Latch. One-bit six transistor SRAM memory cell is volatile. Fast switching speed is its main advantage. It needs a constant power supply because of its volatility. The demand for faster and denser memory devices has seen memristors being proposed as replacements for flash memory, Static Random Access Memory (SRAM) and Random Access Memory (RAM). The most salient feature of memristors is its resistive switching ability that can retain resistance states for long periods despite without power supply. The One-bit non-volatile memory cell can be designed using transmission gates and memristor. Memristive devices have high switching speed, low energy consumption, non-volatile and small device size. The non-volatility of memristor used in designs as the information storage element provides retention ability of up to 10 years in the absence of power supply. The transmission gates used ensures that voltage is not lost through other components of the memory cell, thus improves the switching speed by providing a larger potential difference across the memristor. Other advantages of using memristors in memory devices are its long retention period, excellent endurance properties, and good scalability compared to NAND-based flash memory devices. Reference:DIGITAL ELECTRONICS – Atul P. Godse, Mrs. Deepali A. GodseIEEE XPLORE, Digital library – One-bit non-volatile memory cell using memristor and transmission gates. Computer Organization & Architecture Digital Electronics & Logic Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n22 Aug, 2019" }, { "code": null, "e": 273, "s": 53, "text": "One Bit memory cell is also called Basic Bistable element. It has two cross-coupled inverters, 2 outputs Q and Q’. It is called “Bistable” as the basic bistable element circuit has two stable states logic 0 and logic 1." }, { "code": null, "e": 329, "s": 273, "text": "The following diagram shows the Basic Bistable element:" }, { "code": null, "e": 489, "s": 329, "text": "(A) when A=0,\n(i) In inverter1, Q = A'= B= 1\n(ii)In inverter2, Q' = B' = A = 0\n\n(B) when A=1,\n(i) In inverter1, Q = A'= B= 0\n(ii)In inverter2, Q' = B' = A = 1 " }, { "code": null, "e": 506, "s": 489, "text": "Some key points:" }, { "code": null, "e": 842, "s": 506, "text": "The 2 outputs are always complementary.The circuit has 2 stable states. when Q=1, it is Set state. when Q=0, it is Reset state.The circuit can store 1-bit of digital information and so it is called one-bit memory cell.The one-bit information stored in the circuit is locked or latched in the circuit. This circuit is also called Latch." }, { "code": null, "e": 882, "s": 842, "text": "The 2 outputs are always complementary." }, { "code": null, "e": 971, "s": 882, "text": "The circuit has 2 stable states. when Q=1, it is Set state. when Q=0, it is Reset state." }, { "code": null, "e": 1063, "s": 971, "text": "The circuit can store 1-bit of digital information and so it is called one-bit memory cell." }, { "code": null, "e": 1181, "s": 1063, "text": "The one-bit information stored in the circuit is locked or latched in the circuit. This circuit is also called Latch." }, { "code": null, "e": 1677, "s": 1181, "text": "One-bit six transistor SRAM memory cell is volatile. Fast switching speed is its main advantage. It needs a constant power supply because of its volatility. The demand for faster and denser memory devices has seen memristors being proposed as replacements for flash memory, Static Random Access Memory (SRAM) and Random Access Memory (RAM). The most salient feature of memristors is its resistive switching ability that can retain resistance states for long periods despite without power supply." }, { "code": null, "e": 2241, "s": 1677, "text": "The One-bit non-volatile memory cell can be designed using transmission gates and memristor. Memristive devices have high switching speed, low energy consumption, non-volatile and small device size. The non-volatility of memristor used in designs as the information storage element provides retention ability of up to 10 years in the absence of power supply. The transmission gates used ensures that voltage is not lost through other components of the memory cell, thus improves the switching speed by providing a larger potential difference across the memristor." }, { "code": null, "e": 2425, "s": 2241, "text": "Other advantages of using memristors in memory devices are its long retention period, excellent endurance properties, and good scalability compared to NAND-based flash memory devices." }, { "code": null, "e": 2597, "s": 2425, "text": "Reference:DIGITAL ELECTRONICS – Atul P. Godse, Mrs. Deepali A. GodseIEEE XPLORE, Digital library – One-bit non-volatile memory cell using memristor and transmission gates." }, { "code": null, "e": 2634, "s": 2597, "text": "Computer Organization & Architecture" }, { "code": null, "e": 2669, "s": 2634, "text": "Digital Electronics & Logic Design" } ]
Kotlin Inheritance
01 Oct, 2021 Inheritance is one of the more important features in object-oriented programming. Inheritance enables code re-usability, it allows all the features from an existing class(base class) to be inherited by a new class(derived class). In addition, the derived class can also add some features of its own. Syntax of inheritance: open class baseClass (x:Int ) { .......... } class derivedClass(x:Int) : baseClass(x) { ........... } In Kotlin, all classes are final by default. To permit the derived class to inherit from the base class, we must use the open keyword in front of the base class. Kotlin Inheriting property and methods from base class:When we inherit a class then all the properties and functions are also inherited. We can use the base class variables and functions in the derived class and can also call functions using the derived class object. Kotlin //base classopen class baseClass{ val name = "GeeksforGeeks" fun A(){ println("Base Class") }}//derived classclass derivedClass: baseClass() { fun B() { println(name) //inherit name property println("Derived class") }}fun main(args: Array<String>) { val derived = derivedClass() derived.A() // inheriting the base class function derived.B() // calling derived class function} Output: Base Class GeeksforGeeks Derived class Explanation: Here, we have a base class and a derived class. We create an object while instantiating the derived class, then it is used to invoke the base class and derived class functions. The derived.A() is used to call the function A() which prints “Base Class”. The derived.B() is used to call the function B() which prints the variable name inherited from the base class and also prints “Derived class”. Suppose there are three types of Employee in a company a webDeveloper , an iOSDeveloper and an androidDeveloper. All of them have some shared features like name, age and also have some special kind of skills. First, we create three-class individually and all employees have some common and specific skills. Here, all of them have some name and age but the development skill of all three developers are different. In each of the class, we would be copying the same code for name and age for each character. If we want to add a salary() feature then we need to copy the same code in all three classes. This creates a number of duplicate copies of code in our program, and it will likely lead to more complex and erratic code. By using inheritance, the task becomes easier. We can create a new base class Employee, which contains the common features of the 3 original classes. These three classes can then inherit common features from the base class and can add some special features of their own. We can easily add the salary feature without duplicate copies in the Employee class. Here, for webDeveloper, we inherit all the features from the base class and its own feature website() in the class. Similarly, we can do the same for the other two classes androidDeveloper and iosDeveloper. It makes our code more understandable and extendable. Kotlin program of inheritance – Kotlin //base classopen class Employee( name: String,age: Int,salary : Int) { init { println("My name is $name, $age years old and earning $salary per month. ") }}//derived classclass webDeveloper( name: String,age: Int,salary : Int): Employee(name, age,salary) { fun website() { println("I am website developer") println() }}//derived classclass androidDeveloper( name: String,age: Int,salary : Int): Employee(name, age,salary) { fun android() { println("I am android app developer") println() }}//derived classclass iosDeveloper( name: String,age: Int,salary : Int): Employee(name, age,salary) { fun iosapp() { println("I am iOS app developer") println() }}//main methodfun main(args: Array<String>) { val wd = webDeveloper("Gennady", 25, 10000) wd.website() val ad = androidDeveloper("Gaurav", 24,12000) ad.android() val iosd = iosDeveloper("Praveen", 26,15000) iosd.iosapp()} Output: My name is Gennady, 25 years old and earning 10000 per month. I am website developer My name is Gaurav, 24 years old and earning 12000 per month. I am android app developer My name is Praveen, 26 years old and earning 15000 per month. I am iOS app developer Explanation: Here, we have a base class Employee, prefixed with the open keyword, which contains the common properties of the derived classes. The Employee class, has a primary constructor with three variables ‘name, age and salary’. There are also three derived classes webDeveloper, androidDeveloper and iosDeveloper which also contain primary constructors and all of them having three variables.First, we instantiate an object for the webDeveloper class, and pass the name, age and salary as parameters to the derived class. It will initialize the local variables and pass these values to the base class. Then, we call the member function website() using the object ‘wd’ which prints the string to the standard output.Similarly, we create objects for the other two classes and invoke their respective member functions. If the derived class contains a primary constructor, then we need to initialize the base class constructor using the parameters of the derived class. In the below program, we have two parameters in primary constructor of base class and three parameters in derived class. Kotlin program – Kotlin //base classopen class Employee(name: String,age: Int) { init{ println("Name of the Employee is $name") println("Age of the Employee is $age") }}// derived classclass CEO( name: String, age: Int, salary: Double): Employee(name,age) { init { println("Salary per annum is $salary crore rupees") }}fun main(args: Array<String>) { CEO("Sunder Pichai", 42, 450.00)} Output: Name of the Employee is Sunder Pichai Age of the Employee is 42 Salary per annum is 450.0 crore rupees Explanation: Here, we instantiate the derived class CEO and passed the parameter values name, age and salary. The derived class local variables initialize with the respective values and pass the variable name and age as parameters to the Employee class. The employee class prints the variable’s names and values to the standard output and transfers the control back to the derived class. Then, the derived class executes the println() statement and exits. If the derived class does not contain a primary constructor, we need to call the base class secondary constructor from the secondary constructor of derived class using the super keyword. We also need to initialize the base class secondary constructor using the parameters of the derived class. Kotlin program: Kotlin //base classopen class Employee { constructor(name: String,age: Int){ println("Name of the Employee is $name") println("Age of the Employee is $age") }}// derived classclass CEO : Employee{ constructor( name: String,age: Int, salary: Double): super(name,age) { println("Salary per annum is $salary million dollars") }}fun main(args: Array<String>) { CEO("Satya Nadela", 48, 250.00)} Output: Name of the Employee is Satya Nadela Age of the Employee is 48 Salary per annum is 250.0 million dollars Explanation: Here, we instantiate the class CEO and pass the parameter values to the secondary constructor. It will initialize the local variables and pass to the base class Employee using super(name,age). If the base class and derived class contain a member function with the same name, then we can override the base member function in the derived class using the override keyword and also need to mark the member function of the base class with open keyword. Kotlin program of overriding the member function : Kotlin // base classopen class Animal { open fun run() { println("Animals can run") }}// derived classclass Tiger: Animal() { override fun run() { // overrides the run method of base class println("Tiger can run very fast") }}fun main(args: Array<String>) { val t = Tiger() t.run()} Output: Tiger can run very fast Similarly, we can override the property of the base class in the derived class. Kotlin program of overriding the member property: Kotlin // base classopen class Animal { open var name: String = "Dog" open var speed = "40 km/hr" }// derived classclass Tiger: Animal() { override var name = "Tiger" override var speed = "100 km/hr"}fun main(args: Array<String>) { val t = Tiger() println(t.name+" can run at speed "+t.speed)} Output: Tiger can run at speed 100 km/hr We can also call the base class member functions or properties from the derived class using the super keyword. In the below program we have called the base class property color and function displayCompany() in the derived class using the super keyword. Kotlin // base classopen class Phone() { var color = "Rose Gold" fun displayCompany(name:String) { println("Company is: $name") }}// derived classclass iphone: Phone() { fun displayColor(){ // calling the base class property color println("Color is: "+super.color) // calling the base class member function super.displayCompany("Apple") }}fun main(args: Array<String>) { val p = iphone() p.displayColor()} Output: Color is: Rose Gold Company is: Apple marktahu7 gabaa406 Kotlin OOPs Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Oct, 2021" }, { "code": null, "e": 352, "s": 52, "text": "Inheritance is one of the more important features in object-oriented programming. Inheritance enables code re-usability, it allows all the features from an existing class(base class) to be inherited by a new class(derived class). In addition, the derived class can also add some features of its own." }, { "code": null, "e": 375, "s": 352, "text": "Syntax of inheritance:" }, { "code": null, "e": 488, "s": 375, "text": "open class baseClass (x:Int ) {\n ..........\n}\nclass derivedClass(x:Int) : baseClass(x) {\n ...........\n}" }, { "code": null, "e": 650, "s": 488, "text": "In Kotlin, all classes are final by default. To permit the derived class to inherit from the base class, we must use the open keyword in front of the base class." }, { "code": null, "e": 919, "s": 650, "text": "Kotlin Inheriting property and methods from base class:When we inherit a class then all the properties and functions are also inherited. We can use the base class variables and functions in the derived class and can also call functions using the derived class object. " }, { "code": null, "e": 926, "s": 919, "text": "Kotlin" }, { "code": "//base classopen class baseClass{ val name = \"GeeksforGeeks\" fun A(){ println(\"Base Class\") }}//derived classclass derivedClass: baseClass() { fun B() { println(name) //inherit name property println(\"Derived class\") }}fun main(args: Array<String>) { val derived = derivedClass() derived.A() // inheriting the base class function derived.B() // calling derived class function}", "e": 1375, "s": 926, "text": null }, { "code": null, "e": 1384, "s": 1375, "text": "Output: " }, { "code": null, "e": 1423, "s": 1384, "text": "Base Class\nGeeksforGeeks\nDerived class" }, { "code": null, "e": 1833, "s": 1423, "text": "Explanation: Here, we have a base class and a derived class. We create an object while instantiating the derived class, then it is used to invoke the base class and derived class functions. The derived.A() is used to call the function A() which prints “Base Class”. The derived.B() is used to call the function B() which prints the variable name inherited from the base class and also prints “Derived class”. " }, { "code": null, "e": 2140, "s": 1833, "text": "Suppose there are three types of Employee in a company a webDeveloper , an iOSDeveloper and an androidDeveloper. All of them have some shared features like name, age and also have some special kind of skills. First, we create three-class individually and all employees have some common and specific skills." }, { "code": null, "e": 2913, "s": 2140, "text": "Here, all of them have some name and age but the development skill of all three developers are different. In each of the class, we would be copying the same code for name and age for each character. If we want to add a salary() feature then we need to copy the same code in all three classes. This creates a number of duplicate copies of code in our program, and it will likely lead to more complex and erratic code. By using inheritance, the task becomes easier. We can create a new base class Employee, which contains the common features of the 3 original classes. These three classes can then inherit common features from the base class and can add some special features of their own. We can easily add the salary feature without duplicate copies in the Employee class." }, { "code": null, "e": 3174, "s": 2913, "text": "Here, for webDeveloper, we inherit all the features from the base class and its own feature website() in the class. Similarly, we can do the same for the other two classes androidDeveloper and iosDeveloper. It makes our code more understandable and extendable." }, { "code": null, "e": 3208, "s": 3174, "text": "Kotlin program of inheritance – " }, { "code": null, "e": 3215, "s": 3208, "text": "Kotlin" }, { "code": "//base classopen class Employee( name: String,age: Int,salary : Int) { init { println(\"My name is $name, $age years old and earning $salary per month. \") }}//derived classclass webDeveloper( name: String,age: Int,salary : Int): Employee(name, age,salary) { fun website() { println(\"I am website developer\") println() }}//derived classclass androidDeveloper( name: String,age: Int,salary : Int): Employee(name, age,salary) { fun android() { println(\"I am android app developer\") println() }}//derived classclass iosDeveloper( name: String,age: Int,salary : Int): Employee(name, age,salary) { fun iosapp() { println(\"I am iOS app developer\") println() }}//main methodfun main(args: Array<String>) { val wd = webDeveloper(\"Gennady\", 25, 10000) wd.website() val ad = androidDeveloper(\"Gaurav\", 24,12000) ad.android() val iosd = iosDeveloper(\"Praveen\", 26,15000) iosd.iosapp()}", "e": 4179, "s": 3215, "text": null }, { "code": null, "e": 4188, "s": 4179, "text": "Output: " }, { "code": null, "e": 4451, "s": 4188, "text": "My name is Gennady, 25 years old and earning 10000 per month. \nI am website developer\n\nMy name is Gaurav, 24 years old and earning 12000 per month. \nI am android app developer\n\nMy name is Praveen, 26 years old and earning 15000 per month. \nI am iOS app developer" }, { "code": null, "e": 5274, "s": 4451, "text": "Explanation: Here, we have a base class Employee, prefixed with the open keyword, which contains the common properties of the derived classes. The Employee class, has a primary constructor with three variables ‘name, age and salary’. There are also three derived classes webDeveloper, androidDeveloper and iosDeveloper which also contain primary constructors and all of them having three variables.First, we instantiate an object for the webDeveloper class, and pass the name, age and salary as parameters to the derived class. It will initialize the local variables and pass these values to the base class. Then, we call the member function website() using the object ‘wd’ which prints the string to the standard output.Similarly, we create objects for the other two classes and invoke their respective member functions. " }, { "code": null, "e": 5545, "s": 5274, "text": "If the derived class contains a primary constructor, then we need to initialize the base class constructor using the parameters of the derived class. In the below program, we have two parameters in primary constructor of base class and three parameters in derived class." }, { "code": null, "e": 5564, "s": 5545, "text": "Kotlin program – " }, { "code": null, "e": 5571, "s": 5564, "text": "Kotlin" }, { "code": "//base classopen class Employee(name: String,age: Int) { init{ println(\"Name of the Employee is $name\") println(\"Age of the Employee is $age\") }}// derived classclass CEO( name: String, age: Int, salary: Double): Employee(name,age) { init { println(\"Salary per annum is $salary crore rupees\") }}fun main(args: Array<String>) { CEO(\"Sunder Pichai\", 42, 450.00)}", "e": 5968, "s": 5571, "text": null }, { "code": null, "e": 5977, "s": 5968, "text": "Output: " }, { "code": null, "e": 6080, "s": 5977, "text": "Name of the Employee is Sunder Pichai\nAge of the Employee is 42\nSalary per annum is 450.0 crore rupees" }, { "code": null, "e": 6537, "s": 6080, "text": "Explanation: Here, we instantiate the derived class CEO and passed the parameter values name, age and salary. The derived class local variables initialize with the respective values and pass the variable name and age as parameters to the Employee class. The employee class prints the variable’s names and values to the standard output and transfers the control back to the derived class. Then, the derived class executes the println() statement and exits. " }, { "code": null, "e": 6832, "s": 6537, "text": "If the derived class does not contain a primary constructor, we need to call the base class secondary constructor from the secondary constructor of derived class using the super keyword. We also need to initialize the base class secondary constructor using the parameters of the derived class. " }, { "code": null, "e": 6849, "s": 6832, "text": "Kotlin program: " }, { "code": null, "e": 6856, "s": 6849, "text": "Kotlin" }, { "code": "//base classopen class Employee { constructor(name: String,age: Int){ println(\"Name of the Employee is $name\") println(\"Age of the Employee is $age\") }}// derived classclass CEO : Employee{ constructor( name: String,age: Int, salary: Double): super(name,age) { println(\"Salary per annum is $salary million dollars\") }}fun main(args: Array<String>) { CEO(\"Satya Nadela\", 48, 250.00)}", "e": 7283, "s": 6856, "text": null }, { "code": null, "e": 7292, "s": 7283, "text": "Output: " }, { "code": null, "e": 7397, "s": 7292, "text": "Name of the Employee is Satya Nadela\nAge of the Employee is 48\nSalary per annum is 250.0 million dollars" }, { "code": null, "e": 7604, "s": 7397, "text": "Explanation: Here, we instantiate the class CEO and pass the parameter values to the secondary constructor. It will initialize the local variables and pass to the base class Employee using super(name,age). " }, { "code": null, "e": 7859, "s": 7604, "text": "If the base class and derived class contain a member function with the same name, then we can override the base member function in the derived class using the override keyword and also need to mark the member function of the base class with open keyword." }, { "code": null, "e": 7910, "s": 7859, "text": "Kotlin program of overriding the member function :" }, { "code": null, "e": 7917, "s": 7910, "text": "Kotlin" }, { "code": "// base classopen class Animal { open fun run() { println(\"Animals can run\") }}// derived classclass Tiger: Animal() { override fun run() { // overrides the run method of base class println(\"Tiger can run very fast\") }}fun main(args: Array<String>) { val t = Tiger() t.run()}", "e": 8231, "s": 7917, "text": null }, { "code": null, "e": 8240, "s": 8231, "text": "Output: " }, { "code": null, "e": 8264, "s": 8240, "text": "Tiger can run very fast" }, { "code": null, "e": 8344, "s": 8264, "text": "Similarly, we can override the property of the base class in the derived class." }, { "code": null, "e": 8394, "s": 8344, "text": "Kotlin program of overriding the member property:" }, { "code": null, "e": 8401, "s": 8394, "text": "Kotlin" }, { "code": "// base classopen class Animal { open var name: String = \"Dog\" open var speed = \"40 km/hr\" }// derived classclass Tiger: Animal() { override var name = \"Tiger\" override var speed = \"100 km/hr\"}fun main(args: Array<String>) { val t = Tiger() println(t.name+\" can run at speed \"+t.speed)}", "e": 8706, "s": 8401, "text": null }, { "code": null, "e": 8715, "s": 8706, "text": "Output: " }, { "code": null, "e": 8748, "s": 8715, "text": "Tiger can run at speed 100 km/hr" }, { "code": null, "e": 9002, "s": 8748, "text": "We can also call the base class member functions or properties from the derived class using the super keyword. In the below program we have called the base class property color and function displayCompany() in the derived class using the super keyword. " }, { "code": null, "e": 9009, "s": 9002, "text": "Kotlin" }, { "code": "// base classopen class Phone() { var color = \"Rose Gold\" fun displayCompany(name:String) { println(\"Company is: $name\") }}// derived classclass iphone: Phone() { fun displayColor(){ // calling the base class property color println(\"Color is: \"+super.color) // calling the base class member function super.displayCompany(\"Apple\") }}fun main(args: Array<String>) { val p = iphone() p.displayColor()}", "e": 9482, "s": 9009, "text": null }, { "code": null, "e": 9491, "s": 9482, "text": "Output: " }, { "code": null, "e": 9529, "s": 9491, "text": "Color is: Rose Gold\nCompany is: Apple" }, { "code": null, "e": 9539, "s": 9529, "text": "marktahu7" }, { "code": null, "e": 9548, "s": 9539, "text": "gabaa406" }, { "code": null, "e": 9560, "s": 9548, "text": "Kotlin OOPs" }, { "code": null, "e": 9567, "s": 9560, "text": "Kotlin" } ]
How to Communicate with PC using Android?
06 Jun, 2021 In this article, we would be discussing one of the basic ways of communication between a program on a PC and an Android device. Here we will use the concept of Socket programming. We know communication takes place between a sender and a receiver, Socket programming involves a Client-Server setup, where a client connects to the server, send the message, and the server on the other end receives it. Now, this can be unidirectional or bidirectional based on your code. Socket programming is a method of communicating between two devices connected to the same network. Two sockets, one on the client and one on the server, interact. An IP address plus a port make up a socket’s address. Over the specified port, the server application begins to listen to clients. The client connects to the server using the server’s IP address and the port it opens. After that, bidirectional communication is possible. Refer to this for a depth concept: Introducing Threads in Socket Programming in Java Firstly, let us build the program that is to be executed on the server socket. We will make PC as a server and Android device as a client. Step 1: Create a new project in Eclipse. Step 2: Create a class Server. Java import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket; public class Server { // declaring required variablesprivate static ServerSocket serverSocket;private static Socket clientSocket;private static InputStreamReader inputStreamReader;private static BufferedReader bufferedReader;private static String message=""; public static void main(String[] args) { try { // creating a new ServerSocket at port 4444 serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port: 4444"); } System.out.println("Server started. Listening to the port 4444"); // we keep listening to the socket's // input stream until the message // "over" is encountered while (!message.equalsIgnoreCase("over")) { try { // the accept method waits for a new client connection // and and returns a individual socket for that connection clientSocket = serverSocket.accept(); // get the inputstream from socket, which will have // the message from the clients inputStreamReader = new InputStreamReader(clientSocket.getInputStream()); bufferedReader = new BufferedReader(inputStreamReader); // reading the message message = bufferedReader.readLine(); // printing the message System.out.println(message); // finally it is very important // that you close the sockets inputStreamReader.close(); clientSocket.close(); } catch (IOException ex) { System.out.println("Problem in message reading"); } } }} This program when executed creates a ServerSocket on a specific port which is 4444. Now our server starts listening to the connections made by the clients that are android devices in this case. Please refer to this article for more details: Socket Programming in Java. Now let’s program the android app for clients. 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 AndroidManifest.xml file XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.raghav.clientsocketapp"> <!--We require internet permission to perform networking tasks--> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.ClientSocketApp"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 3: 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:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText1"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:id="@+id/button1"/> </LinearLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import java.io.IOException;import java.io.PrintWriter;import java.net.Socket; public class MainActivity extends AppCompatActivity { // declaring required variables private Socket client; private PrintWriter printwriter; private EditText textField; private Button button; private String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // reference to the text field textField = (EditText) findViewById(R.id.editText1); // reference to the send button button = (Button) findViewById(R.id.button1); // Button press event listener button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // get the text message on the text field message = textField.getText().toString(); // start the Thread to connect to server new Thread(new ClientThread(message)).start(); } }); } // the ClientThread class performs // the networking operations class ClientThread implements Runnable { private final String message; ClientThread(String message) { this.message = message; } @Override public void run() { try { // the IP and port should be correct to have a connection established // Creates a stream socket and connects it to the specified port number on the named host. client = new Socket("192.168.43.114", 4444); // connect to server printwriter = new PrintWriter(client.getOutputStream(),true); printwriter.write(message); // write the message to output stream printwriter.flush(); printwriter.close(); // closing the connection client.close(); } catch (IOException e) { e.printStackTrace(); } // updating the UI runOnUiThread(new Runnable() { @Override public void run() { textField.setText(""); } }); } }} When running on devices with api11 or higher, we would get a NetworkOnMainThreadException if we do the socket programming on the main thread. To resolve this, we can either use AsyncTask class or create a new thread. Since AsyncTask is no more supported in Android R we create a simple Thread that performs the networking part. Getting the correct IP Address Step 1: Enable your device’s hotspot and connect your PC to this(hotspot) network. Step 2: Open the command prompt and write the command “ipconfig” Step 3: Copy the IPv4 Address Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jun, 2021" }, { "code": null, "e": 497, "s": 28, "text": "In this article, we would be discussing one of the basic ways of communication between a program on a PC and an Android device. Here we will use the concept of Socket programming. We know communication takes place between a sender and a receiver, Socket programming involves a Client-Server setup, where a client connects to the server, send the message, and the server on the other end receives it. Now, this can be unidirectional or bidirectional based on your code." }, { "code": null, "e": 1016, "s": 497, "text": "Socket programming is a method of communicating between two devices connected to the same network. Two sockets, one on the client and one on the server, interact. An IP address plus a port make up a socket’s address. Over the specified port, the server application begins to listen to clients. The client connects to the server using the server’s IP address and the port it opens. After that, bidirectional communication is possible. Refer to this for a depth concept: Introducing Threads in Socket Programming in Java" }, { "code": null, "e": 1155, "s": 1016, "text": "Firstly, let us build the program that is to be executed on the server socket. We will make PC as a server and Android device as a client." }, { "code": null, "e": 1196, "s": 1155, "text": "Step 1: Create a new project in Eclipse." }, { "code": null, "e": 1227, "s": 1196, "text": "Step 2: Create a class Server." }, { "code": null, "e": 1232, "s": 1227, "text": "Java" }, { "code": "import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket; public class Server { // declaring required variablesprivate static ServerSocket serverSocket;private static Socket clientSocket;private static InputStreamReader inputStreamReader;private static BufferedReader bufferedReader;private static String message=\"\"; public static void main(String[] args) { try { // creating a new ServerSocket at port 4444 serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println(\"Could not listen on port: 4444\"); } System.out.println(\"Server started. Listening to the port 4444\"); // we keep listening to the socket's // input stream until the message // \"over\" is encountered while (!message.equalsIgnoreCase(\"over\")) { try { // the accept method waits for a new client connection // and and returns a individual socket for that connection clientSocket = serverSocket.accept(); // get the inputstream from socket, which will have // the message from the clients inputStreamReader = new InputStreamReader(clientSocket.getInputStream()); bufferedReader = new BufferedReader(inputStreamReader); // reading the message message = bufferedReader.readLine(); // printing the message System.out.println(message); // finally it is very important // that you close the sockets inputStreamReader.close(); clientSocket.close(); } catch (IOException ex) { System.out.println(\"Problem in message reading\"); } } }}", "e": 3068, "s": 1232, "text": null }, { "code": null, "e": 3384, "s": 3068, "text": "This program when executed creates a ServerSocket on a specific port which is 4444. Now our server starts listening to the connections made by the clients that are android devices in this case. Please refer to this article for more details: Socket Programming in Java. Now let’s program the android app for clients." }, { "code": null, "e": 3413, "s": 3384, "text": "Step 1: Create a New Project" }, { "code": null, "e": 3575, "s": 3413, "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": 3625, "s": 3575, "text": "Step 2: Working with the AndroidManifest.xml file" }, { "code": null, "e": 3629, "s": 3625, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.raghav.clientsocketapp\"> <!--We require internet permission to perform networking tasks--> <uses-permission android:name=\"android.permission.INTERNET\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.ClientSocketApp\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 4483, "s": 3629, "text": null }, { "code": null, "e": 4531, "s": 4483, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 4674, "s": 4531, "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": 4678, "s": 4674, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <EditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/editText1\"/> <Button android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Send\" android:id=\"@+id/button1\"/> </LinearLayout>", "e": 5361, "s": 4678, "text": null }, { "code": null, "e": 5409, "s": 5361, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 5599, "s": 5409, "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": 5604, "s": 5599, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import java.io.IOException;import java.io.PrintWriter;import java.net.Socket; public class MainActivity extends AppCompatActivity { // declaring required variables private Socket client; private PrintWriter printwriter; private EditText textField; private Button button; private String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // reference to the text field textField = (EditText) findViewById(R.id.editText1); // reference to the send button button = (Button) findViewById(R.id.button1); // Button press event listener button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // get the text message on the text field message = textField.getText().toString(); // start the Thread to connect to server new Thread(new ClientThread(message)).start(); } }); } // the ClientThread class performs // the networking operations class ClientThread implements Runnable { private final String message; ClientThread(String message) { this.message = message; } @Override public void run() { try { // the IP and port should be correct to have a connection established // Creates a stream socket and connects it to the specified port number on the named host. client = new Socket(\"192.168.43.114\", 4444); // connect to server printwriter = new PrintWriter(client.getOutputStream(),true); printwriter.write(message); // write the message to output stream printwriter.flush(); printwriter.close(); // closing the connection client.close(); } catch (IOException e) { e.printStackTrace(); } // updating the UI runOnUiThread(new Runnable() { @Override public void run() { textField.setText(\"\"); } }); } }}", "e": 8096, "s": 5604, "text": null }, { "code": null, "e": 8424, "s": 8096, "text": "When running on devices with api11 or higher, we would get a NetworkOnMainThreadException if we do the socket programming on the main thread. To resolve this, we can either use AsyncTask class or create a new thread. Since AsyncTask is no more supported in Android R we create a simple Thread that performs the networking part." }, { "code": null, "e": 8455, "s": 8424, "text": "Getting the correct IP Address" }, { "code": null, "e": 8538, "s": 8455, "text": "Step 1: Enable your device’s hotspot and connect your PC to this(hotspot) network." }, { "code": null, "e": 8603, "s": 8538, "text": "Step 2: Open the command prompt and write the command “ipconfig”" }, { "code": null, "e": 8633, "s": 8603, "text": "Step 3: Copy the IPv4 Address" }, { "code": null, "e": 8641, "s": 8633, "text": "Output:" }, { "code": null, "e": 8649, "s": 8641, "text": "Android" }, { "code": null, "e": 8654, "s": 8649, "text": "Java" }, { "code": null, "e": 8659, "s": 8654, "text": "Java" }, { "code": null, "e": 8667, "s": 8659, "text": "Android" }, { "code": null, "e": 8765, "s": 8667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8834, "s": 8765, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 8866, "s": 8834, "text": "Android SDK and it's Components" }, { "code": null, "e": 8915, "s": 8866, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 8954, "s": 8915, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 8996, "s": 8954, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 9011, "s": 8996, "text": "Arrays in Java" }, { "code": null, "e": 9055, "s": 9011, "text": "Split() String method in Java with examples" }, { "code": null, "e": 9091, "s": 9055, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 9142, "s": 9091, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Java Program to Store Even & Odd Elements of an Array into Separate Arrays
13 Apr, 2022 Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers in it. Create two arrays with size calculated after traversing and start storing them. Below is the implementation of the above approach: Java // Java Program to Store Even & Odd// Elements of an Array into Separate Arrays public class Even_Odd { // Print array method public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + " "); System.out.println(); } public static void main(String[] args) { int n = 8; // array with N size int array[] = { 23, 55, 54, 9, 76, 66, 2, 91 }; int evenSize = 0; int oddSize = 0; for (int i = 0; i < n; i++) { if (array[i] % 2 == 0) evenSize++; else oddSize++; } // odd and even arrays with size int[] even = new int[evenSize]; int[] odd = new int[oddSize]; // odd and even array iterator int j = 0, k = 0; for (int i = 0; i < n; i++) { if (array[i] % 2 == 0) even[j++] = array[i]; else odd[k++] = array[i]; } // print array method System.out.print("Even Array contains: "); printArray(even); System.out.print("Odd Array contains: "); printArray(odd); }} Output: Even Array contains: 54 76 66 2 Odd Array contains: 23 55 9 91 Time Complexity: O(n) Space Complexity: O(n) shmkmr38 Java-Array-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Apr, 2022" }, { "code": null, "e": 438, "s": 52, "text": "Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers in it. Create two arrays with size calculated after traversing and start storing them." }, { "code": null, "e": 489, "s": 438, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 494, "s": 489, "text": "Java" }, { "code": "// Java Program to Store Even & Odd// Elements of an Array into Separate Arrays public class Even_Odd { // Print array method public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) System.out.print(array[i] + \" \"); System.out.println(); } public static void main(String[] args) { int n = 8; // array with N size int array[] = { 23, 55, 54, 9, 76, 66, 2, 91 }; int evenSize = 0; int oddSize = 0; for (int i = 0; i < n; i++) { if (array[i] % 2 == 0) evenSize++; else oddSize++; } // odd and even arrays with size int[] even = new int[evenSize]; int[] odd = new int[oddSize]; // odd and even array iterator int j = 0, k = 0; for (int i = 0; i < n; i++) { if (array[i] % 2 == 0) even[j++] = array[i]; else odd[k++] = array[i]; } // print array method System.out.print(\"Even Array contains: \"); printArray(even); System.out.print(\"Odd Array contains: \"); printArray(odd); }}", "e": 1678, "s": 494, "text": null }, { "code": null, "e": 1686, "s": 1678, "text": "Output:" }, { "code": null, "e": 1751, "s": 1686, "text": "Even Array contains: 54 76 66 2 \nOdd Array contains: 23 55 9 91 " }, { "code": null, "e": 1773, "s": 1751, "text": "Time Complexity: O(n)" }, { "code": null, "e": 1796, "s": 1773, "text": "Space Complexity: O(n)" }, { "code": null, "e": 1805, "s": 1796, "text": "shmkmr38" }, { "code": null, "e": 1825, "s": 1805, "text": "Java-Array-Programs" }, { "code": null, "e": 1830, "s": 1825, "text": "Java" }, { "code": null, "e": 1844, "s": 1830, "text": "Java Programs" }, { "code": null, "e": 1849, "s": 1844, "text": "Java" }, { "code": null, "e": 1947, "s": 1849, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1962, "s": 1947, "text": "Stream In Java" }, { "code": null, "e": 1983, "s": 1962, "text": "Introduction to Java" }, { "code": null, "e": 2004, "s": 1983, "text": "Constructors in Java" }, { "code": null, "e": 2023, "s": 2004, "text": "Exceptions in Java" }, { "code": null, "e": 2040, "s": 2023, "text": "Generics in Java" }, { "code": null, "e": 2066, "s": 2040, "text": "Java Programming Examples" }, { "code": null, "e": 2100, "s": 2066, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2147, "s": 2100, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2185, "s": 2147, "text": "Factory method design pattern in Java" } ]
How to check the current runtime environment is a browser in JavaScript ?
18 Apr, 2021 In this article, we will see how to detect the runtime environment in which our JavaScript code is running. Suppose you are building an application in Node.js and need to include that code in a webpage that would be run on a browser. This would cause some functions of a Node application not to work on browsers and vice-versa. Approach: There is no function, method, or property to detect if the runtime environment is a browser, however, we can make some checks to identify whether a script is running in the browser. Some environments in which the JavaScript code can run are Node.js, Service Workers, or in a web browser. There are different conditions for each type of environment. We will create a function that will return a boolean value indicating whether the environment is a browser or not. In this function, We first check if the process is of the type ‘object’ and the type of require is a function using the typeof operator. When both the conditions are true, then the environment is Node.js, hence we return false. We similarly check if the environment is a service worker by checking if the type of importScripts is a function. We again return false if the condition matches. In the end, we check the type of window to be equal to an ‘object’. A true condition indicates that the environment is a browser, and we return true from the function. Syntax: function isBrowser() { // Check if the environment is Node.js if (typeof process === "object" && typeof require === "function") { return false; } // Check if the environment is a // Service worker if (typeof importScripts === "function") { return false; } // Check if the environment is a Browser if (typeof window === "object") { return true; } } Example: HTML <!DOCTYPE html><html> <body> <h1>Hello Geeks</h1> <script> function isBrowser() { // Check if the environment is Node.js if (typeof process === "object" && typeof require === "function") { return false; } // Check if the environment is // a Service worker if (typeof importScripts === "function") { return false; } // Check if the environment is a Browser if (typeof window === "object") { return true; } } // Calling a alert if the environment is Browser if (isBrowser()) { alert("The Environment is Browser....") } </script></body> </html> Output: JavaScript-Methods JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Apr, 2021" }, { "code": null, "e": 356, "s": 28, "text": "In this article, we will see how to detect the runtime environment in which our JavaScript code is running. Suppose you are building an application in Node.js and need to include that code in a webpage that would be run on a browser. This would cause some functions of a Node application not to work on browsers and vice-versa." }, { "code": null, "e": 654, "s": 356, "text": "Approach: There is no function, method, or property to detect if the runtime environment is a browser, however, we can make some checks to identify whether a script is running in the browser. Some environments in which the JavaScript code can run are Node.js, Service Workers, or in a web browser." }, { "code": null, "e": 848, "s": 654, "text": "There are different conditions for each type of environment. We will create a function that will return a boolean value indicating whether the environment is a browser or not. In this function," }, { "code": null, "e": 1059, "s": 848, "text": "We first check if the process is of the type ‘object’ and the type of require is a function using the typeof operator. When both the conditions are true, then the environment is Node.js, hence we return false. " }, { "code": null, "e": 1221, "s": 1059, "text": "We similarly check if the environment is a service worker by checking if the type of importScripts is a function. We again return false if the condition matches." }, { "code": null, "e": 1389, "s": 1221, "text": "In the end, we check the type of window to be equal to an ‘object’. A true condition indicates that the environment is a browser, and we return true from the function." }, { "code": null, "e": 1397, "s": 1389, "text": "Syntax:" }, { "code": null, "e": 1820, "s": 1397, "text": "function isBrowser() {\n\n // Check if the environment is Node.js\n if (typeof process === \"object\" &&\n typeof require === \"function\") {\n return false;\n }\n\n // Check if the environment is a\n // Service worker\n if (typeof importScripts === \"function\") {\n return false;\n }\n\n // Check if the environment is a Browser\n if (typeof window === \"object\") {\n return true;\n }\n}" }, { "code": null, "e": 1829, "s": 1820, "text": "Example:" }, { "code": null, "e": 1834, "s": 1829, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>Hello Geeks</h1> <script> function isBrowser() { // Check if the environment is Node.js if (typeof process === \"object\" && typeof require === \"function\") { return false; } // Check if the environment is // a Service worker if (typeof importScripts === \"function\") { return false; } // Check if the environment is a Browser if (typeof window === \"object\") { return true; } } // Calling a alert if the environment is Browser if (isBrowser()) { alert(\"The Environment is Browser....\") } </script></body> </html>", "e": 2613, "s": 1834, "text": null }, { "code": null, "e": 2621, "s": 2613, "text": "Output:" }, { "code": null, "e": 2640, "s": 2621, "text": "JavaScript-Methods" }, { "code": null, "e": 2661, "s": 2640, "text": "JavaScript-Questions" }, { "code": null, "e": 2668, "s": 2661, "text": "Picked" }, { "code": null, "e": 2679, "s": 2668, "text": "JavaScript" }, { "code": null, "e": 2696, "s": 2679, "text": "Web Technologies" }, { "code": null, "e": 2794, "s": 2696, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2855, "s": 2794, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2895, "s": 2855, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2936, "s": 2895, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2978, "s": 2936, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3000, "s": 2978, "text": "JavaScript | Promises" }, { "code": null, "e": 3062, "s": 3000, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3095, "s": 3062, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3156, "s": 3095, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3206, "s": 3156, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C++ program to Convert a Matrix to Sparse Matrix
15 Mar, 2021 Given a matrix with most of its elements as 0, convert this matrix to sparse matrix in C++Examples: Input: Matrix: 0 1 1 1 2 2 2 1 3 3 2 5 4 3 4 Output: Sparse Matrix: 0 1 0 0 0 0 2 0 0 3 0 0 0 0 5 0 0 0 0 4 Explanation: Here the Sparse matrix is represented in the form Row Column Value Hence the row 0 1 1 means that the value of the matrix at row 0 and column 1 is 1 Approach: Get the matrix with most of its elements as 0.Create a new 2D array to store the Sparse Matrix of only 3 columns (Row, Column, Value).Iterate through the Matrix, and check if an element is non zero. In this case insert this element into the Sparse Matrix.After each insertion, increment the value of variable length(here ‘len’). This will serve as the row dimension of the Sparse MatrixPrint the Dimension of the Sparse Matrix and its elements. Get the matrix with most of its elements as 0. Create a new 2D array to store the Sparse Matrix of only 3 columns (Row, Column, Value). Iterate through the Matrix, and check if an element is non zero. In this case insert this element into the Sparse Matrix. After each insertion, increment the value of variable length(here ‘len’). This will serve as the row dimension of the Sparse Matrix Print the Dimension of the Sparse Matrix and its elements. CPP // C++ program to convert a Matrix// into Sparse Matrix #include <iostream>using namespace std; // Maximum number of elements in matrix#define MAX 100 // Array representation// of sparse matrix//[][0] represents row//[][1] represents col//[][2] represents valueint data[MAX][3]; // total number of elements in matrixint len; // insert elements into sparse matrixvoid insert(int r, int c, int val){ // insert row value data[len][0] = r; // insert col value data[len][1] = c; // insert element's value data[len][2] = val; // increment number of data in matrix len++;} // printing Sparse Matrixvoid print(){ cout << "\nDimension of Sparse Matrix: " << len << " x " << 3; cout << "\nSparse Matrix: \nRow Column Value\n"; for (int i = 0; i < len; i++) { cout << data[i][0] << " " << data[i][1] << " " << data[i][2] << "\n"; }} // Driver codeint main(){ int i, j; int r = 5, c = 4; // Get the matrix int a[r] = { { 0, 1, 0, 0 }, { 0, 0, 2, 0 }, { 0, 3, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 4 } }; // print the matrix cout << "\nMatrix:\n"; for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { cout << a[i][j] << " "; } cout << endl; } // iterate through the matrix and // insert every non zero elements // in the Sparse Matrix for (i = 0; i < r; i++) for (j = 0; j < c; j++) if (a[i][j] > 0) insert(i, j, a[i][j]); // Print the Sparse Matrix print(); return 0;} Matrix: 0 1 0 0 0 0 2 0 0 3 0 0 0 0 5 0 0 0 0 4 Dimension of Sparse Matrix: 5 x 3 Sparse Matrix: Row Column Value 0 1 1 1 2 2 2 1 3 3 2 5 4 3 4 asme C++ Programs Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ C++ Program to check if a given String is Palindrome or not How to find the minimum and maximum element of a Vector using STL in C++? C Program to Swap two Numbers Passing a function as a parameter in C++ Print a given matrix in spiral form Program to find largest element in an array Rat in a Maze | Backtracking-2 Sudoku | Backtracking-7 The Celebrity Problem
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Mar, 2021" }, { "code": null, "e": 153, "s": 52, "text": "Given a matrix with most of its elements as 0, convert this matrix to sparse matrix in C++Examples: " }, { "code": null, "e": 429, "s": 153, "text": "Input: Matrix:\n0 1 1\n1 2 2\n2 1 3\n3 2 5\n4 3 4\nOutput: Sparse Matrix: \n0 1 0 0 \n0 0 2 0 \n0 3 0 0 \n0 0 5 0 \n0 0 0 4\nExplanation:\nHere the Sparse matrix is represented\nin the form Row Column Value\n\nHence the row 0 1 1 means that the value\nof the matrix at row 0 and column 1 is 1" }, { "code": null, "e": 441, "s": 429, "text": "Approach: " }, { "code": null, "e": 886, "s": 441, "text": "Get the matrix with most of its elements as 0.Create a new 2D array to store the Sparse Matrix of only 3 columns (Row, Column, Value).Iterate through the Matrix, and check if an element is non zero. In this case insert this element into the Sparse Matrix.After each insertion, increment the value of variable length(here ‘len’). This will serve as the row dimension of the Sparse MatrixPrint the Dimension of the Sparse Matrix and its elements." }, { "code": null, "e": 933, "s": 886, "text": "Get the matrix with most of its elements as 0." }, { "code": null, "e": 1022, "s": 933, "text": "Create a new 2D array to store the Sparse Matrix of only 3 columns (Row, Column, Value)." }, { "code": null, "e": 1144, "s": 1022, "text": "Iterate through the Matrix, and check if an element is non zero. In this case insert this element into the Sparse Matrix." }, { "code": null, "e": 1276, "s": 1144, "text": "After each insertion, increment the value of variable length(here ‘len’). This will serve as the row dimension of the Sparse Matrix" }, { "code": null, "e": 1335, "s": 1276, "text": "Print the Dimension of the Sparse Matrix and its elements." }, { "code": null, "e": 1339, "s": 1335, "text": "CPP" }, { "code": "// C++ program to convert a Matrix// into Sparse Matrix #include <iostream>using namespace std; // Maximum number of elements in matrix#define MAX 100 // Array representation// of sparse matrix//[][0] represents row//[][1] represents col//[][2] represents valueint data[MAX][3]; // total number of elements in matrixint len; // insert elements into sparse matrixvoid insert(int r, int c, int val){ // insert row value data[len][0] = r; // insert col value data[len][1] = c; // insert element's value data[len][2] = val; // increment number of data in matrix len++;} // printing Sparse Matrixvoid print(){ cout << \"\\nDimension of Sparse Matrix: \" << len << \" x \" << 3; cout << \"\\nSparse Matrix: \\nRow Column Value\\n\"; for (int i = 0; i < len; i++) { cout << data[i][0] << \" \" << data[i][1] << \" \" << data[i][2] << \"\\n\"; }} // Driver codeint main(){ int i, j; int r = 5, c = 4; // Get the matrix int a[r] = { { 0, 1, 0, 0 }, { 0, 0, 2, 0 }, { 0, 3, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 4 } }; // print the matrix cout << \"\\nMatrix:\\n\"; for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { cout << a[i][j] << \" \"; } cout << endl; } // iterate through the matrix and // insert every non zero elements // in the Sparse Matrix for (i = 0; i < r; i++) for (j = 0; j < c; j++) if (a[i][j] > 0) insert(i, j, a[i][j]); // Print the Sparse Matrix print(); return 0;}", "e": 2963, "s": 1339, "text": null }, { "code": null, "e": 3114, "s": 2963, "text": "Matrix:\n0 1 0 0 \n0 0 2 0 \n0 3 0 0 \n0 0 5 0 \n0 0 0 4 \n\nDimension of Sparse Matrix: 5 x 3\nSparse Matrix: \nRow Column Value\n0 1 1\n1 2 2\n2 1 3\n3 2 5\n4 3 4" }, { "code": null, "e": 3121, "s": 3116, "text": "asme" }, { "code": null, "e": 3134, "s": 3121, "text": "C++ Programs" }, { "code": null, "e": 3141, "s": 3134, "text": "Matrix" }, { "code": null, "e": 3148, "s": 3141, "text": "Matrix" }, { "code": null, "e": 3246, "s": 3148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3280, "s": 3246, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 3340, "s": 3280, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 3414, "s": 3340, "text": "How to find the minimum and maximum element of a Vector using STL in C++?" }, { "code": null, "e": 3444, "s": 3414, "text": "C Program to Swap two Numbers" }, { "code": null, "e": 3485, "s": 3444, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 3521, "s": 3485, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 3565, "s": 3521, "text": "Program to find largest element in an array" }, { "code": null, "e": 3596, "s": 3565, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 3620, "s": 3596, "text": "Sudoku | Backtracking-7" } ]
How to use Bootstrap Datepicker to get date on change event ?
30 Nov, 2021 In this article, we will learn how to use Bootstrap Datepicker to get a date on changes of events. Bootstrap Datepicker is an open-source repository that provides an API to integrate date time picker into the frontend of the website. One should have a basic knowledge of HTML, CSS, jQuery, and Bootstrap. Approach: Create an HTML file. Please follow the below code format to link some external CSS to your code inside the head tag by following this order. Start by including the bootstrap CSS in your file. Add the bootstrap datepicker CSS to your file. Finally, you need to add the font awesome CSS to your HTML file. <link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css” /><link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css” /><link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css” /> Following the below code format, attach some external JavaScript files to your code inside the head tag by following this order. Start by including the jquery JavaScript in your file. The second step is to add the bootstrap JavaScript to your file. Finally, you need to add the bootstrap datetimepicker JavaScript to your HTML file. <script src=”https://code.jquery.com/jquery-3.3.1.slim.min.js”> </script><script src= “https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js”></script> Add a class name as “datepicker” and other bootstrap classes to an input field as required You can use any icon from any resource like font awesome or any other platform to beautify your input field by aligning the icon in line with the input field. It is then necessary to initialize the date picker to the input field so that when the user clicks that input field, the pop-up calendar will appear and they can then pick the date from that prompt. Example: In this example, we take an input field with class name as “datepicker”, and initialize the datepicker on this input using datepicker(). A calendar appears when the user clicks the input field, and a date can be selected from the calendar. As soon as the user selects a date from the calendar, it is automatically written into the input field. We add an event listener onchange for that input field. When a selection is made in that input field, the onchange() callback method is automatically called to get the value of the input field using the jQuery val() method. HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"> </script> <style> .container { display: flex; justify-content: center; margin-top: 30px; } h1, container { color: green; } </style></head> <body> <h1 class="container"> GeeksforGeeks </h1> <div class="container"> <div class="datepicker date input-group p-0 shadow-sm"> <input id="reservationDate" type="text" placeholder="Choose a date" class="form-control py-4 px-4" /> <div class="input-group-append"> <span class="input-group-text px-4"> <i class="fa fa-clock-o"></i> </span> </div> </div> </div> <div class="container"> <p id="showdate"> No Date is Picked </p> </div> <script> $(".datepicker").datepicker({ clearBtn: true, format: "dd/mm/yyyy", }); $(".datepicker").on("change", function() { let pickedDate = $("input").val(); $("#showdate").text( `You picked this ${pickedDate} Date`); }); </script></body> </html> Output: Bootstrap-Questions HTML-Questions jQuery-Methods jQuery-Questions Picked Bootstrap HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 333, "s": 28, "text": "In this article, we will learn how to use Bootstrap Datepicker to get a date on changes of events. Bootstrap Datepicker is an open-source repository that provides an API to integrate date time picker into the frontend of the website. One should have a basic knowledge of HTML, CSS, jQuery, and Bootstrap." }, { "code": null, "e": 343, "s": 333, "text": "Approach:" }, { "code": null, "e": 364, "s": 343, "text": "Create an HTML file." }, { "code": null, "e": 484, "s": 364, "text": "Please follow the below code format to link some external CSS to your code inside the head tag by following this order." }, { "code": null, "e": 648, "s": 484, "text": "Start by including the bootstrap CSS in your file. Add the bootstrap datepicker CSS to your file. Finally, you need to add the font awesome CSS to your HTML file." }, { "code": null, "e": 1007, "s": 648, "text": "<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css” /><link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css” /><link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css” /> " }, { "code": null, "e": 1136, "s": 1007, "text": "Following the below code format, attach some external JavaScript files to your code inside the head tag by following this order." }, { "code": null, "e": 1340, "s": 1136, "text": "Start by including the jquery JavaScript in your file. The second step is to add the bootstrap JavaScript to your file. Finally, you need to add the bootstrap datetimepicker JavaScript to your HTML file." }, { "code": null, "e": 1648, "s": 1340, "text": "<script src=”https://code.jquery.com/jquery-3.3.1.slim.min.js”> </script><script src= “https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js”></script>" }, { "code": null, "e": 1739, "s": 1648, "text": "Add a class name as “datepicker” and other bootstrap classes to an input field as required" }, { "code": null, "e": 1898, "s": 1739, "text": "You can use any icon from any resource like font awesome or any other platform to beautify your input field by aligning the icon in line with the input field." }, { "code": null, "e": 2097, "s": 1898, "text": "It is then necessary to initialize the date picker to the input field so that when the user clicks that input field, the pop-up calendar will appear and they can then pick the date from that prompt." }, { "code": null, "e": 2244, "s": 2097, "text": "Example: In this example, we take an input field with class name as “datepicker”, and initialize the datepicker on this input using datepicker(). " }, { "code": null, "e": 2677, "s": 2244, "text": "A calendar appears when the user clicks the input field, and a date can be selected from the calendar. As soon as the user selects a date from the calendar, it is automatically written into the input field. We add an event listener onchange for that input field. When a selection is made in that input field, the onchange() callback method is automatically called to get the value of the input field using the jQuery val() method. " }, { "code": null, "e": 2682, "s": 2677, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css\" /> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css\" /> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" /> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js\"> </script> <style> .container { display: flex; justify-content: center; margin-top: 30px; } h1, container { color: green; } </style></head> <body> <h1 class=\"container\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"datepicker date input-group p-0 shadow-sm\"> <input id=\"reservationDate\" type=\"text\" placeholder=\"Choose a date\" class=\"form-control py-4 px-4\" /> <div class=\"input-group-append\"> <span class=\"input-group-text px-4\"> <i class=\"fa fa-clock-o\"></i> </span> </div> </div> </div> <div class=\"container\"> <p id=\"showdate\"> No Date is Picked </p> </div> <script> $(\".datepicker\").datepicker({ clearBtn: true, format: \"dd/mm/yyyy\", }); $(\".datepicker\").on(\"change\", function() { let pickedDate = $(\"input\").val(); $(\"#showdate\").text( `You picked this ${pickedDate} Date`); }); </script></body> </html>", "e": 4635, "s": 2682, "text": null }, { "code": null, "e": 4643, "s": 4635, "text": "Output:" }, { "code": null, "e": 4663, "s": 4643, "text": "Bootstrap-Questions" }, { "code": null, "e": 4678, "s": 4663, "text": "HTML-Questions" }, { "code": null, "e": 4693, "s": 4678, "text": "jQuery-Methods" }, { "code": null, "e": 4710, "s": 4693, "text": "jQuery-Questions" }, { "code": null, "e": 4717, "s": 4710, "text": "Picked" }, { "code": null, "e": 4727, "s": 4717, "text": "Bootstrap" }, { "code": null, "e": 4732, "s": 4727, "text": "HTML" }, { "code": null, "e": 4739, "s": 4732, "text": "JQuery" }, { "code": null, "e": 4756, "s": 4739, "text": "Web Technologies" }, { "code": null, "e": 4761, "s": 4756, "text": "HTML" }, { "code": null, "e": 4859, "s": 4761, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4900, "s": 4859, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 4933, "s": 4900, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 4978, "s": 4933, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 5004, "s": 4978, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 5071, "s": 5004, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 5119, "s": 5071, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5181, "s": 5119, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5231, "s": 5181, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5255, "s": 5231, "text": "REST API (Introduction)" } ]
Modify the string by swapping continuous vowels or consonants
12 May, 2021 Given a string str. The task is to modify the string by swapping two adjacent characters if both of them are vowels or both of them are consonants.Examples: Input: str = “geeksforgeeks” Output: geesfkogreesk The alphabets ‘e’ and ‘e’ in geeksforgeeks are vowels so they are swapped so the string becomes geeksforgeeks. The alphabets ‘k’ and ‘s’ in geeksforgeeks are consonants so they are swapped so the string becomes geeskforgeeks. The alphabets ‘k’ and ‘f’ in geeskforgeeks are consonants so they are swapped so the string becomes geesfkorgeeks. The alphabets ‘r’ and ‘g’ in geesfkorgeeks are consonants so they are swapped so the string becomes geeskfogreeks. The alphabets ‘e’ and ‘e’ in geeskfogreeks are vowels so they are swapped so the string becomes geeskfogreeks. The alphabets ‘k’ and ‘s’ in geeskfogreeks are vowels so they are swapped so the string becomes geeskfogreesk. Input:str = “gefeg” Output: gefeg No continuous vowels or consonants. Approach: Traverse through the characters in the string. Consider the current character and the next character. If both the characters are consonants or both the characters are vowels. Then swap the characters. Else continue the process till the end of the string. Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a character is a vowelbool isVowel(char c){ c = tolower(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return true; return false;} // Function to swap two consecutively// repeated vowels or consonantsstring swapRepeated(string str){ // Traverse through the length of the string for (int i = 0; i < str.length() - 1; i++) { // Check if the two consecutive characters // are vowels or consonants if ((isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1]))) // swap the two characters swap(str[i], str[i + 1]); } return str;} // Driver codeint main(){ string str = "geeksforgeeks"; cout << swapRepeated(str); return 0;} // Java implementation of the above approachclass GFG{ // Function to check if a // character is a vowel static boolean isVowel(char c) { c = Character.toLowerCase(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { return true; } return false; } // Function to swap two consecutively // repeated vowels or consonants static String swapRepeated(char str[]) { // Traverse through the // length of the string for (int i = 0; i < str.length - 1; i++) { char c = 0; // Check if the two consecutive characters // are vowels or consonants if ((isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1]))) { // swap the two characters c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } } return String.valueOf(str); } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; System.out.println(swapRepeated(str.toCharArray())); }} // This code is contributed by 29AjayKumar # Python3 implementation of the above approach # Function to check if a character is a voweldef isVowel(c) : c = c.lower(); if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u') : return True; return False; # Function to swap two consecutively# repeated vowels or consonantsdef swapRepeated(string) : # Traverse through the length of the string for i in range(len(string) - 1) : # Check if the two consecutive characters # are vowels or consonants if ((isVowel(string[i]) and isVowel(string[i + 1])) or (not(isVowel(string[i])) and not(isVowel(string[i + 1])))) : # swap the two characters (string[i], string[i + 1]) = (string[i + 1], string[i]); string = "".join(string) return string; # Driver codeif __name__ == "__main__" : string = "geeksforgeeks"; print(swapRepeated(list(string))); # This code is contributed by Ryuga // C# implementation of the above approachusing System; class GFG{ // Function to check if a // character is a vowel static bool isVowel(char c) { c = char.ToLower(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { return true; } return false; } // Function to swap two consecutively // repeated vowels or consonants static String swapRepeated(char []str) { // Traverse through the // length of the string for (int i = 0; i < str.Length - 1; i++) { char c = (char)0; // Check if the two consecutive characters // are vowels or consonants if ((isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1]))) { // swap the two characters c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } } return String.Join("",str); } // Driver code public static void Main(String[] args) { String str = "geeksforgeeks"; Console.WriteLine(swapRepeated(str.ToCharArray())); }} /* This code contributed by PrinciRaj1992 */ <?php // PHP implementation of the above approach // Function to check if a character is a vowelfunction isVowel($c){ $c = strtolower($c); if ($c == 'a' || $c == 'e' || $c == 'i' || $c == 'o' || $c == 'u') return true; return false;} // Function to swap two consecutively// repeated vowels or consonantsfunction swapRepeated($str){ // Traverse through the length of the string for ($i = 0; $i < strlen($str) - 1; $i++) { // Check if the two consecutive characters // are vowels or consonants if ((isVowel($str[$i]) && isVowel($str[$i + 1])) || (!isVowel($str[$i]) && !isVowel($str[$i + 1]))) { // swap the two characters $t = $str[$i]; $str[$i]= $str[$i + 1]; $str[$i+1] = $t; } } return $str;} // Driver code $str = "geeksforgeeks"; echo swapRepeated($str); return 0; // This code is contributed by ChitraNayal?> <script> // JavaScript implementation of the above approach // Function to check if a // character is a vowel function isVowel(c) { c = c.toLowerCase(); if (c === "a" || c === "e" || c === "i" || c === "o" || c === "u") { return true; } return false; } // Function to swap two consecutively // repeated vowels or consonants function swapRepeated(str) { // Traverse through the // length of the string for (var i = 0; i < str.length - 1; i++) { // Check if the two consecutive characters // are vowels or consonants if ( (isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1])) ) { // swap the two characters var c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } } return str.join(""); } // Driver code var str = "geeksforgeeks"; document.write(swapRepeated(str.split(""))); </script> geesfkogreesk ankthon 29AjayKumar princiraj1992 ukasp Akanksha_Rai rdtank vowel-consonant Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Convert string to char array in C++ Check whether two strings are anagram of each other Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string
[ { "code": null, "e": 52, "s": 24, "text": "\n12 May, 2021" }, { "code": null, "e": 211, "s": 52, "text": "Given a string str. The task is to modify the string by swapping two adjacent characters if both of them are vowels or both of them are consonants.Examples: " }, { "code": null, "e": 1012, "s": 211, "text": "Input: str = “geeksforgeeks” Output: geesfkogreesk The alphabets ‘e’ and ‘e’ in geeksforgeeks are vowels so they are swapped so the string becomes geeksforgeeks. The alphabets ‘k’ and ‘s’ in geeksforgeeks are consonants so they are swapped so the string becomes geeskforgeeks. The alphabets ‘k’ and ‘f’ in geeskforgeeks are consonants so they are swapped so the string becomes geesfkorgeeks. The alphabets ‘r’ and ‘g’ in geesfkorgeeks are consonants so they are swapped so the string becomes geeskfogreeks. The alphabets ‘e’ and ‘e’ in geeskfogreeks are vowels so they are swapped so the string becomes geeskfogreeks. The alphabets ‘k’ and ‘s’ in geeskfogreeks are vowels so they are swapped so the string becomes geeskfogreesk. Input:str = “gefeg” Output: gefeg No continuous vowels or consonants. " }, { "code": null, "e": 1026, "s": 1014, "text": "Approach: " }, { "code": null, "e": 1073, "s": 1026, "text": "Traverse through the characters in the string." }, { "code": null, "e": 1128, "s": 1073, "text": "Consider the current character and the next character." }, { "code": null, "e": 1201, "s": 1128, "text": "If both the characters are consonants or both the characters are vowels." }, { "code": null, "e": 1227, "s": 1201, "text": "Then swap the characters." }, { "code": null, "e": 1281, "s": 1227, "text": "Else continue the process till the end of the string." }, { "code": null, "e": 1334, "s": 1281, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1338, "s": 1334, "text": "C++" }, { "code": null, "e": 1343, "s": 1338, "text": "Java" }, { "code": null, "e": 1352, "s": 1343, "text": "Python 3" }, { "code": null, "e": 1355, "s": 1352, "text": "C#" }, { "code": null, "e": 1359, "s": 1355, "text": "PHP" }, { "code": null, "e": 1370, "s": 1359, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to check if a character is a vowelbool isVowel(char c){ c = tolower(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') return true; return false;} // Function to swap two consecutively// repeated vowels or consonantsstring swapRepeated(string str){ // Traverse through the length of the string for (int i = 0; i < str.length() - 1; i++) { // Check if the two consecutive characters // are vowels or consonants if ((isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1]))) // swap the two characters swap(str[i], str[i + 1]); } return str;} // Driver codeint main(){ string str = \"geeksforgeeks\"; cout << swapRepeated(str); return 0;}", "e": 2260, "s": 1370, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to check if a // character is a vowel static boolean isVowel(char c) { c = Character.toLowerCase(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { return true; } return false; } // Function to swap two consecutively // repeated vowels or consonants static String swapRepeated(char str[]) { // Traverse through the // length of the string for (int i = 0; i < str.length - 1; i++) { char c = 0; // Check if the two consecutive characters // are vowels or consonants if ((isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1]))) { // swap the two characters c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } } return String.valueOf(str); } // Driver code public static void main(String[] args) { String str = \"geeksforgeeks\"; System.out.println(swapRepeated(str.toCharArray())); }} // This code is contributed by 29AjayKumar", "e": 3544, "s": 2260, "text": null }, { "code": "# Python3 implementation of the above approach # Function to check if a character is a voweldef isVowel(c) : c = c.lower(); if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u') : return True; return False; # Function to swap two consecutively# repeated vowels or consonantsdef swapRepeated(string) : # Traverse through the length of the string for i in range(len(string) - 1) : # Check if the two consecutive characters # are vowels or consonants if ((isVowel(string[i]) and isVowel(string[i + 1])) or (not(isVowel(string[i])) and not(isVowel(string[i + 1])))) : # swap the two characters (string[i], string[i + 1]) = (string[i + 1], string[i]); string = \"\".join(string) return string; # Driver codeif __name__ == \"__main__\" : string = \"geeksforgeeks\"; print(swapRepeated(list(string))); # This code is contributed by Ryuga", "e": 4541, "s": 3544, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to check if a // character is a vowel static bool isVowel(char c) { c = char.ToLower(c); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { return true; } return false; } // Function to swap two consecutively // repeated vowels or consonants static String swapRepeated(char []str) { // Traverse through the // length of the string for (int i = 0; i < str.Length - 1; i++) { char c = (char)0; // Check if the two consecutive characters // are vowels or consonants if ((isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1]))) { // swap the two characters c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } } return String.Join(\"\",str); } // Driver code public static void Main(String[] args) { String str = \"geeksforgeeks\"; Console.WriteLine(swapRepeated(str.ToCharArray())); }} /* This code contributed by PrinciRaj1992 */", "e": 5832, "s": 4541, "text": null }, { "code": "<?php // PHP implementation of the above approach // Function to check if a character is a vowelfunction isVowel($c){ $c = strtolower($c); if ($c == 'a' || $c == 'e' || $c == 'i' || $c == 'o' || $c == 'u') return true; return false;} // Function to swap two consecutively// repeated vowels or consonantsfunction swapRepeated($str){ // Traverse through the length of the string for ($i = 0; $i < strlen($str) - 1; $i++) { // Check if the two consecutive characters // are vowels or consonants if ((isVowel($str[$i]) && isVowel($str[$i + 1])) || (!isVowel($str[$i]) && !isVowel($str[$i + 1]))) { // swap the two characters $t = $str[$i]; $str[$i]= $str[$i + 1]; $str[$i+1] = $t; } } return $str;} // Driver code $str = \"geeksforgeeks\"; echo swapRepeated($str); return 0; // This code is contributed by ChitraNayal?>", "e": 6796, "s": 5832, "text": null }, { "code": "<script> // JavaScript implementation of the above approach // Function to check if a // character is a vowel function isVowel(c) { c = c.toLowerCase(); if (c === \"a\" || c === \"e\" || c === \"i\" || c === \"o\" || c === \"u\") { return true; } return false; } // Function to swap two consecutively // repeated vowels or consonants function swapRepeated(str) { // Traverse through the // length of the string for (var i = 0; i < str.length - 1; i++) { // Check if the two consecutive characters // are vowels or consonants if ( (isVowel(str[i]) && isVowel(str[i + 1])) || (!isVowel(str[i]) && !isVowel(str[i + 1])) ) { // swap the two characters var c = str[i]; str[i] = str[i + 1]; str[i + 1] = c; } } return str.join(\"\"); } // Driver code var str = \"geeksforgeeks\"; document.write(swapRepeated(str.split(\"\"))); </script>", "e": 7859, "s": 6796, "text": null }, { "code": null, "e": 7873, "s": 7859, "text": "geesfkogreesk" }, { "code": null, "e": 7883, "s": 7875, "text": "ankthon" }, { "code": null, "e": 7895, "s": 7883, "text": "29AjayKumar" }, { "code": null, "e": 7909, "s": 7895, "text": "princiraj1992" }, { "code": null, "e": 7915, "s": 7909, "text": "ukasp" }, { "code": null, "e": 7928, "s": 7915, "text": "Akanksha_Rai" }, { "code": null, "e": 7935, "s": 7928, "text": "rdtank" }, { "code": null, "e": 7951, "s": 7935, "text": "vowel-consonant" }, { "code": null, "e": 7959, "s": 7951, "text": "Strings" }, { "code": null, "e": 7967, "s": 7959, "text": "Strings" }, { "code": null, "e": 8065, "s": 7967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8122, "s": 8065, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 8197, "s": 8122, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 8233, "s": 8197, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 8271, "s": 8233, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 8332, "s": 8271, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 8368, "s": 8332, "text": "Convert string to char array in C++" }, { "code": null, "e": 8420, "s": 8368, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 8465, "s": 8420, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 8529, "s": 8465, "text": "What is Data Structure: Types, Classifications and Applications" } ]
How to Detect Long Press in Android?
23 Feb, 2021 A Long Press refers to pressing a physical button or tap a virtual button on a touchscreen and holding it down for a second or two. Employed on touchscreens, smartphones, tablets, and smartwatches, the long press or long tap increases the user interface’s flexibility. The typical “short press” or “short tap” performs one operation, while pressing/tapping and holding that same button for a short time activates another. Long pressing lets you get some information, download photos from the web, edit pictures, and more. As mentioned, a long press can be used for plenty of applications, some are listed below: Get informationDownload photosEdit picturesCopy, Cut, Paste operations on Text View Get information Download photos Edit pictures Copy, Cut, Paste operations on Text View Through this article, we want to extend our knowledge regarding the long press on a Button as well as a view such as a TextView in Android. We have implemented a method that would detect a long press for a certain duration, and if the criteria are fulfilled, a Toast would be generated. Note that we are going to implement this project using the Kotlin language. To detect a long press on a button in Android, follow the following steps: 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 Kotlin as the programming language. Step 2: Working with the activity_main.xml file Go to the activity_main.xml file which represents the UI of the application, and create a Button that on long-press would generate a Toast. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--This button has to be long-clicked--> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="hold" /> </RelativeLayout> Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare a button val mBtn = findViewById<Button>(R.id.btn) // implement a setOnLongClickListener to the // button that creates a Toast and // returns true when actually long-pressed mBtn.setOnLongClickListener { Toast.makeText(applicationContext, "Button Long Pressed", Toast.LENGTH_SHORT).show() true } }} To detect a long press on a screen in Android, follow the following steps: 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 Kotlin as the programming language. There is nothing to do with the activity_main.xml file. So keep the file as it is. (Assuming that every new project creates a textView in the layout by default) Step 2: Working with the MainActivity.kt file Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport android.view.GestureDetectorimport android.view.GestureDetector.SimpleOnGestureListenerimport android.view.MotionEventimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Do Nothing } // GestureDetecctor to detect long press private val gestureDetector = GestureDetector(object : SimpleOnGestureListener() { override fun onLongPress(e: MotionEvent) { // Toast to notify the Long Press Toast.makeText(applicationContext, "Long Press Detected", Toast.LENGTH_SHORT).show() } }) // onTouchEvent to confirm presence of Touch due to Long Press override fun onTouchEvent(event: MotionEvent?): Boolean { return gestureDetector.onTouchEvent(event) }} Android-Misc Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components How to Communicate Between Fragments in Android? Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts How to Communicate Between Fragments in Android? Kotlin Array Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Feb, 2021" }, { "code": null, "e": 550, "s": 28, "text": "A Long Press refers to pressing a physical button or tap a virtual button on a touchscreen and holding it down for a second or two. Employed on touchscreens, smartphones, tablets, and smartwatches, the long press or long tap increases the user interface’s flexibility. The typical “short press” or “short tap” performs one operation, while pressing/tapping and holding that same button for a short time activates another. Long pressing lets you get some information, download photos from the web, edit pictures, and more." }, { "code": null, "e": 640, "s": 550, "text": "As mentioned, a long press can be used for plenty of applications, some are listed below:" }, { "code": null, "e": 724, "s": 640, "text": "Get informationDownload photosEdit picturesCopy, Cut, Paste operations on Text View" }, { "code": null, "e": 740, "s": 724, "text": "Get information" }, { "code": null, "e": 756, "s": 740, "text": "Download photos" }, { "code": null, "e": 770, "s": 756, "text": "Edit pictures" }, { "code": null, "e": 811, "s": 770, "text": "Copy, Cut, Paste operations on Text View" }, { "code": null, "e": 1174, "s": 811, "text": "Through this article, we want to extend our knowledge regarding the long press on a Button as well as a view such as a TextView in Android. We have implemented a method that would detect a long press for a certain duration, and if the criteria are fulfilled, a Toast would be generated. Note that we are going to implement this project using the Kotlin language." }, { "code": null, "e": 1249, "s": 1174, "text": "To detect a long press on a button in Android, follow the following steps:" }, { "code": null, "e": 1278, "s": 1249, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1442, "s": 1278, "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 Kotlin as the programming language." }, { "code": null, "e": 1490, "s": 1442, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1681, "s": 1490, "text": "Go to the activity_main.xml file which represents the UI of the application, and create a Button that on long-press would generate a Toast. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1685, "s": 1681, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--This button has to be long-clicked--> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"hold\" /> </RelativeLayout>", "e": 2232, "s": 1685, "text": null }, { "code": null, "e": 2278, "s": 2232, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 2465, "s": 2278, "text": "Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2472, "s": 2465, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declare a button val mBtn = findViewById<Button>(R.id.btn) // implement a setOnLongClickListener to the // button that creates a Toast and // returns true when actually long-pressed mBtn.setOnLongClickListener { Toast.makeText(applicationContext, \"Button Long Pressed\", Toast.LENGTH_SHORT).show() true } }}", "e": 3178, "s": 2472, "text": null }, { "code": null, "e": 3253, "s": 3178, "text": "To detect a long press on a screen in Android, follow the following steps:" }, { "code": null, "e": 3282, "s": 3253, "text": "Step 1: Create a New Project" }, { "code": null, "e": 3607, "s": 3282, "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 Kotlin as the programming language. There is nothing to do with the activity_main.xml file. So keep the file as it is. (Assuming that every new project creates a textView in the layout by default)" }, { "code": null, "e": 3653, "s": 3607, "text": "Step 2: Working with the MainActivity.kt file" }, { "code": null, "e": 3840, "s": 3653, "text": "Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3847, "s": 3840, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.view.GestureDetectorimport android.view.GestureDetector.SimpleOnGestureListenerimport android.view.MotionEventimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Do Nothing } // GestureDetecctor to detect long press private val gestureDetector = GestureDetector(object : SimpleOnGestureListener() { override fun onLongPress(e: MotionEvent) { // Toast to notify the Long Press Toast.makeText(applicationContext, \"Long Press Detected\", Toast.LENGTH_SHORT).show() } }) // onTouchEvent to confirm presence of Touch due to Long Press override fun onTouchEvent(event: MotionEvent?): Boolean { return gestureDetector.onTouchEvent(event) }}", "e": 4814, "s": 3847, "text": null }, { "code": null, "e": 4827, "s": 4814, "text": "Android-Misc" }, { "code": null, "e": 4835, "s": 4827, "text": "Android" }, { "code": null, "e": 4842, "s": 4835, "text": "Kotlin" }, { "code": null, "e": 4850, "s": 4842, "text": "Android" }, { "code": null, "e": 4948, "s": 4850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5017, "s": 4948, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5049, "s": 5017, "text": "Android SDK and it's Components" }, { "code": null, "e": 5098, "s": 5049, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5137, "s": 5098, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5179, "s": 5137, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 5248, "s": 5179, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5267, "s": 5248, "text": "Android UI Layouts" }, { "code": null, "e": 5316, "s": 5267, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5329, "s": 5316, "text": "Kotlin Array" } ]
Rooted and Binary Tree
A rooted tree G is a connected acyclic graph with a special node that is called the root of the tree and every edge directly or indirectly originates from the root. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered. If every internal vertex of a rooted tree has not more than m children, it is called an m-ary tree. If every internal vertex of a rooted tree has exactly m children, it is called a full m-ary tree. If m = 2, the rooted tree is called a binary tree. The binary Search tree is a binary tree which satisfies the following property − X in left sub-tree of vertex V, Value(X) ≤ Value (V) Y in right sub-tree of vertex V, Value(Y) ≥ Value (V) So, the value of all the vertices of the left sub-tree of an internal node V are less than or equal to V and the value of all the vertices of the right sub-tree of the internal node V are greater than or equal to V. The number of links from the root node to the deepest node is the height of the Binary Search Tree. BST_Search(x, k) if ( x = NIL or k = Value[x] ) return x; if ( k < Value[x]) return BST_Search (left[x], k); else return BST_Search (right[x], k)
[ { "code": null, "e": 1572, "s": 1062, "text": "A rooted tree G is a connected acyclic graph with a special node that is called the root of the tree and every edge directly or indirectly originates from the root. An ordered rooted tree is a rooted tree where the children of each internal vertex are ordered. If every internal vertex of a rooted tree has not more than m children, it is called an m-ary tree. If every internal vertex of a rooted tree has exactly m children, it is called a full m-ary tree. If m = 2, the rooted tree is called a binary tree." }, { "code": null, "e": 1653, "s": 1572, "text": "The binary Search tree is a binary tree which satisfies the following property −" }, { "code": null, "e": 1706, "s": 1653, "text": "X in left sub-tree of vertex V, Value(X) ≤ Value (V)" }, { "code": null, "e": 1760, "s": 1706, "text": "Y in right sub-tree of vertex V, Value(Y) ≥ Value (V)" }, { "code": null, "e": 2076, "s": 1760, "text": "So, the value of all the vertices of the left sub-tree of an internal node V are less than or equal to V and the value of all the vertices of the right sub-tree of the internal node V are greater than or equal to V. The number of links from the root node to the deepest node is the height of the Binary Search Tree." }, { "code": null, "e": 2231, "s": 2076, "text": "BST_Search(x, k)\nif ( x = NIL or k = Value[x] )\n return x;\nif ( k < Value[x])\n return BST_Search (left[x], k);\nelse\n return BST_Search (right[x], k)" } ]
Powershell - Get System Time
Get-Date cmdlet is used to get System Date-Time. In this example, we're using Get-Date without any parameter Type the following command in PowerShell ISE Console Get-Date You can see following output in PowerShell console. Get-Date Wednesday, April 04, 2018 5:24:51 PM In this example, we're using -DisplayHint to print only Time. Type the following command in PowerShell ISE Console Get-Date -DisplayHint Time You can see following output in PowerShell console. Get-Date -DisplayHint Date 5:26:36 PM 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2083, "s": 2034, "text": "Get-Date cmdlet is used to get System Date-Time." }, { "code": null, "e": 2143, "s": 2083, "text": "In this example, we're using Get-Date without any parameter" }, { "code": null, "e": 2196, "s": 2143, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2205, "s": 2196, "text": "Get-Date" }, { "code": null, "e": 2257, "s": 2205, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2304, "s": 2257, "text": "Get-Date\nWednesday, April 04, 2018 5:24:51 PM\n" }, { "code": null, "e": 2366, "s": 2304, "text": "In this example, we're using -DisplayHint to print only Time." }, { "code": null, "e": 2419, "s": 2366, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2446, "s": 2419, "text": "Get-Date -DisplayHint Time" }, { "code": null, "e": 2498, "s": 2446, "text": "You can see following output in PowerShell console." }, { "code": null, "e": 2537, "s": 2498, "text": "Get-Date -DisplayHint Date\n5:26:36 PM\n" }, { "code": null, "e": 2572, "s": 2537, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2593, "s": 2572, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2628, "s": 2593, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2641, "s": 2628, "text": " Vijay Saini" }, { "code": null, "e": 2678, "s": 2641, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2690, "s": 2678, "text": " Fettah Ben" }, { "code": null, "e": 2697, "s": 2690, "text": " Print" }, { "code": null, "e": 2708, "s": 2697, "text": " Add Notes" } ]
CoffeeScript - Classes and Inheritance
JavaScript does not provide the class keyword. We can achieve inheritance in JavaScript using objects and their prototypes. Every object have their own prototype and they inherit functions and properties from their prototypes. Since the prototype is also an object, it also has its own prototype. Though the prototypal inheritance is far more powerful than classic inheritance, it is difficult and confusing for novice users. Addressing to this problem, CoffeeScript provides a basic structure known as class which is built using the JavaScript's prototypes. You can define a class in CoffeeScript using the class keyword as shown below. class Class_Name Consider the following example, here we have created a class named Student using the keyword class. class Student If you compile the above code, it will generate the following JavaScript. var Student; Student = (function() { function Student() {} return Student; })(); We can instantiate a class using the new operator just like other object oriented programming languages as shown below. new Class_Name You can instantiate the above created (Student) class using the new operator as shown below. class Student new Student If you compile the above code, it will generate the following JavaScript. var Student; Student = (function() { function Student() {} return Student; })(); new Student; A constructor is a function that is invoked when we instantiate a class, its main purpose is to initialize the instance variables. In CoffeeScript, you can define a constructor just by creating a function with name constructor as shown below. class Student constructor: (name)-> @name = name In here, we have defined a constructor and assigned the local variable name to the instance variable. The @ operator is an alias to the this keyword, it is used to point the instance variables of a class. If we place @ before an argument of the constructor, then it will be set as an instance variable automatically. Therefore, the above code can be written simply as shown below − class Student constructor: (@name)-> Here is an example of a constructor in CoffeeScript. Save it in a file with the name constructor_example.coffee #Defining a class class Student constructor: (@name)-> #instantiating a class by passing a string to constructor student = new Student("Mohammed"); console.log "the name of the student is :"+student.name Compiling the code Open command prompt and compile the above example as shown below. c:\>coffee -c constructor_example.coffee On executing the above command it will produce the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var Student, student; Student = (function() { function Student(name) { this.name = name; } return Student; })(); student = new Student("Mohammed"); console.log("The name of the student is :"+student.name); }).call(this); Executing the Code Run the above example by executing the following command on the command prompt. coffee constructor_example.coffee On running, the above example gives you the following output. The name of the student is :Mohammed Same as in objects, we can also have properties within a class. And these are known as instance properties. Consider the following example. In here, we have created variables (name, age) and a function (message()) within the class and accessed them using its object. Save this example in a file named instance_properties_example.coffee #Defining a class class Student name="Ravi" age=24 message: -> "Hello "+name+" how are you" #instantiating a class by passing a string to constructor student = new Student(); console.log student.message() On compiling, the above code generates the following output. // Generated by CoffeeScript 1.10.0 (function() { var Student, student; Student = (function() { var age, name; function Student() {} name = "Ravi"; age = 24; Student.prototype.message = function() { return "Hello " + name + " how are you"; }; return Student; })(); student = new Student(); console.log(student.message()); }).call(this); We can define static properties in the class. The scope of the static properties is restricted within the class and we create static functions using the this keyword or its alias @ symbol and we have to access these properties using the class name as Class_Name.property. In the following example, we have created a static function named message. and accessed it. Save it in a file with the name static_properties_example.coffee. #Defining a class class Student @message:(name) -> "Hello "+name+" how are you" console.log Student.message("Raju") Open the command prompt and compile the above CoffeeScript file using the following command. c:\>coffee -c static_properties_example.coffee On compiling, it gives you the following JavaScript. // Generated by CoffeeScript 1.10.0 (function() { var Student; Student = (function() { function Student() {} Student.message = function(name) { return "Hello " + name + " how are you"; }; return Student; })(); console.log(Student.message("Raju")); }).call(this); Execute the above coffeeScript in command prompt as shown below. c:\>coffee static_properties_example.coffee On executing, the above example gives you the following output. Hello Raju how are you In CoffeeScript, we can inherit the properties of one class in another class using extends keyword. Following is an Example of inheritance in CoffeeScript. In here, we have two classes namely Add and My_class. We inherited the properties of class named Add in the class My_class, and accessed them using the extends keyword. #Defining a class class Add a=20;b=30 addition:-> console.log "Sum of the two numbers is :"+(a+b) class My_class extends Add my_class = new My_class() my_class.addition() CoffeeScript uses prototypal inheritance behind the scenes. In CoffeeScript, whenever we create instances, the parent class's constructor is invoked until we override it. We can invoke the constructor of the parent class from the subclass, using the super() keyword as shown in the example given below. #Defining a class class Add constructor:(@a,@b) -> addition:=> console.log "Sum of the two numbers is :"+(@a+@b) class Mul extends Add constructor:(@a,@b) -> super(@a,@b) multiplication:-> console.log "Product of the two numbers is :"+(@a*@b) mul = new Mul(10,20) mul.addition() mul.multiplication() CoffeeScript uses prototypal inheritance to automatically inherit all the instance properties of a class. This ensures that classes are dynamic; even if you add properties to a parent class after a child has been created, the property will still be propagated to all of its inherited children. class Animal constructor: (@name) -> class Parrot extends Animal Animal::rip = true parrot = new Parrot("Macaw") console.log "This parrot is no more" if parrot.rip On executing, the above CoffeeScript generates the following JavaScript code. // Generated by CoffeeScript 1.10.0 (function() { var Animal, Parrot, parrot, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Animal = (function() { function Animal(name) { this.name = name; } return Animal; })(); Parrot = (function(superClass) { extend(Parrot, superClass); function Parrot() { return Parrot.__super__.constructor.apply(this, arguments); } return Parrot; })(Animal); Animal.prototype.rip = true; parrot = new Parrot("Macaw"); if (parrot.rip) { console.log("This parrot is no more"); } }).call(this); Print Add Notes Bookmark this page
[ { "code": null, "e": 2606, "s": 2309, "text": "JavaScript does not provide the class keyword. We can achieve inheritance in JavaScript using objects and their prototypes. Every object have their own prototype and they inherit functions and properties from their prototypes. Since the prototype is also an object, it also has its own prototype." }, { "code": null, "e": 2735, "s": 2606, "text": "Though the prototypal inheritance is far more powerful than classic inheritance, it is difficult and confusing for novice users." }, { "code": null, "e": 2947, "s": 2735, "text": "Addressing to this problem, CoffeeScript provides a basic structure known as class which is built using the JavaScript's prototypes. You can define a class in CoffeeScript using the class keyword as shown below." }, { "code": null, "e": 2965, "s": 2947, "text": "class Class_Name\n" }, { "code": null, "e": 3065, "s": 2965, "text": "Consider the following example, here we have created a class named Student using the keyword class." }, { "code": null, "e": 3081, "s": 3065, "text": "class Student\n\n" }, { "code": null, "e": 3155, "s": 3081, "text": "If you compile the above code, it will generate the following JavaScript." }, { "code": null, "e": 3243, "s": 3155, "text": "var Student;\n\nStudent = (function() {\n function Student() {}\n\n return Student;\n\n})();" }, { "code": null, "e": 3363, "s": 3243, "text": "We can instantiate a class using the new operator just like other object oriented programming languages as shown below." }, { "code": null, "e": 3378, "s": 3363, "text": "new Class_Name" }, { "code": null, "e": 3471, "s": 3378, "text": "You can instantiate the above created (Student) class using the new operator as shown below." }, { "code": null, "e": 3498, "s": 3471, "text": "class Student\nnew Student" }, { "code": null, "e": 3572, "s": 3498, "text": "If you compile the above code, it will generate the following JavaScript." }, { "code": null, "e": 3674, "s": 3572, "text": "var Student;\n\nStudent = (function() {\n function Student() {}\n\n return Student;\n\n})();\n\nnew Student;" }, { "code": null, "e": 3917, "s": 3674, "text": "A constructor is a function that is invoked when we instantiate a class, its main purpose is to initialize the instance variables. In CoffeeScript, you can define a constructor just by creating a function with name constructor as shown below." }, { "code": null, "e": 3971, "s": 3917, "text": "class Student\n constructor: (name)->\n @name = name\n" }, { "code": null, "e": 4073, "s": 3971, "text": "In here, we have defined a constructor and assigned the local variable name to the instance variable." }, { "code": null, "e": 4176, "s": 4073, "text": "The @ operator is an alias to the this keyword, it is used to point the instance variables of a class." }, { "code": null, "e": 4353, "s": 4176, "text": "If we place @ before an argument of the constructor, then it will be set as an instance variable automatically. Therefore, the above code can be written simply as shown below −" }, { "code": null, "e": 4393, "s": 4353, "text": "class Student\n constructor: (@name)->\n" }, { "code": null, "e": 4505, "s": 4393, "text": "Here is an example of a constructor in CoffeeScript. Save it in a file with the name constructor_example.coffee" }, { "code": null, "e": 4712, "s": 4505, "text": "#Defining a class\nclass Student\n constructor: (@name)->\n\n#instantiating a class by passing a string to constructor\nstudent = new Student(\"Mohammed\");\nconsole.log \"the name of the student is :\"+student.name" }, { "code": null, "e": 4731, "s": 4712, "text": "Compiling the code" }, { "code": null, "e": 4797, "s": 4731, "text": "Open command prompt and compile the above example as shown below." }, { "code": null, "e": 4838, "s": 4797, "text": "c:\\>coffee -c constructor_example.coffee" }, { "code": null, "e": 4911, "s": 4838, "text": "On executing the above command it will produce the following JavaScript." }, { "code": null, "e": 5216, "s": 4911, "text": "// Generated by CoffeeScript 1.10.0\n(function() {\n var Student, student;\n\n Student = (function() {\n function Student(name) {\n this.name = name;\n }\n\n return Student;\n\n })();\n\n student = new Student(\"Mohammed\");\n\n console.log(\"The name of the student is :\"+student.name);\n\n}).call(this);" }, { "code": null, "e": 5235, "s": 5216, "text": "Executing the Code" }, { "code": null, "e": 5315, "s": 5235, "text": "Run the above example by executing the following command on the command prompt." }, { "code": null, "e": 5350, "s": 5315, "text": "coffee constructor_example.coffee\n" }, { "code": null, "e": 5412, "s": 5350, "text": "On running, the above example gives you the following output." }, { "code": null, "e": 5450, "s": 5412, "text": "The name of the student is :Mohammed\n" }, { "code": null, "e": 5558, "s": 5450, "text": "Same as in objects, we can also have properties within a class. And these are known as instance properties." }, { "code": null, "e": 5786, "s": 5558, "text": "Consider the following example. In here, we have created variables (name, age) and a function (message()) within the class and accessed them using its object. Save this example in a file named instance_properties_example.coffee" }, { "code": null, "e": 6003, "s": 5786, "text": "#Defining a class\nclass Student\n name=\"Ravi\"\n age=24\n message: ->\n \"Hello \"+name+\" how are you\" \n\n#instantiating a class by passing a string to constructor\nstudent = new Student();\nconsole.log student.message()" }, { "code": null, "e": 6064, "s": 6003, "text": "On compiling, the above code generates the following output." }, { "code": null, "e": 6455, "s": 6064, "text": "// Generated by CoffeeScript 1.10.0\n(function() {\n var Student, student;\n\n Student = (function() {\n var age, name;\n\n function Student() {}\n\n name = \"Ravi\";\n\n age = 24;\n\n Student.prototype.message = function() {\n return \"Hello \" + name + \" how are you\";\n };\n\n return Student;\n\n })();\n\n student = new Student();\n\n console.log(student.message());\n\n}).call(this);" }, { "code": null, "e": 6727, "s": 6455, "text": "We can define static properties in the class. The scope of the static properties is restricted within the class and we create static functions using the this keyword or its alias @ symbol and we have to access these properties using the class name as Class_Name.property." }, { "code": null, "e": 6885, "s": 6727, "text": "In the following example, we have created a static function named message. and accessed it. Save it in a file with the name static_properties_example.coffee." }, { "code": null, "e": 7008, "s": 6885, "text": "#Defining a class\nclass Student\n @message:(name) ->\n \"Hello \"+name+\" how are you\" \nconsole.log Student.message(\"Raju\")" }, { "code": null, "e": 7101, "s": 7008, "text": "Open the command prompt and compile the above CoffeeScript file using the following command." }, { "code": null, "e": 7150, "s": 7101, "text": "c:\\>coffee -c static_properties_example.coffee\n" }, { "code": null, "e": 7203, "s": 7150, "text": "On compiling, it gives you the following JavaScript." }, { "code": null, "e": 7502, "s": 7203, "text": "// Generated by CoffeeScript 1.10.0\n(function() {\n var Student;\n\n Student = (function() {\n function Student() {}\n\n Student.message = function(name) {\n return \"Hello \" + name + \" how are you\";\n };\n\n return Student;\n\n })();\n\n console.log(Student.message(\"Raju\"));\n\n}).call(this);" }, { "code": null, "e": 7567, "s": 7502, "text": "Execute the above coffeeScript in command prompt as shown below." }, { "code": null, "e": 7612, "s": 7567, "text": "c:\\>coffee static_properties_example.coffee\n" }, { "code": null, "e": 7676, "s": 7612, "text": "On executing, the above example gives you the following output." }, { "code": null, "e": 7700, "s": 7676, "text": "Hello Raju how are you\n" }, { "code": null, "e": 7800, "s": 7700, "text": "In CoffeeScript, we can inherit the properties of one class in another class using extends keyword." }, { "code": null, "e": 8025, "s": 7800, "text": "Following is an Example of inheritance in CoffeeScript. In here, we have two classes namely Add and My_class. We inherited the properties of class named Add in the class My_class, and accessed them using the extends keyword." }, { "code": null, "e": 8214, "s": 8025, "text": "#Defining a class\nclass Add\n a=20;b=30\n \n addition:->\n console.log \"Sum of the two numbers is :\"+(a+b) \n\nclass My_class extends Add\n\nmy_class = new My_class()\nmy_class.addition()" }, { "code": null, "e": 8385, "s": 8214, "text": "CoffeeScript uses prototypal inheritance behind the scenes. In CoffeeScript, whenever we create instances, the parent class's constructor is invoked until we override it." }, { "code": null, "e": 8517, "s": 8385, "text": "We can invoke the constructor of the parent class from the subclass, using the super() keyword as shown in the example given below." }, { "code": null, "e": 8855, "s": 8517, "text": "#Defining a class\nclass Add\n constructor:(@a,@b) ->\n \n addition:=>\n console.log \"Sum of the two numbers is :\"+(@a+@b) \n\nclass Mul extends Add\n constructor:(@a,@b) ->\n super(@a,@b)\n \n multiplication:->\n console.log \"Product of the two numbers is :\"+(@a*@b)\n\nmul = new Mul(10,20)\nmul.addition()\nmul.multiplication()" }, { "code": null, "e": 9149, "s": 8855, "text": "CoffeeScript uses prototypal inheritance to automatically inherit all the instance properties of a class. This ensures that classes are dynamic; even if you add properties to a parent class after a child has been created, the property will still be propagated to all of its inherited children." }, { "code": null, "e": 9318, "s": 9149, "text": "class Animal\n constructor: (@name) ->\n\nclass Parrot extends Animal\n\nAnimal::rip = true\n\nparrot = new Parrot(\"Macaw\")\nconsole.log \"This parrot is no more\" if parrot.rip" }, { "code": null, "e": 9396, "s": 9318, "text": "On executing, the above CoffeeScript generates the following JavaScript code." }, { "code": null, "e": 10281, "s": 9396, "text": "// Generated by CoffeeScript 1.10.0\n(function() {\n var Animal, Parrot, parrot,\n extend = function(child, parent) { for (var key in parent) {\n if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() {\n this.constructor = child; } ctor.prototype = parent.prototype;\n child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n hasProp = {}.hasOwnProperty;\n\n Animal = (function() {\n function Animal(name) {\n this.name = name;\n }\n\n return Animal;\n\n })();\n\n Parrot = (function(superClass) {\n extend(Parrot, superClass);\n\n function Parrot() {\n return Parrot.__super__.constructor.apply(this, arguments);\n }\n\n return Parrot;\n\n })(Animal);\n\n Animal.prototype.rip = true;\n\n parrot = new Parrot(\"Macaw\");\n\n if (parrot.rip) {\n console.log(\"This parrot is no more\");\n }\n \n}).call(this); " }, { "code": null, "e": 10288, "s": 10281, "text": " Print" }, { "code": null, "e": 10299, "s": 10288, "text": " Add Notes" } ]
Naïve Bayes from Scratch using Python only— No Fancy Frameworks | by Aisha Javed | Towards Data Science
So in my previous blog post of Unfolding Naïve Bayes from Scratch! Take-1 🎬, I tried to decode the rocket science behind the working of The Naïve Bayes (NB) ML algorithm, and after going through it’s algorithmic insights, you too must have realized that it’s quite a painless algorithm. In this blog post, we will walk-through it’s complete step by step pythonic implementation ( using basic python only) and it will be quite evident that how easy it is to code NB from scratch and that NB is not that Naïve at classifying ! Since I always wanted to decipher ML for absolute beginners and as it is said that if you can’t explain it, you probably didn't understand it, so yeah this blog post too is especially intended for ML beginners. As I just mentioned above, a complete walk-through of NB pythonic implementation Milestone # 1: Data Preprocessing Function Milestone # 2: Implementation of NaiveBayes Class — Defining Functions for Training & Testing Milestone # 3: Training NB Model on Training Dataset Milestone # 4: Testing Using Trained NB Model Milestone # 5: Proving that the Code for NaiveBayes Class is Absolutely Generic! Before we begin writing code for Naive Bayes in python, I assume you are familiar with: Python ListsNumpy & just a tad bit of vectorized codeDictionariesRegex Python Lists Numpy & just a tad bit of vectorized code Dictionaries Regex Let’s Begin the with the Pythonic Implementation ! Let’s begin with a few imports that we would need while implementing Naive Bayes Milestone # 1 Achieved 👍 The Bonus Part : We will be writing a a fully generic code for the NB Classifier! No matter how many classes come into the training dataset and whatever text dataset is given — it will still be able to train a fully working model. The code for NaiveBayes is just a little extensive — but we just to need to spend a maximum of 10–15 minutes to grasp it! After that, you will have a sound grip over all crucial concepts. There are in total four functions defined in the NaiveBayes Class: 1. def addToBow(self,example,dict_index)2. def train(self,dataset,labels)3. def getExampleProb(self,test_example)4. def test(self,test_set) And the code is divided into two major functions i.e train & test functions. Once you understand the statements defined inside these two functions, you will surely get to know what the code is actually doing and in what order the other two functions are being called. 1. Training function that trains NB Model : def train(self,dataset,labels)2. Testing function that is used to predict class labels for the given test examples : def test(self,test_set) The other two functions are defined to supplement these two major functions 1. BoW function that supplements training function It is called by the train function. It simply splits the given example using space as a tokenizer and adds every tokenized word to its corresponding BoW : def addToBow(self,example,dict_index)2. Probability function that supplements test function. It is called by the test function. It estimates probability of the given test example so that it can be classified for a class label : def getExampleProb(self,test_example) You can view the above code in this Jupyter Notebook too It is much much more easier to organize and reuse the code if we define a class of NB rather than use the traditional structured programming approach. That’s the reason of defining a NB class and all it’s relevant functions inside it. We don’t just want to write code, rather we want to write beautiful, neat & clean, handy, and reusable code . Yes that’s right - we want to possess all the traits that a good data scientist could possibly have ! And guess what? Whenever we will be dealing with a text classification problem that we intend to solve using NB, we will simply instantiate its object and by using the same programming interface, we will be able to train a NB classifier. Plus, as its the general principle of Object Oriented Programming that we only define functions relevant to a class inside that class, so all functions that are not relevant to NB class will be defined separately Milestone # 2 Achieved 👍 👍 And yes that’s it !Just a matter of four functions and we are all set to go for training our NB Model on any text dataset and with any number of class labels! If you are curious to know what the training data actually looks like ..... It’s a newsgroups dataset consisting of newsgroups posts on 20 topics . It has 20 classes, but for the time being, we will train our NB model on just four categories — [‘alt.atheism’, ‘comp.graphics’, ‘sci.med’, ‘soc.religion.christian’] but the code works perfectly well for training against all 20 categories as well. You might be wondering why the column of “Training Labels” is in numeric form rather than their original string textual form. It’s just that every string label has been mapped to it’s unique numeric Integer form. Even if this is unclear to you at the moment, just consider that a dataset has been provided and it has it’s labels in numeric form. Simple ! So before we start training a NB Model, let’s load this dataset...We will load a dataset from sklearn ( python’s ML Framework)— but we still coded NB from scratch! Let’s actually begin Training! Training is Completed !!! Milestone # 3 Achieved 👍 👍 👍 So now that we have trained our NB Model — let’s move to testing!Loading the test set..... Testing on above loaded test examples using our trained NB Model.... Wow! Pretty Good Accuracy of ~ 93% ✌️ See now you realize NB is not that Naïve ! Milestone # 4 Achieved 👍 👍 👍👍 As I mentioned in the beginning that the code we have written is generic, so let’s use the same code on a different dataset and with different class labels to prove it’s “genericity” ! The other text dataset consists of movie reviews and their sentiments & looks something like below: Notice See how the same NaiveBayes code works like a charm on different datasets and yet with same programming interface ! Milestone # 5 Achieved 👍 👍 👍👍👍 So that’s all for this blog post and now you know it all! Upcoming post will include : Unfolding Naïve Bayes from Scratch! Take-3 🎬 Implementation of Naive Bayes using scikit-learn (Python’s Machine Learning Framework) Until that Stay Tuned 📻 📻 📻 If you have any thoughts, comments, or questions, feel free to comment below or connect 📞 with me on LinkedIn
[ { "code": null, "e": 700, "s": 172, "text": "So in my previous blog post of Unfolding Naïve Bayes from Scratch! Take-1 🎬, I tried to decode the rocket science behind the working of The Naïve Bayes (NB) ML algorithm, and after going through it’s algorithmic insights, you too must have realized that it’s quite a painless algorithm. In this blog post, we will walk-through it’s complete step by step pythonic implementation ( using basic python only) and it will be quite evident that how easy it is to code NB from scratch and that NB is not that Naïve at classifying !" }, { "code": null, "e": 911, "s": 700, "text": "Since I always wanted to decipher ML for absolute beginners and as it is said that if you can’t explain it, you probably didn't understand it, so yeah this blog post too is especially intended for ML beginners." }, { "code": null, "e": 992, "s": 911, "text": "As I just mentioned above, a complete walk-through of NB pythonic implementation" }, { "code": null, "e": 1035, "s": 992, "text": "Milestone # 1: Data Preprocessing Function" }, { "code": null, "e": 1129, "s": 1035, "text": "Milestone # 2: Implementation of NaiveBayes Class — Defining Functions for Training & Testing" }, { "code": null, "e": 1182, "s": 1129, "text": "Milestone # 3: Training NB Model on Training Dataset" }, { "code": null, "e": 1228, "s": 1182, "text": "Milestone # 4: Testing Using Trained NB Model" }, { "code": null, "e": 1309, "s": 1228, "text": "Milestone # 5: Proving that the Code for NaiveBayes Class is Absolutely Generic!" }, { "code": null, "e": 1397, "s": 1309, "text": "Before we begin writing code for Naive Bayes in python, I assume you are familiar with:" }, { "code": null, "e": 1468, "s": 1397, "text": "Python ListsNumpy & just a tad bit of vectorized codeDictionariesRegex" }, { "code": null, "e": 1481, "s": 1468, "text": "Python Lists" }, { "code": null, "e": 1523, "s": 1481, "text": "Numpy & just a tad bit of vectorized code" }, { "code": null, "e": 1536, "s": 1523, "text": "Dictionaries" }, { "code": null, "e": 1542, "s": 1536, "text": "Regex" }, { "code": null, "e": 1593, "s": 1542, "text": "Let’s Begin the with the Pythonic Implementation !" }, { "code": null, "e": 1674, "s": 1593, "text": "Let’s begin with a few imports that we would need while implementing Naive Bayes" }, { "code": null, "e": 1699, "s": 1674, "text": "Milestone # 1 Achieved 👍" }, { "code": null, "e": 1930, "s": 1699, "text": "The Bonus Part : We will be writing a a fully generic code for the NB Classifier! No matter how many classes come into the training dataset and whatever text dataset is given — it will still be able to train a fully working model." }, { "code": null, "e": 2118, "s": 1930, "text": "The code for NaiveBayes is just a little extensive — but we just to need to spend a maximum of 10–15 minutes to grasp it! After that, you will have a sound grip over all crucial concepts." }, { "code": null, "e": 2185, "s": 2118, "text": "There are in total four functions defined in the NaiveBayes Class:" }, { "code": null, "e": 2325, "s": 2185, "text": "1. def addToBow(self,example,dict_index)2. def train(self,dataset,labels)3. def getExampleProb(self,test_example)4. def test(self,test_set)" }, { "code": null, "e": 2593, "s": 2325, "text": "And the code is divided into two major functions i.e train & test functions. Once you understand the statements defined inside these two functions, you will surely get to know what the code is actually doing and in what order the other two functions are being called." }, { "code": null, "e": 2785, "s": 2593, "text": "1. Training function that trains NB Model : def train(self,dataset,labels)2. Testing function that is used to predict class labels for the given test examples : def test(self,test_set)" }, { "code": null, "e": 2861, "s": 2785, "text": "The other two functions are defined to supplement these two major functions" }, { "code": null, "e": 3354, "s": 2861, "text": "1. BoW function that supplements training function It is called by the train function. It simply splits the given example using space as a tokenizer and adds every tokenized word to its corresponding BoW : def addToBow(self,example,dict_index)2. Probability function that supplements test function. It is called by the test function. It estimates probability of the given test example so that it can be classified for a class label : def getExampleProb(self,test_example)" }, { "code": null, "e": 3411, "s": 3354, "text": "You can view the above code in this Jupyter Notebook too" }, { "code": null, "e": 3646, "s": 3411, "text": "It is much much more easier to organize and reuse the code if we define a class of NB rather than use the traditional structured programming approach. That’s the reason of defining a NB class and all it’s relevant functions inside it." }, { "code": null, "e": 3858, "s": 3646, "text": "We don’t just want to write code, rather we want to write beautiful, neat & clean, handy, and reusable code . Yes that’s right - we want to possess all the traits that a good data scientist could possibly have !" }, { "code": null, "e": 4309, "s": 3858, "text": "And guess what? Whenever we will be dealing with a text classification problem that we intend to solve using NB, we will simply instantiate its object and by using the same programming interface, we will be able to train a NB classifier. Plus, as its the general principle of Object Oriented Programming that we only define functions relevant to a class inside that class, so all functions that are not relevant to NB class will be defined separately" }, { "code": null, "e": 4336, "s": 4309, "text": "Milestone # 2 Achieved 👍 👍" }, { "code": null, "e": 4495, "s": 4336, "text": "And yes that’s it !Just a matter of four functions and we are all set to go for training our NB Model on any text dataset and with any number of class labels!" }, { "code": null, "e": 4891, "s": 4495, "text": "If you are curious to know what the training data actually looks like ..... It’s a newsgroups dataset consisting of newsgroups posts on 20 topics . It has 20 classes, but for the time being, we will train our NB model on just four categories — [‘alt.atheism’, ‘comp.graphics’, ‘sci.med’, ‘soc.religion.christian’] but the code works perfectly well for training against all 20 categories as well." }, { "code": null, "e": 5246, "s": 4891, "text": "You might be wondering why the column of “Training Labels” is in numeric form rather than their original string textual form. It’s just that every string label has been mapped to it’s unique numeric Integer form. Even if this is unclear to you at the moment, just consider that a dataset has been provided and it has it’s labels in numeric form. Simple !" }, { "code": null, "e": 5410, "s": 5246, "text": "So before we start training a NB Model, let’s load this dataset...We will load a dataset from sklearn ( python’s ML Framework)— but we still coded NB from scratch!" }, { "code": null, "e": 5441, "s": 5410, "text": "Let’s actually begin Training!" }, { "code": null, "e": 5467, "s": 5441, "text": "Training is Completed !!!" }, { "code": null, "e": 5496, "s": 5467, "text": "Milestone # 3 Achieved 👍 👍 👍" }, { "code": null, "e": 5587, "s": 5496, "text": "So now that we have trained our NB Model — let’s move to testing!Loading the test set....." }, { "code": null, "e": 5656, "s": 5587, "text": "Testing on above loaded test examples using our trained NB Model...." }, { "code": null, "e": 5738, "s": 5656, "text": "Wow! Pretty Good Accuracy of ~ 93% ✌️ See now you realize NB is not that Naïve !" }, { "code": null, "e": 5768, "s": 5738, "text": "Milestone # 4 Achieved 👍 👍 👍👍" }, { "code": null, "e": 5953, "s": 5768, "text": "As I mentioned in the beginning that the code we have written is generic, so let’s use the same code on a different dataset and with different class labels to prove it’s “genericity” !" }, { "code": null, "e": 6053, "s": 5953, "text": "The other text dataset consists of movie reviews and their sentiments & looks something like below:" }, { "code": null, "e": 6176, "s": 6053, "text": "Notice See how the same NaiveBayes code works like a charm on different datasets and yet with same programming interface !" }, { "code": null, "e": 6207, "s": 6176, "text": "Milestone # 5 Achieved 👍 👍 👍👍👍" }, { "code": null, "e": 6265, "s": 6207, "text": "So that’s all for this blog post and now you know it all!" }, { "code": null, "e": 6294, "s": 6265, "text": "Upcoming post will include :" }, { "code": null, "e": 6427, "s": 6294, "text": "Unfolding Naïve Bayes from Scratch! Take-3 🎬 Implementation of Naive Bayes using scikit-learn (Python’s Machine Learning Framework)" }, { "code": null, "e": 6455, "s": 6427, "text": "Until that Stay Tuned 📻 📻 📻" } ]
Assertive Programming in R. Your code should work as intended or... | by Denis Gontcharov | Towards Data Science
You might be familiar with unit testing using the testthat package. The goal of unit tests is to check if your function is developed correctly. An assertion checks if your function is used correctly. Unit tests are meant for the developer and are executed on command. Assertions are meant for the user and are executed at every function call. A run-time test, commonly known as an assertion, is a tiny piece of code that checks a condition and fails if the condition isn’t met. Assertions enable your code to fail fast — and that’s a good thing. When something is off we don’t want our program to continue until the error compounds and reveals itself down the line. On the contrary, we want the program to fail immediately at the source of the error with a clear and precise error message. This goal of this article is to make your R functions fail fast. Assuming your function has no bugs or side-effects, the only way an error can creep into your function is through its input. In this article, you will learn how to use assertions to recognize bad input and warn the user (including future you). There are two ways for input to be bad: The function input contains errors. Some errors are spotted by R: from impossible or missing values to inconsistent use of commas and points in decimal numbers. Other errors are more insidious. Think about invalid credit card numbers or non-existing postal codes and bad email formats.You developed your function with a particular use case in mind. You can’t imagine all the ways a user will try to use your code. He or she may use your function with technically correct input but not in the intended way. Have you tried sorting a list with sort.list(list(2, 1, 3))? The function input contains errors. Some errors are spotted by R: from impossible or missing values to inconsistent use of commas and points in decimal numbers. Other errors are more insidious. Think about invalid credit card numbers or non-existing postal codes and bad email formats. You developed your function with a particular use case in mind. You can’t imagine all the ways a user will try to use your code. He or she may use your function with technically correct input but not in the intended way. Have you tried sorting a list with sort.list(list(2, 1, 3))? R has several packages for writing assertions. This article advocates the R package assertive for three reasons: the package provides lots of functions for many different casesits functions are very easy to read the package provides lots of functions for many different cases its functions are very easy to read assert_all_are_positive(c(1, -2, 3)) 3. and provide highly informative error messages Error: is_positive : c(1, -2, 3) contains non-positive values.There was 1 failure: Position Value Cause1 2 -2 too low Install the package directly from CRAN and load it into your R session: install.packages("assertive") library(assertive) Imagine you wrote a function that sums the elements of a numeric vector: add_numbers <- function(numbers) { result <- sum(numbers) return(result)} The values of the vector are allowed to be anything as long as they are numbers. Let’s write an assertion at the beginning of the function to check our input vector: add_numbers <- function(numbers) { assert_is_numeric(numbers) result <- sum(numbers) return(result)}add_numbers(c(1, 2, 2, 3)) # pass Note that assertion is written inside the function. This means it’s always there, waiting to be executed each time the function is called. Checking an assertion only takes a couple of milliseconds which is fine for all but the most performance-critical applications. Imagine you modified your function to expect a vector of unique values. Now you need two assertions: one to check that the vector is numericanother one to check that the vector has no duplicate values one to check that the vector is numeric another one to check that the vector has no duplicate values You can keep your code readable by chaining two or more assertions with the forward pipe %>% from the magrittr package: library(magrittr)add_unique_numbers <- function(input_vector) { input_vector %>% assert_is_numeric %>% assert_has_no_duplicates result <- sum(input_vector) return(result)}add_unique_numbers(c(1.5, 2, 2, 3)) # fail There are a lot of assertive functions for a wide range of cases. It’s not practical to memorize them all. Just search the package documentation on CRAN to find a function that suits your particular need. Let’s try this with an exercise. The function below expects a vector of percentage values, e.g.percentages <- c(64, 55, 97, 85) and computes the mean percentage. Can you find an appropriate assertion in the assertive package? calculate_mean_percentage <- function(percentages) { # ... your assertion goes here result <- mean(percentages) return(result)} Tip: write ls("package:assertive", pattern = "percent") in your R console to search for functions in the assertive whose name matches “percent”. You may start to see a pattern here. All assertions are composed of three parts: they always begin with assert_followed by the predicate is_ or has_and end with an expectation, e.g. numeric they always begin with assert_ followed by the predicate is_ or has_ and end with an expectation, e.g. numeric The predicate is_ changes to all_are_ or any_are_ in when the individual elements of an object are checked instead of the object itself. For example, the assertion below checks if all numbers passed to the function are whole numbers: add_whole_numbers <- function(whole_numbers) { assert_all_are_whole_numbers(whole_numbers) result <- sum(whole_numbers) return(result)}add_unique_numbers(c(1.5, 2, 2, 3)) # fail So far we’ve only dealt with numbers. But the assertive package contains assertions for all kind of cases. To illustrate, we’ll finish our discussion with some examples to check text, dates and even the host operating system. Does your function expect a vector of personal names? Check for missing or empty strings: assert_all_are_non_missing_nor_empty_character() Have a function that only works on Windows? Then make sure the user is running Windows: assert_is_windows() Does your function expect a person’s date of birth? Make sure it’s in the past: assert_is_in_past() In this article, you learned how to write assertions using the assertive package. Thanks to assertions your functions will do what they are supposed to do or fail fast with a clear error message. Cotton, Richard. (2017). Testing R code (1st Edition). Chapman & Hall. Hunt, Andrew. Thomas, Dave. (1999). The Pragmatic Programmer (25th Printing, February 2010). Addison Wesley Longman, Inc.
[ { "code": null, "e": 372, "s": 172, "text": "You might be familiar with unit testing using the testthat package. The goal of unit tests is to check if your function is developed correctly. An assertion checks if your function is used correctly." }, { "code": null, "e": 515, "s": 372, "text": "Unit tests are meant for the developer and are executed on command. Assertions are meant for the user and are executed at every function call." }, { "code": null, "e": 962, "s": 515, "text": "A run-time test, commonly known as an assertion, is a tiny piece of code that checks a condition and fails if the condition isn’t met. Assertions enable your code to fail fast — and that’s a good thing. When something is off we don’t want our program to continue until the error compounds and reveals itself down the line. On the contrary, we want the program to fail immediately at the source of the error with a clear and precise error message." }, { "code": null, "e": 1271, "s": 962, "text": "This goal of this article is to make your R functions fail fast. Assuming your function has no bugs or side-effects, the only way an error can creep into your function is through its input. In this article, you will learn how to use assertions to recognize bad input and warn the user (including future you)." }, { "code": null, "e": 1311, "s": 1271, "text": "There are two ways for input to be bad:" }, { "code": null, "e": 1878, "s": 1311, "text": "The function input contains errors. Some errors are spotted by R: from impossible or missing values to inconsistent use of commas and points in decimal numbers. Other errors are more insidious. Think about invalid credit card numbers or non-existing postal codes and bad email formats.You developed your function with a particular use case in mind. You can’t imagine all the ways a user will try to use your code. He or she may use your function with technically correct input but not in the intended way. Have you tried sorting a list with sort.list(list(2, 1, 3))?" }, { "code": null, "e": 2164, "s": 1878, "text": "The function input contains errors. Some errors are spotted by R: from impossible or missing values to inconsistent use of commas and points in decimal numbers. Other errors are more insidious. Think about invalid credit card numbers or non-existing postal codes and bad email formats." }, { "code": null, "e": 2446, "s": 2164, "text": "You developed your function with a particular use case in mind. You can’t imagine all the ways a user will try to use your code. He or she may use your function with technically correct input but not in the intended way. Have you tried sorting a list with sort.list(list(2, 1, 3))?" }, { "code": null, "e": 2559, "s": 2446, "text": "R has several packages for writing assertions. This article advocates the R package assertive for three reasons:" }, { "code": null, "e": 2658, "s": 2559, "text": "the package provides lots of functions for many different casesits functions are very easy to read" }, { "code": null, "e": 2722, "s": 2658, "text": "the package provides lots of functions for many different cases" }, { "code": null, "e": 2758, "s": 2722, "text": "its functions are very easy to read" }, { "code": null, "e": 2795, "s": 2758, "text": "assert_all_are_positive(c(1, -2, 3))" }, { "code": null, "e": 2844, "s": 2795, "text": "3. and provide highly informative error messages" }, { "code": null, "e": 2962, "s": 2844, "text": "Error: is_positive : c(1, -2, 3) contains non-positive values.There was 1 failure: Position Value Cause1 2 -2 too low" }, { "code": null, "e": 3034, "s": 2962, "text": "Install the package directly from CRAN and load it into your R session:" }, { "code": null, "e": 3064, "s": 3034, "text": "install.packages(\"assertive\")" }, { "code": null, "e": 3083, "s": 3064, "text": "library(assertive)" }, { "code": null, "e": 3156, "s": 3083, "text": "Imagine you wrote a function that sums the elements of a numeric vector:" }, { "code": null, "e": 3232, "s": 3156, "text": "add_numbers <- function(numbers) { result <- sum(numbers) return(result)}" }, { "code": null, "e": 3398, "s": 3232, "text": "The values of the vector are allowed to be anything as long as they are numbers. Let’s write an assertion at the beginning of the function to check our input vector:" }, { "code": null, "e": 3535, "s": 3398, "text": "add_numbers <- function(numbers) { assert_is_numeric(numbers) result <- sum(numbers) return(result)}add_numbers(c(1, 2, 2, 3)) # pass" }, { "code": null, "e": 3802, "s": 3535, "text": "Note that assertion is written inside the function. This means it’s always there, waiting to be executed each time the function is called. Checking an assertion only takes a couple of milliseconds which is fine for all but the most performance-critical applications." }, { "code": null, "e": 3903, "s": 3802, "text": "Imagine you modified your function to expect a vector of unique values. Now you need two assertions:" }, { "code": null, "e": 4003, "s": 3903, "text": "one to check that the vector is numericanother one to check that the vector has no duplicate values" }, { "code": null, "e": 4043, "s": 4003, "text": "one to check that the vector is numeric" }, { "code": null, "e": 4104, "s": 4043, "text": "another one to check that the vector has no duplicate values" }, { "code": null, "e": 4224, "s": 4104, "text": "You can keep your code readable by chaining two or more assertions with the forward pipe %>% from the magrittr package:" }, { "code": null, "e": 4448, "s": 4224, "text": "library(magrittr)add_unique_numbers <- function(input_vector) { input_vector %>% assert_is_numeric %>% assert_has_no_duplicates result <- sum(input_vector) return(result)}add_unique_numbers(c(1.5, 2, 2, 3)) # fail" }, { "code": null, "e": 4653, "s": 4448, "text": "There are a lot of assertive functions for a wide range of cases. It’s not practical to memorize them all. Just search the package documentation on CRAN to find a function that suits your particular need." }, { "code": null, "e": 4879, "s": 4653, "text": "Let’s try this with an exercise. The function below expects a vector of percentage values, e.g.percentages <- c(64, 55, 97, 85) and computes the mean percentage. Can you find an appropriate assertion in the assertive package?" }, { "code": null, "e": 5017, "s": 4879, "text": "calculate_mean_percentage <- function(percentages) { # ... your assertion goes here result <- mean(percentages) return(result)}" }, { "code": null, "e": 5162, "s": 5017, "text": "Tip: write ls(\"package:assertive\", pattern = \"percent\") in your R console to search for functions in the assertive whose name matches “percent”." }, { "code": null, "e": 5243, "s": 5162, "text": "You may start to see a pattern here. All assertions are composed of three parts:" }, { "code": null, "e": 5352, "s": 5243, "text": "they always begin with assert_followed by the predicate is_ or has_and end with an expectation, e.g. numeric" }, { "code": null, "e": 5383, "s": 5352, "text": "they always begin with assert_" }, { "code": null, "e": 5421, "s": 5383, "text": "followed by the predicate is_ or has_" }, { "code": null, "e": 5463, "s": 5421, "text": "and end with an expectation, e.g. numeric" }, { "code": null, "e": 5697, "s": 5463, "text": "The predicate is_ changes to all_are_ or any_are_ in when the individual elements of an object are checked instead of the object itself. For example, the assertion below checks if all numbers passed to the function are whole numbers:" }, { "code": null, "e": 5878, "s": 5697, "text": "add_whole_numbers <- function(whole_numbers) { assert_all_are_whole_numbers(whole_numbers) result <- sum(whole_numbers) return(result)}add_unique_numbers(c(1.5, 2, 2, 3)) # fail" }, { "code": null, "e": 6104, "s": 5878, "text": "So far we’ve only dealt with numbers. But the assertive package contains assertions for all kind of cases. To illustrate, we’ll finish our discussion with some examples to check text, dates and even the host operating system." }, { "code": null, "e": 6194, "s": 6104, "text": "Does your function expect a vector of personal names? Check for missing or empty strings:" }, { "code": null, "e": 6243, "s": 6194, "text": "assert_all_are_non_missing_nor_empty_character()" }, { "code": null, "e": 6331, "s": 6243, "text": "Have a function that only works on Windows? Then make sure the user is running Windows:" }, { "code": null, "e": 6351, "s": 6331, "text": "assert_is_windows()" }, { "code": null, "e": 6431, "s": 6351, "text": "Does your function expect a person’s date of birth? Make sure it’s in the past:" }, { "code": null, "e": 6451, "s": 6431, "text": "assert_is_in_past()" }, { "code": null, "e": 6647, "s": 6451, "text": "In this article, you learned how to write assertions using the assertive package. Thanks to assertions your functions will do what they are supposed to do or fail fast with a clear error message." }, { "code": null, "e": 6718, "s": 6647, "text": "Cotton, Richard. (2017). Testing R code (1st Edition). Chapman & Hall." } ]
How to iterate any Map in Java - GeeksforGeeks
13 May, 2022 There are generally five ways of iterating over a Map in Java. In this article, we will discuss all of them and also look at their advantages and disadvantages.First of all, we cannot iterate a Map directly using iterators, because Map are not Collection. Also before going further, you must know a little-bit about Map.Entry<K, V> interface.Since all maps in Java implement Map interface, following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.) 1. Iterating over Map.entrySet() using For-Each loop :Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry<K, V>. This method is most common and should be used if you need both map keys and values in the loop. Below is the java program to demonstrate it. Java // Java program to demonstrate iteration over // Map.entrySet() entries using for-each loop import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put("GFG", "geeksforgeeks.org"); gfg.put("Practice", "practice.geeksforgeeks.org"); gfg.put("Code", "code.geeksforgeeks.org"); gfg.put("Quiz", "quiz.geeksforgeeks.org"); // using for-each loop for iteration over Map.entrySet() for (Map.Entry<String,String> entry : gfg.entrySet()) System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }} Output: Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org 2. Iterating over keys or values using keySet() and values() methods Map.keySet() method returns a Set view of the keys contained in this map and Map.values() method returns a collection-view of the values contained in this map. So If you need only keys or values from the map, you can iterate over keySet or values using for-each loops. Below is the java program to demonstrate it. Java // Java program to demonstrate iteration over // Map using keySet() and values() methods import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put("GFG", "geeksforgeeks.org"); gfg.put("Practice", "practice.geeksforgeeks.org"); gfg.put("Code", "code.geeksforgeeks.org"); gfg.put("Quiz", "quiz.geeksforgeeks.org"); // using keySet() for iteration over keys for (String name : gfg.keySet()) System.out.println("key: " + name); // using values() for iteration over values for (String url : gfg.values()) System.out.println("value: " + url); }} Output: key: Quiz key: Practice key: GFG key: Code value: quiz.geeksforgeeks.org value: practice.geeksforgeeks.org value: geeksforgeeks.org value: code.geeksforgeeks.org 3. Iterating using iterators over Map.Entry<K, V> This method is somewhat similar to first one. In first method we use for-each loop over Map.Entry<K, V>, but here we use iterators. Using iterators over Map.Entry<K, V> has it’s own advantage,i.e. we can remove entries from the map during iteration by calling iterator.remove() method. Java // Java program to demonstrate iteration over // Map using keySet() and values() methods import java.util.Map;import java.util.HashMap;import java.util.Iterator; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put("GFG", "geeksforgeeks.org"); gfg.put("Practice", "practice.geeksforgeeks.org"); gfg.put("Code", "code.geeksforgeeks.org"); gfg.put("Quiz", "quiz.geeksforgeeks.org"); // using iterators Iterator<Map.Entry<String, String>> itr = gfg.entrySet().iterator(); while(itr.hasNext()) { Map.Entry<String, String> entry = itr.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } }} Output: Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org 4. Using forEach(action) method : In Java 8, you can iterate a map using Map.forEach(action) method and using lambda expression. This technique is clean and fast. Java // Java code illustrating iteration// over map using forEach(action) method import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put("GFG", "geeksforgeeks.org"); gfg.put("Practice", "practice.geeksforgeeks.org"); gfg.put("Code", "code.geeksforgeeks.org"); gfg.put("Quiz", "quiz.geeksforgeeks.org"); // forEach(action) method to iterate map gfg.forEach((k,v) -> System.out.println("Key = " + k + ", Value = " + v)); }} Output : Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org 5. Iterating over keys and searching for values (inefficient) Here first we loop over keys(using Map.keySet() method) and then search for value(using Map.get(key) method) for each key.This method is not used in practice as it is pretty slow and inefficient as getting values by a key might be time-consuming. Java // Java program to demonstrate iteration// over keys and searching for values import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put("GFG", "geeksforgeeks.org"); gfg.put("Practice", "practice.geeksforgeeks.org"); gfg.put("Code", "code.geeksforgeeks.org"); gfg.put("Quiz", "quiz.geeksforgeeks.org"); // looping over keys for (String name : gfg.keySet()) { // search for value String url = gfg.get(name); System.out.println("Key = " + name + ", Value = " + url); } }} Output: Key = Quiz, Value = quiz.geeksforgeeks.org Key = Practice, Value = practice.geeksforgeeks.org Key = GFG, Value = geeksforgeeks.org Key = Code, Value = code.geeksforgeeks.org References : StackoverflowThis article is contributed by Gaurav Miglani and Abhishek Verma. 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. shivam2608 Java-Collections Java-Map-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multithreading in Java Collections in Java Queue Interface In Java Initializing a List in Java LinkedList in Java
[ { "code": null, "e": 25453, "s": 25425, "text": "\n13 May, 2022" }, { "code": null, "e": 25952, "s": 25453, "text": "There are generally five ways of iterating over a Map in Java. In this article, we will discuss all of them and also look at their advantages and disadvantages.First of all, we cannot iterate a Map directly using iterators, because Map are not Collection. Also before going further, you must know a little-bit about Map.Entry<K, V> interface.Since all maps in Java implement Map interface, following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)" }, { "code": null, "e": 26352, "s": 25952, "text": "1. Iterating over Map.entrySet() using For-Each loop :Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry<K, V>. This method is most common and should be used if you need both map keys and values in the loop. Below is the java program to demonstrate it." }, { "code": null, "e": 26357, "s": 26352, "text": "Java" }, { "code": "// Java program to demonstrate iteration over // Map.entrySet() entries using for-each loop import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put(\"GFG\", \"geeksforgeeks.org\"); gfg.put(\"Practice\", \"practice.geeksforgeeks.org\"); gfg.put(\"Code\", \"code.geeksforgeeks.org\"); gfg.put(\"Quiz\", \"quiz.geeksforgeeks.org\"); // using for-each loop for iteration over Map.entrySet() for (Map.Entry<String,String> entry : gfg.entrySet()) System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); }}", "e": 27128, "s": 26357, "text": null }, { "code": null, "e": 27137, "s": 27128, "text": "Output: " }, { "code": null, "e": 27311, "s": 27137, "text": "Key = Quiz, Value = quiz.geeksforgeeks.org\nKey = Practice, Value = practice.geeksforgeeks.org\nKey = GFG, Value = geeksforgeeks.org\nKey = Code, Value = code.geeksforgeeks.org" }, { "code": null, "e": 27694, "s": 27311, "text": "2. Iterating over keys or values using keySet() and values() methods Map.keySet() method returns a Set view of the keys contained in this map and Map.values() method returns a collection-view of the values contained in this map. So If you need only keys or values from the map, you can iterate over keySet or values using for-each loops. Below is the java program to demonstrate it." }, { "code": null, "e": 27699, "s": 27694, "text": "Java" }, { "code": "// Java program to demonstrate iteration over // Map using keySet() and values() methods import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put(\"GFG\", \"geeksforgeeks.org\"); gfg.put(\"Practice\", \"practice.geeksforgeeks.org\"); gfg.put(\"Code\", \"code.geeksforgeeks.org\"); gfg.put(\"Quiz\", \"quiz.geeksforgeeks.org\"); // using keySet() for iteration over keys for (String name : gfg.keySet()) System.out.println(\"key: \" + name); // using values() for iteration over values for (String url : gfg.values()) System.out.println(\"value: \" + url); }}", "e": 28507, "s": 27699, "text": null }, { "code": null, "e": 28515, "s": 28507, "text": "Output:" }, { "code": null, "e": 28677, "s": 28515, "text": "key: Quiz\nkey: Practice\nkey: GFG\nkey: Code\nvalue: quiz.geeksforgeeks.org\nvalue: practice.geeksforgeeks.org\nvalue: geeksforgeeks.org\nvalue: code.geeksforgeeks.org" }, { "code": null, "e": 29013, "s": 28677, "text": "3. Iterating using iterators over Map.Entry<K, V> This method is somewhat similar to first one. In first method we use for-each loop over Map.Entry<K, V>, but here we use iterators. Using iterators over Map.Entry<K, V> has it’s own advantage,i.e. we can remove entries from the map during iteration by calling iterator.remove() method." }, { "code": null, "e": 29018, "s": 29013, "text": "Java" }, { "code": "// Java program to demonstrate iteration over // Map using keySet() and values() methods import java.util.Map;import java.util.HashMap;import java.util.Iterator; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put(\"GFG\", \"geeksforgeeks.org\"); gfg.put(\"Practice\", \"practice.geeksforgeeks.org\"); gfg.put(\"Code\", \"code.geeksforgeeks.org\"); gfg.put(\"Quiz\", \"quiz.geeksforgeeks.org\"); // using iterators Iterator<Map.Entry<String, String>> itr = gfg.entrySet().iterator(); while(itr.hasNext()) { Map.Entry<String, String> entry = itr.next(); System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); } }}", "e": 29908, "s": 29018, "text": null }, { "code": null, "e": 29916, "s": 29908, "text": "Output:" }, { "code": null, "e": 30090, "s": 29916, "text": "Key = Quiz, Value = quiz.geeksforgeeks.org\nKey = Practice, Value = practice.geeksforgeeks.org\nKey = GFG, Value = geeksforgeeks.org\nKey = Code, Value = code.geeksforgeeks.org" }, { "code": null, "e": 30253, "s": 30090, "text": "4. Using forEach(action) method : In Java 8, you can iterate a map using Map.forEach(action) method and using lambda expression. This technique is clean and fast." }, { "code": null, "e": 30258, "s": 30253, "text": "Java" }, { "code": "// Java code illustrating iteration// over map using forEach(action) method import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put(\"GFG\", \"geeksforgeeks.org\"); gfg.put(\"Practice\", \"practice.geeksforgeeks.org\"); gfg.put(\"Code\", \"code.geeksforgeeks.org\"); gfg.put(\"Quiz\", \"quiz.geeksforgeeks.org\"); // forEach(action) method to iterate map gfg.forEach((k,v) -> System.out.println(\"Key = \" + k + \", Value = \" + v)); }}", "e": 30922, "s": 30258, "text": null }, { "code": null, "e": 30932, "s": 30922, "text": "Output : " }, { "code": null, "e": 31106, "s": 30932, "text": "Key = Quiz, Value = quiz.geeksforgeeks.org\nKey = Practice, Value = practice.geeksforgeeks.org\nKey = GFG, Value = geeksforgeeks.org\nKey = Code, Value = code.geeksforgeeks.org" }, { "code": null, "e": 31415, "s": 31106, "text": "5. Iterating over keys and searching for values (inefficient) Here first we loop over keys(using Map.keySet() method) and then search for value(using Map.get(key) method) for each key.This method is not used in practice as it is pretty slow and inefficient as getting values by a key might be time-consuming." }, { "code": null, "e": 31420, "s": 31415, "text": "Java" }, { "code": "// Java program to demonstrate iteration// over keys and searching for values import java.util.Map;import java.util.HashMap; class IterationDemo { public static void main(String[] arg) { Map<String,String> gfg = new HashMap<String,String>(); // enter name/url pair gfg.put(\"GFG\", \"geeksforgeeks.org\"); gfg.put(\"Practice\", \"practice.geeksforgeeks.org\"); gfg.put(\"Code\", \"code.geeksforgeeks.org\"); gfg.put(\"Quiz\", \"quiz.geeksforgeeks.org\"); // looping over keys for (String name : gfg.keySet()) { // search for value String url = gfg.get(name); System.out.println(\"Key = \" + name + \", Value = \" + url); } }}", "e": 32158, "s": 31420, "text": null }, { "code": null, "e": 32167, "s": 32158, "text": "Output: " }, { "code": null, "e": 32341, "s": 32167, "text": "Key = Quiz, Value = quiz.geeksforgeeks.org\nKey = Practice, Value = practice.geeksforgeeks.org\nKey = GFG, Value = geeksforgeeks.org\nKey = Code, Value = code.geeksforgeeks.org" }, { "code": null, "e": 32809, "s": 32341, "text": "References : StackoverflowThis article is contributed by Gaurav Miglani and Abhishek Verma. 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": 32820, "s": 32809, "text": "shivam2608" }, { "code": null, "e": 32837, "s": 32820, "text": "Java-Collections" }, { "code": null, "e": 32855, "s": 32837, "text": "Java-Map-Programs" }, { "code": null, "e": 32860, "s": 32855, "text": "Java" }, { "code": null, "e": 32865, "s": 32860, "text": "Java" }, { "code": null, "e": 32882, "s": 32865, "text": "Java-Collections" }, { "code": null, "e": 32980, "s": 32882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32995, "s": 32980, "text": "Stream In Java" }, { "code": null, "e": 33014, "s": 32995, "text": "Interfaces in Java" }, { "code": null, "e": 33032, "s": 33014, "text": "ArrayList in Java" }, { "code": null, "e": 33052, "s": 33032, "text": "Stack Class in Java" }, { "code": null, "e": 33076, "s": 33052, "text": "Singleton Class in Java" }, { "code": null, "e": 33099, "s": 33076, "text": "Multithreading in Java" }, { "code": null, "e": 33119, "s": 33099, "text": "Collections in Java" }, { "code": null, "e": 33143, "s": 33119, "text": "Queue Interface In Java" }, { "code": null, "e": 33171, "s": 33143, "text": "Initializing a List in Java" } ]