title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
CherryPy - ToolBox
Within CherryPy, built-in tools offer a single interface to call the CherryPy library. The tools defined in CherryPy can be implemented in the following ways − From the configuration settings As a Python decorator or via the special _cp_config attribute of a page handler As a Python callable that can be applied from within any function The purpose of this tool is to provide basic authentication to the application designed in the application. This tool uses the following arguments − Let us take an example to understand how it works − import sha import cherrypy class Root: @cherrypy.expose def index(self): return """ <html> <head></head> <body> <a href = "admin">Admin </a> </body> </html> """ class Admin: @cherrypy.expose def index(self): return "This is a private area" if __name__ == '__main__': def get_users(): # 'test': 'test' return {'test': 'b110ba61c4c0873d3101e10871082fbbfd3'} def encrypt_pwd(token): return sha.new(token).hexdigest() conf = {'/admin': {'tools.basic_auth.on': True, tools.basic_auth.realm': 'Website name', 'tools.basic_auth.users': get_users, 'tools.basic_auth.encrypt': encrypt_pwd}} root = Root() root.admin = Admin() cherrypy.quickstart(root, '/', config=conf) The get_users function returns a hard-coded dictionary but also fetches the values from a database or anywhere else. The class admin includes this function which makes use of an authentication built-in tool of CherryPy. The authentication encrypts the password and the user Id. The basic authentication tool is not really secure, as the password can be encoded and decoded by an intruder. The purpose of this tool is to provide memory caching of CherryPy generated content. This tool uses the following arguments − The purpose of this tool is to decode the incoming request parameters. This tool uses the following arguments − Let us take an example to understand how it works − import cherrypy from cherrypy import tools class Root: @cherrypy.expose def index(self): return """ <html> <head></head> <body> <form action = "hello.html" method = "post"> <input type = "text" name = "name" value = "" /> <input type = ”submit” name = "submit"/> </form> </body> </html> """ @cherrypy.expose @tools.decode(encoding='ISO-88510-1') def hello(self, name): return "Hello %s" % (name, ) if __name__ == '__main__': cherrypy.quickstart(Root(), '/') The above code takes a string from the user and it will redirect the user to "hello.html" page where it will be displayed as “Hello” with the given name. The output of the above code is as follows − hello.html Print Add Notes Bookmark this page
[ { "code": null, "e": 2045, "s": 1885, "text": "Within CherryPy, built-in tools offer a single interface to call the CherryPy library. The tools defined in CherryPy can be implemented in the following ways −" }, { "code": null, "e": 2077, "s": 2045, "text": "From the configuration settings" }, { "code": null, "e": 2157, "s": 2077, "text": "As a Python decorator or via the special _cp_config attribute of a page handler" }, { "code": null, "e": 2223, "s": 2157, "text": "As a Python callable that can be applied from within any function" }, { "code": null, "e": 2331, "s": 2223, "text": "The purpose of this tool is to provide basic authentication to the application designed in the application." }, { "code": null, "e": 2372, "s": 2331, "text": "This tool uses the following arguments −" }, { "code": null, "e": 2424, "s": 2372, "text": "Let us take an example to understand how it works −" }, { "code": null, "e": 3131, "s": 2424, "text": "import sha\nimport cherrypy\n\nclass Root:\[email protected]\ndef index(self):\n\nreturn \"\"\"\n<html>\n <head></head>\n <body>\n <a href = \"admin\">Admin </a>\n </body>\n</html>\n\"\"\" \n\nclass Admin:\n\[email protected]\ndef index(self):\nreturn \"This is a private area\"\n\nif __name__ == '__main__':\ndef get_users():\n# 'test': 'test'\nreturn {'test': 'b110ba61c4c0873d3101e10871082fbbfd3'}\ndef encrypt_pwd(token):\n\nreturn sha.new(token).hexdigest()\n conf = {'/admin': {'tools.basic_auth.on': True,\n tools.basic_auth.realm': 'Website name',\n 'tools.basic_auth.users': get_users,\n 'tools.basic_auth.encrypt': encrypt_pwd}}\n root = Root()\nroot.admin = Admin()\ncherrypy.quickstart(root, '/', config=conf)" }, { "code": null, "e": 3409, "s": 3131, "text": "The get_users function returns a hard-coded dictionary but also fetches the values from a database or anywhere else. The class admin includes this function which makes use of an authentication built-in tool of CherryPy. The authentication encrypts the password and the user Id." }, { "code": null, "e": 3520, "s": 3409, "text": "The basic authentication tool is not really secure, as the password can be encoded and decoded by an intruder." }, { "code": null, "e": 3605, "s": 3520, "text": "The purpose of this tool is to provide memory caching of CherryPy generated content." }, { "code": null, "e": 3646, "s": 3605, "text": "This tool uses the following arguments −" }, { "code": null, "e": 3717, "s": 3646, "text": "The purpose of this tool is to decode the incoming request parameters." }, { "code": null, "e": 3758, "s": 3717, "text": "This tool uses the following arguments −" }, { "code": null, "e": 3810, "s": 3758, "text": "Let us take an example to understand how it works −" }, { "code": null, "e": 4311, "s": 3810, "text": "import cherrypy\nfrom cherrypy import tools\n\nclass Root:\[email protected]\ndef index(self):\n\nreturn \"\"\" \n<html>\n <head></head>\n <body>\n <form action = \"hello.html\" method = \"post\">\n <input type = \"text\" name = \"name\" value = \"\" />\n <input type = ”submit” name = \"submit\"/>\n </form>\n </body>\n</html>\n\"\"\"\n\[email protected]\[email protected](encoding='ISO-88510-1')\ndef hello(self, name):\nreturn \"Hello %s\" % (name, )\nif __name__ == '__main__':\ncherrypy.quickstart(Root(), '/')" }, { "code": null, "e": 4465, "s": 4311, "text": "The above code takes a string from the user and it will redirect the user to \"hello.html\" page where it will be displayed as “Hello” with the given name." }, { "code": null, "e": 4510, "s": 4465, "text": "The output of the above code is as follows −" }, { "code": null, "e": 4522, "s": 4510, "text": "hello.html\n" }, { "code": null, "e": 4529, "s": 4522, "text": " Print" }, { "code": null, "e": 4540, "s": 4529, "text": " Add Notes" } ]
Construct a Turing Machine for language L = {a^n b^m c^nm where n >=0 and m >= 0} - GeeksforGeeks
12 Jun, 2020 Prerequisite – Turing Machine The language L = {anbmcnm | n >= 0 and m>=0} represents a kind of language where we use only 3 symbols, i.e., a, b and c. In the beginning language has n number of a’s followed by m number of b’s and then n*m number of c’s. Any such string which falls in this category will be accepted by this language. Examples: Input : abbcc Output : YES Input : abbbcc Output : NO Input : or empty string Output : YES Basic Representation : Start of Computation :The tape contains the input string w, the tape head is on the leftmost symbol of w, and the Turing machine is in the start state Q0. Basic Idea :The tape head reads the leftmost symbol of w, which is a and at start only we will make it Blank. Then we will traverse to make leftmost b a $ and replace rightmost c by a Blank, we will do this zigzag pattern of replacing b by $ and c by Blank till all b are not replaced by $.After this we will traverse back in left direction till we get leftmost a and replacing all $ by b in the traversal. After this we have reduced our string into form an-1bmcnm-m so we can figure if all a’s are replaced by blankand if the string belongs to Language L then there will be no c’s left hence it will get accepted. Meanings of symbols used:R, L – direction of movement of one unit on either side.B-Blank,a, b, c -symbols whose combination string is to be tested.$-Temporarily symbol to replace b. Working Procedure : Step-1:We first replace leftmost a by Blank and then traverse to replace leftmost b by $ and rightmost c by Blank.Repeat this step from state Q1 till there is no more b left. Step-2:After replacing all b by $ we have also replaced m rightmost c’s with Blanks and then we will traverse back to left most a and replace all $ by b’s.After this step if check the string it is now reduced to an-1bmcnm-m form.Now we will repeat from step 1 till all a’s are not made Blank. Step-3:So after all a’s are made blank and if the string belonged to Language L then 0 c’s must be left which we check at state Q0 and Q6 as only b’s will be left and after which if Blank is found then all c’s must have been replace by Blank as we where making c’s Blank from rightmost end of the string. Step-4:So if we get a Blank symbol at state Q6 the the string is accepted at final state Q7. Also if the string was empty then it will also be accepted as Blank symbol input at state Q0 then it will got to state Q7 and gets accepted. Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chomsky Hierarchy in Theory of Computation Converting Context Free Grammar to Chomsky Normal Form Introduction of Pushdown Automata Construct Pushdown Automata for given languages How to identify if a language is regular or not Introduction of Theory of Computation Simplifying Context Free Grammars Closure properties of Regular languages Closure Properties of Context Free Languages Recursive and Recursive Enumerable Languages in TOC
[ { "code": null, "e": 24896, "s": 24868, "text": "\n12 Jun, 2020" }, { "code": null, "e": 24926, "s": 24896, "text": "Prerequisite – Turing Machine" }, { "code": null, "e": 25230, "s": 24926, "text": "The language L = {anbmcnm | n >= 0 and m>=0} represents a kind of language where we use only 3 symbols, i.e., a, b and c. In the beginning language has n number of a’s followed by m number of b’s and then n*m number of c’s. Any such string which falls in this category will be accepted by this language." }, { "code": null, "e": 25240, "s": 25230, "text": "Examples:" }, { "code": null, "e": 25335, "s": 25240, "text": "Input : abbcc\nOutput : YES\n\nInput : abbbcc\nOutput : NO\n\nInput : or empty string\nOutput : YES " }, { "code": null, "e": 25358, "s": 25335, "text": "Basic Representation :" }, { "code": null, "e": 25513, "s": 25358, "text": "Start of Computation :The tape contains the input string w, the tape head is on the leftmost symbol of w, and the Turing machine is in the start state Q0." }, { "code": null, "e": 26128, "s": 25513, "text": "Basic Idea :The tape head reads the leftmost symbol of w, which is a and at start only we will make it Blank. Then we will traverse to make leftmost b a $ and replace rightmost c by a Blank, we will do this zigzag pattern of replacing b by $ and c by Blank till all b are not replaced by $.After this we will traverse back in left direction till we get leftmost a and replacing all $ by b in the traversal. After this we have reduced our string into form an-1bmcnm-m so we can figure if all a’s are replaced by blankand if the string belongs to Language L then there will be no c’s left hence it will get accepted." }, { "code": null, "e": 26310, "s": 26128, "text": "Meanings of symbols used:R, L – direction of movement of one unit on either side.B-Blank,a, b, c -symbols whose combination string is to be tested.$-Temporarily symbol to replace b." }, { "code": null, "e": 26330, "s": 26310, "text": "Working Procedure :" }, { "code": null, "e": 26505, "s": 26330, "text": "Step-1:We first replace leftmost a by Blank and then traverse to replace leftmost b by $ and rightmost c by Blank.Repeat this step from state Q1 till there is no more b left." }, { "code": null, "e": 26798, "s": 26505, "text": "Step-2:After replacing all b by $ we have also replaced m rightmost c’s with Blanks and then we will traverse back to left most a and replace all $ by b’s.After this step if check the string it is now reduced to an-1bmcnm-m form.Now we will repeat from step 1 till all a’s are not made Blank." }, { "code": null, "e": 27103, "s": 26798, "text": "Step-3:So after all a’s are made blank and if the string belonged to Language L then 0 c’s must be left which we check at state Q0 and Q6 as only b’s will be left and after which if Blank is found then all c’s must have been replace by Blank as we where making c’s Blank from rightmost end of the string." }, { "code": null, "e": 27337, "s": 27103, "text": "Step-4:So if we get a Blank symbol at state Q6 the the string is accepted at final state Q7. Also if the string was empty then it will also be accepted as Blank symbol input at state Q0 then it will got to state Q7 and gets accepted." }, { "code": null, "e": 27370, "s": 27337, "text": "Theory of Computation & Automata" }, { "code": null, "e": 27468, "s": 27370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27511, "s": 27468, "text": "Chomsky Hierarchy in Theory of Computation" }, { "code": null, "e": 27566, "s": 27511, "text": "Converting Context Free Grammar to Chomsky Normal Form" }, { "code": null, "e": 27600, "s": 27566, "text": "Introduction of Pushdown Automata" }, { "code": null, "e": 27648, "s": 27600, "text": "Construct Pushdown Automata for given languages" }, { "code": null, "e": 27696, "s": 27648, "text": "How to identify if a language is regular or not" }, { "code": null, "e": 27734, "s": 27696, "text": "Introduction of Theory of Computation" }, { "code": null, "e": 27768, "s": 27734, "text": "Simplifying Context Free Grammars" }, { "code": null, "e": 27808, "s": 27768, "text": "Closure properties of Regular languages" }, { "code": null, "e": 27853, "s": 27808, "text": "Closure Properties of Context Free Languages" } ]
CICS - ENDBR
When we have finished reading a file sequentially, we terminate the browse using the ENDBR command. It tells the CICS that the browse is being terminated. Following is the syntax of the ENDBR command − EXEC CICS ENDBR FILE ('name') END-EXEC. Print Add Notes Bookmark this page
[ { "code": null, "e": 2081, "s": 1926, "text": "When we have finished reading a file sequentially, we terminate the browse using the ENDBR command. It tells the CICS that the browse is being terminated." }, { "code": null, "e": 2128, "s": 2081, "text": "Following is the syntax of the ENDBR command −" }, { "code": null, "e": 2172, "s": 2128, "text": "EXEC CICS ENDBR\n FILE ('name')\nEND-EXEC.\n" }, { "code": null, "e": 2179, "s": 2172, "text": " Print" }, { "code": null, "e": 2190, "s": 2179, "text": " Add Notes" } ]
Cross-entropy method for Reinforcement Learning | by Avishree Khare | Towards Data Science
If you have ever gathered the courage to explore the field of Reinforcement Learning, there are good chances that you found yourself lost in fancy vocabulary. Big words, names of complex algorithms with even more complex math behind them. But what if there were simpler, much more intuitive, and super-efficient algorithms out there that worked well? Meet the Cross-Entropy Method: An evolutionary algorithm for parameterized policy optimization that John Schulman claims works “embarrassingly well” on complex RL problems2. From a biological viewpoint, it is an Evolutionary Algorithm. Some individuals are sampled from a population and only the best ones govern the characteristics of future generations. Mathematically, it can be seen as a Derivative-Free Optimization (DFO) technique, i.e., it can find optima without the overhead of calculating derivatives (no backpropagation!). Assume for a second that you do not know what are agents, environments, and policies. You are just given a “black-box” which takes some numbers as inputs and outputs some other numbers. You can only choose the values for your inputs and observe the outputs. How do you guess the inputs such that the outputs are the values you want? One simple way of doing this would be to take a bunch of inputs, see the outputs produced, choose the inputs that have led to the best outputs and tune them till you are satisfied with the outputs you see. This is essentially what the cross-entropy method does. Let’s understand the working of CEM step-by-step with an example. I have added some python code snippets with each step for a better understanding of the implementation. The code is heavily borrowed from Udacity’s course on Deep Reinforcement Learning (amazing python RL resources btw, Github link at the end of this article)1. Consider your policy network. You want to find the best weights which can take the right “meaningful” actions based on your agent’s state. A CEM-based approach for finding these weights is as follows: Step 1: Draw a bunch of initial weights from a random distribution. Although this distribution is generally chosen to be Gaussian, you can choose any distribution that you believe the weights are from. Let’s say I drew 10 candidates for weights w1, w2, ..., w10 from a Gaussian distribution with mean μ and variance σ2. Consider μ=0, σ=1, n_weights=10 (number of candidates) and weights_dim represents dimensions of the weight vector. mean = 0.0 std = 1.0n_weights = 10weights_pop = [mean + std*np.random.randn(weights_dim) for i_weight in range(n_weights)] Step 2: Now let the agent pick actions from the policy network based on these weights, run the agent through an episode and collect the rewards generated by the environment. For our example, say w1 generates a cumulative reward r1, w2 generates r2 and so on. The evaluate method for an agent takes a weight candidate as input, plays an episode and outputs the cumulative reward from that episode. rewards = [agent.evaluate(weights) for weights in weights_pop] Step 3: Find the weights which generated the best rewards. Assume the best 4 weights were w1, w2, w5 and w6 (also called the “elite” weights). Here 4 is a number that we have chosen. In general, you consider best n weights, where n is chosen by you. n_elite = 4elite_idxs = np.array(rewards).argsort()[-n_elite:]elite_weights = [weights_pop[idx] for idx in elite_idxs] Step 4: Pick the new weights from a distribution defined by the elite weights. Say μ’ is the mean of the best weights (w1, w2, w5 and w6) and σ’2 is their variance. We now draw 10 candidates from a gaussian distribution with mean μ’ and variance σ’2. mean = np.array(elite_weights).mean()std = np.array(elite_weights).std()weights_pop = [mean + std*np.random.randn(weights_dim) for i_weight in range(n_weights)] Step 5: Repeat steps 2–4 until you are happy with the rewards you get. If python code is not your thing and you love to read algorithms with math jargon, here is the pseudocode for you2: Cross-Entropy Method is a simple algorithm that you can use for training RL agents. This method has outperformed several RL techniques on famous tasks including the game of Tetris4. You can use this as a baseline3 before moving to more complex RL algorithms like PPO, A3C, etc. There are several variants of CEM, however, the structure defined in this article is the backbone of all of them. That concludes this article on the Cross-Entropy Method for Reinforcement Learning. I hope you liked what you just read and thank you for your time. [1] https://github.com/udacity/deep-reinforcement-learning/tree/master/cross-entropy [2] MLSS 2016 on Deep Reinforcement Learning by John Schulman (https://www.youtube.com/watch?v=aUrX-rP_ss4) [3] http://karpathy.github.io/2016/05/31/rl/ [4] I. Szita and A. Lorincz, Learning Tetris Using the Noisy Cross-Entropy Method (2006), Neural Computation
[ { "code": null, "e": 523, "s": 172, "text": "If you have ever gathered the courage to explore the field of Reinforcement Learning, there are good chances that you found yourself lost in fancy vocabulary. Big words, names of complex algorithms with even more complex math behind them. But what if there were simpler, much more intuitive, and super-efficient algorithms out there that worked well?" }, { "code": null, "e": 697, "s": 523, "text": "Meet the Cross-Entropy Method: An evolutionary algorithm for parameterized policy optimization that John Schulman claims works “embarrassingly well” on complex RL problems2." }, { "code": null, "e": 879, "s": 697, "text": "From a biological viewpoint, it is an Evolutionary Algorithm. Some individuals are sampled from a population and only the best ones govern the characteristics of future generations." }, { "code": null, "e": 1057, "s": 879, "text": "Mathematically, it can be seen as a Derivative-Free Optimization (DFO) technique, i.e., it can find optima without the overhead of calculating derivatives (no backpropagation!)." }, { "code": null, "e": 1390, "s": 1057, "text": "Assume for a second that you do not know what are agents, environments, and policies. You are just given a “black-box” which takes some numbers as inputs and outputs some other numbers. You can only choose the values for your inputs and observe the outputs. How do you guess the inputs such that the outputs are the values you want?" }, { "code": null, "e": 1652, "s": 1390, "text": "One simple way of doing this would be to take a bunch of inputs, see the outputs produced, choose the inputs that have led to the best outputs and tune them till you are satisfied with the outputs you see. This is essentially what the cross-entropy method does." }, { "code": null, "e": 1980, "s": 1652, "text": "Let’s understand the working of CEM step-by-step with an example. I have added some python code snippets with each step for a better understanding of the implementation. The code is heavily borrowed from Udacity’s course on Deep Reinforcement Learning (amazing python RL resources btw, Github link at the end of this article)1." }, { "code": null, "e": 2181, "s": 1980, "text": "Consider your policy network. You want to find the best weights which can take the right “meaningful” actions based on your agent’s state. A CEM-based approach for finding these weights is as follows:" }, { "code": null, "e": 2501, "s": 2181, "text": "Step 1: Draw a bunch of initial weights from a random distribution. Although this distribution is generally chosen to be Gaussian, you can choose any distribution that you believe the weights are from. Let’s say I drew 10 candidates for weights w1, w2, ..., w10 from a Gaussian distribution with mean μ and variance σ2." }, { "code": null, "e": 2616, "s": 2501, "text": "Consider μ=0, σ=1, n_weights=10 (number of candidates) and weights_dim represents dimensions of the weight vector." }, { "code": null, "e": 2745, "s": 2616, "text": "mean = 0.0 std = 1.0n_weights = 10weights_pop = [mean + std*np.random.randn(weights_dim) for i_weight in range(n_weights)]" }, { "code": null, "e": 3004, "s": 2745, "text": "Step 2: Now let the agent pick actions from the policy network based on these weights, run the agent through an episode and collect the rewards generated by the environment. For our example, say w1 generates a cumulative reward r1, w2 generates r2 and so on." }, { "code": null, "e": 3142, "s": 3004, "text": "The evaluate method for an agent takes a weight candidate as input, plays an episode and outputs the cumulative reward from that episode." }, { "code": null, "e": 3205, "s": 3142, "text": "rewards = [agent.evaluate(weights) for weights in weights_pop]" }, { "code": null, "e": 3455, "s": 3205, "text": "Step 3: Find the weights which generated the best rewards. Assume the best 4 weights were w1, w2, w5 and w6 (also called the “elite” weights). Here 4 is a number that we have chosen. In general, you consider best n weights, where n is chosen by you." }, { "code": null, "e": 3574, "s": 3455, "text": "n_elite = 4elite_idxs = np.array(rewards).argsort()[-n_elite:]elite_weights = [weights_pop[idx] for idx in elite_idxs]" }, { "code": null, "e": 3825, "s": 3574, "text": "Step 4: Pick the new weights from a distribution defined by the elite weights. Say μ’ is the mean of the best weights (w1, w2, w5 and w6) and σ’2 is their variance. We now draw 10 candidates from a gaussian distribution with mean μ’ and variance σ’2." }, { "code": null, "e": 3986, "s": 3825, "text": "mean = np.array(elite_weights).mean()std = np.array(elite_weights).std()weights_pop = [mean + std*np.random.randn(weights_dim) for i_weight in range(n_weights)]" }, { "code": null, "e": 4057, "s": 3986, "text": "Step 5: Repeat steps 2–4 until you are happy with the rewards you get." }, { "code": null, "e": 4173, "s": 4057, "text": "If python code is not your thing and you love to read algorithms with math jargon, here is the pseudocode for you2:" }, { "code": null, "e": 4565, "s": 4173, "text": "Cross-Entropy Method is a simple algorithm that you can use for training RL agents. This method has outperformed several RL techniques on famous tasks including the game of Tetris4. You can use this as a baseline3 before moving to more complex RL algorithms like PPO, A3C, etc. There are several variants of CEM, however, the structure defined in this article is the backbone of all of them." }, { "code": null, "e": 4714, "s": 4565, "text": "That concludes this article on the Cross-Entropy Method for Reinforcement Learning. I hope you liked what you just read and thank you for your time." }, { "code": null, "e": 4799, "s": 4714, "text": "[1] https://github.com/udacity/deep-reinforcement-learning/tree/master/cross-entropy" }, { "code": null, "e": 4907, "s": 4799, "text": "[2] MLSS 2016 on Deep Reinforcement Learning by John Schulman (https://www.youtube.com/watch?v=aUrX-rP_ss4)" }, { "code": null, "e": 4952, "s": 4907, "text": "[3] http://karpathy.github.io/2016/05/31/rl/" } ]
Python Packages for NLP-Part 1. Polyglot- Python package for NLP... | by Himanshu Sharma | Towards Data Science
Natural Language Processing aims at manipulating the human/natural language to make it understandable for the machine. It deals with text analysis, text mining, sentiment analysis, polarity analysis, etc. There are different python packages that make NLP operations easy and effortless. All NLP packages have different functionalities and operations which makes it easier for end-user to perform text analysis and all sorts of NLP operations. In this series of articles, we will explore different NLP packages for python and all of their functionalities. In this article, we will be discussing Polyglot which is an open-source python package used for manipulating text and extracting useful information from it. It has got several functionalities that make it better and easy to use than other NLP-based libraries. Here we will discuss its different functionalities and how to implement them. Let’s get started. In order to get started, we first need to install polyglot and all of its dependencies. For this article we will be using Google Colab, the code given below will install polyglot and its dependencies. !pip3 install polyglot!pip3 install pyicu!pip3 install pycld2!pip3 install morfessor After installing these libraries we also need to install some functionalities of polyglot which will be used in this article. !polyglot download embeddings2.en!polyglot download pos2.en!polyglot download ner2.en!polyglot download morph2.en!polyglot download sentiment2.en!polyglot download transliteration2.hi The next step is to import the required libraries and functionalities of polyglot that we will explore in this article. import polyglotfrom polyglot.detect import Detectorfrom polyglot.text import Text, Wordfrom polyglot.mapping import Embeddingfrom polyglot.transliteration import Transliterator Let us start by exploring some of the NLP functionalities that are provided by polyglot, but before that let us input some sample data that we will be working on. sample_text = '''Piyush is an Aspiring Data Scientist and is working hard to get there. He stood Kaggle grandmaster 4 year consistently. His goal is to work for Google.''' Language Detection Language Detection Polyglot’s language detector can easily identify the language in which the text is written. #Language detectiondetector = Detector(sample_text)print(detector.language) 2. Sentences and Words In order to extract the sentences or words from the text/corpus, we can use polyglot functions. #Tokenizetext = Text(sample_text)text.words text.sentences 3. POS Tagging Part of speech tagging is an important NLP operation that helps us in understanding the text and their tagging. #POS taggingtext.pos_tags 4. Named Entity Recognition NER is used to identify the person, organization, and location if any in the corpus/text dataset. #Named entity extractiontext.entities 5. Morphological Analysis #Morphological Analysiswords = ["programming", "parallel", "inevitable", "handsome"]for w in words: w = Word(w, language="en") print(w, w.morphemes) 6. Sentiment Analysis We can analyze the sentiment of a sentence. #Sentiment analysistext = Text("Himanshu is a good programmer.")for w in text.words: print(w, w.polarity) 7. Translate We can translate text into different languages. #Transliterationtransliterator = Transliterator(source_lang="en", target_lang="hi")new_text = ""for i in "Piyush Ingale".split(): new_text = new_text + " " + transliterator.transliterate(i)new_text This is how you can explore the different properties of Polyglot for text datasets easily without any hassle. Go ahead try this with different textual datasets, in case you find any difficulty you can post that in the response section. This post is in collaboration with Piyush Ingale Thanks for reading! If you want to get in touch with me, feel free to reach me on [email protected] or my LinkedIn Profile. You can view my Github profile for different data science projects and packages tutorials. Also, feel free to explore my profile and read different articles I have written related to Data Science.
[ { "code": null, "e": 459, "s": 172, "text": "Natural Language Processing aims at manipulating the human/natural language to make it understandable for the machine. It deals with text analysis, text mining, sentiment analysis, polarity analysis, etc. There are different python packages that make NLP operations easy and effortless." }, { "code": null, "e": 727, "s": 459, "text": "All NLP packages have different functionalities and operations which makes it easier for end-user to perform text analysis and all sorts of NLP operations. In this series of articles, we will explore different NLP packages for python and all of their functionalities." }, { "code": null, "e": 1065, "s": 727, "text": "In this article, we will be discussing Polyglot which is an open-source python package used for manipulating text and extracting useful information from it. It has got several functionalities that make it better and easy to use than other NLP-based libraries. Here we will discuss its different functionalities and how to implement them." }, { "code": null, "e": 1084, "s": 1065, "text": "Let’s get started." }, { "code": null, "e": 1285, "s": 1084, "text": "In order to get started, we first need to install polyglot and all of its dependencies. For this article we will be using Google Colab, the code given below will install polyglot and its dependencies." }, { "code": null, "e": 1370, "s": 1285, "text": "!pip3 install polyglot!pip3 install pyicu!pip3 install pycld2!pip3 install morfessor" }, { "code": null, "e": 1496, "s": 1370, "text": "After installing these libraries we also need to install some functionalities of polyglot which will be used in this article." }, { "code": null, "e": 1680, "s": 1496, "text": "!polyglot download embeddings2.en!polyglot download pos2.en!polyglot download ner2.en!polyglot download morph2.en!polyglot download sentiment2.en!polyglot download transliteration2.hi" }, { "code": null, "e": 1800, "s": 1680, "text": "The next step is to import the required libraries and functionalities of polyglot that we will explore in this article." }, { "code": null, "e": 1977, "s": 1800, "text": "import polyglotfrom polyglot.detect import Detectorfrom polyglot.text import Text, Wordfrom polyglot.mapping import Embeddingfrom polyglot.transliteration import Transliterator" }, { "code": null, "e": 2140, "s": 1977, "text": "Let us start by exploring some of the NLP functionalities that are provided by polyglot, but before that let us input some sample data that we will be working on." }, { "code": null, "e": 2312, "s": 2140, "text": "sample_text = '''Piyush is an Aspiring Data Scientist and is working hard to get there. He stood Kaggle grandmaster 4 year consistently. His goal is to work for Google.'''" }, { "code": null, "e": 2331, "s": 2312, "text": "Language Detection" }, { "code": null, "e": 2350, "s": 2331, "text": "Language Detection" }, { "code": null, "e": 2442, "s": 2350, "text": "Polyglot’s language detector can easily identify the language in which the text is written." }, { "code": null, "e": 2518, "s": 2442, "text": "#Language detectiondetector = Detector(sample_text)print(detector.language)" }, { "code": null, "e": 2541, "s": 2518, "text": "2. Sentences and Words" }, { "code": null, "e": 2637, "s": 2541, "text": "In order to extract the sentences or words from the text/corpus, we can use polyglot functions." }, { "code": null, "e": 2681, "s": 2637, "text": "#Tokenizetext = Text(sample_text)text.words" }, { "code": null, "e": 2696, "s": 2681, "text": "text.sentences" }, { "code": null, "e": 2711, "s": 2696, "text": "3. POS Tagging" }, { "code": null, "e": 2823, "s": 2711, "text": "Part of speech tagging is an important NLP operation that helps us in understanding the text and their tagging." }, { "code": null, "e": 2849, "s": 2823, "text": "#POS taggingtext.pos_tags" }, { "code": null, "e": 2877, "s": 2849, "text": "4. Named Entity Recognition" }, { "code": null, "e": 2975, "s": 2877, "text": "NER is used to identify the person, organization, and location if any in the corpus/text dataset." }, { "code": null, "e": 3013, "s": 2975, "text": "#Named entity extractiontext.entities" }, { "code": null, "e": 3039, "s": 3013, "text": "5. Morphological Analysis" }, { "code": null, "e": 3196, "s": 3039, "text": "#Morphological Analysiswords = [\"programming\", \"parallel\", \"inevitable\", \"handsome\"]for w in words: w = Word(w, language=\"en\") print(w, w.morphemes)" }, { "code": null, "e": 3218, "s": 3196, "text": "6. Sentiment Analysis" }, { "code": null, "e": 3262, "s": 3218, "text": "We can analyze the sentiment of a sentence." }, { "code": null, "e": 3370, "s": 3262, "text": "#Sentiment analysistext = Text(\"Himanshu is a good programmer.\")for w in text.words: print(w, w.polarity)" }, { "code": null, "e": 3383, "s": 3370, "text": "7. Translate" }, { "code": null, "e": 3431, "s": 3383, "text": "We can translate text into different languages." }, { "code": null, "e": 3630, "s": 3431, "text": "#Transliterationtransliterator = Transliterator(source_lang=\"en\", target_lang=\"hi\")new_text = \"\"for i in \"Piyush Ingale\".split(): new_text = new_text + \" \" + transliterator.transliterate(i)new_text" }, { "code": null, "e": 3740, "s": 3630, "text": "This is how you can explore the different properties of Polyglot for text datasets easily without any hassle." }, { "code": null, "e": 3866, "s": 3740, "text": "Go ahead try this with different textual datasets, in case you find any difficulty you can post that in the response section." }, { "code": null, "e": 3915, "s": 3866, "text": "This post is in collaboration with Piyush Ingale" } ]
How to set timezone offset using JavaScript ? - GeeksforGeeks
30 Jul, 2021 Timezone offset is the time difference in hours or minutes between the Coordinated Universal Time (UTC) and a given time zone. The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC. The returned value is not constant if the host system is configured for daylight saving. Syntax: date.getTimezoneOffset() Here, date is a JavaScript date object. Code Snippet: In the below code snippet, date.getTimezoneOffset() method will return the timezone difference in minutes, between the UTC and the local time. This will be stored in offset variable. Javascript var date = new Date();var offset = date.getTimezoneOffset(); Example: On clicking the “submit” button, showOffset() method is called which stores the value of timezone offset in offset variable. Then result text is inserted in the empty p tag. HTML <!DOCTYPE html><html> <body> <h2>Timezone offset</h2> <p> Click on submit button to display timezone offset in minutes </p><br> <!--Call showOffset() on clicking the submit button--> <input type="button" value="submit" onclick="showOffset()"> <br><br> <p id="time"></p> <script> function showOffset() { // Date object var date = new Date(); // Offset variable will store // timezone offset between // UTC and your local time var offset = date.getTimezoneOffset(); document.getElementById("time") .innerHTML = "Timezone offset: " + offset + " minutes"; } </script></body> </html> Output: Before Clicking the button: After Clicking the button: Note: The method returns your local timezone offset in minutes and not the timezone offset of the “date” object. // Output will be your local timezone offset // It does not depend on date object. var date = new Date('August 21, 2000 18:02:25 GMT+05:00'); console.log(date.getTimezoneOffset()); JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 24405, "s": 24377, "text": "\n30 Jul, 2021" }, { "code": null, "e": 24532, "s": 24405, "text": "Timezone offset is the time difference in hours or minutes between the Coordinated Universal Time (UTC) and a given time zone." }, { "code": null, "e": 24918, "s": 24532, "text": "The JavaScript getTimezoneOffset() method is used to find the timezone offset. It returns the timezone difference in minutes, between the UTC and the current local time. If the returned value is positive, local timezone is behind the UTC and if it is negative, the local timezone if ahead of UTC. The returned value is not constant if the host system is configured for daylight saving." }, { "code": null, "e": 24926, "s": 24918, "text": "Syntax:" }, { "code": null, "e": 24953, "s": 24926, "text": " date.getTimezoneOffset()\n" }, { "code": null, "e": 24993, "s": 24953, "text": "Here, date is a JavaScript date object." }, { "code": null, "e": 25190, "s": 24993, "text": "Code Snippet: In the below code snippet, date.getTimezoneOffset() method will return the timezone difference in minutes, between the UTC and the local time. This will be stored in offset variable." }, { "code": null, "e": 25201, "s": 25190, "text": "Javascript" }, { "code": "var date = new Date();var offset = date.getTimezoneOffset();", "e": 25262, "s": 25201, "text": null }, { "code": null, "e": 25445, "s": 25262, "text": "Example: On clicking the “submit” button, showOffset() method is called which stores the value of timezone offset in offset variable. Then result text is inserted in the empty p tag." }, { "code": null, "e": 25450, "s": 25445, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2>Timezone offset</h2> <p> Click on submit button to display timezone offset in minutes </p><br> <!--Call showOffset() on clicking the submit button--> <input type=\"button\" value=\"submit\" onclick=\"showOffset()\"> <br><br> <p id=\"time\"></p> <script> function showOffset() { // Date object var date = new Date(); // Offset variable will store // timezone offset between // UTC and your local time var offset = date.getTimezoneOffset(); document.getElementById(\"time\") .innerHTML = \"Timezone offset: \" + offset + \" minutes\"; } </script></body> </html>", "e": 26258, "s": 25450, "text": null }, { "code": null, "e": 26266, "s": 26258, "text": "Output:" }, { "code": null, "e": 26294, "s": 26266, "text": "Before Clicking the button:" }, { "code": null, "e": 26321, "s": 26294, "text": "After Clicking the button:" }, { "code": null, "e": 26434, "s": 26321, "text": "Note: The method returns your local timezone offset in minutes and not the timezone offset of the “date” object." }, { "code": null, "e": 26618, "s": 26434, "text": "// Output will be your local timezone offset \n// It does not depend on date object.\n\nvar date = new Date('August 21, 2000 18:02:25 GMT+05:00');\nconsole.log(date.getTimezoneOffset());\n" }, { "code": null, "e": 26837, "s": 26618, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 27023, "s": 26837, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 27032, "s": 27023, "text": "CSS-Misc" }, { "code": null, "e": 27042, "s": 27032, "text": "HTML-Misc" }, { "code": null, "e": 27058, "s": 27042, "text": "JavaScript-Misc" }, { "code": null, "e": 27062, "s": 27058, "text": "CSS" }, { "code": null, "e": 27067, "s": 27062, "text": "HTML" }, { "code": null, "e": 27078, "s": 27067, "text": "JavaScript" }, { "code": null, "e": 27095, "s": 27078, "text": "Web Technologies" }, { "code": null, "e": 27100, "s": 27095, "text": "HTML" }, { "code": null, "e": 27198, "s": 27100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27207, "s": 27198, "text": "Comments" }, { "code": null, "e": 27220, "s": 27207, "text": "Old Comments" }, { "code": null, "e": 27278, "s": 27220, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27315, "s": 27278, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27356, "s": 27315, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27393, "s": 27356, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27457, "s": 27393, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27517, "s": 27457, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27570, "s": 27517, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27607, "s": 27570, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27657, "s": 27607, "text": "How to Insert Form Data into Database using PHP ?" } ]
SQLite - C/C++
In this chapter, you will learn how to use SQLite in C/C++ programs. Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check SQLite Installation chapter to understand the installation process. Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation. sqlite3_open(const char *filename, sqlite3 **ppDb) This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines. If the filename argument is NULL or ':memory:', sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session. If the filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name. sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg) This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command. Here, the first argument sqlite3 is an open database object, sqlite_callback is a call back for which data is the 1st argument and errmsg will be returned to capture any error raised by the routine. SQLite3_exec() routine parses and executes every command given in the sql argument until it reaches the end of the string or encounters an error. sqlite3_close(sqlite3*) This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection. If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements. Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. #include <stdio.h> #include <sqlite3.h> int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } sqlite3_close(db); } Now, let's compile and run the above program to create our database test.db in the current directory. You can change your path as per your requirement. $gcc test.c -l sqlite3 $./a.out Opened database successfully If you are going to use C++ source code, then you can compile your code as follows − $g++ test.c -l sqlite3 Here, we are linking our program with sqlite3 library to provide required functions to C program. This will create a database file test.db in your directory and you will have the following result. -rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out -rw-r--r--. 1 root root 323 May 8 02:05 test.c -rw-r--r--. 1 root root 0 May 8 02:06 test.db Following C code segment will be used to create a table in the previously created database − #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stdout, "Opened database successfully\n"); } /* Create SQL statement */ sql = "CREATE TABLE COMPANY(" \ "ID INT PRIMARY KEY NOT NULL," \ "NAME TEXT NOT NULL," \ "AGE INT NOT NULL," \ "ADDRESS CHAR(50)," \ "SALARY REAL );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Table created successfully\n"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will create COMPANY table in your test.db and the final listing of the file will be as follows − -rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out -rw-r--r--. 1 root root 1207 May 8 02:31 test.c -rw-r--r--. 1 root root 3072 May 8 02:31 test.db Following C code segment shows how you can create records in COMPANY table created in the above example − #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (1, 'Paul', 32, 'California', 20000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) " \ "VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); " \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );" \ "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" \ "VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Records created successfully\n"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will create the given records in COMPANY table and will display the following two lines − Opened database successfully Records created successfully Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration − typedef int (*sqlite3_callback)( void*, /* Data provided in the 4th argument of sqlite3_exec() */ int, /* The number of columns in row */ char**, /* An array of strings representing fields in the row */ char** /* An array of strings representing column names */ ); If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument. Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example − #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create SQL statement */ sql = "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will produce the following result. Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully Following C code segment shows how we can use UPDATE statement to update any record and then fetch and display updated records from the COMPANY table. #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName){ int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create merged SQL statement */ sql = "UPDATE COMPANY set SALARY = 25000.00 where ID=1; " \ "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will produce the following result. Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 25000.0 Callback function called: ID = 2 NAME = Allen AGE = 25 ADDRESS = Texas SALARY = 15000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully Following C code segment shows how you can use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table. #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> static int callback(void *data, int argc, char **argv, char **azColName) { int i; fprintf(stderr, "%s: ", (const char*)data); for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char *sql; const char* data = "Callback function called"; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } /* Create merged SQL statement */ sql = "DELETE from COMPANY where ID=2; " \ "SELECT * from COMPANY"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\n"); } sqlite3_close(db); return 0; } When the above program is compiled and executed, it will produce the following result. Opened database successfully Callback function called: ID = 1 NAME = Paul AGE = 32 ADDRESS = California SALARY = 20000.0 Callback function called: ID = 3 NAME = Teddy AGE = 23 ADDRESS = Norway SALARY = 20000.0 Callback function called: ID = 4 NAME = Mark AGE = 25 ADDRESS = Rich-Mond SALARY = 65000.0 Operation done successfully 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2707, "s": 2638, "text": "In this chapter, you will learn how to use SQLite in C/C++ programs." }, { "code": null, "e": 2916, "s": 2707, "text": "Before you start using SQLite in our C/C++ programs, you need to make sure that you have SQLite library set up on the machine. You can check SQLite Installation chapter to understand the installation process." }, { "code": null, "e": 3173, "s": 2916, "text": "Following are important C/C++ SQLite interface routines, which can suffice your requirement to work with SQLite database from your C/C++ program. If you are looking for a more sophisticated application, then you can look into SQLite official documentation." }, { "code": null, "e": 3224, "s": 3173, "text": "sqlite3_open(const char *filename, sqlite3 **ppDb)" }, { "code": null, "e": 3361, "s": 3224, "text": "This routine opens a connection to an SQLite database file and returns a database connection object to be used by other SQLite routines." }, { "code": null, "e": 3514, "s": 3361, "text": "If the filename argument is NULL or ':memory:', sqlite3_open() will create an in-memory database in RAM that lasts only for the duration of the session." }, { "code": null, "e": 3704, "s": 3514, "text": "If the filename is not NULL, sqlite3_open() attempts to open the database file by using its value. If no file by that name exists, sqlite3_open() will open a new database file by that name." }, { "code": null, "e": 3788, "s": 3704, "text": "sqlite3_exec(sqlite3*, const char *sql, sqlite_callback, void *data, char **errmsg)" }, { "code": null, "e": 3925, "s": 3788, "text": "This routine provides a quick, easy way to execute SQL commands provided by sql argument which can consist of more than one SQL command." }, { "code": null, "e": 4124, "s": 3925, "text": "Here, the first argument sqlite3 is an open database object, sqlite_callback is a call back for which data is the 1st argument and errmsg will be returned to capture any error raised by the routine." }, { "code": null, "e": 4270, "s": 4124, "text": "SQLite3_exec() routine parses and executes every command given in the sql argument until it reaches the end of the string or encounters an error." }, { "code": null, "e": 4294, "s": 4270, "text": "sqlite3_close(sqlite3*)" }, { "code": null, "e": 4491, "s": 4294, "text": "This routine closes a database connection previously opened by a call to sqlite3_open(). All prepared statements associated with the connection should be finalized prior to closing the connection." }, { "code": null, "e": 4653, "s": 4491, "text": "If any queries remain that have not been finalized, sqlite3_close() will return SQLITE_BUSY with the error message Unable to close due to unfinalized statements." }, { "code": null, "e": 4828, "s": 4653, "text": "Following C code segment shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned." }, { "code": null, "e": 5195, "s": 4828, "text": "#include <stdio.h>\n#include <sqlite3.h> \n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n\n rc = sqlite3_open(\"test.db\", &db);\n\n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n sqlite3_close(db);\n}" }, { "code": null, "e": 5347, "s": 5195, "text": "Now, let's compile and run the above program to create our database test.db in the current directory. You can change your path as per your requirement." }, { "code": null, "e": 5408, "s": 5347, "text": "$gcc test.c -l sqlite3\n$./a.out\nOpened database successfully" }, { "code": null, "e": 5493, "s": 5408, "text": "If you are going to use C++ source code, then you can compile your code as follows −" }, { "code": null, "e": 5516, "s": 5493, "text": "$g++ test.c -l sqlite3" }, { "code": null, "e": 5713, "s": 5516, "text": "Here, we are linking our program with sqlite3 library to provide required functions to C program. This will create a database file test.db in your directory and you will have the following result." }, { "code": null, "e": 5858, "s": 5713, "text": "-rwxr-xr-x. 1 root root 7383 May 8 02:06 a.out\n-rw-r--r--. 1 root root 323 May 8 02:05 test.c\n-rw-r--r--. 1 root root 0 May 8 02:06 test.db\n" }, { "code": null, "e": 5951, "s": 5858, "text": "Following C code segment will be used to create a table in the previously created database −" }, { "code": null, "e": 7146, "s": 5951, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stdout, \"Opened database successfully\\n\");\n }\n\n /* Create SQL statement */\n sql = \"CREATE TABLE COMPANY(\" \\\n \"ID INT PRIMARY KEY NOT NULL,\" \\\n \"NAME TEXT NOT NULL,\" \\\n \"AGE INT NOT NULL,\" \\\n \"ADDRESS CHAR(50),\" \\\n \"SALARY REAL );\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n \n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Table created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 7295, "s": 7146, "text": "When the above program is compiled and executed, it will create COMPANY table in your test.db and the final listing of the file will be as follows −" }, { "code": null, "e": 7440, "s": 7295, "text": "-rwxr-xr-x. 1 root root 9567 May 8 02:31 a.out\n-rw-r--r--. 1 root root 1207 May 8 02:31 test.c\n-rw-r--r--. 1 root root 3072 May 8 02:31 test.db\n" }, { "code": null, "e": 7546, "s": 7440, "text": "Following C code segment shows how you can create records in COMPANY table created in the above example −" }, { "code": null, "e": 9009, "s": 7546, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *NotUsed, int argc, char **argv, char **azColName) {\n int i;\n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create SQL statement */\n sql = \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (1, 'Paul', 32, 'California', 20000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \" \\\n \"VALUES (2, 'Allen', 25, 'Texas', 15000.00 ); \" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );\" \\\n \"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)\" \\\n \"VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);\n \n if( rc != SQLITE_OK ){\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Records created successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 9151, "s": 9009, "text": "When the above program is compiled and executed, it will create the given records in COMPANY table and will display the following two lines −" }, { "code": null, "e": 9210, "s": 9151, "text": "Opened database successfully\nRecords created successfully\n" }, { "code": null, "e": 9464, "s": 9210, "text": "Before proceeding with actual example to fetch records, let us look at some detail about the callback function, which we are using in our examples. This callback provides a way to obtain results from SELECT statements. It has the following declaration −" }, { "code": null, "e": 9754, "s": 9464, "text": "typedef int (*sqlite3_callback)(\n void*, /* Data provided in the 4th argument of sqlite3_exec() */\n int, /* The number of columns in row */\n char**, /* An array of strings representing fields in the row */\n char** /* An array of strings representing column names */\n);" }, { "code": null, "e": 9961, "s": 9754, "text": "If the above callback is provided in sqlite_exec() routine as the third argument, SQLite will call this callback function for each record processed in each SELECT statement executed within the SQL argument." }, { "code": null, "e": 10084, "s": 9961, "text": "Following C code segment shows how you can fetch and display records from the COMPANY table created in the above example −" }, { "code": null, "e": 11193, "s": 10084, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *data, int argc, char **argv, char **azColName){\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n \n for(i = 0; i<argc; i++){\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n \n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create SQL statement */\n sql = \"SELECT * from COMPANY\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n \n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 11280, "s": 11193, "text": "When the above program is compiled and executed, it will produce the following result." }, { "code": null, "e": 11702, "s": 11280, "text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\n\nCallback function called: ID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n" }, { "code": null, "e": 11853, "s": 11702, "text": "Following C code segment shows how we can use UPDATE statement to update any record and then fetch and display updated records from the COMPANY table." }, { "code": null, "e": 13029, "s": 11853, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *data, int argc, char **argv, char **azColName){\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n \n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create merged SQL statement */\n sql = \"UPDATE COMPANY set SALARY = 25000.00 where ID=1; \" \\\n \"SELECT * from COMPANY\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n \n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 13116, "s": 13029, "text": "When the above program is compiled and executed, it will produce the following result." }, { "code": null, "e": 13538, "s": 13116, "text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 25000.0\n\nCallback function called: ID = 2\nNAME = Allen\nAGE = 25\nADDRESS = Texas\nSALARY = 15000.0\n\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n" }, { "code": null, "e": 13696, "s": 13538, "text": "Following C code segment shows how you can use DELETE statement to delete any record and then fetch and display the remaining records from the COMPANY table." }, { "code": null, "e": 14856, "s": 13696, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h> \n\nstatic int callback(void *data, int argc, char **argv, char **azColName) {\n int i;\n fprintf(stderr, \"%s: \", (const char*)data);\n \n for(i = 0; i<argc; i++) {\n printf(\"%s = %s\\n\", azColName[i], argv[i] ? argv[i] : \"NULL\");\n }\n printf(\"\\n\");\n return 0;\n}\n\nint main(int argc, char* argv[]) {\n sqlite3 *db;\n char *zErrMsg = 0;\n int rc;\n char *sql;\n const char* data = \"Callback function called\";\n\n /* Open database */\n rc = sqlite3_open(\"test.db\", &db);\n \n if( rc ) {\n fprintf(stderr, \"Can't open database: %s\\n\", sqlite3_errmsg(db));\n return(0);\n } else {\n fprintf(stderr, \"Opened database successfully\\n\");\n }\n\n /* Create merged SQL statement */\n sql = \"DELETE from COMPANY where ID=2; \" \\\n \"SELECT * from COMPANY\";\n\n /* Execute SQL statement */\n rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);\n \n if( rc != SQLITE_OK ) {\n fprintf(stderr, \"SQL error: %s\\n\", zErrMsg);\n sqlite3_free(zErrMsg);\n } else {\n fprintf(stdout, \"Operation done successfully\\n\");\n }\n sqlite3_close(db);\n return 0;\n}" }, { "code": null, "e": 14943, "s": 14856, "text": "When the above program is compiled and executed, it will produce the following result." }, { "code": null, "e": 15276, "s": 14943, "text": "Opened database successfully\nCallback function called: ID = 1\nNAME = Paul\nAGE = 32\nADDRESS = California\nSALARY = 20000.0\n\nCallback function called: ID = 3\nNAME = Teddy\nAGE = 23\nADDRESS = Norway\nSALARY = 20000.0\n\nCallback function called: ID = 4\nNAME = Mark\nAGE = 25\nADDRESS = Rich-Mond\nSALARY = 65000.0\n\nOperation done successfully\n" }, { "code": null, "e": 15311, "s": 15276, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 15332, "s": 15311, "text": " Sandip Bhattacharya" }, { "code": null, "e": 15365, "s": 15332, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 15382, "s": 15365, "text": " Laurence Svekis" }, { "code": null, "e": 15413, "s": 15382, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 15426, "s": 15413, "text": " Vinay Kumar" }, { "code": null, "e": 15433, "s": 15426, "text": " Print" }, { "code": null, "e": 15444, "s": 15433, "text": " Add Notes" } ]
Design a stack with operations on middle element
15 Jul, 2022 How to implement a stack which will support the following operations in O(1) time complexity? 1) push() which adds an element to the top of stack. 2) pop() which removes an element from top of stack. 3) findMiddle() which will return middle element of the stack. 4) deleteMiddle() which will delete the middle element. Push and pop are standard stack operations. Method 1:The important question is, whether to use a linked list or array for the implementation of the stack? Please note that we need to find and delete the middle element. Deleting an element from the middle is not O(1) for the array. Also, we may need to move the middle pointer up when we push an element and move down when we pop(). In a singly linked list, moving the middle pointer in both directions is not possible. The idea is to use a Doubly Linked List (DLL). We can delete the middle element in O(1) time by maintaining mid pointer. We can move the mid pointer in both directions using previous and next pointers. Following is implementation of push(), pop() and findMiddle() operations. If there are even elements in stack, findMiddle() returns the second middle element. For example, if stack contains {1, 2, 3, 4}, then findMiddle() would return 3. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. C++ C Java Python3 C# /* C++ Program to implement a stackthat supports findMiddle() anddeleteMiddle in O(1) time */#include <bits/stdc++.h>using namespace std; class myStack { struct Node { int num; Node* next; Node* prev; Node(int num) { this->num = num; } }; // Members of stack Node* head = NULL; Node* mid = NULL; int size = 0; public: void push(int data) { Node* temp = new Node(data); if (size == 0) { head = temp; mid = temp; size++; return; } head->next = temp; temp->prev = head; // update the pointers head = head->next; if (size % 2 == 1) { mid = mid->next; } size++; } int pop() { int data=-1; if (size != 0) { data=head->num; if (size == 1) { head = NULL; mid = NULL; } else { head = head->prev; head->next = NULL; if (size % 2 == 0) { mid = mid->prev; } } size--; } return data; } int findMiddle() { if (size == 0) { return -1; } return mid->num; } void deleteMiddle() { if (size != 0) { if (size == 1) { head = NULL; mid = NULL; } else if (size == 2) { head = head->prev; mid = mid->prev; head->next = NULL; } else { mid->next->prev = mid->prev; mid->prev->next = mid->next; if (size % 2 == 0) { mid = mid->prev; } else { mid = mid->next; } } size--; } }}; int main(){ myStack st; st.push(11); st.push(22); st.push(33); st.push(44); st.push(55); st.push(66); st.push(77); st.push(88); st.push(99); cout <<"Popped : "<< st.pop() << endl; cout <<"Popped : "<< st.pop() << endl; cout <<"Middle Element : "<< st.findMiddle() << endl; st.deleteMiddle(); cout <<"New Middle Element : "<< st.findMiddle() << endl; return 0;}// This code is contributed by Nikhil Goswami// Updated by Amsavarthan LV /* Program to implement a stack that supports findMiddle() and deleteMiddle in O(1) time */#include <stdio.h>#include <stdlib.h> /* A Doubly Linked List Node */struct DLLNode { struct DLLNode* prev; int data; struct DLLNode* next;}; /* Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes */struct myStack { struct DLLNode* head; struct DLLNode* mid; int count;}; /* Function to create the stack data structure */struct myStack* createMyStack(){ struct myStack* ms = (struct myStack*)malloc(sizeof(struct myStack)); ms->count = 0; return ms;}; /* Function to push an element to the stack */void push(struct myStack* ms, int new_data){ /* allocate DLLNode and put in data */ struct DLLNode* new_DLLNode = (struct DLLNode*)malloc(sizeof(struct DLLNode)); new_DLLNode->data = new_data; /* Since we are adding at the beginning, prev is always NULL */ new_DLLNode->prev = NULL; /* link the old list off the new DLLNode */ new_DLLNode->next = ms->head; /* Increment count of items in stack */ ms->count += 1; /* Change mid pointer in two cases 1) Linked List is empty 2) Number of nodes in linked list is odd */ if (ms->count == 1) { ms->mid = new_DLLNode; } else { ms->head->prev = new_DLLNode; if (ms->count & 1) // Update mid if ms->count is odd ms->mid = ms->mid->prev; } /* move head to point to the new DLLNode */ ms->head = new_DLLNode;} /* Function to pop an element from stack */int pop(struct myStack* ms){ /* Stack underflow */ if (ms->count == 0) { printf("Stack is empty\n"); return -1; } struct DLLNode* head = ms->head; int item = head->data; ms->head = head->next; // If linked list doesn't become empty, update prev // of new head as NULL if (ms->head != NULL) ms->head->prev = NULL; ms->count -= 1; // update the mid pointer when we have even number of // elements in the stack, i,e move down the mid pointer. if (!((ms->count) & 1)) ms->mid = ms->mid->next; free(head); return item;} // Function for finding middle of the stackint findMiddle(struct myStack* ms){ if (ms->count == 0) { printf("Stack is empty now\n"); return -1; } return ms->mid->data;} void deleteMiddle(struct myStack* ms){ if (ms->count == 0) { printf("Stack is empty now\n"); return; } ms->count -= 1; ms->mid->next->prev = ms->mid->prev; ms->mid->prev->next = ms->mid->next; if (ms->count % 2 != 0) { ms->mid=ms->mid->next; }else { ms->mid=ms->mid->prev; }} // Driver program to test functions of myStackint main(){ /* Let us create a stack using push() operation*/ struct myStack* ms = createMyStack(); push(ms, 11); push(ms, 22); push(ms, 33); push(ms, 44); push(ms, 55); push(ms, 66); push(ms, 77); push(ms, 88); push(ms, 99); printf("Popped : %d\n", pop(ms)); printf("Popped : %d\n", pop(ms)); printf("Middle Element : %d\n", findMiddle(ms)); deleteMiddle(ms); printf("New Middle Element : %d\n", findMiddle(ms)); return 0;}//Updated by Amsavarthan Lv /* Java Program to implement a stack that supportsfindMiddle() and deleteMiddle in O(1) time *//* A Doubly Linked List Node */class DLLNode { DLLNode prev; int data; DLLNode next; DLLNode(int data) { this.data = data; }} /* Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes */public class myStack { DLLNode head; DLLNode mid; DLLNode prev; DLLNode next; int size; /* Function to push an element to the stack */ void push(int new_data) { /* allocate DLLNode and put in data */ DLLNode new_node = new DLLNode(new_data); // if stack is empty if (size == 0) { head = new_node; mid = new_node; size++; return; } head.next = new_node; new_node.prev = head; head = head.next; if (size % 2 != 0) { mid = mid.next; } size++; } /* Function to pop an element from stack */ int pop() { int data = -1; /* Stack underflow */ if (size == 0) { System.out.println("Stack is empty"); // return -1; } if (size != 0) { if (size == 1) { head = null; mid = null; } else { data = head.data; head = head.prev; head.next = null; if (size % 2 == 0) { mid = mid.prev; } } size--; } return data; } // Function for finding middle of the stack int findMiddle() { if (size == 0) { System.out.println("Stack is empty now"); return -1; } return mid.data; } void deleteMiddleElement() { // This function will not only delete the middle // element // but also update the mid in case of even and // odd number of Elements // when the size is even then findmiddle() will show the // second middle element as mentioned in the problem // statement if (size != 0) { if (size == 1) { head = null; mid = null; } else if (size == 2) { head = head.prev; mid = mid.prev; head.next = null; } else { mid.next.prev = mid.prev; mid.prev.next = mid.next; if (size % 2 == 0) { mid = mid.prev; } else { mid = mid.next; } } size--; } } // Driver program to test functions of myStack public static void main(String args[]) { myStack ms = new myStack(); ms.push(11); ms.push(22); ms.push(33); ms.push(44); ms.push(55); ms.push(66); ms.push(77); ms.push(88); ms.push(99); System.out.println("Popped : " + ms.pop()); System.out.println("Popped : " + ms.pop()); System.out.println("Middle Element : " + ms.findMiddle()); ms.deleteMiddleElement(); System.out.println("New Middle Element : " + ms.findMiddle()); }}// This code is contributed by Abhishek Jha// Updated by Amsavarthan Lv ''' Python3 Program to implement a stack that supports findMiddle() and deleteMiddle in O(1) time ''' ''' A Doubly Linked List Node ''' class DLLNode: def __init__(self, d): self.prev = None self.data = d self.next = None ''' Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes ''' class myStack: def __init__(self): self.head = None self.mid = None self.count = 0 ''' Function to create the stack data structure ''' def createMyStack(): ms = myStack() ms.count = 0 return ms ''' Function to push an element to the stack ''' def push(ms, new_data): ''' allocate DLLNode and put in data ''' new_DLLNode = DLLNode(new_data) ''' Since we are adding at the beginning, prev is always NULL ''' new_DLLNode.prev = None ''' link the old list off the new DLLNode ''' new_DLLNode.next = ms.head ''' Increment count of items in stack ''' ms.count += 1 ''' Change mid pointer in two cases 1) Linked List is empty 2) Number of nodes in linked list is odd ''' if(ms.count == 1): ms.mid = new_DLLNode else: ms.head.prev = new_DLLNode # Update mid if ms->count is odd if((ms.count % 2) != 0): ms.mid = ms.mid.prev ''' move head to point to the new DLLNode ''' ms.head = new_DLLNode ''' Function to pop an element from stack ''' def pop(ms): ''' Stack underflow ''' if(ms.count == 0): print("Stack is empty") return -1 head = ms.head item = head.data ms.head = head.next # If linked list doesn't become empty, # update prev of new head as NULL if(ms.head != None): ms.head.prev = None ms.count -= 1 # update the mid pointer when # we have even number of elements # in the stack, i,e move down # the mid pointer. if(ms.count % 2 == 0): ms.mid = ms.mid.next return item # Function for finding middle of the stack def findMiddle(ms): if(ms.count == 0): print("Stack is empty now") return -1 return ms.mid.data def deleteMiddle(ms): if(ms.count == 0): print("Stack is empty now") return ms.count-=1 ms.mid.next.prev=ms.mid.prev ms.mid.prev.next=ms.mid.next if ms.count %2==1: ms.mid=ms.mid.next else: ms.mid=ms.mid.prev # Driver codeif __name__ == '__main__': ms = createMyStack() push(ms, 11) push(ms, 22) push(ms, 33) push(ms, 44) push(ms, 55) push(ms, 66) push(ms, 77) push(ms, 88) push(ms, 99) print("Popped : " + str(pop(ms))) print("Popped : " + str(pop(ms))) print("Middle Element : " + str(findMiddle(ms))) deleteMiddle(ms) print("New Middle Element : " + str(findMiddle(ms))) # This code is contributed by rutvik_56. # Updated by Amsavarthan Lv /* C# Program to implement a stackthat supports findMiddle()and deleteMiddle in O(1) time */using System; class GFG { /* A Doubly Linked List Node */ public class DLLNode { public DLLNode prev; public int data; public DLLNode next; public DLLNode(int d) { data = d; } } /* Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes */ public class myStack { public DLLNode head; public DLLNode mid; public int count; } /* Function to create the stack data structure */ myStack createMyStack() { myStack ms = new myStack(); ms.count = 0; return ms; } /* Function to push an element to the stack */ void push(myStack ms, int new_data) { /* allocate DLLNode and put in data */ DLLNode new_DLLNode = new DLLNode(new_data); /* Since we are adding at the beginning, prev is always NULL */ new_DLLNode.prev = null; /* link the old list off the new DLLNode */ new_DLLNode.next = ms.head; /* Increment count of items in stack */ ms.count += 1; /* Change mid pointer in two cases 1) Linked List is empty 2) Number of nodes in linked list is odd */ if (ms.count == 1) { ms.mid = new_DLLNode; } else { ms.head.prev = new_DLLNode; // Update mid if ms->count is odd if ((ms.count % 2) != 0) ms.mid = ms.mid.prev; } /* move head to point to the new DLLNode */ ms.head = new_DLLNode; } /* Function to pop an element from stack */ int pop(myStack ms) { /* Stack underflow */ if (ms.count == 0) { Console.WriteLine("Stack is empty"); return -1; } DLLNode head = ms.head; int item = head.data; ms.head = head.next; // If linked list doesn't become empty, // update prev of new head as NULL if (ms.head != null) ms.head.prev = null; ms.count -= 1; // update the mid pointer when // we have even number of elements // in the stack, i,e move down // the mid pointer. if (ms.count % 2 == 0) ms.mid = ms.mid.next; return item; } // Function for finding middle of the stack int findMiddle(myStack ms) { if (ms.count == 0) { Console.WriteLine("Stack is empty now"); return -1; } return ms.mid.data; } void deleteMiddle(myStack ms){ if (ms.count == 0) { Console.WriteLine("Stack is empty now"); return; } ms.count-=1; ms.mid.next.prev=ms.mid.prev; ms.mid.prev.next=ms.mid.next; if(ms.count %2!=0){ ms.mid=ms.mid.next; }else{ ms.mid=ms.mid.prev; } } // Driver code public static void Main(String[] args) { GFG ob = new GFG(); myStack ms = ob.createMyStack(); ob.push(ms, 11); ob.push(ms, 22); ob.push(ms, 33); ob.push(ms, 44); ob.push(ms, 55); ob.push(ms, 66); ob.push(ms, 77); ob.push(ms, 88); ob.push(ms, 99);ber144 index143 alt1"> Console.WriteLine("Popped : " + ob.pop(ms)); Console.WriteLine("Popped : " + ob.pop(ms)); Console.WriteLine("Middle Element : " + ob.findMiddle(ms)); ob.deleteMiddle(ms); Console.WriteLine("New Middle Element : " + ob.findMiddle(ms)); }} // This code is contributed// by Arnab Kundu // Updated by Amsavarthan Lv Popped : 99 Popped : 88 Middle Element : 44 New Middle Element : 55 Method 2: Using a standard stack and a deque We will use a standard stack to store half of the elements and the other half of the elements which were added recently will be present in the deque. Insert operation on myStack will add an element into the back of the deque. The number of elements in the deque stays 1 more or equal to that in the stack, however, whenever the number of elements present in the deque exceeds the number of elements in the stack by more than 1 we pop an element from the front of the deque and push it into the stack. The pop operation on myStack will remove an element from the back of the deque. If after the pop operation, the size of the deque is less than the size of the stack, we pop an element from the top of the stack and insert it back into the front of the deque so that size of the deque is not less than the stack. We will see that the middle element is always the front element of the deque. So deleting of the middle element can be done in O(1) if we just pop the element from the front of the deque. Consider Operations on My_stack: Operation stack deque add(2) { } {2} add(5) {2} {5} add(3) {2} {5,3} add(7) {2,5} {3,7} add(4) {2,5} {3,7,4} deleteMiddle() {2,5} {7,4} deleteMiddle() {2} {5,4} pop() {2} {5} pop() { } {2} deleteMiddle() { } { } C++ #include <bits/stdc++.h>using namespace std; class myStack { stack<int> st; deque<int> dq; public: void add(int data) { dq.push_back(data); if (dq.size() > st.size() + 1) { int temp = dq.front(); dq.pop_front(); st.push(temp); } } void pop() { int data = dq.back(); dq.pop_back(); if (st.size() > dq.size()) { int temp = st.top(); st.pop(); dq.push_front(temp); } } int getMiddleElement() { return dq.front(); } void deleteMiddleElement() { dq.pop_front(); if (st.size() > dq.size()) { // new middle element int temp = st.top(); // should come at front of deque st.pop(); dq.push_front(temp); } }}; int main(){ myStack st; st.add(2); st.add(5); cout << "Middle Element: " << st.getMiddleElement() << endl; st.add(3); st.add(7); st.add(4); cout << "Middle Element: " << st.getMiddleElement() << endl; st.deleteMiddleElement(); cout << "Middle Element: " << st.getMiddleElement() << endl; st.deleteMiddleElement(); cout << "Middle Element: " << st.getMiddleElement() << endl; st.pop(); st.pop(); st.deleteMiddleElement();} //By- Vijay Chadokar Middle Element: 5 Middle Element: 3 Middle Element: 7 Middle Element: 5 This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above andrew1234 rathbhupendra Akanksha_Rai logesh1998 ShreyPaharia rutvik_56 anushikasethh msohaibayub nikhil070g jhaabhishek45 amsavarthan chadokarvijay shivamgupta2 Stack Stack Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jul, 2022" }, { "code": null, "e": 418, "s": 54, "text": "How to implement a stack which will support the following operations in O(1) time complexity? 1) push() which adds an element to the top of stack. 2) pop() which removes an element from top of stack. 3) findMiddle() which will return middle element of the stack. 4) deleteMiddle() which will delete the middle element. Push and pop are standard stack operations. " }, { "code": null, "e": 1286, "s": 418, "text": "Method 1:The important question is, whether to use a linked list or array for the implementation of the stack? Please note that we need to find and delete the middle element. Deleting an element from the middle is not O(1) for the array. Also, we may need to move the middle pointer up when we push an element and move down when we pop(). In a singly linked list, moving the middle pointer in both directions is not possible. The idea is to use a Doubly Linked List (DLL). We can delete the middle element in O(1) time by maintaining mid pointer. We can move the mid pointer in both directions using previous and next pointers. Following is implementation of push(), pop() and findMiddle() operations. If there are even elements in stack, findMiddle() returns the second middle element. For example, if stack contains {1, 2, 3, 4}, then findMiddle() would return 3. " }, { "code": null, "e": 1295, "s": 1286, "text": "Chapters" }, { "code": null, "e": 1322, "s": 1295, "text": "descriptions off, selected" }, { "code": null, "e": 1372, "s": 1322, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1395, "s": 1372, "text": "captions off, selected" }, { "code": null, "e": 1403, "s": 1395, "text": "English" }, { "code": null, "e": 1427, "s": 1403, "text": "This is a modal window." }, { "code": null, "e": 1496, "s": 1427, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1518, "s": 1496, "text": "End of dialog window." }, { "code": null, "e": 1522, "s": 1518, "text": "C++" }, { "code": null, "e": 1524, "s": 1522, "text": "C" }, { "code": null, "e": 1529, "s": 1524, "text": "Java" }, { "code": null, "e": 1537, "s": 1529, "text": "Python3" }, { "code": null, "e": 1540, "s": 1537, "text": "C#" }, { "code": "/* C++ Program to implement a stackthat supports findMiddle() anddeleteMiddle in O(1) time */#include <bits/stdc++.h>using namespace std; class myStack { struct Node { int num; Node* next; Node* prev; Node(int num) { this->num = num; } }; // Members of stack Node* head = NULL; Node* mid = NULL; int size = 0; public: void push(int data) { Node* temp = new Node(data); if (size == 0) { head = temp; mid = temp; size++; return; } head->next = temp; temp->prev = head; // update the pointers head = head->next; if (size % 2 == 1) { mid = mid->next; } size++; } int pop() { int data=-1; if (size != 0) { data=head->num; if (size == 1) { head = NULL; mid = NULL; } else { head = head->prev; head->next = NULL; if (size % 2 == 0) { mid = mid->prev; } } size--; } return data; } int findMiddle() { if (size == 0) { return -1; } return mid->num; } void deleteMiddle() { if (size != 0) { if (size == 1) { head = NULL; mid = NULL; } else if (size == 2) { head = head->prev; mid = mid->prev; head->next = NULL; } else { mid->next->prev = mid->prev; mid->prev->next = mid->next; if (size % 2 == 0) { mid = mid->prev; } else { mid = mid->next; } } size--; } }}; int main(){ myStack st; st.push(11); st.push(22); st.push(33); st.push(44); st.push(55); st.push(66); st.push(77); st.push(88); st.push(99); cout <<\"Popped : \"<< st.pop() << endl; cout <<\"Popped : \"<< st.pop() << endl; cout <<\"Middle Element : \"<< st.findMiddle() << endl; st.deleteMiddle(); cout <<\"New Middle Element : \"<< st.findMiddle() << endl; return 0;}// This code is contributed by Nikhil Goswami// Updated by Amsavarthan LV", "e": 3919, "s": 1540, "text": null }, { "code": "/* Program to implement a stack that supports findMiddle() and deleteMiddle in O(1) time */#include <stdio.h>#include <stdlib.h> /* A Doubly Linked List Node */struct DLLNode { struct DLLNode* prev; int data; struct DLLNode* next;}; /* Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes */struct myStack { struct DLLNode* head; struct DLLNode* mid; int count;}; /* Function to create the stack data structure */struct myStack* createMyStack(){ struct myStack* ms = (struct myStack*)malloc(sizeof(struct myStack)); ms->count = 0; return ms;}; /* Function to push an element to the stack */void push(struct myStack* ms, int new_data){ /* allocate DLLNode and put in data */ struct DLLNode* new_DLLNode = (struct DLLNode*)malloc(sizeof(struct DLLNode)); new_DLLNode->data = new_data; /* Since we are adding at the beginning, prev is always NULL */ new_DLLNode->prev = NULL; /* link the old list off the new DLLNode */ new_DLLNode->next = ms->head; /* Increment count of items in stack */ ms->count += 1; /* Change mid pointer in two cases 1) Linked List is empty 2) Number of nodes in linked list is odd */ if (ms->count == 1) { ms->mid = new_DLLNode; } else { ms->head->prev = new_DLLNode; if (ms->count & 1) // Update mid if ms->count is odd ms->mid = ms->mid->prev; } /* move head to point to the new DLLNode */ ms->head = new_DLLNode;} /* Function to pop an element from stack */int pop(struct myStack* ms){ /* Stack underflow */ if (ms->count == 0) { printf(\"Stack is empty\\n\"); return -1; } struct DLLNode* head = ms->head; int item = head->data; ms->head = head->next; // If linked list doesn't become empty, update prev // of new head as NULL if (ms->head != NULL) ms->head->prev = NULL; ms->count -= 1; // update the mid pointer when we have even number of // elements in the stack, i,e move down the mid pointer. if (!((ms->count) & 1)) ms->mid = ms->mid->next; free(head); return item;} // Function for finding middle of the stackint findMiddle(struct myStack* ms){ if (ms->count == 0) { printf(\"Stack is empty now\\n\"); return -1; } return ms->mid->data;} void deleteMiddle(struct myStack* ms){ if (ms->count == 0) { printf(\"Stack is empty now\\n\"); return; } ms->count -= 1; ms->mid->next->prev = ms->mid->prev; ms->mid->prev->next = ms->mid->next; if (ms->count % 2 != 0) { ms->mid=ms->mid->next; }else { ms->mid=ms->mid->prev; }} // Driver program to test functions of myStackint main(){ /* Let us create a stack using push() operation*/ struct myStack* ms = createMyStack(); push(ms, 11); push(ms, 22); push(ms, 33); push(ms, 44); push(ms, 55); push(ms, 66); push(ms, 77); push(ms, 88); push(ms, 99); printf(\"Popped : %d\\n\", pop(ms)); printf(\"Popped : %d\\n\", pop(ms)); printf(\"Middle Element : %d\\n\", findMiddle(ms)); deleteMiddle(ms); printf(\"New Middle Element : %d\\n\", findMiddle(ms)); return 0;}//Updated by Amsavarthan Lv", "e": 7306, "s": 3919, "text": null }, { "code": "/* Java Program to implement a stack that supportsfindMiddle() and deleteMiddle in O(1) time *//* A Doubly Linked List Node */class DLLNode { DLLNode prev; int data; DLLNode next; DLLNode(int data) { this.data = data; }} /* Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes */public class myStack { DLLNode head; DLLNode mid; DLLNode prev; DLLNode next; int size; /* Function to push an element to the stack */ void push(int new_data) { /* allocate DLLNode and put in data */ DLLNode new_node = new DLLNode(new_data); // if stack is empty if (size == 0) { head = new_node; mid = new_node; size++; return; } head.next = new_node; new_node.prev = head; head = head.next; if (size % 2 != 0) { mid = mid.next; } size++; } /* Function to pop an element from stack */ int pop() { int data = -1; /* Stack underflow */ if (size == 0) { System.out.println(\"Stack is empty\"); // return -1; } if (size != 0) { if (size == 1) { head = null; mid = null; } else { data = head.data; head = head.prev; head.next = null; if (size % 2 == 0) { mid = mid.prev; } } size--; } return data; } // Function for finding middle of the stack int findMiddle() { if (size == 0) { System.out.println(\"Stack is empty now\"); return -1; } return mid.data; } void deleteMiddleElement() { // This function will not only delete the middle // element // but also update the mid in case of even and // odd number of Elements // when the size is even then findmiddle() will show the // second middle element as mentioned in the problem // statement if (size != 0) { if (size == 1) { head = null; mid = null; } else if (size == 2) { head = head.prev; mid = mid.prev; head.next = null; } else { mid.next.prev = mid.prev; mid.prev.next = mid.next; if (size % 2 == 0) { mid = mid.prev; } else { mid = mid.next; } } size--; } } // Driver program to test functions of myStack public static void main(String args[]) { myStack ms = new myStack(); ms.push(11); ms.push(22); ms.push(33); ms.push(44); ms.push(55); ms.push(66); ms.push(77); ms.push(88); ms.push(99); System.out.println(\"Popped : \" + ms.pop()); System.out.println(\"Popped : \" + ms.pop()); System.out.println(\"Middle Element : \" + ms.findMiddle()); ms.deleteMiddleElement(); System.out.println(\"New Middle Element : \" + ms.findMiddle()); }}// This code is contributed by Abhishek Jha// Updated by Amsavarthan Lv", "e": 10827, "s": 7306, "text": null }, { "code": "''' Python3 Program to implement a stack that supports findMiddle() and deleteMiddle in O(1) time ''' ''' A Doubly Linked List Node ''' class DLLNode: def __init__(self, d): self.prev = None self.data = d self.next = None ''' Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes ''' class myStack: def __init__(self): self.head = None self.mid = None self.count = 0 ''' Function to create the stack data structure ''' def createMyStack(): ms = myStack() ms.count = 0 return ms ''' Function to push an element to the stack ''' def push(ms, new_data): ''' allocate DLLNode and put in data ''' new_DLLNode = DLLNode(new_data) ''' Since we are adding at the beginning, prev is always NULL ''' new_DLLNode.prev = None ''' link the old list off the new DLLNode ''' new_DLLNode.next = ms.head ''' Increment count of items in stack ''' ms.count += 1 ''' Change mid pointer in two cases 1) Linked List is empty 2) Number of nodes in linked list is odd ''' if(ms.count == 1): ms.mid = new_DLLNode else: ms.head.prev = new_DLLNode # Update mid if ms->count is odd if((ms.count % 2) != 0): ms.mid = ms.mid.prev ''' move head to point to the new DLLNode ''' ms.head = new_DLLNode ''' Function to pop an element from stack ''' def pop(ms): ''' Stack underflow ''' if(ms.count == 0): print(\"Stack is empty\") return -1 head = ms.head item = head.data ms.head = head.next # If linked list doesn't become empty, # update prev of new head as NULL if(ms.head != None): ms.head.prev = None ms.count -= 1 # update the mid pointer when # we have even number of elements # in the stack, i,e move down # the mid pointer. if(ms.count % 2 == 0): ms.mid = ms.mid.next return item # Function for finding middle of the stack def findMiddle(ms): if(ms.count == 0): print(\"Stack is empty now\") return -1 return ms.mid.data def deleteMiddle(ms): if(ms.count == 0): print(\"Stack is empty now\") return ms.count-=1 ms.mid.next.prev=ms.mid.prev ms.mid.prev.next=ms.mid.next if ms.count %2==1: ms.mid=ms.mid.next else: ms.mid=ms.mid.prev # Driver codeif __name__ == '__main__': ms = createMyStack() push(ms, 11) push(ms, 22) push(ms, 33) push(ms, 44) push(ms, 55) push(ms, 66) push(ms, 77) push(ms, 88) push(ms, 99) print(\"Popped : \" + str(pop(ms))) print(\"Popped : \" + str(pop(ms))) print(\"Middle Element : \" + str(findMiddle(ms))) deleteMiddle(ms) print(\"New Middle Element : \" + str(findMiddle(ms))) # This code is contributed by rutvik_56. # Updated by Amsavarthan Lv", "e": 13835, "s": 10827, "text": null }, { "code": "/* C# Program to implement a stackthat supports findMiddle()and deleteMiddle in O(1) time */using System; class GFG { /* A Doubly Linked List Node */ public class DLLNode { public DLLNode prev; public int data; public DLLNode next; public DLLNode(int d) { data = d; } } /* Representation of the stack data structure that supports findMiddle() in O(1) time. The Stack is implemented using Doubly Linked List. It maintains pointer to head node, pointer to middle node and count of nodes */ public class myStack { public DLLNode head; public DLLNode mid; public int count; } /* Function to create the stack data structure */ myStack createMyStack() { myStack ms = new myStack(); ms.count = 0; return ms; } /* Function to push an element to the stack */ void push(myStack ms, int new_data) { /* allocate DLLNode and put in data */ DLLNode new_DLLNode = new DLLNode(new_data); /* Since we are adding at the beginning, prev is always NULL */ new_DLLNode.prev = null; /* link the old list off the new DLLNode */ new_DLLNode.next = ms.head; /* Increment count of items in stack */ ms.count += 1; /* Change mid pointer in two cases 1) Linked List is empty 2) Number of nodes in linked list is odd */ if (ms.count == 1) { ms.mid = new_DLLNode; } else { ms.head.prev = new_DLLNode; // Update mid if ms->count is odd if ((ms.count % 2) != 0) ms.mid = ms.mid.prev; } /* move head to point to the new DLLNode */ ms.head = new_DLLNode; } /* Function to pop an element from stack */ int pop(myStack ms) { /* Stack underflow */ if (ms.count == 0) { Console.WriteLine(\"Stack is empty\"); return -1; } DLLNode head = ms.head; int item = head.data; ms.head = head.next; // If linked list doesn't become empty, // update prev of new head as NULL if (ms.head != null) ms.head.prev = null; ms.count -= 1; // update the mid pointer when // we have even number of elements // in the stack, i,e move down // the mid pointer. if (ms.count % 2 == 0) ms.mid = ms.mid.next; return item; } // Function for finding middle of the stack int findMiddle(myStack ms) { if (ms.count == 0) { Console.WriteLine(\"Stack is empty now\"); return -1; } return ms.mid.data; } void deleteMiddle(myStack ms){ if (ms.count == 0) { Console.WriteLine(\"Stack is empty now\"); return; } ms.count-=1; ms.mid.next.prev=ms.mid.prev; ms.mid.prev.next=ms.mid.next; if(ms.count %2!=0){ ms.mid=ms.mid.next; }else{ ms.mid=ms.mid.prev; } } // Driver code public static void Main(String[] args) { GFG ob = new GFG(); myStack ms = ob.createMyStack(); ob.push(ms, 11); ob.push(ms, 22); ob.push(ms, 33); ob.push(ms, 44); ob.push(ms, 55); ob.push(ms, 66); ob.push(ms, 77); ob.push(ms, 88); ob.push(ms, 99);ber144 index143 alt1\"> Console.WriteLine(\"Popped : \" + ob.pop(ms)); Console.WriteLine(\"Popped : \" + ob.pop(ms)); Console.WriteLine(\"Middle Element : \" + ob.findMiddle(ms)); ob.deleteMiddle(ms); Console.WriteLine(\"New Middle Element : \" + ob.findMiddle(ms)); }} // This code is contributed// by Arnab Kundu // Updated by Amsavarthan Lv", "e": 17639, "s": 13835, "text": null }, { "code": null, "e": 17707, "s": 17639, "text": "Popped : 99\nPopped : 88\nMiddle Element : 44\nNew Middle Element : 55" }, { "code": null, "e": 17753, "s": 17707, "text": "Method 2: Using a standard stack and a deque " }, { "code": null, "e": 18754, "s": 17753, "text": "We will use a standard stack to store half of the elements and the other half of the elements which were added recently will be present in the deque. Insert operation on myStack will add an element into the back of the deque. The number of elements in the deque stays 1 more or equal to that in the stack, however, whenever the number of elements present in the deque exceeds the number of elements in the stack by more than 1 we pop an element from the front of the deque and push it into the stack. The pop operation on myStack will remove an element from the back of the deque. If after the pop operation, the size of the deque is less than the size of the stack, we pop an element from the top of the stack and insert it back into the front of the deque so that size of the deque is not less than the stack. We will see that the middle element is always the front element of the deque. So deleting of the middle element can be done in O(1) if we just pop the element from the front of the deque. " }, { "code": null, "e": 18787, "s": 18754, "text": "Consider Operations on My_stack:" }, { "code": null, "e": 18871, "s": 18787, "text": "Operation stack deque" }, { "code": null, "e": 18960, "s": 18871, "text": "add(2) { } {2}" }, { "code": null, "e": 19048, "s": 18960, "text": "add(5) {2} {5}" }, { "code": null, "e": 19138, "s": 19048, "text": "add(3) {2} {5,3}" }, { "code": null, "e": 19227, "s": 19138, "text": "add(7) {2,5} {3,7}" }, { "code": null, "e": 19318, "s": 19227, "text": "add(4) {2,5} {3,7,4}" }, { "code": null, "e": 19403, "s": 19318, "text": "deleteMiddle() {2,5} {7,4}" }, { "code": null, "e": 19489, "s": 19403, "text": "deleteMiddle() {2} {5,4}" }, { "code": null, "e": 19578, "s": 19489, "text": "pop() {2} {5}" }, { "code": null, "e": 19668, "s": 19578, "text": "pop() { } {2}" }, { "code": null, "e": 19753, "s": 19668, "text": "deleteMiddle() { } { }" }, { "code": null, "e": 19757, "s": 19753, "text": "C++" }, { "code": "#include <bits/stdc++.h>using namespace std; class myStack { stack<int> st; deque<int> dq; public: void add(int data) { dq.push_back(data); if (dq.size() > st.size() + 1) { int temp = dq.front(); dq.pop_front(); st.push(temp); } } void pop() { int data = dq.back(); dq.pop_back(); if (st.size() > dq.size()) { int temp = st.top(); st.pop(); dq.push_front(temp); } } int getMiddleElement() { return dq.front(); } void deleteMiddleElement() { dq.pop_front(); if (st.size() > dq.size()) { // new middle element int temp = st.top(); // should come at front of deque st.pop(); dq.push_front(temp); } }}; int main(){ myStack st; st.add(2); st.add(5); cout << \"Middle Element: \" << st.getMiddleElement() << endl; st.add(3); st.add(7); st.add(4); cout << \"Middle Element: \" << st.getMiddleElement() << endl; st.deleteMiddleElement(); cout << \"Middle Element: \" << st.getMiddleElement() << endl; st.deleteMiddleElement(); cout << \"Middle Element: \" << st.getMiddleElement() << endl; st.pop(); st.pop(); st.deleteMiddleElement();} //By- Vijay Chadokar", "e": 21073, "s": 19757, "text": null }, { "code": null, "e": 21145, "s": 21073, "text": "Middle Element: 5\nMiddle Element: 3\nMiddle Element: 7\nMiddle Element: 5" }, { "code": null, "e": 21318, "s": 21145, "text": "This article is contributed by Chandra Prakash. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 21329, "s": 21318, "text": "andrew1234" }, { "code": null, "e": 21343, "s": 21329, "text": "rathbhupendra" }, { "code": null, "e": 21356, "s": 21343, "text": "Akanksha_Rai" }, { "code": null, "e": 21367, "s": 21356, "text": "logesh1998" }, { "code": null, "e": 21380, "s": 21367, "text": "ShreyPaharia" }, { "code": null, "e": 21390, "s": 21380, "text": "rutvik_56" }, { "code": null, "e": 21404, "s": 21390, "text": "anushikasethh" }, { "code": null, "e": 21416, "s": 21404, "text": "msohaibayub" }, { "code": null, "e": 21427, "s": 21416, "text": "nikhil070g" }, { "code": null, "e": 21441, "s": 21427, "text": "jhaabhishek45" }, { "code": null, "e": 21453, "s": 21441, "text": "amsavarthan" }, { "code": null, "e": 21467, "s": 21453, "text": "chadokarvijay" }, { "code": null, "e": 21480, "s": 21467, "text": "shivamgupta2" }, { "code": null, "e": 21486, "s": 21480, "text": "Stack" }, { "code": null, "e": 21492, "s": 21486, "text": "Stack" } ]
Number of shortest paths in an unweighted and directed graph
21 Aug, 2021 Given an unweighted directed graph, can be cyclic or acyclic. Print the number of shortest paths from a given vertex to each of the vertices. For example consider the below graph. There is one shortest path vertex 0 to vertex 0 (from each vertex there is a single shortest path to itself), one shortest path between vertex 0 to vertex 2 (0->2), and there are 4 different shortest paths from vertex 0 to vertex 6: 1. 0->1->3->4->6 2. 0->1->3->5->6 3. 0->2->3->4->6 4. 0->2->3->5->6 The idea is to use BFS. We use two arrays called dist[] and paths[], dist[] represents the shortest distances from source vertex, and paths[] represents the number of different shortest paths from the source vertex to each of the vertices. Initially all the elements in dist[] are infinity except source vertex which is equal to 0, since the distance to source vertex from itself is 0, and all the elements in paths[] are 0 except source vertex which is equal to 1, since each vertex has a single shortest path to itself. after that, we start traversing the graph using BFS manner. Then, for every neighbor Y of each vertex X do: 1) if dist[Y] > dist[X]+1 decrease the dist[Y] to dist[X] +1 and assign the number of paths of vertex X to number of paths of vertex Y. 2) else if dist[Y] = dist[X] + 1, then add the number of paths of vertex X to the number of paths of vertex Y. For example: Let’s take a look at the below graph. The source vertex is 0. Suppose we traverse on vertex 2, we check all its neighbors, which is only 3.since vertex 3 was already visited when we were traversed vertex 1, dist[3] = 2 and paths[3] = 1. The second condition is true, so it means that additional shortest paths have been found, so we add to the number of paths of vertex 3, the number of paths of vertex 2. The equal condition happens when we traverse on vertex 5: C++ Java Python3 C# Javascript // CPP program to count number of shortest// paths from a given source to every other// vertex using BFS.#include <bits/stdc++.h>using namespace std; // Traverses graph in BFS manner. It fills// dist[] and paths[]void BFS(vector<int> adj[], int src, int dist[], int paths[], int n){ bool visited[n]; for (int i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; queue <int> q; q.push(src); visited[src] = true; while (!q.empty()) { int curr = q.front(); q.pop(); // For all neighbors of current vertex do: for (auto x : adj[curr]) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.push(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } }} // function to find number of different// shortest paths form given vertex s.// n is number of vertices.void findShortestPaths(vector<int> adj[], int s, int n){ int dist[n], paths[n]; for (int i = 0; i < n; i++) dist[i] = INT_MAX; for (int i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); cout << "Numbers of shortest Paths are: "; for (int i = 0; i < n; i++) cout << paths[i] << " ";} // A utility function to add an edge in a// directed graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v);} // Driver codeint main(){ int n = 7; // Number of vertices vector <int> adj[n]; addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 3, 5); addEdge(adj, 4, 6); addEdge(adj, 5, 6); findShortestPaths(adj, 0, 7); return 0;} // Java program to count number of shortest// paths from a given source to every other// vertex using BFS.import java.io.*;import java.util.*; class GFG{ // Traverses graph in BFS manner. // It fills dist[] and paths[] static void BFS(Vector<Integer>[] adj, int src, int dist[], int paths[], int n) { boolean[] visited = new boolean[n]; for (int i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; Queue<Integer> q = new LinkedList<>(); q.add(src); visited[src] = true; while (!q.isEmpty()) { int curr = q.peek(); q.poll(); // For all neighbors of current vertex do: for (int x : adj[curr]) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.add(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } } } // function to find number of different // shortest paths form given vertex s. // n is number of vertices. static void findShortestPaths(Vector<Integer> adj[], int s, int n) { int[] dist = new int[n], paths = new int[n]; for (int i = 0; i < n; i++) dist[i] = Integer.MAX_VALUE; for (int i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); System.out.print("Numbers of shortest Paths are: "); for (int i = 0; i < n; i++) System.out.print(paths[i] + " "); } // A utility function to add an edge in a // directed graph. static void addEdge(Vector<Integer> adj[], int u, int v) { adj[u].add(v); } // Driver Code public static void main(String[] args) { int n = 7; // Number of vertices Vector<Integer>[] adj = new Vector[n]; for (int i = 0; i < n; i++) adj[i] = new Vector<>(); addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 3, 5); addEdge(adj, 4, 6); addEdge(adj, 5, 6); findShortestPaths(adj, 0, 7); }} // This code is contributed by// sanjeev2552 # Python3 program to count number of shortest# paths from a given source to every other# vertex using BFS.from collections import dequefrom sys import maxsize as INT_MAX # Traverses graph in BFS manner. It fills# dist[] and paths[]def BFS(adj: list, src: int, dist: list, paths: list, n: int): visited = [False] * n dist[src] = 0 paths[src] = 1 q = deque() q.append(src) visited[src] = True while q: curr = q[0] q.popleft() # For all neighbors of current vertex do: for x in adj[curr]: # if the current vertex is not yet # visited, then push it to the queue. if not visited[x]: q.append(x) visited[x] = True # check if there is a better path. if dist[x] > dist[curr] + 1: dist[x] = dist[curr] + 1 paths[x] = paths[curr] # additional shortest paths found elif dist[x] == dist[curr] + 1: paths[x] += paths[curr] # function to find number of different# shortest paths form given vertex s.# n is number of vertices.def findShortestPaths(adj: list, s: int, n: int): dist = [INT_MAX] * n paths = [0] * n BFS(adj, s, dist, paths, n) print("Numbers of shortest Paths are:", end=" ") for i in paths: print(i, end=" ") # A utility function to add an edge in a# directed graph.def addEdge(adj: list, u: int, v: int): adj[u].append(v) # Driver Codeif __name__ == "__main__": n = 7 # Number of vertices adj = [0] * n for i in range(n): adj[i] = [] addEdge(adj, 0, 1) addEdge(adj, 0, 2) addEdge(adj, 1, 2) addEdge(adj, 1, 3) addEdge(adj, 2, 3) addEdge(adj, 3, 4) addEdge(adj, 3, 5) addEdge(adj, 4, 6) addEdge(adj, 5, 6) findShortestPaths(adj, 0, 7) # This code is contributed by# sanjeev2552 // C# program to count number of shortest// paths from a given source to every other// vertex using BFS.using System;using System.Collections.Generic; class GFG{ // Traverses graph in BFS manner. // It fills dist[] and paths[] static void BFS(List<int>[] adj, int src, int []dist, int []paths, int n) { bool[] visited = new bool[n]; for (int i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; List<int> q = new List<int>(); q.Add(src); visited[src] = true; while (q.Count != 0) { int curr = q[0]; q.RemoveAt(0); // For all neighbors of current vertex do: foreach (int x in adj[curr]) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.Add(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } } } // function to find number of different // shortest paths form given vertex s. // n is number of vertices. static void findShortestPaths(List<int> []adj, int s, int n) { int[] dist = new int[n], paths = new int[n]; for (int i = 0; i < n; i++) dist[i] = int.MaxValue; for (int i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); Console.Write("Numbers of shortest Paths are: "); for (int i = 0; i < n; i++) Console.Write(paths[i] + " "); } // A utility function to add an edge in a // directed graph. static void addEdge(List<int> []adj, int u, int v) { adj[u].Add(v); } // Driver Code public static void Main(String[] args) { int n = 7; // Number of vertices List<int>[] adj = new List<int>[n]; for (int i = 0; i < n; i++) adj[i] = new List<int>(); addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 3, 5); addEdge(adj, 4, 6); addEdge(adj, 5, 6); findShortestPaths(adj, 0, 7); }} // This code is contributed by 29AjayKumar <script>// Javascript program to count number of shortest// paths from a given source to every other// vertex using BFS. // Traverses graph in BFS manner. // It fills dist[] and paths[]function BFS(adj,src,dist,paths,n){ let visited = new Array(n); for (let i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; let q = []; q.push(src); visited[src] = true; while (q.length!=0) { let curr = q[0]; q.shift(); // For all neighbors of current vertex do: for (let x of adj[curr].values()) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.push(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } }} // function to find number of different // shortest paths form given vertex s. // n is number of vertices.function findShortestPaths(adj,s,n){ let dist = new Array(n), paths = new Array(n); for (let i = 0; i < n; i++) dist[i] = Number.MAX_VALUE; for (let i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); document.write("Numbers of shortest Paths are: "); for (let i = 0; i < n; i++) document.write(paths[i] + " ");} // A utility function to add an edge in a // directed graph.function addEdge(adj,u,v){ adj[u].push(v);} // Driver Codelet n = 7; // Number of vertices let adj = new Array(n);for (let i = 0; i < n; i++) adj[i] = []; addEdge(adj, 0, 1);addEdge(adj, 0, 2);addEdge(adj, 1, 2);addEdge(adj, 1, 3);addEdge(adj, 2, 3);addEdge(adj, 3, 4);addEdge(adj, 3, 5);addEdge(adj, 4, 6);addEdge(adj, 5, 6);findShortestPaths(adj, 0, 7); // This code is contributed by rag2127</script> Numbers of shortest Paths are: 1 1 1 2 2 2 4 Time Complexity : O(V + E) Shlomi Elhaiani sanjeev2552 29AjayKumar varshagumber28 rag2127 surinderdawra388 BFS graph-connectivity Shortest Path Graph Graph Shortest Path BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Aug, 2021" }, { "code": null, "e": 535, "s": 52, "text": "Given an unweighted directed graph, can be cyclic or acyclic. Print the number of shortest paths from a given vertex to each of the vertices. For example consider the below graph. There is one shortest path vertex 0 to vertex 0 (from each vertex there is a single shortest path to itself), one shortest path between vertex 0 to vertex 2 (0->2), and there are 4 different shortest paths from vertex 0 to vertex 6: 1. 0->1->3->4->6 2. 0->1->3->5->6 3. 0->2->3->4->6 4. 0->2->3->5->6 " }, { "code": null, "e": 1892, "s": 537, "text": "The idea is to use BFS. We use two arrays called dist[] and paths[], dist[] represents the shortest distances from source vertex, and paths[] represents the number of different shortest paths from the source vertex to each of the vertices. Initially all the elements in dist[] are infinity except source vertex which is equal to 0, since the distance to source vertex from itself is 0, and all the elements in paths[] are 0 except source vertex which is equal to 1, since each vertex has a single shortest path to itself. after that, we start traversing the graph using BFS manner. Then, for every neighbor Y of each vertex X do: 1) if dist[Y] > dist[X]+1 decrease the dist[Y] to dist[X] +1 and assign the number of paths of vertex X to number of paths of vertex Y. 2) else if dist[Y] = dist[X] + 1, then add the number of paths of vertex X to the number of paths of vertex Y. For example: Let’s take a look at the below graph. The source vertex is 0. Suppose we traverse on vertex 2, we check all its neighbors, which is only 3.since vertex 3 was already visited when we were traversed vertex 1, dist[3] = 2 and paths[3] = 1. The second condition is true, so it means that additional shortest paths have been found, so we add to the number of paths of vertex 3, the number of paths of vertex 2. The equal condition happens when we traverse on vertex 5: " }, { "code": null, "e": 1898, "s": 1894, "text": "C++" }, { "code": null, "e": 1903, "s": 1898, "text": "Java" }, { "code": null, "e": 1911, "s": 1903, "text": "Python3" }, { "code": null, "e": 1914, "s": 1911, "text": "C#" }, { "code": null, "e": 1925, "s": 1914, "text": "Javascript" }, { "code": "// CPP program to count number of shortest// paths from a given source to every other// vertex using BFS.#include <bits/stdc++.h>using namespace std; // Traverses graph in BFS manner. It fills// dist[] and paths[]void BFS(vector<int> adj[], int src, int dist[], int paths[], int n){ bool visited[n]; for (int i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; queue <int> q; q.push(src); visited[src] = true; while (!q.empty()) { int curr = q.front(); q.pop(); // For all neighbors of current vertex do: for (auto x : adj[curr]) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.push(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } }} // function to find number of different// shortest paths form given vertex s.// n is number of vertices.void findShortestPaths(vector<int> adj[], int s, int n){ int dist[n], paths[n]; for (int i = 0; i < n; i++) dist[i] = INT_MAX; for (int i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); cout << \"Numbers of shortest Paths are: \"; for (int i = 0; i < n; i++) cout << paths[i] << \" \";} // A utility function to add an edge in a// directed graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v);} // Driver codeint main(){ int n = 7; // Number of vertices vector <int> adj[n]; addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 3, 5); addEdge(adj, 4, 6); addEdge(adj, 5, 6); findShortestPaths(adj, 0, 7); return 0;}", "e": 4066, "s": 1925, "text": null }, { "code": "// Java program to count number of shortest// paths from a given source to every other// vertex using BFS.import java.io.*;import java.util.*; class GFG{ // Traverses graph in BFS manner. // It fills dist[] and paths[] static void BFS(Vector<Integer>[] adj, int src, int dist[], int paths[], int n) { boolean[] visited = new boolean[n]; for (int i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; Queue<Integer> q = new LinkedList<>(); q.add(src); visited[src] = true; while (!q.isEmpty()) { int curr = q.peek(); q.poll(); // For all neighbors of current vertex do: for (int x : adj[curr]) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.add(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } } } // function to find number of different // shortest paths form given vertex s. // n is number of vertices. static void findShortestPaths(Vector<Integer> adj[], int s, int n) { int[] dist = new int[n], paths = new int[n]; for (int i = 0; i < n; i++) dist[i] = Integer.MAX_VALUE; for (int i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); System.out.print(\"Numbers of shortest Paths are: \"); for (int i = 0; i < n; i++) System.out.print(paths[i] + \" \"); } // A utility function to add an edge in a // directed graph. static void addEdge(Vector<Integer> adj[], int u, int v) { adj[u].add(v); } // Driver Code public static void main(String[] args) { int n = 7; // Number of vertices Vector<Integer>[] adj = new Vector[n]; for (int i = 0; i < n; i++) adj[i] = new Vector<>(); addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 3, 5); addEdge(adj, 4, 6); addEdge(adj, 5, 6); findShortestPaths(adj, 0, 7); }} // This code is contributed by// sanjeev2552", "e": 6839, "s": 4066, "text": null }, { "code": "# Python3 program to count number of shortest# paths from a given source to every other# vertex using BFS.from collections import dequefrom sys import maxsize as INT_MAX # Traverses graph in BFS manner. It fills# dist[] and paths[]def BFS(adj: list, src: int, dist: list, paths: list, n: int): visited = [False] * n dist[src] = 0 paths[src] = 1 q = deque() q.append(src) visited[src] = True while q: curr = q[0] q.popleft() # For all neighbors of current vertex do: for x in adj[curr]: # if the current vertex is not yet # visited, then push it to the queue. if not visited[x]: q.append(x) visited[x] = True # check if there is a better path. if dist[x] > dist[curr] + 1: dist[x] = dist[curr] + 1 paths[x] = paths[curr] # additional shortest paths found elif dist[x] == dist[curr] + 1: paths[x] += paths[curr] # function to find number of different# shortest paths form given vertex s.# n is number of vertices.def findShortestPaths(adj: list, s: int, n: int): dist = [INT_MAX] * n paths = [0] * n BFS(adj, s, dist, paths, n) print(\"Numbers of shortest Paths are:\", end=\" \") for i in paths: print(i, end=\" \") # A utility function to add an edge in a# directed graph.def addEdge(adj: list, u: int, v: int): adj[u].append(v) # Driver Codeif __name__ == \"__main__\": n = 7 # Number of vertices adj = [0] * n for i in range(n): adj[i] = [] addEdge(adj, 0, 1) addEdge(adj, 0, 2) addEdge(adj, 1, 2) addEdge(adj, 1, 3) addEdge(adj, 2, 3) addEdge(adj, 3, 4) addEdge(adj, 3, 5) addEdge(adj, 4, 6) addEdge(adj, 5, 6) findShortestPaths(adj, 0, 7) # This code is contributed by# sanjeev2552", "e": 8695, "s": 6839, "text": null }, { "code": "// C# program to count number of shortest// paths from a given source to every other// vertex using BFS.using System;using System.Collections.Generic; class GFG{ // Traverses graph in BFS manner. // It fills dist[] and paths[] static void BFS(List<int>[] adj, int src, int []dist, int []paths, int n) { bool[] visited = new bool[n]; for (int i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; List<int> q = new List<int>(); q.Add(src); visited[src] = true; while (q.Count != 0) { int curr = q[0]; q.RemoveAt(0); // For all neighbors of current vertex do: foreach (int x in adj[curr]) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.Add(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } } } // function to find number of different // shortest paths form given vertex s. // n is number of vertices. static void findShortestPaths(List<int> []adj, int s, int n) { int[] dist = new int[n], paths = new int[n]; for (int i = 0; i < n; i++) dist[i] = int.MaxValue; for (int i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); Console.Write(\"Numbers of shortest Paths are: \"); for (int i = 0; i < n; i++) Console.Write(paths[i] + \" \"); } // A utility function to add an edge in a // directed graph. static void addEdge(List<int> []adj, int u, int v) { adj[u].Add(v); } // Driver Code public static void Main(String[] args) { int n = 7; // Number of vertices List<int>[] adj = new List<int>[n]; for (int i = 0; i < n; i++) adj[i] = new List<int>(); addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 1, 2); addEdge(adj, 1, 3); addEdge(adj, 2, 3); addEdge(adj, 3, 4); addEdge(adj, 3, 5); addEdge(adj, 4, 6); addEdge(adj, 5, 6); findShortestPaths(adj, 0, 7); }} // This code is contributed by 29AjayKumar", "e": 11429, "s": 8695, "text": null }, { "code": "<script>// Javascript program to count number of shortest// paths from a given source to every other// vertex using BFS. // Traverses graph in BFS manner. // It fills dist[] and paths[]function BFS(adj,src,dist,paths,n){ let visited = new Array(n); for (let i = 0; i < n; i++) visited[i] = false; dist[src] = 0; paths[src] = 1; let q = []; q.push(src); visited[src] = true; while (q.length!=0) { let curr = q[0]; q.shift(); // For all neighbors of current vertex do: for (let x of adj[curr].values()) { // if the current vertex is not yet // visited, then push it to the queue. if (visited[x] == false) { q.push(x); visited[x] = true; } // check if there is a better path. if (dist[x] > dist[curr] + 1) { dist[x] = dist[curr] + 1; paths[x] = paths[curr]; } // additional shortest paths found else if (dist[x] == dist[curr] + 1) paths[x] += paths[curr]; } }} // function to find number of different // shortest paths form given vertex s. // n is number of vertices.function findShortestPaths(adj,s,n){ let dist = new Array(n), paths = new Array(n); for (let i = 0; i < n; i++) dist[i] = Number.MAX_VALUE; for (let i = 0; i < n; i++) paths[i] = 0; BFS(adj, s, dist, paths, n); document.write(\"Numbers of shortest Paths are: \"); for (let i = 0; i < n; i++) document.write(paths[i] + \" \");} // A utility function to add an edge in a // directed graph.function addEdge(adj,u,v){ adj[u].push(v);} // Driver Codelet n = 7; // Number of vertices let adj = new Array(n);for (let i = 0; i < n; i++) adj[i] = []; addEdge(adj, 0, 1);addEdge(adj, 0, 2);addEdge(adj, 1, 2);addEdge(adj, 1, 3);addEdge(adj, 2, 3);addEdge(adj, 3, 4);addEdge(adj, 3, 5);addEdge(adj, 4, 6);addEdge(adj, 5, 6);findShortestPaths(adj, 0, 7); // This code is contributed by rag2127</script>", "e": 13699, "s": 11429, "text": null }, { "code": null, "e": 13744, "s": 13699, "text": "Numbers of shortest Paths are: 1 1 1 2 2 2 4" }, { "code": null, "e": 13774, "s": 13746, "text": "Time Complexity : O(V + E) " }, { "code": null, "e": 13790, "s": 13774, "text": "Shlomi Elhaiani" }, { "code": null, "e": 13802, "s": 13790, "text": "sanjeev2552" }, { "code": null, "e": 13814, "s": 13802, "text": "29AjayKumar" }, { "code": null, "e": 13829, "s": 13814, "text": "varshagumber28" }, { "code": null, "e": 13837, "s": 13829, "text": "rag2127" }, { "code": null, "e": 13854, "s": 13837, "text": "surinderdawra388" }, { "code": null, "e": 13858, "s": 13854, "text": "BFS" }, { "code": null, "e": 13877, "s": 13858, "text": "graph-connectivity" }, { "code": null, "e": 13891, "s": 13877, "text": "Shortest Path" }, { "code": null, "e": 13897, "s": 13891, "text": "Graph" }, { "code": null, "e": 13903, "s": 13897, "text": "Graph" }, { "code": null, "e": 13917, "s": 13903, "text": "Shortest Path" }, { "code": null, "e": 13921, "s": 13917, "text": "BFS" } ]
Python | Tokenizing strings in list of strings
29 Apr, 2019 Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let’s discuss certain ways in which this can be done. Method #1 : Using list comprehension + split() We can achieve this particular task using list comprehension to traverse for each strings from list of strings and split function performs the task of tokenization. # Python3 code to demonstrate# Tokenizing strings in list of strings# using list comprehension + split() # initializing listtest_list = ['Geeks for Geeks', 'is', 'best computer science portal'] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + split()# Tokenizing strings in list of stringsres = [sub.split() for sub in test_list] # print resultprint("The list after split of strings is : " + str(res)) The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]] Method #2 : Using map() + split()This is yet another method in which this particular task can be solved. In this method, we just perform the similar task as above, just we use map function to bind the split logic to the entire list. # Python3 code to demonstrate# Tokenizing strings in list of strings# using map() + split() # initializing listtest_list = ['Geeks for Geeks', 'is', 'best computer science portal'] # printing original listprint("The original list : " + str(test_list)) # using map() + split()# Tokenizing strings in list of stringsres = list(map(str.split, test_list)) # print resultprint("The list after split of strings is : " + str(res)) The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2019" }, { "code": null, "e": 312, "s": 54, "text": "Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 359, "s": 312, "text": "Method #1 : Using list comprehension + split()" }, { "code": null, "e": 524, "s": 359, "text": "We can achieve this particular task using list comprehension to traverse for each strings from list of strings and split function performs the task of tokenization." }, { "code": "# Python3 code to demonstrate# Tokenizing strings in list of strings# using list comprehension + split() # initializing listtest_list = ['Geeks for Geeks', 'is', 'best computer science portal'] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + split()# Tokenizing strings in list of stringsres = [sub.split() for sub in test_list] # print resultprint(\"The list after split of strings is : \" + str(res))", "e": 981, "s": 524, "text": null }, { "code": null, "e": 1174, "s": 981, "text": "The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]]" }, { "code": null, "e": 1409, "s": 1176, "text": "Method #2 : Using map() + split()This is yet another method in which this particular task can be solved. In this method, we just perform the similar task as above, just we use map function to bind the split logic to the entire list." }, { "code": "# Python3 code to demonstrate# Tokenizing strings in list of strings# using map() + split() # initializing listtest_list = ['Geeks for Geeks', 'is', 'best computer science portal'] # printing original listprint(\"The original list : \" + str(test_list)) # using map() + split()# Tokenizing strings in list of stringsres = list(map(str.split, test_list)) # print resultprint(\"The list after split of strings is : \" + str(res))", "e": 1837, "s": 1409, "text": null }, { "code": null, "e": 2030, "s": 1837, "text": "The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]]" }, { "code": null, "e": 2051, "s": 2030, "text": "Python list-programs" }, { "code": null, "e": 2058, "s": 2051, "text": "Python" }, { "code": null, "e": 2074, "s": 2058, "text": "Python Programs" } ]
Maximum sum in a 2 x n grid such that no two elements are adjacent
28 May, 2022 Given a rectangular grid of dimension 2 x n. We need to find out the maximum sum such that no two chosen numbers are adjacent, vertically, diagonally, or horizontally. Examples: Input: 1 4 5 2 0 0 Output: 7 If we start from 1 then we can add only 5 or 0. So max_sum = 6 in this case. If we select 2 then also we can add only 5 or 0. So max_sum = 7 in this case. If we select from 4 or 0 then there is no further elements can be added. So, Max sum is 7. Input: 1 2 3 4 5 6 7 8 9 10 Output: 24 Approach: This problem is an extension of Maximum sum such that no two elements are adjacent. The only thing to be changed is to take a maximum element of both rows of a particular column. We traverse column by column and maintain the maximum sum considering two cases. 1) An element of the current column is included. In this case, we take a maximum of two elements in the current column. 2) An element of the current column is excluded (or not included)Below is the implementation of the above steps. C++ C Java Python3 C# PHP Javascript // C++ program to find maximum sum in a grid such that// no two elements are adjacent.#include<bits/stdc++.h>#define MAX 1000using namespace std; // Function to find max sum without adjacentint maxSum(int grid[2][MAX], int n){ // Sum including maximum element of first column int incl = max(grid[0][0], grid[1][0]); // Not including first column's element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i<n; i++ ) { // Update max_sum on including or excluding // of previous column excl_new = max(excl, incl); // Include current column. Add maximum element // from both row of current column incl = excl + max(grid[0][i], grid[1][i]); // If current column doesn't to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return max(excl, incl);} // Driver codeint main(){ int grid[2][MAX] = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; cout << maxSum(grid, n); return 0;} // C program to find maximum sum in a grid such that// no two elements are adjacent.#include <stdio.h> #define MAX 1000 // Function to find max sum without adjacentint maxSum(int grid[2][MAX], int n){ // Sum including maximum element of first column int max = grid[0][0]; if(max < grid[1][0]) max = grid[1][0]; int incl = max; // Not including first column's element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i<n; i++ ) { // Update max_sum on including or excluding // of previous column max = excl; if(max < incl) max = incl; excl_new = max; // Include current column. Add maximum element // from both row of current column max = grid[0][i]; if(max < grid[1][i]) max = grid[1][i]; incl = excl + max; // If current column doesn't to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum max = excl; if(max < incl) max = incl; return max;} // Driver codeint main(){ int grid[2][MAX] = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; printf("%d",maxSum(grid, n)); return 0;} // This code is contributed by kothavvsaakash. // Java Code for Maximum sum in a 2 x n grid// such that no two elements are adjacentimport java.util.*; class GFG { // Function to find max sum without adjacent public static int maxSum(int grid[][], int n) { // Sum including maximum element of first // column int incl = Math.max(grid[0][0], grid[1][0]); // Not including first column's element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i < n; i++ ) { // Update max_sum on including or // excluding of previous column excl_new = Math.max(excl, incl); // Include current column. Add maximum element // from both row of current column incl = excl + Math.max(grid[0][i], grid[1][i]); // If current column doesn't to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return Math.max(excl, incl); } /* Driver program to test above function */ public static void main(String[] args) { int grid[][] = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; System.out.println(maxSum(grid, n)); } }// This code is contributed by Arnav Kr. Mandal. # Python3 program to find maximum sum in a grid such that# no two elements are adjacent. # Function to find max sum without adjacentdef maxSum(grid, n) : # Sum including maximum element of first column incl = max(grid[0][0], grid[1][0]) # Not including first column's element excl = 0 # Traverse for further elements for i in range(1, n) : # Update max_sum on including or excluding # of previous column excl_new = max(excl, incl) # Include current column. Add maximum element # from both row of current column incl = excl + max(grid[0][i], grid[1][i]) # If current column doesn't to be included excl = excl_new # Return maximum of excl and incl # As that will be the maximum sum return max(excl, incl) # Driver codeif __name__ == "__main__" : grid = [ [ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10] ] n = 5 print(maxSum(grid, n)) // This code is contributed by Ryuga // C# program Code for Maximum sum// in a 2 x n grid such that no two// elements are adjacentusing System; class GFG{ // Function to find max sum// without adjacentpublic static int maxSum(int [,]grid, int n){ // Sum including maximum element // of first column int incl = Math.Max(grid[0, 0], grid[1, 0]); // Not including first column's // element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i < n; i++ ) { // Update max_sum on including or // excluding of previous column excl_new = Math.Max(excl, incl); // Include current column. Add // maximum element from both // row of current column incl = excl + Math.Max(grid[0, i], grid[1, i]); // If current column doesn't // to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return Math.Max(excl, incl);} // Driver Codepublic static void Main(String[] args){ int [,]grid = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; Console.Write(maxSum(grid, n));}} // This code is contributed// by PrinciRaj1992 <?php// PHP program to find maximum sum// in a grid such that no two elements// are adjacent. // Function to find max sum// without adjacentfunction maxSum($grid, $n){ // Sum including maximum element // of first column $incl = max($grid[0][0], $grid[1][0]); // Not including first column's element $excl = 0; $excl_new; // Traverse for further elements for ($i = 1; $i < $n; $i++ ) { // Update max_sum on including or // excluding of previous column $excl_new = max($excl, $incl); // Include current column. Add maximum // element from both row of current column $incl = $excl + max($grid[0][$i], $grid[1][$i]); // If current column doesn't // to be included $excl = $excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return max($excl, $incl);} // Driver code$grid = array(array(1, 2, 3, 4, 5), array(6, 7, 8, 9, 10)); $n = 5;echo maxSum($grid, $n); // This code is contributed by Sachin..?> <script> // JavaScript program Code for Maximum sum// in a 2 x n grid such that no two// elements are adjacent // Function to find max sum// without adjacentfunction maxSum(grid,n){ // Sum including maximum element // of first column let incl = Math.max(grid[0][0], grid[1][0]); // Not including first column's // element let excl = 0, excl_new; // Traverse for further elements for (let i = 1; i < n; i++ ) { // Update max_sum on including or // excluding of previous column excl_new = Math.max(excl, incl); // Include current column. Add // maximum element from both // row of current column incl = excl + Math.max(grid[0][i], grid[1][i]); // If current column doesn't // to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return Math.max(excl, incl);} // Driver Code let grid =[[ 1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]; let n = 5;document.write(maxSum(grid, n)); // This code is contributed// by PrinciRaj1992 </script> Output: 24 Time Complexity: O(n) where n is number of elements in given array. As, we are using a loop to traverse N times so it will cost us O(N) time Auxiliary Space: O(1), as we are not using any extra space.This article is contributed by Sahil Chhabra. 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. princiraj1992 ankthon Sach_Code gfg_sal_gfg hem chandra mohit kumar 29 kothavvsaakash rohitkumarsinghcna Epic Systems Dynamic Programming Matrix Epic Systems Dynamic Programming Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 May, 2022" }, { "code": null, "e": 233, "s": 54, "text": "Given a rectangular grid of dimension 2 x n. We need to find out the maximum sum such that no two chosen numbers are adjacent, vertically, diagonally, or horizontally. Examples: " }, { "code": null, "e": 565, "s": 233, "text": "Input: 1 4 5\n 2 0 0\nOutput: 7\nIf we start from 1 then we can add only 5 or 0. \nSo max_sum = 6 in this case.\nIf we select 2 then also we can add only 5 or 0.\nSo max_sum = 7 in this case.\nIf we select from 4 or 0 then there is no further \nelements can be added.\nSo, Max sum is 7.\n\nInput: 1 2 3 4 5\n 6 7 8 9 10\nOutput: 24" }, { "code": null, "e": 575, "s": 565, "text": "Approach:" }, { "code": null, "e": 1069, "s": 575, "text": "This problem is an extension of Maximum sum such that no two elements are adjacent. The only thing to be changed is to take a maximum element of both rows of a particular column. We traverse column by column and maintain the maximum sum considering two cases. 1) An element of the current column is included. In this case, we take a maximum of two elements in the current column. 2) An element of the current column is excluded (or not included)Below is the implementation of the above steps. " }, { "code": null, "e": 1073, "s": 1069, "text": "C++" }, { "code": null, "e": 1075, "s": 1073, "text": "C" }, { "code": null, "e": 1080, "s": 1075, "text": "Java" }, { "code": null, "e": 1088, "s": 1080, "text": "Python3" }, { "code": null, "e": 1091, "s": 1088, "text": "C#" }, { "code": null, "e": 1095, "s": 1091, "text": "PHP" }, { "code": null, "e": 1106, "s": 1095, "text": "Javascript" }, { "code": "// C++ program to find maximum sum in a grid such that// no two elements are adjacent.#include<bits/stdc++.h>#define MAX 1000using namespace std; // Function to find max sum without adjacentint maxSum(int grid[2][MAX], int n){ // Sum including maximum element of first column int incl = max(grid[0][0], grid[1][0]); // Not including first column's element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i<n; i++ ) { // Update max_sum on including or excluding // of previous column excl_new = max(excl, incl); // Include current column. Add maximum element // from both row of current column incl = excl + max(grid[0][i], grid[1][i]); // If current column doesn't to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return max(excl, incl);} // Driver codeint main(){ int grid[2][MAX] = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; cout << maxSum(grid, n); return 0;}", "e": 2187, "s": 1106, "text": null }, { "code": "// C program to find maximum sum in a grid such that// no two elements are adjacent.#include <stdio.h> #define MAX 1000 // Function to find max sum without adjacentint maxSum(int grid[2][MAX], int n){ // Sum including maximum element of first column int max = grid[0][0]; if(max < grid[1][0]) max = grid[1][0]; int incl = max; // Not including first column's element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i<n; i++ ) { // Update max_sum on including or excluding // of previous column max = excl; if(max < incl) max = incl; excl_new = max; // Include current column. Add maximum element // from both row of current column max = grid[0][i]; if(max < grid[1][i]) max = grid[1][i]; incl = excl + max; // If current column doesn't to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum max = excl; if(max < incl) max = incl; return max;} // Driver codeint main(){ int grid[2][MAX] = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; printf(\"%d\",maxSum(grid, n)); return 0;} // This code is contributed by kothavvsaakash.", "e": 3386, "s": 2187, "text": null }, { "code": "// Java Code for Maximum sum in a 2 x n grid// such that no two elements are adjacentimport java.util.*; class GFG { // Function to find max sum without adjacent public static int maxSum(int grid[][], int n) { // Sum including maximum element of first // column int incl = Math.max(grid[0][0], grid[1][0]); // Not including first column's element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i < n; i++ ) { // Update max_sum on including or // excluding of previous column excl_new = Math.max(excl, incl); // Include current column. Add maximum element // from both row of current column incl = excl + Math.max(grid[0][i], grid[1][i]); // If current column doesn't to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return Math.max(excl, incl); } /* Driver program to test above function */ public static void main(String[] args) { int grid[][] = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; System.out.println(maxSum(grid, n)); } }// This code is contributed by Arnav Kr. Mandal.", "e": 4739, "s": 3386, "text": null }, { "code": "# Python3 program to find maximum sum in a grid such that# no two elements are adjacent. # Function to find max sum without adjacentdef maxSum(grid, n) : # Sum including maximum element of first column incl = max(grid[0][0], grid[1][0]) # Not including first column's element excl = 0 # Traverse for further elements for i in range(1, n) : # Update max_sum on including or excluding # of previous column excl_new = max(excl, incl) # Include current column. Add maximum element # from both row of current column incl = excl + max(grid[0][i], grid[1][i]) # If current column doesn't to be included excl = excl_new # Return maximum of excl and incl # As that will be the maximum sum return max(excl, incl) # Driver codeif __name__ == \"__main__\" : grid = [ [ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10] ] n = 5 print(maxSum(grid, n)) // This code is contributed by Ryuga", "e": 5723, "s": 4739, "text": null }, { "code": "// C# program Code for Maximum sum// in a 2 x n grid such that no two// elements are adjacentusing System; class GFG{ // Function to find max sum// without adjacentpublic static int maxSum(int [,]grid, int n){ // Sum including maximum element // of first column int incl = Math.Max(grid[0, 0], grid[1, 0]); // Not including first column's // element int excl = 0, excl_new; // Traverse for further elements for (int i = 1; i < n; i++ ) { // Update max_sum on including or // excluding of previous column excl_new = Math.Max(excl, incl); // Include current column. Add // maximum element from both // row of current column incl = excl + Math.Max(grid[0, i], grid[1, i]); // If current column doesn't // to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return Math.Max(excl, incl);} // Driver Codepublic static void Main(String[] args){ int [,]grid = {{ 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10}}; int n = 5; Console.Write(maxSum(grid, n));}} // This code is contributed// by PrinciRaj1992", "e": 6956, "s": 5723, "text": null }, { "code": "<?php// PHP program to find maximum sum// in a grid such that no two elements// are adjacent. // Function to find max sum// without adjacentfunction maxSum($grid, $n){ // Sum including maximum element // of first column $incl = max($grid[0][0], $grid[1][0]); // Not including first column's element $excl = 0; $excl_new; // Traverse for further elements for ($i = 1; $i < $n; $i++ ) { // Update max_sum on including or // excluding of previous column $excl_new = max($excl, $incl); // Include current column. Add maximum // element from both row of current column $incl = $excl + max($grid[0][$i], $grid[1][$i]); // If current column doesn't // to be included $excl = $excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return max($excl, $incl);} // Driver code$grid = array(array(1, 2, 3, 4, 5), array(6, 7, 8, 9, 10)); $n = 5;echo maxSum($grid, $n); // This code is contributed by Sachin..?>", "e": 8028, "s": 6956, "text": null }, { "code": "<script> // JavaScript program Code for Maximum sum// in a 2 x n grid such that no two// elements are adjacent // Function to find max sum// without adjacentfunction maxSum(grid,n){ // Sum including maximum element // of first column let incl = Math.max(grid[0][0], grid[1][0]); // Not including first column's // element let excl = 0, excl_new; // Traverse for further elements for (let i = 1; i < n; i++ ) { // Update max_sum on including or // excluding of previous column excl_new = Math.max(excl, incl); // Include current column. Add // maximum element from both // row of current column incl = excl + Math.max(grid[0][i], grid[1][i]); // If current column doesn't // to be included excl = excl_new; } // Return maximum of excl and incl // As that will be the maximum sum return Math.max(excl, incl);} // Driver Code let grid =[[ 1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]; let n = 5;document.write(maxSum(grid, n)); // This code is contributed// by PrinciRaj1992 </script>", "e": 9113, "s": 8028, "text": null }, { "code": null, "e": 9122, "s": 9113, "text": "Output: " }, { "code": null, "e": 9125, "s": 9122, "text": "24" }, { "code": null, "e": 9746, "s": 9125, "text": "Time Complexity: O(n) where n is number of elements in given array. As, we are using a loop to traverse N times so it will cost us O(N) time Auxiliary Space: O(1), as we are not using any extra space.This article is contributed by Sahil Chhabra. 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": 9760, "s": 9746, "text": "princiraj1992" }, { "code": null, "e": 9768, "s": 9760, "text": "ankthon" }, { "code": null, "e": 9778, "s": 9768, "text": "Sach_Code" }, { "code": null, "e": 9790, "s": 9778, "text": "gfg_sal_gfg" }, { "code": null, "e": 9802, "s": 9790, "text": "hem chandra" }, { "code": null, "e": 9817, "s": 9802, "text": "mohit kumar 29" }, { "code": null, "e": 9832, "s": 9817, "text": "kothavvsaakash" }, { "code": null, "e": 9851, "s": 9832, "text": "rohitkumarsinghcna" }, { "code": null, "e": 9864, "s": 9851, "text": "Epic Systems" }, { "code": null, "e": 9884, "s": 9864, "text": "Dynamic Programming" }, { "code": null, "e": 9891, "s": 9884, "text": "Matrix" }, { "code": null, "e": 9904, "s": 9891, "text": "Epic Systems" }, { "code": null, "e": 9924, "s": 9904, "text": "Dynamic Programming" }, { "code": null, "e": 9931, "s": 9924, "text": "Matrix" } ]
UGC-NET | UGC NET CS 2017 Jan – III | Question 72
03 Apr, 2018 A neuron with 3 inputs has the weight vector [0.2 –0.1 0.1]T and a bias θ = 0. If the input vector is X = [0.2 0.4 0.2]T then the total input to the neuron is :(A) 0.20(B) 1.0(C) 0.02(D) –1.0Answer: (C)Explanation: Given: weight vector(WT) = [0.2 –0.1 0.1]T input vector(X) = [0.2 0.4 0.2]T Θ = 0 f(x) = WT*X + Θ i.e. = [0.2 –0.1 0.1] * [0.2 0.4 0.2] + 0 = [0.2 * 0.2 – 0.1 * 0.4 + 0.1 * 0.2] + 0 = 0.02 So, option (C) is correct.Quiz of this Question UGC-NET Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. UGC-NET | UGC NET CS 2016 Aug - III | Question 32 UGC-NET | UGC NET CS 2015 Jun - III | Question 64 UGC-NET | UGC NET CS 2015 Jun - III | Question 35 UGC-NET | UGC NET CS 2015 Jun - III | Question 33 UGC-NET | UGC NET CS 2015 Jun - II | Question 1 UGC-NET | UGC NET CS 2015 Jun - III | Question 34 UGC-NET | UGC NET CS 2015 Jun - III | Question 31 UGC-NET | UGC NET CS 2018 July - II | Question 26 UGC-NET | UGC NET CS 2016 July – III | Question 32 UGC-NET | UGC NET CS 2018 July - II | Question 21
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Apr, 2018" }, { "code": null, "e": 243, "s": 28, "text": "A neuron with 3 inputs has the weight vector [0.2 –0.1 0.1]T and a bias θ = 0. If the input vector is X = [0.2 0.4 0.2]T then the total input to the neuron is :(A) 0.20(B) 1.0(C) 0.02(D) –1.0Answer: (C)Explanation:" }, { "code": null, "e": 465, "s": 243, "text": "Given:\n weight vector(WT) = [0.2 –0.1 0.1]T \n input vector(X) = [0.2 0.4 0.2]T\n Θ = 0\nf(x) = WT*X + Θ\ni.e. = [0.2 –0.1 0.1] * [0.2 0.4 0.2] + 0\n = [0.2 * 0.2 – 0.1 * 0.4 + 0.1 * 0.2] + 0\n = 0.02" }, { "code": null, "e": 513, "s": 465, "text": "So, option (C) is correct.Quiz of this Question" }, { "code": null, "e": 521, "s": 513, "text": "UGC-NET" }, { "code": null, "e": 619, "s": 521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 669, "s": 619, "text": "UGC-NET | UGC NET CS 2016 Aug - III | Question 32" }, { "code": null, "e": 719, "s": 669, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 64" }, { "code": null, "e": 769, "s": 719, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 35" }, { "code": null, "e": 819, "s": 769, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 33" }, { "code": null, "e": 867, "s": 819, "text": "UGC-NET | UGC NET CS 2015 Jun - II | Question 1" }, { "code": null, "e": 917, "s": 867, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 34" }, { "code": null, "e": 967, "s": 917, "text": "UGC-NET | UGC NET CS 2015 Jun - III | Question 31" }, { "code": null, "e": 1017, "s": 967, "text": "UGC-NET | UGC NET CS 2018 July - II | Question 26" }, { "code": null, "e": 1068, "s": 1017, "text": "UGC-NET | UGC NET CS 2016 July – III | Question 32" } ]
Print the path between any two nodes of a tree | DFS
09 Jun, 2021 Given a tree of distinct nodes N with N-1 edges and a pair of nodes P. The task is to find and print the path between the two given nodes of the tree using DFS. Input: N = 10 1 / \ 2 3 / | \ / | \ 4 5 6 7 8 9 Pair = {4, 8} Output: 4 -> 2 -> 1 -> 3 -> 8 Input: N = 3 1 / \ 2 3 Pair = {2, 3} Output: 2 -> 1 -> 3 For example, in the above tree the path between nodes 5 and 3 is 5 -> 2 -> 1 -> 3. Path between nodes 4 and 8 is 4 -> 2 -> 1 -> 3 -> 8. Approach: The idea is to run DFS from the source node and push the traversed nodes into a stack till the destination node is traversed. Whenever backtracking occurs pop the node from the stack. Note: There should be a path between the given pair of nodes. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation#include <bits/stdc++.h>using namespace std; // An utility function to add an edge in an// undirected graph.void addEdge(vector<int> v[], int x, int y){ v[x].push_back(y); v[y].push_back(x);} // A function to print the path between// the given pair of nodes.void printPath(vector<int> stack){ int i; for (i = 0; i < (int)stack.size() - 1; i++) { cout << stack[i] << " -> "; } cout << stack[i];} // An utility function to do// DFS of graph recursively// from a given vertex x.void DFS(vector<int> v[], bool vis[], int x, int y, vector<int> stack){ stack.push_back(x); if (x == y) { // print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // if backtracking is taking place if (!v[x].empty()) { for (int j = 0; j < v[x].size(); j++) { // if the node is not visited if (vis[v[x][j]] == false) DFS(v, vis, v[x][j], y, stack); } } stack.pop_back();} // A utility function to initialise// visited for the node and call// DFS function for a given vertex x.void DFSCall(int x, int y, vector<int> v[], int n, vector<int> stack){ // visited array bool vis[n + 1]; memset(vis, false, sizeof(vis)); // DFS function call DFS(v, vis, x, y, stack);} // Driver Codeint main(){ int n = 10; vector<int> v[n], stack; // Vertex numbers should be from 1 to 9. addEdge(v, 1, 2); addEdge(v, 1, 3); addEdge(v, 2, 4); addEdge(v, 2, 5); addEdge(v, 2, 6); addEdge(v, 3, 7); addEdge(v, 3, 8); addEdge(v, 3, 9); // Function Call DFSCall(4, 8, v, n, stack); return 0;} // Java implementation of the above approachimport java.util.*;class GFG{ static Vector<Vector<Integer>> v = new Vector<Vector<Integer>>(); // An utility function to add an edge in an // undirected graph. static void addEdge(int x, int y){ v.get(x).add(y); v.get(y).add(x); } // A function to print the path between // the given pair of nodes. static void printPath(Vector<Integer> stack) { for(int i = 0; i < stack.size() - 1; i++) { System.out.print(stack.get(i) + " -> "); } System.out.println(stack.get(stack.size() - 1)); } // An utility function to do // DFS of graph recursively // from a given vertex x. static void DFS(boolean vis[], int x, int y, Vector<Integer> stack) { stack.add(x); if (x == y) { // print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // if backtracking is taking place if (v.get(x).size() > 0) { for(int j = 0; j < v.get(x).size(); j++) { // if the node is not visited if (vis[v.get(x).get(j)] == false) { DFS(vis, v.get(x).get(j), y, stack); } } } stack.remove(stack.size() - 1); } // A utility function to initialise // visited for the node and call // DFS function for a given vertex x. static void DFSCall(int x, int y, int n, Vector<Integer> stack) { // visited array boolean vis[] = new boolean[n + 1]; Arrays.fill(vis, false); // memset(vis, false, sizeof(vis)) // DFS function call DFS(vis, x, y, stack); } // Driver code public static void main(String[] args) { for(int i = 0; i < 100; i++) { v.add(new Vector<Integer>()); } int n = 10; Vector<Integer> stack = new Vector<Integer>(); // Vertex numbers should be from 1 to 9. addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); addEdge(3, 9); // Function Call DFSCall(4, 8, n, stack); }} // This code is contributed by divyeshrabadiya07 # Python3 implementation of the above approachv = [[] for i in range(100)] # An utility function to add an edge in an# undirected graph.def addEdge(x, y): v[x].append(y) v[y].append(x) # A function to print the path between# the given pair of nodes.def printPath(stack): for i in range(len(stack) - 1): print(stack[i], end = " -> ") print(stack[-1]) # An utility function to do# DFS of graph recursively# from a given vertex x.def DFS(vis, x, y, stack): stack.append(x) if (x == y): # print the path and return on # reaching the destination node printPath(stack) return vis[x] = True # if backtracking is taking place if (len(v[x]) > 0): for j in v[x]: # if the node is not visited if (vis[j] == False): DFS(vis, j, y, stack) del stack[-1] # A utility function to initialise# visited for the node and call# DFS function for a given vertex x.def DFSCall(x, y, n, stack): # visited array vis = [0 for i in range(n + 1)] #memset(vis, false, sizeof(vis)) # DFS function call DFS(vis, x, y, stack) # Driver Coden = 10stack = [] # Vertex numbers should be from 1 to 9.addEdge(1, 2)addEdge(1, 3)addEdge(2, 4)addEdge(2, 5)addEdge(2, 6)addEdge(3, 7)addEdge(3, 8)addEdge(3, 9) # Function CallDFSCall(4, 8, n, stack) # This code is contributed by Mohit Kumar // C# implementation of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ static List<List<int>> v = new List<List<int>>(); // An utility function to Add an edge in an // undirected graph. static void addEdge(int x, int y) { v[x].Add(y); v[y].Add(x); } // A function to print the path between // the given pair of nodes. static void printPath(List<int> stack) { for(int i = 0; i < stack.Count - 1; i++) { Console.Write(stack[i] + " -> "); } Console.WriteLine(stack[stack.Count - 1]); } // An utility function to do // DFS of graph recursively // from a given vertex x. static void DFS(bool []vis, int x, int y, List<int> stack) { stack.Add(x); if (x == y) { // print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // if backtracking is taking place if (v[x].Count > 0) { for(int j = 0; j < v[x].Count; j++) { // if the node is not visited if (vis[v[x][j]] == false) { DFS(vis, v[x][j], y, stack); } } } stack.RemoveAt(stack.Count - 1); } // A utility function to initialise // visited for the node and call // DFS function for a given vertex x. static void DFSCall(int x, int y, int n, List<int> stack) { // visited array bool []vis = new bool[n + 1]; Array.Fill(vis, false); // memset(vis, false, sizeof(vis)) // DFS function call DFS(vis, x, y, stack); } // Driver code public static void Main(string[] args) { for(int i = 0; i < 100; i++) { v.Add(new List<int>()); } int n = 10; List<int> stack = new List<int>(); // Vertex numbers should be from 1 to 9. addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); addEdge(3, 9); // Function Call DFSCall(4, 8, n, stack); }} // This code is contributed by rutvik_56 <script> // Javascript implementation of the above approachlet v = []; // An utility function to add an edge in an// undirected graph.function addEdge(x, y){ v[x].push(y); v[y].push(x);} // A function to print the path between// the given pair of nodes.function printPath(stack){ for(let i = 0; i < stack.length - 1; i++) { document.write(stack[i] + " -> "); } document.write(stack[stack.length - 1] + "<br>");} // An utility function to do// DFS of graph recursively// from a given vertex x.function DFS(vis, x, y, stack){ stack.push(x); if (x == y) { // Print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // If backtracking is taking place if (v[x].length > 0) { for(let j = 0; j < v[x].length; j++) { // If the node is not visited if (vis[v[x][j]] == false) { DFS(vis, v[x][j], y, stack); } } } stack.pop();} // A utility function to initialise// visited for the node and call// DFS function for a given vertex x.function DFSCall(x, y, n, stack){ // Visited array let vis = new Array(n + 1); for(let i = 0; i < (n + 1); i++) { vis[i] = false; } // memset(vis, false, sizeof(vis)) // DFS function call DFS(vis, x, y, stack);} // Driver codefor(let i = 0; i < 100; i++){ v.push([]);} let n = 10;let stack = []; // Vertex numbers should be from 1 to 9.addEdge(1, 2);addEdge(1, 3);addEdge(2, 4);addEdge(2, 5);addEdge(2, 6);addEdge(3, 7);addEdge(3, 8);addEdge(3, 9); // Function CallDFSCall(4, 8, n, stack); // This code is contributed by patel2127 </script> 4 -> 2 -> 1 -> 3 -> 8 Efficient Approach : In this approach we will utilise the concept of Lowest Common Ancestor (LCA). 1. We will find level and parent of every node using DFS. 2. We will find lowest common ancestor (LCA) of the two given nodes. 3. Starting from the first node we will travel to the LCA and keep on pushing the intermediates nodes in our path vector. 4. Then, from the second node we will again travel to the LCA but this time we will reverse the encountered intermediate nodes and then push them in our path vector. 5. Finally, print the path vector to get the path between the two nodes. C++ // C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // An utility function to add an edge in the treevoid addEdge(vector<int> adj[], int x, int y){ adj[x].push_back(y); adj[y].push_back(x);} // running dfs to find level and parent of every nodevoid dfs(vector<int> adj[], int node, int l, int p, int lvl[], int par[]){ lvl[node] = l; par[node] = p; for(int child : adj[node]) { if(child != p) dfs(adj, child, l+1, node, lvl, par); }} int LCA(int a, int b, int par[], int lvl[]){ // if node a is at deeper level than // node b if(lvl[a] > lvl[b]) swap(a, b); // finding the difference in levels // of node a and b int diff = lvl[b] - lvl[a]; // moving b to the level of a while(diff != 0) { b = par[b]; diff--; } // means we have found the LCA if(a == b) return a; // finding the LCA while(a != b) a=par[a], b=par[b]; return a;} void printPath(vector<int> adj[], int a, int b, int n){ // stores level of every node int lvl[n+1]; // stores parent of every node int par[n+1]; // running dfs to find parent and level // of every node in the tree dfs(adj, 1, 0, -1, lvl, par); // finding the lowest common ancestor // of the nodes a and b int lca = LCA(a, b, par, lvl); // stores path between nodes a and b vector<int> path; // traversing the path from a to lca while(a != lca) path.push_back(a), a = par[a]; path.push_back(a); vector<int> temp; // traversing the path from b to lca while(b != lca) temp.push_back(b), b=par[b]; // reversing the path to get actual path reverse(temp.begin(), temp.end()); for(int x : temp) path.push_back(x); // printing the path for(int i = 0; i < path.size() - 1; i++) cout << path[i] << " -> "; cout << path[path.size() - 1] << endl;} // Driver Codeint main(){ /* 1 / \ 2 7 / \ 3 6 / | \ 4 8 5 */ // number of nodes in the tree int n = 8; // adjacency list representation of the tree vector<int> adj[n+1]; addEdge(adj, 1, 2); addEdge(adj, 1, 7); addEdge(adj, 2, 3); addEdge(adj, 2, 6); addEdge(adj, 3, 4); addEdge(adj, 3, 8); addEdge(adj, 3, 5); // taking two input nodes // between which path is // to be printed int a = 4, b = 7; printPath(adj, a, b, n); return 0;} 4 -> 3 -> 2 -> 1 -> 7 Time Complexity : O(N) Space Complexity : O(N) mohit kumar 29 nidhi_biet debdutgoswami divyeshrabadiya07 rutvik_56 pawanharwani11 patel2127 C++ Programs Competitive Programming Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Jun, 2021" }, { "code": null, "e": 216, "s": 54, "text": "Given a tree of distinct nodes N with N-1 edges and a pair of nodes P. The task is to find and print the path between the two given nodes of the tree using DFS. " }, { "code": null, "e": 428, "s": 216, "text": "Input: N = 10\n 1\n / \\\n 2 3\n / | \\ / | \\\n 4 5 6 7 8 9\nPair = {4, 8}\nOutput: 4 -> 2 -> 1 -> 3 -> 8\n\nInput: N = 3\n 1\n / \\\n 2 3\nPair = {2, 3}\nOutput: 2 -> 1 -> 3" }, { "code": null, "e": 566, "s": 430, "text": "For example, in the above tree the path between nodes 5 and 3 is 5 -> 2 -> 1 -> 3. Path between nodes 4 and 8 is 4 -> 2 -> 1 -> 3 -> 8." }, { "code": null, "e": 577, "s": 566, "text": "Approach: " }, { "code": null, "e": 703, "s": 577, "text": "The idea is to run DFS from the source node and push the traversed nodes into a stack till the destination node is traversed." }, { "code": null, "e": 761, "s": 703, "text": "Whenever backtracking occurs pop the node from the stack." }, { "code": null, "e": 823, "s": 761, "text": "Note: There should be a path between the given pair of nodes." }, { "code": null, "e": 876, "s": 823, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 880, "s": 876, "text": "C++" }, { "code": null, "e": 885, "s": 880, "text": "Java" }, { "code": null, "e": 893, "s": 885, "text": "Python3" }, { "code": null, "e": 896, "s": 893, "text": "C#" }, { "code": null, "e": 907, "s": 896, "text": "Javascript" }, { "code": "// C++ implementation#include <bits/stdc++.h>using namespace std; // An utility function to add an edge in an// undirected graph.void addEdge(vector<int> v[], int x, int y){ v[x].push_back(y); v[y].push_back(x);} // A function to print the path between// the given pair of nodes.void printPath(vector<int> stack){ int i; for (i = 0; i < (int)stack.size() - 1; i++) { cout << stack[i] << \" -> \"; } cout << stack[i];} // An utility function to do// DFS of graph recursively// from a given vertex x.void DFS(vector<int> v[], bool vis[], int x, int y, vector<int> stack){ stack.push_back(x); if (x == y) { // print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // if backtracking is taking place if (!v[x].empty()) { for (int j = 0; j < v[x].size(); j++) { // if the node is not visited if (vis[v[x][j]] == false) DFS(v, vis, v[x][j], y, stack); } } stack.pop_back();} // A utility function to initialise// visited for the node and call// DFS function for a given vertex x.void DFSCall(int x, int y, vector<int> v[], int n, vector<int> stack){ // visited array bool vis[n + 1]; memset(vis, false, sizeof(vis)); // DFS function call DFS(v, vis, x, y, stack);} // Driver Codeint main(){ int n = 10; vector<int> v[n], stack; // Vertex numbers should be from 1 to 9. addEdge(v, 1, 2); addEdge(v, 1, 3); addEdge(v, 2, 4); addEdge(v, 2, 5); addEdge(v, 2, 6); addEdge(v, 3, 7); addEdge(v, 3, 8); addEdge(v, 3, 9); // Function Call DFSCall(4, 8, v, n, stack); return 0;}", "e": 2724, "s": 907, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*;class GFG{ static Vector<Vector<Integer>> v = new Vector<Vector<Integer>>(); // An utility function to add an edge in an // undirected graph. static void addEdge(int x, int y){ v.get(x).add(y); v.get(y).add(x); } // A function to print the path between // the given pair of nodes. static void printPath(Vector<Integer> stack) { for(int i = 0; i < stack.size() - 1; i++) { System.out.print(stack.get(i) + \" -> \"); } System.out.println(stack.get(stack.size() - 1)); } // An utility function to do // DFS of graph recursively // from a given vertex x. static void DFS(boolean vis[], int x, int y, Vector<Integer> stack) { stack.add(x); if (x == y) { // print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // if backtracking is taking place if (v.get(x).size() > 0) { for(int j = 0; j < v.get(x).size(); j++) { // if the node is not visited if (vis[v.get(x).get(j)] == false) { DFS(vis, v.get(x).get(j), y, stack); } } } stack.remove(stack.size() - 1); } // A utility function to initialise // visited for the node and call // DFS function for a given vertex x. static void DFSCall(int x, int y, int n, Vector<Integer> stack) { // visited array boolean vis[] = new boolean[n + 1]; Arrays.fill(vis, false); // memset(vis, false, sizeof(vis)) // DFS function call DFS(vis, x, y, stack); } // Driver code public static void main(String[] args) { for(int i = 0; i < 100; i++) { v.add(new Vector<Integer>()); } int n = 10; Vector<Integer> stack = new Vector<Integer>(); // Vertex numbers should be from 1 to 9. addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); addEdge(3, 9); // Function Call DFSCall(4, 8, n, stack); }} // This code is contributed by divyeshrabadiya07", "e": 5219, "s": 2724, "text": null }, { "code": "# Python3 implementation of the above approachv = [[] for i in range(100)] # An utility function to add an edge in an# undirected graph.def addEdge(x, y): v[x].append(y) v[y].append(x) # A function to print the path between# the given pair of nodes.def printPath(stack): for i in range(len(stack) - 1): print(stack[i], end = \" -> \") print(stack[-1]) # An utility function to do# DFS of graph recursively# from a given vertex x.def DFS(vis, x, y, stack): stack.append(x) if (x == y): # print the path and return on # reaching the destination node printPath(stack) return vis[x] = True # if backtracking is taking place if (len(v[x]) > 0): for j in v[x]: # if the node is not visited if (vis[j] == False): DFS(vis, j, y, stack) del stack[-1] # A utility function to initialise# visited for the node and call# DFS function for a given vertex x.def DFSCall(x, y, n, stack): # visited array vis = [0 for i in range(n + 1)] #memset(vis, false, sizeof(vis)) # DFS function call DFS(vis, x, y, stack) # Driver Coden = 10stack = [] # Vertex numbers should be from 1 to 9.addEdge(1, 2)addEdge(1, 3)addEdge(2, 4)addEdge(2, 5)addEdge(2, 6)addEdge(3, 7)addEdge(3, 8)addEdge(3, 9) # Function CallDFSCall(4, 8, n, stack) # This code is contributed by Mohit Kumar", "e": 6635, "s": 5219, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ static List<List<int>> v = new List<List<int>>(); // An utility function to Add an edge in an // undirected graph. static void addEdge(int x, int y) { v[x].Add(y); v[y].Add(x); } // A function to print the path between // the given pair of nodes. static void printPath(List<int> stack) { for(int i = 0; i < stack.Count - 1; i++) { Console.Write(stack[i] + \" -> \"); } Console.WriteLine(stack[stack.Count - 1]); } // An utility function to do // DFS of graph recursively // from a given vertex x. static void DFS(bool []vis, int x, int y, List<int> stack) { stack.Add(x); if (x == y) { // print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // if backtracking is taking place if (v[x].Count > 0) { for(int j = 0; j < v[x].Count; j++) { // if the node is not visited if (vis[v[x][j]] == false) { DFS(vis, v[x][j], y, stack); } } } stack.RemoveAt(stack.Count - 1); } // A utility function to initialise // visited for the node and call // DFS function for a given vertex x. static void DFSCall(int x, int y, int n, List<int> stack) { // visited array bool []vis = new bool[n + 1]; Array.Fill(vis, false); // memset(vis, false, sizeof(vis)) // DFS function call DFS(vis, x, y, stack); } // Driver code public static void Main(string[] args) { for(int i = 0; i < 100; i++) { v.Add(new List<int>()); } int n = 10; List<int> stack = new List<int>(); // Vertex numbers should be from 1 to 9. addEdge(1, 2); addEdge(1, 3); addEdge(2, 4); addEdge(2, 5); addEdge(2, 6); addEdge(3, 7); addEdge(3, 8); addEdge(3, 9); // Function Call DFSCall(4, 8, n, stack); }} // This code is contributed by rutvik_56", "e": 9067, "s": 6635, "text": null }, { "code": "<script> // Javascript implementation of the above approachlet v = []; // An utility function to add an edge in an// undirected graph.function addEdge(x, y){ v[x].push(y); v[y].push(x);} // A function to print the path between// the given pair of nodes.function printPath(stack){ for(let i = 0; i < stack.length - 1; i++) { document.write(stack[i] + \" -> \"); } document.write(stack[stack.length - 1] + \"<br>\");} // An utility function to do// DFS of graph recursively// from a given vertex x.function DFS(vis, x, y, stack){ stack.push(x); if (x == y) { // Print the path and return on // reaching the destination node printPath(stack); return; } vis[x] = true; // If backtracking is taking place if (v[x].length > 0) { for(let j = 0; j < v[x].length; j++) { // If the node is not visited if (vis[v[x][j]] == false) { DFS(vis, v[x][j], y, stack); } } } stack.pop();} // A utility function to initialise// visited for the node and call// DFS function for a given vertex x.function DFSCall(x, y, n, stack){ // Visited array let vis = new Array(n + 1); for(let i = 0; i < (n + 1); i++) { vis[i] = false; } // memset(vis, false, sizeof(vis)) // DFS function call DFS(vis, x, y, stack);} // Driver codefor(let i = 0; i < 100; i++){ v.push([]);} let n = 10;let stack = []; // Vertex numbers should be from 1 to 9.addEdge(1, 2);addEdge(1, 3);addEdge(2, 4);addEdge(2, 5);addEdge(2, 6);addEdge(3, 7);addEdge(3, 8);addEdge(3, 9); // Function CallDFSCall(4, 8, n, stack); // This code is contributed by patel2127 </script>", "e": 10823, "s": 9067, "text": null }, { "code": null, "e": 10845, "s": 10823, "text": "4 -> 2 -> 1 -> 3 -> 8" }, { "code": null, "e": 10869, "s": 10847, "text": "Efficient Approach : " }, { "code": null, "e": 10947, "s": 10869, "text": "In this approach we will utilise the concept of Lowest Common Ancestor (LCA)." }, { "code": null, "e": 11005, "s": 10947, "text": "1. We will find level and parent of every node using DFS." }, { "code": null, "e": 11074, "s": 11005, "text": "2. We will find lowest common ancestor (LCA) of the two given nodes." }, { "code": null, "e": 11152, "s": 11074, "text": "3. Starting from the first node we will travel to the LCA and keep on pushing" }, { "code": null, "e": 11196, "s": 11152, "text": "the intermediates nodes in our path vector." }, { "code": null, "e": 11272, "s": 11196, "text": "4. Then, from the second node we will again travel to the LCA but this time" }, { "code": null, "e": 11345, "s": 11272, "text": "we will reverse the encountered intermediate nodes and then push them in" }, { "code": null, "e": 11362, "s": 11345, "text": "our path vector." }, { "code": null, "e": 11435, "s": 11362, "text": "5. Finally, print the path vector to get the path between the two nodes." }, { "code": null, "e": 11439, "s": 11435, "text": "C++" }, { "code": "// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // An utility function to add an edge in the treevoid addEdge(vector<int> adj[], int x, int y){ adj[x].push_back(y); adj[y].push_back(x);} // running dfs to find level and parent of every nodevoid dfs(vector<int> adj[], int node, int l, int p, int lvl[], int par[]){ lvl[node] = l; par[node] = p; for(int child : adj[node]) { if(child != p) dfs(adj, child, l+1, node, lvl, par); }} int LCA(int a, int b, int par[], int lvl[]){ // if node a is at deeper level than // node b if(lvl[a] > lvl[b]) swap(a, b); // finding the difference in levels // of node a and b int diff = lvl[b] - lvl[a]; // moving b to the level of a while(diff != 0) { b = par[b]; diff--; } // means we have found the LCA if(a == b) return a; // finding the LCA while(a != b) a=par[a], b=par[b]; return a;} void printPath(vector<int> adj[], int a, int b, int n){ // stores level of every node int lvl[n+1]; // stores parent of every node int par[n+1]; // running dfs to find parent and level // of every node in the tree dfs(adj, 1, 0, -1, lvl, par); // finding the lowest common ancestor // of the nodes a and b int lca = LCA(a, b, par, lvl); // stores path between nodes a and b vector<int> path; // traversing the path from a to lca while(a != lca) path.push_back(a), a = par[a]; path.push_back(a); vector<int> temp; // traversing the path from b to lca while(b != lca) temp.push_back(b), b=par[b]; // reversing the path to get actual path reverse(temp.begin(), temp.end()); for(int x : temp) path.push_back(x); // printing the path for(int i = 0; i < path.size() - 1; i++) cout << path[i] << \" -> \"; cout << path[path.size() - 1] << endl;} // Driver Codeint main(){ /* 1 / \\ 2 7 / \\ 3 6 / | \\ 4 8 5 */ // number of nodes in the tree int n = 8; // adjacency list representation of the tree vector<int> adj[n+1]; addEdge(adj, 1, 2); addEdge(adj, 1, 7); addEdge(adj, 2, 3); addEdge(adj, 2, 6); addEdge(adj, 3, 4); addEdge(adj, 3, 8); addEdge(adj, 3, 5); // taking two input nodes // between which path is // to be printed int a = 4, b = 7; printPath(adj, a, b, n); return 0;}", "e": 14094, "s": 11439, "text": null }, { "code": null, "e": 14116, "s": 14094, "text": "4 -> 3 -> 2 -> 1 -> 7" }, { "code": null, "e": 14140, "s": 14116, "text": "Time Complexity : O(N) " }, { "code": null, "e": 14164, "s": 14140, "text": "Space Complexity : O(N)" }, { "code": null, "e": 14179, "s": 14164, "text": "mohit kumar 29" }, { "code": null, "e": 14190, "s": 14179, "text": "nidhi_biet" }, { "code": null, "e": 14204, "s": 14190, "text": "debdutgoswami" }, { "code": null, "e": 14222, "s": 14204, "text": "divyeshrabadiya07" }, { "code": null, "e": 14232, "s": 14222, "text": "rutvik_56" }, { "code": null, "e": 14247, "s": 14232, "text": "pawanharwani11" }, { "code": null, "e": 14257, "s": 14247, "text": "patel2127" }, { "code": null, "e": 14270, "s": 14257, "text": "C++ Programs" }, { "code": null, "e": 14294, "s": 14270, "text": "Competitive Programming" }, { "code": null, "e": 14300, "s": 14294, "text": "Graph" }, { "code": null, "e": 14306, "s": 14300, "text": "Graph" } ]
Virtually Indexed Physically Tagged (VIPT) Cache
07 Oct, 2021 Prerequisites: Cache MemoryMemory AccessPagingTransition Look Aside Buffer Cache Memory Memory Access Paging Transition Look Aside Buffer Revisiting Cache AccessWhen a CPU generates physical address, the access to main memory precedes with access to cache. Data is checked in cache by using the tag and index/set bits as show here. Such cache where the tag and index bits are generated from physical address is called as a Physically Indexed and Physically Tagged(PIPT) cache. When there is a cache hit, the memory access time is reduced significantly. Cache Hit Average Memory Access Time = Hit Time + Miss Rate* Miss Penalty Here, Hit Time= Cache Hit Time= Time it takes to access a memory location in the cacheMiss Penalty= time it takes to load a cache line from main memory into cacheMiss Rate= over a long period of time In today’s systems, CPU generates a logical address(also called virtual address) for a process. When using a PIPT cache, the logical address needs to be converted to its corresponding physical address before the PIPT cache can be searched for data. This conversion from logical address to physical address includes the following steps: Check the logical address in the Transition Look Aside Buffer(TLB) and If it is present in TLB, get the physical address of page from the TLB.If it is not present, access the page table from physical memory and then use the page table to obtain the physical address. Check the logical address in the Transition Look Aside Buffer(TLB) and If it is present in TLB, get the physical address of page from the TLB. If it is not present, access the page table from physical memory and then use the page table to obtain the physical address. All this time adds to the hit time. Hence, hit time = TLB latency + cache latency TLB and PIPT Cache: Hit and Miss Limitations of PIPT Cache This process is quite sequential hence high hit time.Not ideal for inner level caches.Data cache is accessed frequently by any system and TLB access for data every time will slow the system significantly. This process is quite sequential hence high hit time. Not ideal for inner level caches. Data cache is accessed frequently by any system and TLB access for data every time will slow the system significantly. Virtually Indexed Virtually Tagged CacheAn immediate solution appears to be a Virtually Indexed Virtually Tagged(VIVT) cache. VIVT cache directly checks the data in cache and fetch it without translating it to physical address reducing the hit time significantly. In such a cache, the tag and index will be a part of the logical/ virtual address generated by CPU. Now the address generated directly by the CPU can be used to fetch the data reducing the hit time significantly. Only if the data is not present in cache, TLB will be checked and finally after converting to physical address, the data will be brought into the VIVT cache. Hence, hit time for VIVT = cache hit time. VIVT Cache Hit and Miss Limitations of VIVT Cache: The TLB contains important flags like the dirty bit and invalid bit so even with VIVT cache, TLB needs to be checked anyways.Lots of cache misses on context switch: Since the cache is specific to logical address and each process has its own logical address space, two process can use the same address but refer to different data.Remember that this is the same reason for having a page table for every process. This means that for every context switch, the cache needs to be flushed and every context switch follows with a lot of cache misses both of which is time-consuming and adds to the hit time. The TLB contains important flags like the dirty bit and invalid bit so even with VIVT cache, TLB needs to be checked anyways. Lots of cache misses on context switch: Since the cache is specific to logical address and each process has its own logical address space, two process can use the same address but refer to different data.Remember that this is the same reason for having a page table for every process. This means that for every context switch, the cache needs to be flushed and every context switch follows with a lot of cache misses both of which is time-consuming and adds to the hit time. A solution to these problems is Virtually Indexed Physically Tagged Cache (VIPT Cache). The next sections in the article covers VIPT Cache, challenge in VIPT Cache and some solutions Virtually Indexed Physically Tagged Cache (VIPT)The VIPT cache uses tag bits from physical address and index as index from logical/ virtual address. The cache is searched using the virtual address and tag part of physical address is obtained. The TLB is searched with virtual address, and physical address is obtained. Finally, the tag part of physical address obtained from the VIPT cache is compared with physical address’s tag obtained from TLB. If they both are same, then it is a cache hit else a cache miss. VIPT Cache Hit and Miss Since TLB is smaller in size than cache, TLB’s access time will be lesser than Cache’s access time. Hence, hit time= cache hit time. VIPT cache takes same time as VIVT cache during a hit and solves the problem VIVT cache: Since the TLB is also accessed in parallel the flags can be checked at the same time.The VIPT cache uses part of physical address as index and since every memory access in the system will correspond to a unique physical address, data for multiple processes can exist in the cache and hence no need to flush data for every context switch. Since the TLB is also accessed in parallel the flags can be checked at the same time. The VIPT cache uses part of physical address as index and since every memory access in the system will correspond to a unique physical address, data for multiple processes can exist in the cache and hence no need to flush data for every context switch. A problem that can be thought of is the case when there is a cache hit but a TLB miss which will require a memory access to the page table in physical memory. This happens very rarely since TLB stores only bits(address and flags) as its entries which requires very less space as compared to a whole block(several bytes) of memory in case of cache. Hence, the number of entries in TLB is way more than the cache blocks in cache i.e. entries in TLB entries in tag directory of cache. Advantages of Virtually Indexed Physically Tagged Cache Avoids sequential access reducing the hit timeUseful in data caches where the access to cache is frequentAvoids cache misses on context switchTLB flags can be accessed in parallel with cache access Avoids sequential access reducing the hit time Useful in data caches where the access to cache is frequent Avoids cache misses on context switch TLB flags can be accessed in parallel with cache access Challenge in Virtually Indexed Physically Tagged CacheVirtually indexing in VIPT cache causes a challenge. A process can have two virtual addressed mapped to the same physical location. This can be done using mmap in linux: mmap(virtual_addr_A,4096,file_descriptor,offset)mmap(virtual_addr_B,4096,file_descriptor,offset) The above two lines map file pointed by file_descriptor to two different virtual addresses but the same physical address. Since these two virtual addresses are different and cache is virtually indexed, both these locations may get indexed to different locations in the cache. This will lead to having two copies of the data block and when these locations are updated, the data will be inconsistent. This problem is called Aliasing. Aliasing can also happen with a shared block by two processes. Following are the four solutions to solve the problem: The first solution requires invalidating the any other copy of data in cache when updating a memory location.The second solution would be to update every other copy of data in the cache when updating a memory locationNote that the first and second solution requires checking if any other location maps to the same physical memory location. This requires translating the virtual address to physical address; but VIPT was aimed to avoid translation as it adds up to the hit latency.The third solution involves reducing the cache size. Remember that during translation of virtual address to physical address the page offset of a virtual address is same as that of physical address. This means that the two virtual address will also have the same page offset. To make sure that the two virtual addresses are mapped to the same index in the cache, the index field must be completely in the page offset part. The first solution requires invalidating the any other copy of data in cache when updating a memory location. The second solution would be to update every other copy of data in the cache when updating a memory locationNote that the first and second solution requires checking if any other location maps to the same physical memory location. This requires translating the virtual address to physical address; but VIPT was aimed to avoid translation as it adds up to the hit latency. The third solution involves reducing the cache size. Remember that during translation of virtual address to physical address the page offset of a virtual address is same as that of physical address. This means that the two virtual address will also have the same page offset. To make sure that the two virtual addresses are mapped to the same index in the cache, the index field must be completely in the page offset part. Example demonstrating Aliasing: Consider a system with: 32 bit virtual address, block size 16 Bytes and page size 4 KB (i) Direct Mapped Cache: 64 KB (ii) Direct Mapped Cache: 4 KB (iii) Direct Mapped Cache: 2 KB (i) In the 32-bit virtual address, for a 64KB direct mapped cache, bits 15 to 4 are for index, bits 11 to 0 are page offset(which means for any two VA pointing to the same PA, 12 LSB bits will be the same). 6 KB Direct mapped cache Two virtual addresses can be 0x0045626E and FF21926E mapped to the same physical address. The first address will get indexed to (626)H cache line and second address will get indexed to (926)H. This shows aliasing happens with a 64KB direct mapped cache for the system. Also note that the last 12 bits are same in both the addressed since they have mapped to the same physical addressed and last 12 bits form the page offset which will be same for both the virtual addresses. (ii) In the 32-bit virtual address, for a 4KB direct mapped cache, bits 11 to 4 are for index, bits 11 to 0 are page offset(which means for any two VA pointing to the same PA, 12 LSB bits will be the same). 4 KB Direct mapped cache Two addresses can be 0x12345678 and 0xFEDCB678. Note that the 12 LSB bits are same i.e. (678)H . Since for a 2KB direct mapped cache, the index bits are completely a part of the same page offset, the index of cache where both the virtual addresses will map will be the same. Hence, only one copy stays at a time and no aliasing occurs. (iii) Following is a representation for a 2KB direct mapped cache for the system showing no aliasing. Hence, any direct mapped cache of size smaller or equal to 4KB will cause no aliasing. 2 KB Direct mapped cache 4. The third solution to aliasing requires the cache to be smaller, smaller cache will cause more cache misses. Solutions 1, 2 and 3 are hardware based. Yet another solution called page color/ cache coloring is a software solution implemented by the operating system to solve aliasing without limiting the cache size. In case of 64KB cache 16 colors are needed to ensure no aliasing happens. Further, read: Page Coloring on ARMv6 rajeev0719singh memory-management Computer Organization & Architecture 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": 52, "s": 24, "text": "\n07 Oct, 2021" }, { "code": null, "e": 67, "s": 52, "text": "Prerequisites:" }, { "code": null, "e": 127, "s": 67, "text": "Cache MemoryMemory AccessPagingTransition Look Aside Buffer" }, { "code": null, "e": 140, "s": 127, "text": "Cache Memory" }, { "code": null, "e": 154, "s": 140, "text": "Memory Access" }, { "code": null, "e": 161, "s": 154, "text": "Paging" }, { "code": null, "e": 190, "s": 161, "text": "Transition Look Aside Buffer" }, { "code": null, "e": 605, "s": 190, "text": "Revisiting Cache AccessWhen a CPU generates physical address, the access to main memory precedes with access to cache. Data is checked in cache by using the tag and index/set bits as show here. Such cache where the tag and index bits are generated from physical address is called as a Physically Indexed and Physically Tagged(PIPT) cache. When there is a cache hit, the memory access time is reduced significantly." }, { "code": null, "e": 615, "s": 605, "text": "Cache Hit" }, { "code": null, "e": 679, "s": 615, "text": "Average Memory Access Time =\nHit Time + Miss Rate* Miss Penalty" }, { "code": null, "e": 879, "s": 679, "text": "Here, Hit Time= Cache Hit Time= Time it takes to access a memory location in the cacheMiss Penalty= time it takes to load a cache line from main memory into cacheMiss Rate= over a long period of time" }, { "code": null, "e": 1215, "s": 879, "text": "In today’s systems, CPU generates a logical address(also called virtual address) for a process. When using a PIPT cache, the logical address needs to be converted to its corresponding physical address before the PIPT cache can be searched for data. This conversion from logical address to physical address includes the following steps:" }, { "code": null, "e": 1482, "s": 1215, "text": "Check the logical address in the Transition Look Aside Buffer(TLB) and If it is present in TLB, get the physical address of page from the TLB.If it is not present, access the page table from physical memory and then use the page table to obtain the physical address." }, { "code": null, "e": 1625, "s": 1482, "text": "Check the logical address in the Transition Look Aside Buffer(TLB) and If it is present in TLB, get the physical address of page from the TLB." }, { "code": null, "e": 1750, "s": 1625, "text": "If it is not present, access the page table from physical memory and then use the page table to obtain the physical address." }, { "code": null, "e": 1832, "s": 1750, "text": "All this time adds to the hit time. Hence, hit time = TLB latency + cache latency" }, { "code": null, "e": 1865, "s": 1832, "text": "TLB and PIPT Cache: Hit and Miss" }, { "code": null, "e": 1891, "s": 1865, "text": "Limitations of PIPT Cache" }, { "code": null, "e": 2096, "s": 1891, "text": "This process is quite sequential hence high hit time.Not ideal for inner level caches.Data cache is accessed frequently by any system and TLB access for data every time will slow the system significantly." }, { "code": null, "e": 2150, "s": 2096, "text": "This process is quite sequential hence high hit time." }, { "code": null, "e": 2184, "s": 2150, "text": "Not ideal for inner level caches." }, { "code": null, "e": 2303, "s": 2184, "text": "Data cache is accessed frequently by any system and TLB access for data every time will slow the system significantly." }, { "code": null, "e": 2982, "s": 2303, "text": "Virtually Indexed Virtually Tagged CacheAn immediate solution appears to be a Virtually Indexed Virtually Tagged(VIVT) cache. VIVT cache directly checks the data in cache and fetch it without translating it to physical address reducing the hit time significantly. In such a cache, the tag and index will be a part of the logical/ virtual address generated by CPU. Now the address generated directly by the CPU can be used to fetch the data reducing the hit time significantly. Only if the data is not present in cache, TLB will be checked and finally after converting to physical address, the data will be brought into the VIVT cache. Hence, hit time for VIVT = cache hit time." }, { "code": null, "e": 3006, "s": 2982, "text": "VIVT Cache Hit and Miss" }, { "code": null, "e": 3033, "s": 3006, "text": "Limitations of VIVT Cache:" }, { "code": null, "e": 3633, "s": 3033, "text": "The TLB contains important flags like the dirty bit and invalid bit so even with VIVT cache, TLB needs to be checked anyways.Lots of cache misses on context switch: Since the cache is specific to logical address and each process has its own logical address space, two process can use the same address but refer to different data.Remember that this is the same reason for having a page table for every process. This means that for every context switch, the cache needs to be flushed and every context switch follows with a lot of cache misses both of which is time-consuming and adds to the hit time." }, { "code": null, "e": 3759, "s": 3633, "text": "The TLB contains important flags like the dirty bit and invalid bit so even with VIVT cache, TLB needs to be checked anyways." }, { "code": null, "e": 4234, "s": 3759, "text": "Lots of cache misses on context switch: Since the cache is specific to logical address and each process has its own logical address space, two process can use the same address but refer to different data.Remember that this is the same reason for having a page table for every process. This means that for every context switch, the cache needs to be flushed and every context switch follows with a lot of cache misses both of which is time-consuming and adds to the hit time." }, { "code": null, "e": 4417, "s": 4234, "text": "A solution to these problems is Virtually Indexed Physically Tagged Cache (VIPT Cache). The next sections in the article covers VIPT Cache, challenge in VIPT Cache and some solutions" }, { "code": null, "e": 4931, "s": 4417, "text": "Virtually Indexed Physically Tagged Cache (VIPT)The VIPT cache uses tag bits from physical address and index as index from logical/ virtual address. The cache is searched using the virtual address and tag part of physical address is obtained. The TLB is searched with virtual address, and physical address is obtained. Finally, the tag part of physical address obtained from the VIPT cache is compared with physical address’s tag obtained from TLB. If they both are same, then it is a cache hit else a cache miss." }, { "code": null, "e": 4955, "s": 4931, "text": "VIPT Cache Hit and Miss" }, { "code": null, "e": 5177, "s": 4955, "text": "Since TLB is smaller in size than cache, TLB’s access time will be lesser than Cache’s access time. Hence, hit time= cache hit time. VIPT cache takes same time as VIVT cache during a hit and solves the problem VIVT cache:" }, { "code": null, "e": 5515, "s": 5177, "text": "Since the TLB is also accessed in parallel the flags can be checked at the same time.The VIPT cache uses part of physical address as index and since every memory access in the system will correspond to a unique physical address, data for multiple processes can exist in the cache and hence no need to flush data for every context switch." }, { "code": null, "e": 5601, "s": 5515, "text": "Since the TLB is also accessed in parallel the flags can be checked at the same time." }, { "code": null, "e": 5854, "s": 5601, "text": "The VIPT cache uses part of physical address as index and since every memory access in the system will correspond to a unique physical address, data for multiple processes can exist in the cache and hence no need to flush data for every context switch." }, { "code": null, "e": 6337, "s": 5854, "text": "A problem that can be thought of is the case when there is a cache hit but a TLB miss which will require a memory access to the page table in physical memory. This happens very rarely since TLB stores only bits(address and flags) as its entries which requires very less space as compared to a whole block(several bytes) of memory in case of cache. Hence, the number of entries in TLB is way more than the cache blocks in cache i.e. entries in TLB entries in tag directory of cache." }, { "code": null, "e": 6393, "s": 6337, "text": "Advantages of Virtually Indexed Physically Tagged Cache" }, { "code": null, "e": 6591, "s": 6393, "text": "Avoids sequential access reducing the hit timeUseful in data caches where the access to cache is frequentAvoids cache misses on context switchTLB flags can be accessed in parallel with cache access" }, { "code": null, "e": 6638, "s": 6591, "text": "Avoids sequential access reducing the hit time" }, { "code": null, "e": 6698, "s": 6638, "text": "Useful in data caches where the access to cache is frequent" }, { "code": null, "e": 6736, "s": 6698, "text": "Avoids cache misses on context switch" }, { "code": null, "e": 6792, "s": 6736, "text": "TLB flags can be accessed in parallel with cache access" }, { "code": null, "e": 7017, "s": 6792, "text": "Challenge in Virtually Indexed Physically Tagged CacheVirtually indexing in VIPT cache causes a challenge. A process can have two virtual addressed mapped to the same physical location. This can be done using mmap in linux:" }, { "code": null, "e": 7114, "s": 7017, "text": "mmap(virtual_addr_A,4096,file_descriptor,offset)mmap(virtual_addr_B,4096,file_descriptor,offset)" }, { "code": null, "e": 7609, "s": 7114, "text": "The above two lines map file pointed by file_descriptor to two different virtual addresses but the same physical address. Since these two virtual addresses are different and cache is virtually indexed, both these locations may get indexed to different locations in the cache. This will lead to having two copies of the data block and when these locations are updated, the data will be inconsistent. This problem is called Aliasing. Aliasing can also happen with a shared block by two processes." }, { "code": null, "e": 7664, "s": 7609, "text": "Following are the four solutions to solve the problem:" }, { "code": null, "e": 8567, "s": 7664, "text": "The first solution requires invalidating the any other copy of data in cache when updating a memory location.The second solution would be to update every other copy of data in the cache when updating a memory locationNote that the first and second solution requires checking if any other location maps to the same physical memory location. This requires translating the virtual address to physical address; but VIPT was aimed to avoid translation as it adds up to the hit latency.The third solution involves reducing the cache size. Remember that during translation of virtual address to physical address the page offset of a virtual address is same as that of physical address. This means that the two virtual address will also have the same page offset. To make sure that the two virtual addresses are mapped to the same index in the cache, the index field must be completely in the page offset part." }, { "code": null, "e": 8677, "s": 8567, "text": "The first solution requires invalidating the any other copy of data in cache when updating a memory location." }, { "code": null, "e": 9049, "s": 8677, "text": "The second solution would be to update every other copy of data in the cache when updating a memory locationNote that the first and second solution requires checking if any other location maps to the same physical memory location. This requires translating the virtual address to physical address; but VIPT was aimed to avoid translation as it adds up to the hit latency." }, { "code": null, "e": 9472, "s": 9049, "text": "The third solution involves reducing the cache size. Remember that during translation of virtual address to physical address the page offset of a virtual address is same as that of physical address. This means that the two virtual address will also have the same page offset. To make sure that the two virtual addresses are mapped to the same index in the cache, the index field must be completely in the page offset part." }, { "code": null, "e": 9504, "s": 9472, "text": "Example demonstrating Aliasing:" }, { "code": null, "e": 9685, "s": 9504, "text": "Consider a system with:\n32 bit virtual address,\nblock size 16 Bytes and page size 4 KB\n(i) Direct Mapped Cache: 64 KB\n(ii) Direct Mapped Cache: 4 KB\n(iii) Direct Mapped Cache: 2 KB" }, { "code": null, "e": 9892, "s": 9685, "text": "(i) In the 32-bit virtual address, for a 64KB direct mapped cache, bits 15 to 4 are for index, bits 11 to 0 are page offset(which means for any two VA pointing to the same PA, 12 LSB bits will be the same)." }, { "code": null, "e": 9917, "s": 9892, "text": "6 KB Direct mapped cache" }, { "code": null, "e": 10392, "s": 9917, "text": "Two virtual addresses can be 0x0045626E and FF21926E mapped to the same physical address. The first address will get indexed to (626)H cache line and second address will get indexed to (926)H. This shows aliasing happens with a 64KB direct mapped cache for the system. Also note that the last 12 bits are same in both the addressed since they have mapped to the same physical addressed and last 12 bits form the page offset which will be same for both the virtual addresses." }, { "code": null, "e": 10599, "s": 10392, "text": "(ii) In the 32-bit virtual address, for a 4KB direct mapped cache, bits 11 to 4 are for index, bits 11 to 0 are page offset(which means for any two VA pointing to the same PA, 12 LSB bits will be the same)." }, { "code": null, "e": 10624, "s": 10599, "text": "4 KB Direct mapped cache" }, { "code": null, "e": 10961, "s": 10624, "text": "Two addresses can be 0x12345678 and 0xFEDCB678. Note that the 12 LSB bits are same i.e. (678)H . Since for a 2KB direct mapped cache, the index bits are completely a part of the same page offset, the index of cache where both the virtual addresses will map will be the same. Hence, only one copy stays at a time and no aliasing occurs. " }, { "code": null, "e": 11150, "s": 10961, "text": "(iii) Following is a representation for a 2KB direct mapped cache for the system showing no aliasing. Hence, any direct mapped cache of size smaller or equal to 4KB will cause no aliasing." }, { "code": null, "e": 11175, "s": 11150, "text": "2 KB Direct mapped cache" }, { "code": null, "e": 11662, "s": 11175, "text": " 4. The third solution to aliasing requires the cache to be smaller, smaller cache will cause more cache misses. Solutions 1, 2 and 3 are hardware based. Yet another solution called page color/ cache coloring is a software solution implemented by the operating system to solve aliasing without limiting the cache size. In case of 64KB cache 16 colors are needed to ensure no aliasing happens. Further, read: Page Coloring on ARMv6" }, { "code": null, "e": 11678, "s": 11662, "text": "rajeev0719singh" }, { "code": null, "e": 11696, "s": 11678, "text": "memory-management" }, { "code": null, "e": 11733, "s": 11696, "text": "Computer Organization & Architecture" }, { "code": null, "e": 11741, "s": 11733, "text": "GATE CS" }, { "code": null, "e": 11759, "s": 11741, "text": "Operating Systems" }, { "code": null, "e": 11777, "s": 11759, "text": "Operating Systems" } ]
PLY (Python lex-Yacc) – An Introduction
16 Feb, 2022 We all have heard of lex which is a tool that generates lexical analyzer which is then used to tokenify input streams and yacc which is a parser generator but there is a python implementation of these two tools in form of separate modules in a package called PLY. These modules are named lex.py and yacc.py and work similar to the original UNIX tools lex and yacc. PLY works differently from its UNIX counterparts in a way that it doesn’t require a special input file instead it takes the python program as inputs directly. The traditional tools also make use of parsing tables which are hard on compiler time whereas PLY caches the results generated and saves them for use and regenerates them as needed. This is one of the key modules in this package because the working of yacc.py also depends on lex.py as it is responsible for generating a collection of tokens from the input text and that collection is then identified using the regular expression rules. To import this module in your python code use import ply.lex as lex Example: Suppose you wrote a simple expression: y = a + 2 * b When this is passed through ply.py, the following tokens are generated 'y','=', 'a', '+', '2', '*', 'b' These generated tokens are usually used with token names which are always required. #Token list of above tokens will be tokens = ('ID','EQUAL','ID', 'PLUS', 'NUMBER', 'TIMES','ID' ) #Regular expression rules for the above example t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' More specifically, these can be represented as tuples of token type and token ('ID', 'y'), ('EQUALS', '='), ('ID', 'a'), ('PLUS', '+'), ('NUMBER', '2'), ('TIMES', '*'), ('NUMBER', '3') This module provides an external interface too in the form of token() which returns the valid tokens from the input. Another module of this package is yacc.py where yacc stands for Yet Another Compiler Compiler. This can be used to implement one-pass compilers. It provides a lot of features that are already available in UNIX yacc and some extra features that give yacc.py some advantages over traditional yacc You can use the following to import yacc into your python code import ply.yacc as yacc. These features include: LALR(1) parsingGrammar ValidationSupport for empty productionsExtensive error checking capabilityAmbiguity Resolution LALR(1) parsing Grammar Validation Support for empty productions Extensive error checking capability Ambiguity Resolution The explicit token generation token() is also used by yacc.py which continuously calls this on user demand to collect tokens and grammar rules. yacc.py spits out Abstract Syntax Tree (AST) as output. Advantage over UNIX yacc: Python implementation yacc.py doesn’t involve code-generation process instead it uses reflection to make its lexers and parsers which saves space as it doesn’t require any extra compiler constructions step and code file generation. For importing the tokens from your lex file use from lex_file_name_here import tokens where tokens are the list of tokens specified in the lex file. To specify the grammar rules we have to define functions in our yacc file. The syntax for the same is as follows: def function_name_here(symbol): expression = expression token_name term References: https://www.dabeaz.com/ply/ply.html vpiitkgp1 sumitgumber28 sagar0719kumar python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Feb, 2022" }, { "code": null, "e": 319, "s": 54, "text": "We all have heard of lex which is a tool that generates lexical analyzer which is then used to tokenify input streams and yacc which is a parser generator but there is a python implementation of these two tools in form of separate modules in a package called PLY. " }, { "code": null, "e": 421, "s": 319, "text": "These modules are named lex.py and yacc.py and work similar to the original UNIX tools lex and yacc. " }, { "code": null, "e": 763, "s": 421, "text": "PLY works differently from its UNIX counterparts in a way that it doesn’t require a special input file instead it takes the python program as inputs directly. The traditional tools also make use of parsing tables which are hard on compiler time whereas PLY caches the results generated and saves them for use and regenerates them as needed. " }, { "code": null, "e": 1023, "s": 767, "text": "This is one of the key modules in this package because the working of yacc.py also depends on lex.py as it is responsible for generating a collection of tokens from the input text and that collection is then identified using the regular expression rules. " }, { "code": null, "e": 1092, "s": 1023, "text": "To import this module in your python code use import ply.lex as lex " }, { "code": null, "e": 1155, "s": 1092, "text": "Example: Suppose you wrote a simple expression: y = a + 2 * b " }, { "code": null, "e": 1227, "s": 1155, "text": "When this is passed through ply.py, the following tokens are generated " }, { "code": null, "e": 1260, "s": 1227, "text": "'y','=', 'a', '+', '2', '*', 'b'" }, { "code": null, "e": 1345, "s": 1260, "text": "These generated tokens are usually used with token names which are always required. " }, { "code": null, "e": 1567, "s": 1345, "text": "#Token list of above tokens will be\ntokens = ('ID','EQUAL','ID', 'PLUS', 'NUMBER', 'TIMES','ID' )\n\n#Regular expression rules for the above example \n t_PLUS = r'\\+'\n t_MINUS = r'-'\n t_TIMES = r'\\*'\n t_DIVIDE = r'/'" }, { "code": null, "e": 1647, "s": 1567, "text": "More specifically, these can be represented as tuples of token type and token " }, { "code": null, "e": 1755, "s": 1647, "text": "('ID', 'y'), ('EQUALS', '='), ('ID', 'a'), ('PLUS', '+'), \n('NUMBER', '2'), ('TIMES', '*'), ('NUMBER', '3')" }, { "code": null, "e": 1873, "s": 1755, "text": "This module provides an external interface too in the form of token() which returns the valid tokens from the input. " }, { "code": null, "e": 2171, "s": 1875, "text": "Another module of this package is yacc.py where yacc stands for Yet Another Compiler Compiler. This can be used to implement one-pass compilers. It provides a lot of features that are already available in UNIX yacc and some extra features that give yacc.py some advantages over traditional yacc " }, { "code": null, "e": 2260, "s": 2171, "text": "You can use the following to import yacc into your python code import ply.yacc as yacc. " }, { "code": null, "e": 2285, "s": 2260, "text": "These features include: " }, { "code": null, "e": 2403, "s": 2285, "text": "LALR(1) parsingGrammar ValidationSupport for empty productionsExtensive error checking capabilityAmbiguity Resolution" }, { "code": null, "e": 2419, "s": 2403, "text": "LALR(1) parsing" }, { "code": null, "e": 2438, "s": 2419, "text": "Grammar Validation" }, { "code": null, "e": 2468, "s": 2438, "text": "Support for empty productions" }, { "code": null, "e": 2504, "s": 2468, "text": "Extensive error checking capability" }, { "code": null, "e": 2525, "s": 2504, "text": "Ambiguity Resolution" }, { "code": null, "e": 2726, "s": 2525, "text": "The explicit token generation token() is also used by yacc.py which continuously calls this on user demand to collect tokens and grammar rules. yacc.py spits out Abstract Syntax Tree (AST) as output. " }, { "code": null, "e": 3248, "s": 2726, "text": "Advantage over UNIX yacc: Python implementation yacc.py doesn’t involve code-generation process instead it uses reflection to make its lexers and parsers which saves space as it doesn’t require any extra compiler constructions step and code file generation. For importing the tokens from your lex file use from lex_file_name_here import tokens where tokens are the list of tokens specified in the lex file. To specify the grammar rules we have to define functions in our yacc file. The syntax for the same is as follows: " }, { "code": null, "e": 3324, "s": 3248, "text": "def function_name_here(symbol):\n expression = expression token_name term" }, { "code": null, "e": 3373, "s": 3324, "text": "References: https://www.dabeaz.com/ply/ply.html " }, { "code": null, "e": 3383, "s": 3373, "text": "vpiitkgp1" }, { "code": null, "e": 3397, "s": 3383, "text": "sumitgumber28" }, { "code": null, "e": 3412, "s": 3397, "text": "sagar0719kumar" }, { "code": null, "e": 3427, "s": 3412, "text": "python-modules" }, { "code": null, "e": 3434, "s": 3427, "text": "Python" }, { "code": null, "e": 3532, "s": 3434, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3564, "s": 3532, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3591, "s": 3564, "text": "Python Classes and Objects" }, { "code": null, "e": 3622, "s": 3591, "text": "Python | os.path.join() method" }, { "code": null, "e": 3643, "s": 3622, "text": "Python OOPs Concepts" }, { "code": null, "e": 3666, "s": 3643, "text": "Introduction To PYTHON" }, { "code": null, "e": 3722, "s": 3666, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3764, "s": 3722, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3806, "s": 3764, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3845, "s": 3806, "text": "Python | Get unique values from a list" } ]
Python | Denoising of colored images using opencv
14 Jan, 2019 Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. It refers to one of the major pre-processing steps. There are four functions in opencv which is used for denoising of different images. Syntax: cv2.fastNlMeansDenoisingColored( P1, P2, float P3, float P4, int P5, int P6) Parameters:P1 – Source Image ArrayP2 – Destination Image ArrayP3 – Size in pixels of the template patch that is used to compute weights.P4 – Size in pixels of the window that is used to compute a weighted average for the given pixel.P5 – Parameter regulating filter strength for luminance component.P6 – Same as above but for color components // Not used in a grayscale image. Below is the implementation: # importing librariesimport numpy as npimport cv2from matplotlib import pyplot as plt # Reading image from folder where it is storedimg = cv2.imread('bear.png') # denoising of image saving it into dst imagedst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 15) # Plotting of source and destination imageplt.subplot(121), plt.imshow(img)plt.subplot(122), plt.imshow(dst) plt.show() Output: Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2019" }, { "code": null, "e": 341, "s": 28, "text": "Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. It refers to one of the major pre-processing steps. There are four functions in opencv which is used for denoising of different images." }, { "code": null, "e": 426, "s": 341, "text": "Syntax: cv2.fastNlMeansDenoisingColored( P1, P2, float P3, float P4, int P5, int P6)" }, { "code": null, "e": 803, "s": 426, "text": "Parameters:P1 – Source Image ArrayP2 – Destination Image ArrayP3 – Size in pixels of the template patch that is used to compute weights.P4 – Size in pixels of the window that is used to compute a weighted average for the given pixel.P5 – Parameter regulating filter strength for luminance component.P6 – Same as above but for color components // Not used in a grayscale image." }, { "code": null, "e": 832, "s": 803, "text": "Below is the implementation:" }, { "code": "# importing librariesimport numpy as npimport cv2from matplotlib import pyplot as plt # Reading image from folder where it is storedimg = cv2.imread('bear.png') # denoising of image saving it into dst imagedst = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 15) # Plotting of source and destination imageplt.subplot(121), plt.imshow(img)plt.subplot(122), plt.imshow(dst) plt.show()", "e": 1226, "s": 832, "text": null }, { "code": null, "e": 1234, "s": 1226, "text": "Output:" }, { "code": null, "e": 1251, "s": 1234, "text": "Image-Processing" }, { "code": null, "e": 1258, "s": 1251, "text": "OpenCV" }, { "code": null, "e": 1265, "s": 1258, "text": "Python" } ]
Drop duplicate rows in PySpark DataFrame
16 Dec, 2021 In this article, we are going to drop the duplicate rows by using distinct() and dropDuplicates() functions from dataframe using pyspark in Python. Let’s create a sample Dataframe Python3 # importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 1"], ["3", "rohith", "company 2"], ["4", "sridevi", "company 1"], ["1", "sravan", "company 1"], ["4", "sridevi", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company'] # creating a dataframe from the# lists of datadataframe = spark.createDataFrame(data, columns) print('Actual data in dataframe')dataframe.show() Output: Distinct data means unique data. It will remove the duplicate rows in the dataframe Syntax: dataframe.distinct() where, dataframe is the dataframe name created from the nested lists using pyspark Python3 print('distinct data after dropping duplicate rows') # display distinct datadataframe.distinct().show() Output: We can use the select() function along with distinct function to get distinct values from particular columns Syntax: dataframe.select([‘column 1′,’column n’]).distinct().show() Python3 # display distinct data in Employee# ID and Employee NAMEdataframe.select(['Employee ID', 'Employee NAME']).distinct().show() Output: Syntax: dataframe.dropDuplicates() where, dataframe is the dataframe name created from the nested lists using pyspark Python3 # remove duplicate data using# dropDuplicates()functiondataframe.dropDuplicates().show() Output: Python program to remove duplicate values in specific columns Python3 # remove duplicate data using# dropDuplicates() function in# two columnsdataframe.select(['Employee ID', 'Employee NAME'] ).dropDuplicates().show() Output: sagar0719kumar Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2021" }, { "code": null, "e": 177, "s": 28, "text": "In this article, we are going to drop the duplicate rows by using distinct() and dropDuplicates() functions from dataframe using pyspark in Python. " }, { "code": null, "e": 209, "s": 177, "text": "Let’s create a sample Dataframe" }, { "code": null, "e": 217, "s": 209, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from# pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving# an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 1\"], [\"3\", \"rohith\", \"company 2\"], [\"4\", \"sridevi\", \"company 1\"], [\"1\", \"sravan\", \"company 1\"], [\"4\", \"sridevi\", \"company 1\"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company'] # creating a dataframe from the# lists of datadataframe = spark.createDataFrame(data, columns) print('Actual data in dataframe')dataframe.show()", "e": 915, "s": 217, "text": null }, { "code": null, "e": 923, "s": 915, "text": "Output:" }, { "code": null, "e": 1007, "s": 923, "text": "Distinct data means unique data. It will remove the duplicate rows in the dataframe" }, { "code": null, "e": 1036, "s": 1007, "text": "Syntax: dataframe.distinct()" }, { "code": null, "e": 1119, "s": 1036, "text": "where, dataframe is the dataframe name created from the nested lists using pyspark" }, { "code": null, "e": 1127, "s": 1119, "text": "Python3" }, { "code": "print('distinct data after dropping duplicate rows') # display distinct datadataframe.distinct().show()", "e": 1231, "s": 1127, "text": null }, { "code": null, "e": 1239, "s": 1231, "text": "Output:" }, { "code": null, "e": 1348, "s": 1239, "text": "We can use the select() function along with distinct function to get distinct values from particular columns" }, { "code": null, "e": 1416, "s": 1348, "text": "Syntax: dataframe.select([‘column 1′,’column n’]).distinct().show()" }, { "code": null, "e": 1424, "s": 1416, "text": "Python3" }, { "code": "# display distinct data in Employee# ID and Employee NAMEdataframe.select(['Employee ID', 'Employee NAME']).distinct().show()", "e": 1550, "s": 1424, "text": null }, { "code": null, "e": 1558, "s": 1550, "text": "Output:" }, { "code": null, "e": 1593, "s": 1558, "text": "Syntax: dataframe.dropDuplicates()" }, { "code": null, "e": 1676, "s": 1593, "text": "where, dataframe is the dataframe name created from the nested lists using pyspark" }, { "code": null, "e": 1684, "s": 1676, "text": "Python3" }, { "code": "# remove duplicate data using# dropDuplicates()functiondataframe.dropDuplicates().show()", "e": 1773, "s": 1684, "text": null }, { "code": null, "e": 1781, "s": 1773, "text": "Output:" }, { "code": null, "e": 1843, "s": 1781, "text": "Python program to remove duplicate values in specific columns" }, { "code": null, "e": 1851, "s": 1843, "text": "Python3" }, { "code": "# remove duplicate data using# dropDuplicates() function in# two columnsdataframe.select(['Employee ID', 'Employee NAME'] ).dropDuplicates().show()", "e": 2014, "s": 1851, "text": null }, { "code": null, "e": 2022, "s": 2014, "text": "Output:" }, { "code": null, "e": 2037, "s": 2022, "text": "sagar0719kumar" }, { "code": null, "e": 2044, "s": 2037, "text": "Picked" }, { "code": null, "e": 2059, "s": 2044, "text": "Python-Pyspark" }, { "code": null, "e": 2066, "s": 2059, "text": "Python" } ]
Maekawa’s Algorithm for Mutual Exclusion in Distributed System
14 Aug, 2019 Prerequisite – Mutual exclusion in distributed systemsMaekawa’s Algorithm is quorum based approach to ensure mutual exclusion in distributed systems. As we know, In permission based algorithms like Lamport’s Algorithm, Ricart-Agrawala Algorithm etc. a site request permission from every other site but in quorum based approach, A site does not request permission from every other site but from a subset of sites which is called quorum. In this algorithm: Three type of messages ( REQUEST, REPLY and RELEASE) are used. A site send a REQUEST message to all other site in its request set or quorum to get their permission to enter critical section. A site send a REPLY message to requesting site to give its permission to enter the critical section. A site send a RELEASE message to all other site in its request set or quorum upon exiting the critical section. The construction of request set or Quorum:A request set or Quorum in Maekawa’s algorithm must satisfy the following properties: ∀i ∀j : i ≠ j, 1 ≤ i, j ≤ N :: Ri ⋂ Rj ≠ ∅ i.e there is at least one common site between the request sets of any two sites.∀i : 1 ≤ i ≤ N :: Si ∊ Ri ∀i : 1 ≤ i ≤ N :: |Ri| = K Any site Si is contained in exactly K sets.N = K(K - 1) +1 and |Ri| = √N ∀i ∀j : i ≠ j, 1 ≤ i, j ≤ N :: Ri ⋂ Rj ≠ ∅ i.e there is at least one common site between the request sets of any two sites. ∀i ∀j : i ≠ j, 1 ≤ i, j ≤ N :: Ri ⋂ Rj ≠ ∅ i.e there is at least one common site between the request sets of any two sites. ∀i : 1 ≤ i ≤ N :: Si ∊ Ri ∀i : 1 ≤ i ≤ N :: Si ∊ Ri ∀i : 1 ≤ i ≤ N :: |Ri| = K ∀i : 1 ≤ i ≤ N :: |Ri| = K Any site Si is contained in exactly K sets. N = K(K - 1) +1 and |Ri| = √N N = K(K - 1) +1 and |Ri| = √N Algorithm: To enter Critical section:When a site Si wants to enter the critical section, it sends a request message REQUEST(i) to all other sites in the request set Ri.When a site Sj receives the request message REQUEST(i) from site Si, it returns a REPLY message to site Si if it has not sent a REPLY message to the site from the time it received the last RELEASE message. Otherwise, it queues up the request.. When a site Si wants to enter the critical section, it sends a request message REQUEST(i) to all other sites in the request set Ri. When a site Sj receives the request message REQUEST(i) from site Si, it returns a REPLY message to site Si if it has not sent a REPLY message to the site from the time it received the last RELEASE message. Otherwise, it queues up the request. . To execute the critical section:A site Si can enter the critical section if it has received the REPLY message from all the site in request set Ri A site Si can enter the critical section if it has received the REPLY message from all the site in request set Ri To release the critical section:When a site Si exits the critical section, it sends RELEASE(i) message to all other sites in request set RiWhen a site Sj receives the RELEASE(i) message from site Si, it send REPLY message to the next site waiting in the queue and deletes that entry from the queueIn case queue is empty, site Sj update its status to show that it has not sent any REPLY message since the receipt of the last RELEASE message When a site Si exits the critical section, it sends RELEASE(i) message to all other sites in request set Ri When a site Sj receives the RELEASE(i) message from site Si, it send REPLY message to the next site waiting in the queue and deletes that entry from the queue In case queue is empty, site Sj update its status to show that it has not sent any REPLY message since the receipt of the last RELEASE message Message Complexity:Maekawa’s Algorithm requires invocation of 3√N messages per critical section execution as the size of a request set is √N. These 3√N messages involves. √N request messages √N reply messages √N release messages Drawbacks of Maekawa’s Algorithm: This algorithm is deadlock prone because a site is exclusively locked by other sites and requests are not prioritized by their timestamp. Performance: Synchronization delay is equal to twice the message propagation delay time It requires 3√n messages per critical section execution. Distributed System 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": 490, "s": 54, "text": "Prerequisite – Mutual exclusion in distributed systemsMaekawa’s Algorithm is quorum based approach to ensure mutual exclusion in distributed systems. As we know, In permission based algorithms like Lamport’s Algorithm, Ricart-Agrawala Algorithm etc. a site request permission from every other site but in quorum based approach, A site does not request permission from every other site but from a subset of sites which is called quorum." }, { "code": null, "e": 509, "s": 490, "text": "In this algorithm:" }, { "code": null, "e": 572, "s": 509, "text": "Three type of messages ( REQUEST, REPLY and RELEASE) are used." }, { "code": null, "e": 700, "s": 572, "text": "A site send a REQUEST message to all other site in its request set or quorum to get their permission to enter critical section." }, { "code": null, "e": 801, "s": 700, "text": "A site send a REPLY message to requesting site to give its permission to enter the critical section." }, { "code": null, "e": 913, "s": 801, "text": "A site send a RELEASE message to all other site in its request set or quorum upon exiting the critical section." }, { "code": null, "e": 1041, "s": 913, "text": "The construction of request set or Quorum:A request set or Quorum in Maekawa’s algorithm must satisfy the following properties:" }, { "code": null, "e": 1293, "s": 1041, "text": "∀i ∀j : i ≠ j, 1 ≤ i, j ≤ N :: Ri ⋂ Rj ≠ ∅ i.e there is at least one common site between the request sets of any two sites.∀i : 1 ≤ i ≤ N :: Si ∊ Ri ∀i : 1 ≤ i ≤ N :: |Ri| = K Any site Si is contained in exactly K sets.N = K(K - 1) +1 and |Ri| = √N " }, { "code": null, "e": 1419, "s": 1293, "text": "∀i ∀j : i ≠ j, 1 ≤ i, j ≤ N :: Ri ⋂ Rj ≠ ∅ i.e there is at least one common site between the request sets of any two sites." }, { "code": null, "e": 1465, "s": 1419, "text": "∀i ∀j : i ≠ j, 1 ≤ i, j ≤ N :: Ri ⋂ Rj ≠ ∅ " }, { "code": null, "e": 1546, "s": 1465, "text": "i.e there is at least one common site between the request sets of any two sites." }, { "code": null, "e": 1573, "s": 1546, "text": "∀i : 1 ≤ i ≤ N :: Si ∊ Ri " }, { "code": null, "e": 1600, "s": 1573, "text": "∀i : 1 ≤ i ≤ N :: Si ∊ Ri " }, { "code": null, "e": 1628, "s": 1600, "text": "∀i : 1 ≤ i ≤ N :: |Ri| = K " }, { "code": null, "e": 1656, "s": 1628, "text": "∀i : 1 ≤ i ≤ N :: |Ri| = K " }, { "code": null, "e": 1700, "s": 1656, "text": "Any site Si is contained in exactly K sets." }, { "code": null, "e": 1731, "s": 1700, "text": "N = K(K - 1) +1 and |Ri| = √N " }, { "code": null, "e": 1762, "s": 1731, "text": "N = K(K - 1) +1 and |Ri| = √N " }, { "code": null, "e": 1773, "s": 1762, "text": "Algorithm:" }, { "code": null, "e": 2174, "s": 1773, "text": "To enter Critical section:When a site Si wants to enter the critical section, it sends a request message REQUEST(i) to all other sites in the request set Ri.When a site Sj receives the request message REQUEST(i) from site Si, it returns a REPLY message to site Si if it has not sent a REPLY message to the site from the time it received the last RELEASE message. Otherwise, it queues up the request.." }, { "code": null, "e": 2306, "s": 2174, "text": "When a site Si wants to enter the critical section, it sends a request message REQUEST(i) to all other sites in the request set Ri." }, { "code": null, "e": 2549, "s": 2306, "text": "When a site Sj receives the request message REQUEST(i) from site Si, it returns a REPLY message to site Si if it has not sent a REPLY message to the site from the time it received the last RELEASE message. Otherwise, it queues up the request." }, { "code": null, "e": 2551, "s": 2549, "text": "." }, { "code": null, "e": 2697, "s": 2551, "text": "To execute the critical section:A site Si can enter the critical section if it has received the REPLY message from all the site in request set Ri" }, { "code": null, "e": 2811, "s": 2697, "text": "A site Si can enter the critical section if it has received the REPLY message from all the site in request set Ri" }, { "code": null, "e": 3251, "s": 2811, "text": "To release the critical section:When a site Si exits the critical section, it sends RELEASE(i) message to all other sites in request set RiWhen a site Sj receives the RELEASE(i) message from site Si, it send REPLY message to the next site waiting in the queue and deletes that entry from the queueIn case queue is empty, site Sj update its status to show that it has not sent any REPLY message since the receipt of the last RELEASE message" }, { "code": null, "e": 3359, "s": 3251, "text": "When a site Si exits the critical section, it sends RELEASE(i) message to all other sites in request set Ri" }, { "code": null, "e": 3518, "s": 3359, "text": "When a site Sj receives the RELEASE(i) message from site Si, it send REPLY message to the next site waiting in the queue and deletes that entry from the queue" }, { "code": null, "e": 3661, "s": 3518, "text": "In case queue is empty, site Sj update its status to show that it has not sent any REPLY message since the receipt of the last RELEASE message" }, { "code": null, "e": 3832, "s": 3661, "text": "Message Complexity:Maekawa’s Algorithm requires invocation of 3√N messages per critical section execution as the size of a request set is √N. These 3√N messages involves." }, { "code": null, "e": 3852, "s": 3832, "text": "√N request messages" }, { "code": null, "e": 3870, "s": 3852, "text": "√N reply messages" }, { "code": null, "e": 3890, "s": 3870, "text": "√N release messages" }, { "code": null, "e": 3924, "s": 3890, "text": "Drawbacks of Maekawa’s Algorithm:" }, { "code": null, "e": 4062, "s": 3924, "text": "This algorithm is deadlock prone because a site is exclusively locked by other sites and requests are not prioritized by their timestamp." }, { "code": null, "e": 4075, "s": 4062, "text": "Performance:" }, { "code": null, "e": 4150, "s": 4075, "text": "Synchronization delay is equal to twice the message propagation delay time" }, { "code": null, "e": 4207, "s": 4150, "text": "It requires 3√n messages per critical section execution." }, { "code": null, "e": 4226, "s": 4207, "text": "Distributed System" }, { "code": null, "e": 4244, "s": 4226, "text": "Operating Systems" }, { "code": null, "e": 4262, "s": 4244, "text": "Operating Systems" } ]
Stack.ToArray() Method in C#
04 Feb, 2019 This method(comes under System.Collections namespace) is used to copy a Stack to a new array. The elements are copied onto the array in last-in-first-out (LIFO) order, similar to the order of the elements returned by a succession of calls to Pop. This method is an O(n) operation, where n is Count. Syntax: public virtual object[] ToArray (); Return Type: This method returns a new array of type System.Object containing copies of the elements of the Stack. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to illustrate the// Stack.ToArray() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // Converting the Stack into array Object[] arr = myStack.ToArray(); // Displaying the elements in array foreach(Object str in arr) { Console.WriteLine(str); } }} GeeksforGeeks Data Structures Noida Geeks Classes Geeks Example 2: // C# code to illustrate the// Stack.ToArray() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // Converting the Stack into array Object[] arr = myStack.ToArray(); // Displaying the elements in array foreach(Object i in arr) { Console.WriteLine(i); } }} 6 5 4 3 2 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.toarray?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# C# Dictionary with examples C# | How to check whether a List contains a specified element C# | Arrays of Strings Introduction to .NET Framework C# | IsNullOrEmpty() Method String.Split() Method in C# with Examples C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Delegates
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Feb, 2019" }, { "code": null, "e": 327, "s": 28, "text": "This method(comes under System.Collections namespace) is used to copy a Stack to a new array. The elements are copied onto the array in last-in-first-out (LIFO) order, similar to the order of the elements returned by a succession of calls to Pop. This method is an O(n) operation, where n is Count." }, { "code": null, "e": 335, "s": 327, "text": "Syntax:" }, { "code": null, "e": 372, "s": 335, "text": "public virtual object[] ToArray ();\n" }, { "code": null, "e": 487, "s": 372, "text": "Return Type: This method returns a new array of type System.Object containing copies of the elements of the Stack." }, { "code": null, "e": 567, "s": 487, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 578, "s": 567, "text": "Example 1:" }, { "code": "// C# code to illustrate the// Stack.ToArray() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); // Converting the Stack into array Object[] arr = myStack.ToArray(); // Displaying the elements in array foreach(Object str in arr) { Console.WriteLine(str); } }}", "e": 1251, "s": 578, "text": null }, { "code": null, "e": 1308, "s": 1251, "text": "GeeksforGeeks\nData Structures\nNoida\nGeeks Classes\nGeeks\n" }, { "code": null, "e": 1319, "s": 1308, "text": "Example 2:" }, { "code": "// C# code to illustrate the// Stack.ToArray() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // Converting the Stack into array Object[] arr = myStack.ToArray(); // Displaying the elements in array foreach(Object i in arr) { Console.WriteLine(i); } }}", "e": 1932, "s": 1319, "text": null }, { "code": null, "e": 1943, "s": 1932, "text": "6\n5\n4\n3\n2\n" }, { "code": null, "e": 1954, "s": 1943, "text": "Reference:" }, { "code": null, "e": 2055, "s": 1954, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.toarray?view=netframework-4.7.2" }, { "code": null, "e": 2084, "s": 2055, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 2109, "s": 2084, "text": "CSharp-Collections-Stack" }, { "code": null, "e": 2123, "s": 2109, "text": "CSharp-method" }, { "code": null, "e": 2126, "s": 2123, "text": "C#" }, { "code": null, "e": 2224, "s": 2126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2278, "s": 2224, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 2306, "s": 2278, "text": "C# Dictionary with examples" }, { "code": null, "e": 2368, "s": 2306, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 2391, "s": 2368, "text": "C# | Arrays of Strings" }, { "code": null, "e": 2422, "s": 2391, "text": "Introduction to .NET Framework" }, { "code": null, "e": 2450, "s": 2422, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 2492, "s": 2450, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 2535, "s": 2492, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2584, "s": 2535, "text": "Differences Between .NET Core and .NET Framework" } ]
Serialize and Deserialize a Binary Tree | Practice | GeeksforGeeks
Serialization is to store a tree in an array so that it can be later restored and Deserialization is reading tree back from the array. Now your task is to complete the function serialize which stores the tree into an array A[ ] and deSerialize which deserializes the array to the tree and returns it. Note: The structure of the tree must be maintained. Multiple nodes can have the same data. Example 1: Input: 1 / \ 2 3 Output: 2 1 3 Example 2: Input: 10 / \ 20 30 / \ 40 60 Output: 40 20 60 10 30 Your Task: The task is to complete two function serialize which takes the root node of the tree as input and stores the tree into an array and deSerialize which deserializes the array to the original tree and returns the root of it. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= Number of nodes <= 1000 1 <= Data of a node <= 1000 Note: The Input/Ouput format and Example given above are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console, and should not print anything on stdout/console. The task is to complete the function specified, and not to write the full code. +1 amishasahu3283 weeks ago class Solution { public: //Function to serialize a tree and return a list containing nodes of tree. vector<int> ans; vector<int> serialize(Node *root) { //Your code here if(root == NULL) { ans.push_back(-1); return ans; } ans.push_back(root->data); serialize(root->left); serialize(root->right); return ans; } //Function to deserialize a list and construct the tree. int i = 0;; Node * deSerialize(vector<int> &A) { //Your code here if(i == A.size()) return NULL; int val = A[i]; i++; if(val == -1) return NULL; Node *root = new Node(val); root->left = deSerialize(A); root->right = deSerialize(A); return root; } }; 0 abiradb981 month ago C++ Solution(0.0s) class Solution { public: //Function to serialize a tree and return a list containing nodes of tree. vector<int> serialize(Node *root) { //Your code here vector<int> res; queue<Node*> q; q.push(root); while (!q.empty()) { Node* curr = q.front(); q.pop(); if (!curr) { res.push_back(-1); } else { res.push_back(curr->data); q.push(curr->left); q.push(curr->right); } } return res; } //Function to deserialize a list and construct the tree. Node * deSerialize(vector<int> &A) { //Your code here Node* root = new Node(A[0]); queue<Node*> q; q.push(root); int index = 1; while (!q.empty()) { Node* curr = q.front(); q.pop(); int newN = A[index++]; if (newN == -1) { curr->left = NULL; } else { curr->left = new Node(newN); q.push(curr->left); } newN = A[index++]; if (newN == -1) { curr->right = NULL; } else { curr->right = new Node(newN); q.push(curr->right); } } return root; } }; 0 adityagagtiwari1 month ago Hi! Can anyone help me in getting rid of the static variable t in the following code. Even though this code works fine i want to know if there is any way to remove the static variable without harming the functionality of the code class Tree { //Function to serialize a tree and return a list containing nodes of tree.public void serialize(Node root, ArrayList<Integer> A) { //code here if(root==null) return; Stack<Node> stk = new Stack<>(); stk.push(root); while(stk.size()>0) { Node removed = stk.pop(); if(removed==null) { A.add(-1); } else { A.add(removed.data); stk.push(removed.right); stk.push(removed.left); } } System.out.println(A); }//Function to deserialize a list and construct the tree.static int t ; public Node deSerialize(ArrayList<Integer> A) { //code here //int t=0; t=0; Node root = newDeserial(A); return root; } public Node newDeserial(ArrayList<Integer> A) { if(A.get(t)==-1) return null; Node root = new Node(A.get(t)); t++; root.left = newDeserial(A); t++; root.right = newDeserial(A); return root; } }; +1 codecrackerp2 months ago vector<int> serialize(Node *root) { vector<int>a; if (root==NULL){ a.push_back(0); return a; } queue<Node*>q; q.push(root); while(!q.empty()){ Node*frnt=q.front(); q.pop(); if(frnt==NULL){ a.push_back(0); } else{ a.push_back(frnt->data); q.push(frnt->left); q.push(frnt->right); } } return a; } //Function to deserialize a list and construct the tree. Node*Create_Node(int Data){ if(Data==0)return NULL; Node*newnode=new Node(Data); return newnode; } Node * deSerialize(vector<int> &A) { int i=0; if(A[i]==0){ return NULL; } Node*root=Create_Node(A[i++]); queue<Node*>q; q.push(root); while(!q.empty()){ Node*frnt=q.front(); q.pop(); frnt->left=Create_Node(A[i++]); frnt->right=Create_Node(A[i++]); if(frnt->left!=NULL)q.push(frnt->left); if(frnt->right!=NULL)q.push(frnt->right); } return root; } +2 arvindchoudhary62902 months ago class Solution { public: //Function to serialize a tree and return a list containing nodes of tree. vector<int> serialize(Node *root) { vector<int> nodes; if(root == NULL) return nodes; queue<Node*> q; q.push(root); while(!q.empty()) { Node* currentnode = q.front(); q.pop(); if(currentnode == NULL) { nodes.push_back(-1); } else { nodes.push_back(currentnode->data); } if(currentnode!=NULL) { q.push(currentnode->left); q.push(currentnode->right); } } return nodes; } Node * deSerialize(vector<int> &A) { if(A.size() == 0) return NULL; int i=0; Node* root = new Node(A[i]); i++; queue<Node*> q; q.push(root); while(!q.empty()) { Node* node = q.front(); q.pop(); if(A[i] == -1) { node->left = NULL; i++; } else { Node* leftnode = new Node(A[i]); node->left = leftnode; q.push(leftnode); i++; } if(A[i] == -1) { node->right = NULL; i++; } else { Node* rightnode = new Node(A[i]); node->right = rightnode; q.push(rightnode); i++; } } return root; } }; +2 vishnu12653 months ago Java Solution: class Tree { //Function to serialize a tree and return a list containing nodes of tree. public void serialize(Node root, ArrayList<Integer> A) { if(root==null){ A.add(-1); return ; } A.add(root.data); serialize(root.left,A); serialize(root.right,A); } //Function to deserialize a list and construct the tree. public Node deSerialize(ArrayList<Integer> A) { if(A.get(0)==-1){ A.remove(0); return null; } Node root = new Node(A.remove(0)); root.left = deSerialize(A); root.right = deSerialize(A); return root; } } +4 abhixhek053 months ago /* Using preorder traversal to store data in vector and storing -1 when there is NULL /* class Solution { public: void func1(Node* root,vector<int> &ans){ if(root==NULL){ans.push_back(-1); return;} ans.push_back(root->data); func1(root->left, ans); func1(root->right, ans); } //Function to serialize a tree and return a list containing nodes of tree. vector<int> serialize(Node *root) { //Your code here vector<int> ans; func1(root, ans); return ans; } //Function to deserialize a list and construct the tree. int i=0; Node * deSerialize(vector<int> &A) { //Your code here if(i==A.size()) return NULL; int val = A[i]; i++; if(val==-1) return NULL; Node* root = new Node(val); root->left = deSerialize(A); root->right = deSerialize(A); return root; } }; +1 kalamarham3 months ago class Solution{ public: //Function to serialize a tree and return a list containing nodes of tree. vector<int> serialize(Node *root) { //Your code here vector<int> v; if(root==NULL) { v.push_back(-1); return v; } serialize(root->left); cout<<root->data<<" "; serialize(root->right); } //Function to deserialize a list and construct the tree. int i=0; Node * deSerialize(vector<int> &A) { //Your code here if(A.size()==0) return NULL; if(A[i]==-1) { i++; return NULL; } Node* root=new Node(A[i++]); root->left=deSerialize(A); root->right=deSerialize(A); return root; } }; 0 palakparihar1443 months ago class Tree { //Function to serialize a tree and return a list containing nodes of tree.public void serialize(Node root, ArrayList<Integer> A) { //code if(root == null){ return; } serialize(root.left, A); A.add(root.data); serialize(root.right, A);}//Function to deserialize a list and construct the tree.class Index { int index;}public Node solve(ArrayList<Integer> A, int low, int high, Index index){ if(index.index >= A.size() || low > high){ Node root ; return root = null; } //storing value of root Node root = new Node(A.get(index.index)); index.index+=1; // check if there exist any subtree further if(low == high){ return root; } // find the next greater element to the right of root int i; for(i=low; i>=high; i++){ if(A.get(i) > root.data){ //found the start of right sub tree break; } } //constructing the left subtree root.left = solve(A, index.index, i-1, index); root.right = solve(A,i,high, index); return root;} public Node deSerialize(ArrayList<Integer> A) { //code here // System.out.println(A); Index index = new Index(); index.index = 0; return solve(A, 0, A.size()-1,index); }}; -1 mulayam6614 months ago class Solution { public: void helper2(Node *root,vector<int>&a) { if(root==NULL) { a.push_back(int(NULL)); return; } a.push_back(root->data); helper2(root->left,a); helper2(root->right,a); return ; } //Function to serialize a tree and return a list containing nodes of tree. vector<int> serialize(Node *root) { vector<int>a; helper2(root,a); return a; } //Function to deserialize a list and construct the tree. int idx=0; Node * deSerialize(vector<int> &a) { if((a.size()-1)<idx||a[idx]==NULL) { idx++; return NULL; } Node*root=new Node(a[idx++]); root->left=deSerialize(a); root->right=deSerialize(a); return root; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 630, "s": 238, "text": "Serialization is to store a tree in an array so that it can be later restored and Deserialization is reading tree back from the array. Now your task is to complete the function serialize which stores the tree into an array A[ ] and deSerialize which deserializes the array to the tree and returns it.\nNote: The structure of the tree must be maintained. Multiple nodes can have the same data." }, { "code": null, "e": 641, "s": 630, "text": "Example 1:" }, { "code": null, "e": 692, "s": 641, "text": "Input:\n 1\n / \\\n 2 3\nOutput: 2 1 3\n" }, { "code": null, "e": 703, "s": 692, "text": "Example 2:" }, { "code": null, "e": 795, "s": 703, "text": "Input:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput: 40 20 60 10 30\n" }, { "code": null, "e": 1028, "s": 795, "text": "Your Task:\nThe task is to complete two function serialize which takes the root node of the tree as input and stores the tree into an array and deSerialize which deserializes the array to the original tree and returns the root of it." }, { "code": null, "e": 1092, "s": 1028, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1162, "s": 1092, "text": "Constraints:\n1 <= Number of nodes <= 1000\n1 <= Data of a node <= 1000" }, { "code": null, "e": 1530, "s": 1162, "text": "\nNote: The Input/Ouput format and Example given above are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console, and should not print anything on stdout/console. The task is to complete the function specified, and not to write the full code.\n " }, { "code": null, "e": 1533, "s": 1530, "text": "+1" }, { "code": null, "e": 1558, "s": 1533, "text": "amishasahu3283 weeks ago" }, { "code": null, "e": 2403, "s": 1558, "text": "class Solution\n{\n public:\n //Function to serialize a tree and return a list containing nodes of tree.\n vector<int> ans;\n vector<int> serialize(Node *root) \n {\n //Your code here\n if(root == NULL)\n {\n ans.push_back(-1);\n return ans;\n }\n \n ans.push_back(root->data);\n serialize(root->left);\n serialize(root->right);\n \n return ans;\n }\n \n //Function to deserialize a list and construct the tree.\n int i = 0;;\n Node * deSerialize(vector<int> &A)\n {\n //Your code here\n if(i == A.size()) return NULL;\n int val = A[i];\n i++;\n if(val == -1) return NULL;\n \n Node *root = new Node(val);\n root->left = deSerialize(A);\n root->right = deSerialize(A);\n return root;\n }\n\n};" }, { "code": null, "e": 2405, "s": 2403, "text": "0" }, { "code": null, "e": 2426, "s": 2405, "text": "abiradb981 month ago" }, { "code": null, "e": 2445, "s": 2426, "text": "C++ Solution(0.0s)" }, { "code": null, "e": 3911, "s": 2445, "text": "class Solution\n{\n public:\n //Function to serialize a tree and return a list containing nodes of tree.\n vector<int> serialize(Node *root) \n {\n //Your code here\n vector<int> res;\n queue<Node*> q;\n q.push(root);\n \n while (!q.empty()) {\n Node* curr = q.front();\n q.pop();\n \n if (!curr) {\n res.push_back(-1);\n }\n else {\n res.push_back(curr->data); \n q.push(curr->left);\n q.push(curr->right);\n }\n }\n \n return res; \n }\n \n \n //Function to deserialize a list and construct the tree.\n Node * deSerialize(vector<int> &A)\n {\n //Your code here\n Node* root = new Node(A[0]);\n queue<Node*> q;\n q.push(root);\n int index = 1;\n \n while (!q.empty()) {\n Node* curr = q.front();\n q.pop();\n \n int newN = A[index++];\n if (newN == -1) {\n curr->left = NULL;\n }\n else {\n curr->left = new Node(newN);\n q.push(curr->left);\n }\n \n newN = A[index++];\n if (newN == -1) {\n curr->right = NULL;\n }\n else {\n curr->right = new Node(newN);\n q.push(curr->right);\n }\n }\n return root;\n }\n\n};" }, { "code": null, "e": 3913, "s": 3911, "text": "0" }, { "code": null, "e": 3940, "s": 3913, "text": "adityagagtiwari1 month ago" }, { "code": null, "e": 4026, "s": 3940, "text": "Hi! Can anyone help me in getting rid of the static variable t in the following code." }, { "code": null, "e": 4170, "s": 4026, "text": "Even though this code works fine i want to know if there is any way to remove the static variable without harming the functionality of the code" }, { "code": null, "e": 5185, "s": 4170, "text": "class Tree { //Function to serialize a tree and return a list containing nodes of tree.public void serialize(Node root, ArrayList<Integer> A) { //code here if(root==null) return; Stack<Node> stk = new Stack<>(); stk.push(root); while(stk.size()>0) { Node removed = stk.pop(); if(removed==null) { A.add(-1); } else { A.add(removed.data); stk.push(removed.right); stk.push(removed.left); } } System.out.println(A); }//Function to deserialize a list and construct the tree.static int t ; public Node deSerialize(ArrayList<Integer> A) { //code here //int t=0; t=0; Node root = newDeserial(A); return root; } public Node newDeserial(ArrayList<Integer> A) { if(A.get(t)==-1) return null; Node root = new Node(A.get(t)); t++; root.left = newDeserial(A); t++; root.right = newDeserial(A); return root; } };" }, { "code": null, "e": 5188, "s": 5185, "text": "+1" }, { "code": null, "e": 5213, "s": 5188, "text": "codecrackerp2 months ago" }, { "code": null, "e": 6427, "s": 5213, "text": "vector<int> serialize(Node *root) \n { \n vector<int>a;\n if (root==NULL){\n a.push_back(0);\n return a;\n }\n queue<Node*>q;\n q.push(root);\n while(!q.empty()){\n Node*frnt=q.front();\n q.pop();\n if(frnt==NULL){\n a.push_back(0);\n }\n else{\n a.push_back(frnt->data);\n q.push(frnt->left);\n q.push(frnt->right);\n }\n }\n return a;\n }\n \n //Function to deserialize a list and construct the tree.\n Node*Create_Node(int Data){\n if(Data==0)return NULL;\n Node*newnode=new Node(Data);\n return newnode;\n }\n Node * deSerialize(vector<int> &A)\n { \n int i=0;\n if(A[i]==0){\n return NULL;\n }\n Node*root=Create_Node(A[i++]);\n queue<Node*>q;\n q.push(root);\n while(!q.empty()){\n Node*frnt=q.front();\n q.pop();\n frnt->left=Create_Node(A[i++]);\n frnt->right=Create_Node(A[i++]);\n if(frnt->left!=NULL)q.push(frnt->left);\n if(frnt->right!=NULL)q.push(frnt->right);\n }\n return root;\n }" }, { "code": null, "e": 6430, "s": 6427, "text": "+2" }, { "code": null, "e": 6462, "s": 6430, "text": "arvindchoudhary62902 months ago" }, { "code": null, "e": 8237, "s": 6462, "text": "class Solution\n{\n public:\n \n \n //Function to serialize a tree and return a list containing nodes of tree.\n vector<int> serialize(Node *root) \n {\n vector<int> nodes;\n if(root == NULL) return nodes;\n \n queue<Node*> q;\n q.push(root);\n while(!q.empty())\n {\n Node* currentnode = q.front();\n q.pop();\n \n if(currentnode == NULL)\n {\n nodes.push_back(-1);\n }\n else\n {\n nodes.push_back(currentnode->data);\n }\n if(currentnode!=NULL)\n {\n q.push(currentnode->left);\n q.push(currentnode->right);\n }\n }\n return nodes;\n \n }\n \n \n Node * deSerialize(vector<int> &A)\n {\n if(A.size() == 0) return NULL;\n \n int i=0;\n Node* root = new Node(A[i]);\n i++;\n queue<Node*> q;\n q.push(root);\n \n while(!q.empty())\n {\n Node* node = q.front();\n q.pop();\n \n if(A[i] == -1)\n {\n node->left = NULL;\n i++;\n }\n else\n {\n Node* leftnode = new Node(A[i]);\n node->left = leftnode;\n q.push(leftnode);\n i++;\n }\n if(A[i] == -1)\n {\n node->right = NULL;\n i++;\n }\n else\n {\n Node* rightnode = new Node(A[i]);\n node->right = rightnode;\n q.push(rightnode);\n i++;\n }\n }\n return root;\n \n \n \n \n \n \n }\n\n};" }, { "code": null, "e": 8240, "s": 8237, "text": "+2" }, { "code": null, "e": 8263, "s": 8240, "text": "vishnu12653 months ago" }, { "code": null, "e": 8278, "s": 8263, "text": "Java Solution:" }, { "code": null, "e": 8962, "s": 8278, "text": "class Tree \n{\n //Function to serialize a tree and return a list containing nodes of tree.\n\tpublic void serialize(Node root, ArrayList<Integer> A) \n\t{\n\t if(root==null){\n\t A.add(-1);\n\t return ;\n\t }\n\t A.add(root.data);\n\t serialize(root.left,A);\n\t serialize(root.right,A);\n\t \n\t}\n\t\n\t//Function to deserialize a list and construct the tree.\n public Node deSerialize(ArrayList<Integer> A)\n {\n if(A.get(0)==-1){\n A.remove(0);\n return null;\n }\n Node root = new Node(A.remove(0));\n root.left = deSerialize(A);\n root.right = deSerialize(A);\n return root;\n \n \n \n }\n}" }, { "code": null, "e": 8965, "s": 8962, "text": "+4" }, { "code": null, "e": 8988, "s": 8965, "text": "abhixhek053 months ago" }, { "code": null, "e": 9944, "s": 8988, "text": "/* Using preorder traversal to store data in vector and storing -1 when there is NULL /*\n\n\nclass Solution\n{\n public:\n \n void func1(Node* root,vector<int> &ans){\n if(root==NULL){ans.push_back(-1); return;}\n ans.push_back(root->data);\n func1(root->left, ans);\n func1(root->right, ans);\n \n }\n //Function to serialize a tree and return a list containing nodes of tree.\n vector<int> serialize(Node *root) \n {\n //Your code here\n vector<int> ans;\n func1(root, ans);\n return ans;\n }\n \n //Function to deserialize a list and construct the tree.\n int i=0;\n Node * deSerialize(vector<int> &A)\n {\n //Your code here\n if(i==A.size()) return NULL;\n int val = A[i];\n i++;\n if(val==-1) return NULL;\n Node* root = new Node(val);\n \n root->left = deSerialize(A);\n root->right = deSerialize(A);\n return root;\n \n }\n\n};\n" }, { "code": null, "e": 9947, "s": 9944, "text": "+1" }, { "code": null, "e": 9970, "s": 9947, "text": "kalamarham3 months ago" }, { "code": null, "e": 10694, "s": 9970, "text": "class Solution{ public: //Function to serialize a tree and return a list containing nodes of tree. vector<int> serialize(Node *root) { //Your code here vector<int> v; if(root==NULL) { v.push_back(-1); return v; } serialize(root->left); cout<<root->data<<\" \"; serialize(root->right); } //Function to deserialize a list and construct the tree. int i=0; Node * deSerialize(vector<int> &A) { //Your code here if(A.size()==0) return NULL; if(A[i]==-1) { i++; return NULL; } Node* root=new Node(A[i++]); root->left=deSerialize(A); root->right=deSerialize(A); return root; }" }, { "code": null, "e": 10698, "s": 10694, "text": "}; " }, { "code": null, "e": 10700, "s": 10698, "text": "0" }, { "code": null, "e": 10728, "s": 10700, "text": "palakparihar1443 months ago" }, { "code": null, "e": 12003, "s": 10728, "text": "class Tree { //Function to serialize a tree and return a list containing nodes of tree.public void serialize(Node root, ArrayList<Integer> A) { //code if(root == null){ return; } serialize(root.left, A); A.add(root.data); serialize(root.right, A);}//Function to deserialize a list and construct the tree.class Index { int index;}public Node solve(ArrayList<Integer> A, int low, int high, Index index){ if(index.index >= A.size() || low > high){ Node root ; return root = null; } //storing value of root Node root = new Node(A.get(index.index)); index.index+=1; // check if there exist any subtree further if(low == high){ return root; } // find the next greater element to the right of root int i; for(i=low; i>=high; i++){ if(A.get(i) > root.data){ //found the start of right sub tree break; } } //constructing the left subtree root.left = solve(A, index.index, i-1, index); root.right = solve(A,i,high, index); return root;} public Node deSerialize(ArrayList<Integer> A) { //code here // System.out.println(A); Index index = new Index(); index.index = 0; return solve(A, 0, A.size()-1,index); }};" }, { "code": null, "e": 12006, "s": 12003, "text": "-1" }, { "code": null, "e": 12029, "s": 12006, "text": "mulayam6614 months ago" }, { "code": null, "e": 12896, "s": 12029, "text": "class Solution\n{\n public:\n void helper2(Node *root,vector<int>&a) \n {\n if(root==NULL)\n {\n a.push_back(int(NULL));\n return;\n }\n a.push_back(root->data);\n helper2(root->left,a);\n helper2(root->right,a);\n return ;\n \n }\n //Function to serialize a tree and return a list containing nodes of tree.\n vector<int> serialize(Node *root) \n {\n vector<int>a;\n helper2(root,a);\n return a;\n }\n \n //Function to deserialize a list and construct the tree.\n int idx=0;\n Node * deSerialize(vector<int> &a)\n {\n if((a.size()-1)<idx||a[idx]==NULL)\n {\n idx++;\n return NULL;\n }\n Node*root=new Node(a[idx++]);\n root->left=deSerialize(a);\n root->right=deSerialize(a);\n return root;\n }\n\n};\n" }, { "code": null, "e": 13042, "s": 12896, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 13078, "s": 13042, "text": " Login to access your submissions. " }, { "code": null, "e": 13088, "s": 13078, "text": "\nProblem\n" }, { "code": null, "e": 13098, "s": 13088, "text": "\nContest\n" }, { "code": null, "e": 13161, "s": 13098, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 13309, "s": 13161, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 13517, "s": 13309, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 13623, "s": 13517, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
AVL Tree Deletion | Practice | GeeksforGeeks
Given a AVL tree and N values to be deleted from the tree. Write a function to delete a given value from the tree. Example 1: Tree = 4 / \ 2 6 / \ / \ 1 3 5 7 N = 4 Values to be deleted = {4,1,3,6} Input: Value to be deleted = 4 Output: 5 / \ 2 6 / \ \ 1 3 7 Input: Value to be deleted = 1 Output: 5 / \ 2 6 \ \ 3 7 Input: Value to be deleted = 3 Output: 5 / \ 2 6 \ 7 Input: Value to be deleted = 6 Output: 5 / \ 2 7 Your Task: You dont need to read input or print anything. Complete the function delelteNode() which takes the root of the tree and the value of the node to be deleted as input parameters and returns the root of the modified tree. Note: The tree will be checked after each deletion. If it violates the properties of balanced BST, an error message will be printed followed by the inorder traversal of the tree at that moment. If instead all deletion are successful, inorder traversal of tree will be printed. If every single node is deleted from tree, 'null' will be printed. Expected Time Complexity: O(height of tree) Expected Auxiliary Space: O(height of tree) Constraints: 1 ≤ N ≤ 500 0 chhitizgoyal2 weeks ago Java Solution. class Sol{ Node root; static int height(Node N) { if (N == null) return 0; return N.height; } static int max(int a, int b) { return (a > b) ? a : b; } static Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; return x; } static Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; y.left = x; x.right = T2; x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; } static int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } static Node minValueNode(Node node) { Node current = node; while (current.left != null) current = current.left; return current; } public static Node deleteNode(Node root, int key) { if (root == null) return root; if (key < root.data) root.left = deleteNode(root.left, key); else if (key > root.data) root.right = deleteNode(root.right, key); else { if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; if (temp == null) { temp = root; root = null; } else root = temp; } else { Node temp = minValueNode(root.right); root.data = temp.data; root.right = deleteNode(root.right, temp.data); } } if (root == null) return root; root.height = max(height(root.left), height(root.right)) + 1; int balance = getBalance(root); if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; }} +1 vinitkumawat1122 months ago Easy C++ solution int NodeHeight(Node* p) { int hl=0, hr=0; hl = p&&p->left?p->left->height:0; hr = p&&p->right?p->right->height:0; return (hl>hr?hl+1:hr+1); } int BalanceFactor(Node* p) { // hl-hr int hl=0, hr=0; hl = p&&p->left?p->left->height:0; hr = p&&p->right?p->right->height:0; return (hl-hr); } Node* LLRotate(Node* p) { Node* pl = p->left; Node* plr = pl->right; pl->right = p; p->left = plr; p->height = NodeHeight(p); pl->height = NodeHeight(pl); return pl; } Node* LRRotate(Node* p) { Node* pl = p->left; Node* plr = pl->right; pl->right = plr->left; p->left = plr->right; plr->left = pl; plr->right = p; p->height = NodeHeight(p); pl->height = NodeHeight(pl); plr->height = NodeHeight(plr); return plr; } Node* RRRotate(Node* p) { Node* pr = p->right; Node* prl = pr->left; pr->left = p; p->right = prl; p->height = NodeHeight(p); pr->height = NodeHeight(pr); return pr; } Node* RLRotate(Node* p) { Node* pr = p->right; Node* prl = pr->left; p->right = prl->left; pr->left = prl->right; prl->left = p; prl->right = pr; p->height = NodeHeight(p); pr->height = NodeHeight(pr); prl->height = NodeHeight(prl); return prl; } Node* InSuccessor(Node* p) { while(p && p->left) { p=p->left; } return p; } Node* InPredecessor(Node* p) { while(p && p->right) p=p->right; return p; } Node* deleteNode(Node* root, int data) { if(root==NULL) return NULL; if(root->left==NULL && root->right==NULL) { if(data==root->data) { free(root); return NULL; } } if(data<root->data) root->left = deleteNode(root->left,data); else if(data>root->data) root->right = deleteNode(root->right,data); else { if(root->right!=NULL) { // successor Node* q = InSuccessor(root->right); root->data = q->data; root->right = deleteNode(root->right, q->data); } else { // Predecessor Node* q = InPredecessor(root->left); root->data = q->data; root->left = deleteNode(root->left,q->data); } } root->height = NodeHeight(root); if(BalanceFactor(root)==2 && BalanceFactor(root->left)==1) return LLRotate(root); else if(BalanceFactor(root)==2&&BalanceFactor(root->left)==-1) return LRRotate(root); else if(BalanceFactor(root)==2&&BalanceFactor(root->left)==0) return LLRotate(root); else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==1) return RLRotate(root); else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==-1) return RRRotate(root); else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==0) return RRRotate(root); return root; } 0 arjun62613 months ago can any one help me why it show run time error int max(int a, int b){ if(a>b){ return a; } return b;} int height(Node *root) { if (root == NULL) { return 0; } return max(height(root->left),height(root->right))+1;} Node *rightRotate(Node *y) { Node *x = y->left; Node *T2 = x->right; x->right = y; y->left = T2; y->height = height(y); x->height =height(x); return x; } Node *leftRotate(Node *x) { Node *y = x->right; Node *T2 = y->left; y->left = x; x->right = T2; x->height = height(x); y->height = height(y); return y; } //int bf(Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } Node* insert(Node* node, int data) { if (node == NULL) return new Node(data); if (data < node->data) node->left = insert(node->left, data); else if (data > node->data) node->right = insert(node->right, data); else return node; node->height = height(node); int b = bf(node); if (b> 1 && data < node->left->data) return rightRotate(node); if (b < -1 && data > node->right->data) return leftRotate(node); if (b > 1 && data > node->left->data) { node->left = leftRotate(node->left); return rightRotate(node); } if (b < -1 && data < node->right->data) { node->right = rightRotate(node->right); return leftRotate(node); } return node; } Node * min(Node* node) { Node* current = node; while (current->left != NULL) current = current->left; return current; } Node* deleteNode(Node* root, int data) { if (root == NULL) return root; if ( data < root->data) root->left = deleteNode(root->left, data); else if( data > root->data ) root->right = deleteNode(root->right, data); else { if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right; if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; free(temp); } else { Node* temp = min(root->right); root->data = temp->data; root->right = deleteNode(root->right, temp->data); } } if (root == NULL) return root; root->height = height(root); int b = bf(root); if (b> 1 && data < root->left->data) return rightRotate(root); if (b < -1 && data > root->right->data) return leftRotate(root); if (b > 1 && data > root->left->data) { root->left = leftRotate(root->left); return rightRotate(root); } if (b < -1 && data < root->right->data) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } int max(int a, int b){ if(a>b){ return a; } return b;} int height(Node *root) { if (root == NULL) { return 0; } return max(height(root->left),height(root->right))+1;} Node *rightRotate(Node *y) { Node *x = y->left; Node *T2 = x->right; x->right = y; y->left = T2; y->height = height(y); x->height =height(x); return x; } Node *leftRotate(Node *x) { Node *y = x->right; Node *T2 = y->left; y->left = x; x->right = T2; x->height = height(x); y->height = height(y); return y; } //int bf(Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } Node* insert(Node* node, int data) { if (node == NULL) return new Node(data); if (data < node->data) node->left = insert(node->left, data); else if (data > node->data) node->right = insert(node->right, data); else return node; node->height = height(node); int b = bf(node); if (b> 1 && data < node->left->data) return rightRotate(node); if (b < -1 && data > node->right->data) return leftRotate(node); if (b > 1 && data > node->left->data) { node->left = leftRotate(node->left); return rightRotate(node); } if (b < -1 && data < node->right->data) { node->right = rightRotate(node->right); return leftRotate(node); } return node; } Node * min(Node* node) { Node* current = node; while (current->left != NULL) current = current->left; return current; } Node* deleteNode(Node* root, int data) { if (root == NULL) return root; if ( data < root->data) root->left = deleteNode(root->left, data); else if( data > root->data ) root->right = deleteNode(root->right, data); else { if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right; if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; free(temp); } else { Node* temp = min(root->right); root->data = temp->data; root->right = deleteNode(root->right, temp->data); } } if (root == NULL) return root; root->height = height(root); int b = bf(root); if (b> 1 && data < root->left->data) return rightRotate(root); if (b < -1 && data > root->right->data) return leftRotate(root); if (b > 1 && data > root->left->data) { root->left = leftRotate(root->left); return rightRotate(root); } if (b < -1 && data < root->right->data) { root->right = rightRotate(root->right); return leftRotate(root); } return root; } 0 gyanikug20cse4 months ago Why i am getting wrong ans in this test case. int height(Node *root){ if(!root) return 0; return root->height;} Node *insucc(Node *root){ while(root->left) root=root->left; return root;} Node* rightRot(Node *r){ Node *rl=r->left; Node *rlr=rl->right; //Rotation rl->right=r; r->left=rlr; return rl;} Node* leftRot(Node *r){ Node *rr=r->right; Node *rrl=rr->left; //Rotation rr->left=r; r->right=rrl; return rr;} int getBalFac(Node *root){ if(!root) return 0; return height(root->left)-height(root->right);} Node* deleteNode(Node* root, int data){ //BST Deletion if(!root) return NULL; if(data<root->data) root->left=deleteNode(root->left,data); else if(data>root->data) root->right=deleteNode(root->right,data); else{ if(root->left==NULL||root->right==NULL) { Node *temp; if(!root->left) temp=root->right; else temp=root->left; if(temp==NULL) { temp=root; root=NULL; } else *root=*temp; free(temp); } else { Node *temp=insucc(root->right); root->data=temp->data; root->right=deleteNode(root->right,temp->data); } } if(root==NULL) return root; root->height=1+max(height(root->left),height(root->right)); int bf=getBalFac(root); if(bf==2&&getBalFac(root->left)>=0) return rightRot(root); if(bf==2&&getBalFac(root->left)==-1) { root->left=leftRot(root->left); return rightRot(root); } if(bf==-2&&getBalFac(root->right)<=0) return leftRot(root); if(bf==-2&&getBalFac(root->right)==1) { root->right=rightRot(root->right); return leftRot(root); } return root; } 0 Y0U Cha*ngE9 months ago Y0U Cha*ngE int findheight(Node *root) { if(root==NULL) return 0; return (1+ max(findheight(root->left),findheight(root->right))); } void updateheight(Node *root) { if(root==NULL) return; root->height= findheight(root); } int balancefactor(Node *root) { if(root==NULL) return 0; else return (findheight(root->left) - findheight(root->right)); } /*You are required to complete this method */ Node* LL(Node* root) { Node *l= root->left; Node*lr= l->right; l->right=root; root->left=lr; updateheight(root); updateheight(l); return l; } Node* RR(Node* root) { Node *r=root->right; Node* rl=r->left; r->left=root; root->right=rl; updateheight(root); updateheight(r); return r; } Node* LR(Node *root) { root->left=RR(root->left); return LL(root); } Node* RL(Node *root) { root->right=LL(root->right); return RR(root); } Node* deleteNode(Node* root, int data){ if(root==NULL) return root; if(root->data >data) root->left=deleteNode(root->left,data); else if(root->data <data) root-="">right=deleteNode(root->right,data); else if((root->data) == data) { if(!root->left && !root->right) root=NULL; else if(!root->left || !root->right) { Node *temp= ((root->left)?(root->left):(root->right)); root= temp; } else{ Node *temp=root->left; while(temp->right!=NULL) temp= temp->right; root->data=temp->data; root->left=deleteNode(root->left,temp->data); } } updateheight(root); int bl=balancefactor(root); if(bl>1 && balancefactor(root->left)>=0) root=LL(root); if(bl>1 && balancefactor(root->left)<0) root=LR(root); if(bl<-1 && balancefactor(root->right)<=0) root=RR(root); if(bl<-1 && balancefactor(root->right)>0) root=RL(root); return root;} Possibly your code doesn't work correctly for multiple test-cases (TCs). The first test case where your code failed: Input: 80 51 95 29 66 89 99 6 40 N 71 N 94 98126 95 80 89 98 99 66 29 51 71 40 94 Its Correct output is: null And Your Code's output is: Unbalanced BST, inorder traversal : 29 40 51 66 71... 0 Kunwar Sadanand This comment was deleted. 0 Joya2 years ago Joya Get Clue with comment when you stuck at any point +2 Pratiik Priyadarsan2 years ago Pratiik Priyadarsan Not an actual method to delete an element from an AVL tree. There will be rotations involved.But this is certainly a way to deal with the task at hand. void inorder(vector<int>&v,Node*root,const int data){ if(root){ inorder(v,root->left,data); if(root->data != data) v.push_back(root->data); inorder(v,root->right,data); }}Node* buildTree(vector<int>&v,int s,int e){ if(s>e) return NULL; int mid = (s+e)/2; Node* root = new Node(v[mid]); root->left = buildTree(v,s,mid-1); root->right = buildTree(v,mid+1,e); return root;}Node* deleteNode(Node* root, int data){//add code here, vector<int>v; inorder(v,root,data); return buildTree(v,0,v.size()-1);} 0 Kamal Meena2 years ago Kamal Meena Please Add Python compiler And Add more Que on Avl Tree or on red black tree 0 Animesh Srivastawa2 years ago Animesh Srivastawa can someone explain me what is wrong with my code ?void print(Node *root){ if(root == NULL) return; cout<<root->data<<"--->"<<root->height<<" "; print(root->left); print(root->right);}Node *inOrderSuc(Node *&parent, Node *root){ if(root == NULL) return NULL; if(root->left == NULL) return root; parent = root; return inOrderSuc(parent, root->left);}int calculateHeight(Node *root){ int l = root->left ? root->left->height : 1; int r = root->right ? root->right->height : 1; return max(l, r);}Node* deleteNode(Node* root, int data){//add code here, if(root == NULL) return NULL; if(root->data > data) root->left = deleteNode(root->left, data); else if(root->data < data) root->right = deleteNode(root->right, data); else if(root->data == data){ Node *tmp = root; if(!root->left || !root->right){ if(!root->left && !root->right){ delete(root); return NULL; } if(!root->left) root = root->right; else root = root->left; delete(tmp); } else{ Node *parent = root; Node *inOrder = inOrderSuc(parent, root->right); //Node *tmp = inOrder->right; cout<<inorder->data<<" "; if(parent == root) parent->right = inOrder->right; else parent->left = inOrder->right; inOrder->left = root->left; inOrder->right = root->right; root = inOrder; parent->height = calculateHeight(parent); root->right = deleteNode(root->right, -1); delete(tmp); } } if(root != NULL){ int l = root->left ? root->left->height : 1; int r = root->right ? root->right->height : 1; int diff = abs(l - r); if(diff > 1){ if(l > r){ // print(root); // cout<<endl; int="" l1="root-">left->left ? root->left->left->height : 1; int r1 = root->left->right ? root->left->right->height : 1; int diff2 = l1 - r1; if(diff2 < 0) root->left = leftRotate(root->left); root = rightRotate(root); } else{ int l1 = root->right->left ? root->right->left->height : 1; int r1 = root->right->right ? root->right->right->height : 1; int diff2 = l1 - r1; if(diff2 > 0) root->right = rightRotate(root->right); root = leftRotate(root); } } l = root->left ? root->left->height+1 : 1; r = root->right ? root->right->height+1: 1; root->height = max(l,r); print(root); cout<<endl; }="" return="" root;="" }="" <="" code=""> We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 353, "s": 238, "text": "Given a AVL tree and N values to be deleted from the tree. Write a function to delete a given value from the tree." }, { "code": null, "e": 890, "s": 353, "text": "Example 1:\n\nTree = \n 4\n / \\\n 2 6\n / \\ / \\ \n 1 3 5 7\n\nN = 4\nValues to be deleted = {4,1,3,6}\n\nInput: Value to be deleted = 4\nOutput:\n 5 \n / \\\n 2 6\n / \\ \\ \n 1 3 7\n\nInput: Value to be deleted = 1\nOutput:\n 5 \n / \\\n 2 6\n \\ \\ \n 3 7\n\nInput: Value to be deleted = 3\nOutput:\n 5 \n / \\\n 2 6\n \\ \n 7\n\nInput: Value to be deleted = 6\nOutput:\n 5 \n / \\\n 2 7\n\n" }, { "code": null, "e": 1122, "s": 890, "text": "Your Task: \nYou dont need to read input or print anything. Complete the function delelteNode() which takes the root of the tree and the value of the node to be deleted as input parameters and returns the root of the modified tree." }, { "code": null, "e": 1469, "s": 1122, "text": "Note: The tree will be checked after each deletion. \nIf it violates the properties of balanced BST, an error message will be printed followed by the inorder traversal of the tree at that moment.\nIf instead all deletion are successful, inorder traversal of tree will be printed.\nIf every single node is deleted from tree, 'null' will be printed.\n " }, { "code": null, "e": 1557, "s": 1469, "text": "Expected Time Complexity: O(height of tree)\nExpected Auxiliary Space: O(height of tree)" }, { "code": null, "e": 1583, "s": 1557, "text": "\nConstraints:\n1 ≤ N ≤ 500" }, { "code": null, "e": 1585, "s": 1583, "text": "0" }, { "code": null, "e": 1609, "s": 1585, "text": "chhitizgoyal2 weeks ago" }, { "code": null, "e": 1624, "s": 1609, "text": "Java Solution." }, { "code": null, "e": 4221, "s": 1624, "text": "class Sol{ Node root; static int height(Node N) { if (N == null) return 0; return N.height; } static int max(int a, int b) { return (a > b) ? a : b; } static Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; // Perform rotation x.right = y; y.left = T2; y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; return x; } static Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; y.left = x; x.right = T2; x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; } static int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } static Node minValueNode(Node node) { Node current = node; while (current.left != null) current = current.left; return current; } public static Node deleteNode(Node root, int key) { if (root == null) return root; if (key < root.data) root.left = deleteNode(root.left, key); else if (key > root.data) root.right = deleteNode(root.right, key); else { if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; if (temp == null) { temp = root; root = null; } else root = temp; } else { Node temp = minValueNode(root.right); root.data = temp.data; root.right = deleteNode(root.right, temp.data); } } if (root == null) return root; root.height = max(height(root.left), height(root.right)) + 1; int balance = getBalance(root); if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; }}" }, { "code": null, "e": 4224, "s": 4221, "text": "+1" }, { "code": null, "e": 4252, "s": 4224, "text": "vinitkumawat1122 months ago" }, { "code": null, "e": 4270, "s": 4252, "text": "Easy C++ solution" }, { "code": null, "e": 7275, "s": 4272, "text": "int NodeHeight(Node* p)\n{\n int hl=0, hr=0;\n hl = p&&p->left?p->left->height:0;\n hr = p&&p->right?p->right->height:0;\n return (hl>hr?hl+1:hr+1);\n}\n\nint BalanceFactor(Node* p)\n{\n // hl-hr\n int hl=0, hr=0;\n hl = p&&p->left?p->left->height:0;\n hr = p&&p->right?p->right->height:0;\n \n return (hl-hr);\n}\n\nNode* LLRotate(Node* p)\n{\n Node* pl = p->left;\n Node* plr = pl->right;\n \n pl->right = p;\n p->left = plr;\n \n p->height = NodeHeight(p);\n pl->height = NodeHeight(pl);\n \n return pl;\n}\n\nNode* LRRotate(Node* p)\n{\n Node* pl = p->left;\n Node* plr = pl->right;\n \n pl->right = plr->left;\n p->left = plr->right;\n \n plr->left = pl;\n plr->right = p;\n \n p->height = NodeHeight(p);\n pl->height = NodeHeight(pl);\n plr->height = NodeHeight(plr);\n \n return plr;\n}\n\nNode* RRRotate(Node* p)\n{\n Node* pr = p->right;\n Node* prl = pr->left;\n \n pr->left = p;\n p->right = prl;\n \n p->height = NodeHeight(p);\n pr->height = NodeHeight(pr);\n \n return pr;\n}\n\nNode* RLRotate(Node* p)\n{\n Node* pr = p->right;\n Node* prl = pr->left;\n \n p->right = prl->left;\n pr->left = prl->right;\n \n prl->left = p;\n prl->right = pr;\n \n p->height = NodeHeight(p);\n pr->height = NodeHeight(pr);\n prl->height = NodeHeight(prl);\n \n return prl;\n}\n\nNode* InSuccessor(Node* p)\n{\n while(p && p->left)\n {\n p=p->left;\n }\n return p;\n}\n\nNode* InPredecessor(Node* p)\n{\n while(p && p->right)\n p=p->right;\n return p;\n}\n\n\nNode* deleteNode(Node* root, int data)\n{\n if(root==NULL) return NULL;\n if(root->left==NULL && root->right==NULL)\n {\n if(data==root->data)\n {\n free(root);\n return NULL;\n }\n }\n \n if(data<root->data)\n root->left = deleteNode(root->left,data);\n else if(data>root->data)\n root->right = deleteNode(root->right,data);\n else\n {\n if(root->right!=NULL)\n {\n // successor\n Node* q = InSuccessor(root->right);\n root->data = q->data;\n root->right = deleteNode(root->right, q->data);\n }\n else\n {\n // Predecessor\n Node* q = InPredecessor(root->left);\n root->data = q->data;\n root->left = deleteNode(root->left,q->data);\n }\n }\n root->height = NodeHeight(root);\n if(BalanceFactor(root)==2 && BalanceFactor(root->left)==1)\n return LLRotate(root);\n else if(BalanceFactor(root)==2&&BalanceFactor(root->left)==-1)\n return LRRotate(root);\n else if(BalanceFactor(root)==2&&BalanceFactor(root->left)==0)\n return LLRotate(root);\n else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==1)\n return RLRotate(root);\n else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==-1)\n return RRRotate(root);\n else if(BalanceFactor(root)==-2&&BalanceFactor(root->right)==0)\n return RRRotate(root);\n \n return root;\n}" }, { "code": null, "e": 7277, "s": 7275, "text": "0" }, { "code": null, "e": 7299, "s": 7277, "text": "arjun62613 months ago" }, { "code": null, "e": 7320, "s": 7299, "text": "can any one help me " }, { "code": null, "e": 7347, "s": 7320, "text": "why it show run time error" }, { "code": null, "e": 7414, "s": 7347, "text": "int max(int a, int b){ if(a>b){ return a; } return b;}" }, { "code": null, "e": 7537, "s": 7414, "text": "int height(Node *root) { if (root == NULL) { return 0; } return max(height(root->left),height(root->right))+1;}" }, { "code": null, "e": 7616, "s": 7541, "text": "Node *rightRotate(Node *y) { Node *x = y->left; Node *T2 = x->right;" }, { "code": null, "e": 7717, "s": 7616, "text": " x->right = y; y->left = T2; y->height = height(y); x->height =height(x); return x; }" }, { "code": null, "e": 7825, "s": 7717, "text": "Node *leftRotate(Node *x) { Node *y = x->right; Node *T2 = y->left; y->left = x; x->right = T2;" }, { "code": null, "e": 7879, "s": 7825, "text": " x->height = height(x); y->height = height(y);" }, { "code": null, "e": 8010, "s": 7879, "text": " return y; } //int bf(Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); }" }, { "code": null, "e": 8098, "s": 8010, "text": "Node* insert(Node* node, int data) { if (node == NULL) return new Node(data);" }, { "code": null, "e": 8277, "s": 8098, "text": " if (data < node->data) node->left = insert(node->left, data); else if (data > node->data) node->right = insert(node->right, data); else return node;" }, { "code": null, "e": 8312, "s": 8277, "text": " node->height = height(node);" }, { "code": null, "e": 8336, "s": 8312, "text": " int b = bf(node);" }, { "code": null, "e": 8412, "s": 8336, "text": " if (b> 1 && data < node->left->data) return rightRotate(node);" }, { "code": null, "e": 8487, "s": 8412, "text": " if (b < -1 && data > node->right->data) return leftRotate(node);" }, { "code": null, "e": 8615, "s": 8487, "text": " if (b > 1 && data > node->left->data) { node->left = leftRotate(node->left); return rightRotate(node); }" }, { "code": null, "e": 8747, "s": 8615, "text": " if (b < -1 && data < node->right->data) { node->right = rightRotate(node->right); return leftRotate(node); }" }, { "code": null, "e": 8768, "s": 8747, "text": " return node; }" }, { "code": null, "e": 8818, "s": 8768, "text": "Node * min(Node* node) { Node* current = node;" }, { "code": null, "e": 8886, "s": 8818, "text": " while (current->left != NULL) current = current->left;" }, { "code": null, "e": 8907, "s": 8886, "text": " return current; }" }, { "code": null, "e": 8996, "s": 8907, "text": "Node* deleteNode(Node* root, int data) { if (root == NULL) return root;" }, { "code": null, "e": 9076, "s": 8996, "text": " if ( data < root->data) root->left = deleteNode(root->left, data);" }, { "code": null, "e": 9371, "s": 9076, "text": " else if( data > root->data ) root->right = deleteNode(root->right, data); else { if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right;" }, { "code": null, "e": 9680, "s": 9371, "text": " if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; free(temp); } else { Node* temp = min(root->right);" }, { "code": null, "e": 9726, "s": 9680, "text": " root->data = temp->data;" }, { "code": null, "e": 9850, "s": 9726, "text": " root->right = deleteNode(root->right, temp->data); } }" }, { "code": null, "e": 9887, "s": 9850, "text": " if (root == NULL) return root;" }, { "code": null, "e": 9945, "s": 9887, "text": " root->height = height(root); int b = bf(root);" }, { "code": null, "e": 10015, "s": 9945, "text": "if (b> 1 && data < root->left->data) return rightRotate(root);" }, { "code": null, "e": 10090, "s": 10015, "text": " if (b < -1 && data > root->right->data) return leftRotate(root);" }, { "code": null, "e": 10218, "s": 10090, "text": " if (b > 1 && data > root->left->data) { root->left = leftRotate(root->left); return rightRotate(root); }" }, { "code": null, "e": 10350, "s": 10218, "text": " if (b < -1 && data < root->right->data) { root->right = rightRotate(root->right); return leftRotate(root); }" }, { "code": null, "e": 10437, "s": 10352, "text": " return root; } int max(int a, int b){ if(a>b){ return a; } return b;}" }, { "code": null, "e": 10560, "s": 10437, "text": "int height(Node *root) { if (root == NULL) { return 0; } return max(height(root->left),height(root->right))+1;}" }, { "code": null, "e": 10639, "s": 10564, "text": "Node *rightRotate(Node *y) { Node *x = y->left; Node *T2 = x->right;" }, { "code": null, "e": 10740, "s": 10639, "text": " x->right = y; y->left = T2; y->height = height(y); x->height =height(x); return x; }" }, { "code": null, "e": 10848, "s": 10740, "text": "Node *leftRotate(Node *x) { Node *y = x->right; Node *T2 = y->left; y->left = x; x->right = T2;" }, { "code": null, "e": 10902, "s": 10848, "text": " x->height = height(x); y->height = height(y);" }, { "code": null, "e": 11033, "s": 10902, "text": " return y; } //int bf(Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); }" }, { "code": null, "e": 11121, "s": 11033, "text": "Node* insert(Node* node, int data) { if (node == NULL) return new Node(data);" }, { "code": null, "e": 11300, "s": 11121, "text": " if (data < node->data) node->left = insert(node->left, data); else if (data > node->data) node->right = insert(node->right, data); else return node;" }, { "code": null, "e": 11335, "s": 11300, "text": " node->height = height(node);" }, { "code": null, "e": 11359, "s": 11335, "text": " int b = bf(node);" }, { "code": null, "e": 11435, "s": 11359, "text": " if (b> 1 && data < node->left->data) return rightRotate(node);" }, { "code": null, "e": 11510, "s": 11435, "text": " if (b < -1 && data > node->right->data) return leftRotate(node);" }, { "code": null, "e": 11638, "s": 11510, "text": " if (b > 1 && data > node->left->data) { node->left = leftRotate(node->left); return rightRotate(node); }" }, { "code": null, "e": 11770, "s": 11638, "text": " if (b < -1 && data < node->right->data) { node->right = rightRotate(node->right); return leftRotate(node); }" }, { "code": null, "e": 11791, "s": 11770, "text": " return node; }" }, { "code": null, "e": 11841, "s": 11791, "text": "Node * min(Node* node) { Node* current = node;" }, { "code": null, "e": 11909, "s": 11841, "text": " while (current->left != NULL) current = current->left;" }, { "code": null, "e": 11930, "s": 11909, "text": " return current; }" }, { "code": null, "e": 12019, "s": 11930, "text": "Node* deleteNode(Node* root, int data) { if (root == NULL) return root;" }, { "code": null, "e": 12099, "s": 12019, "text": " if ( data < root->data) root->left = deleteNode(root->left, data);" }, { "code": null, "e": 12394, "s": 12099, "text": " else if( data > root->data ) root->right = deleteNode(root->right, data); else { if( (root->left == NULL) || (root->right == NULL) ) { Node *temp = root->left ? root->left : root->right;" }, { "code": null, "e": 12703, "s": 12394, "text": " if (temp == NULL) { temp = root; root = NULL; } else // One child case *root = *temp; free(temp); } else { Node* temp = min(root->right);" }, { "code": null, "e": 12749, "s": 12703, "text": " root->data = temp->data;" }, { "code": null, "e": 12873, "s": 12749, "text": " root->right = deleteNode(root->right, temp->data); } }" }, { "code": null, "e": 12910, "s": 12873, "text": " if (root == NULL) return root;" }, { "code": null, "e": 12968, "s": 12910, "text": " root->height = height(root); int b = bf(root);" }, { "code": null, "e": 13038, "s": 12968, "text": "if (b> 1 && data < root->left->data) return rightRotate(root);" }, { "code": null, "e": 13113, "s": 13038, "text": " if (b < -1 && data > root->right->data) return leftRotate(root);" }, { "code": null, "e": 13241, "s": 13113, "text": " if (b > 1 && data > root->left->data) { root->left = leftRotate(root->left); return rightRotate(root); }" }, { "code": null, "e": 13373, "s": 13241, "text": " if (b < -1 && data < root->right->data) { root->right = rightRotate(root->right); return leftRotate(root); }" }, { "code": null, "e": 13394, "s": 13375, "text": " return root; } " }, { "code": null, "e": 13396, "s": 13394, "text": "0" }, { "code": null, "e": 13422, "s": 13396, "text": "gyanikug20cse4 months ago" }, { "code": null, "e": 13468, "s": 13422, "text": "Why i am getting wrong ans in this test case." }, { "code": null, "e": 13541, "s": 13468, "text": "int height(Node *root){ if(!root) return 0; return root->height;}" }, { "code": null, "e": 13622, "s": 13541, "text": "Node *insucc(Node *root){ while(root->left) root=root->left; return root;}" }, { "code": null, "e": 13753, "s": 13622, "text": "Node* rightRot(Node *r){ Node *rl=r->left; Node *rlr=rl->right; //Rotation rl->right=r; r->left=rlr; return rl;}" }, { "code": null, "e": 13883, "s": 13753, "text": "Node* leftRot(Node *r){ Node *rr=r->right; Node *rrl=rr->left; //Rotation rr->left=r; r->right=rrl; return rr;}" }, { "code": null, "e": 13982, "s": 13883, "text": "int getBalFac(Node *root){ if(!root) return 0; return height(root->left)-height(root->right);}" }, { "code": null, "e": 15260, "s": 13982, "text": "Node* deleteNode(Node* root, int data){ //BST Deletion if(!root) return NULL; if(data<root->data) root->left=deleteNode(root->left,data); else if(data>root->data) root->right=deleteNode(root->right,data); else{ if(root->left==NULL||root->right==NULL) { Node *temp; if(!root->left) temp=root->right; else temp=root->left; if(temp==NULL) { temp=root; root=NULL; } else *root=*temp; free(temp); } else { Node *temp=insucc(root->right); root->data=temp->data; root->right=deleteNode(root->right,temp->data); } } if(root==NULL) return root; root->height=1+max(height(root->left),height(root->right)); int bf=getBalFac(root); if(bf==2&&getBalFac(root->left)>=0) return rightRot(root); if(bf==2&&getBalFac(root->left)==-1) { root->left=leftRot(root->left); return rightRot(root); } if(bf==-2&&getBalFac(root->right)<=0) return leftRot(root); if(bf==-2&&getBalFac(root->right)==1) { root->right=rightRot(root->right); return leftRot(root); } return root; }" }, { "code": null, "e": 15262, "s": 15260, "text": "0" }, { "code": null, "e": 15286, "s": 15262, "text": "Y0U Cha*ngE9 months ago" }, { "code": null, "e": 15298, "s": 15286, "text": "Y0U Cha*ngE" }, { "code": null, "e": 16171, "s": 15298, "text": "int findheight(Node *root) { if(root==NULL) return 0; return (1+ max(findheight(root->left),findheight(root->right))); } void updateheight(Node *root) { if(root==NULL) return; root->height= findheight(root); } int balancefactor(Node *root) { if(root==NULL) return 0; else return (findheight(root->left) - findheight(root->right)); } /*You are required to complete this method */ Node* LL(Node* root) { Node *l= root->left; Node*lr= l->right; l->right=root; root->left=lr; updateheight(root); updateheight(l); return l; } Node* RR(Node* root) { Node *r=root->right; Node* rl=r->left; r->left=root; root->right=rl; updateheight(root); updateheight(r); return r;" }, { "code": null, "e": 16363, "s": 16171, "text": " } Node* LR(Node *root) { root->left=RR(root->left); return LL(root); } Node* RL(Node *root) { root->right=LL(root->right); return RR(root); }" }, { "code": null, "e": 17365, "s": 16363, "text": "Node* deleteNode(Node* root, int data){ if(root==NULL) return root; if(root->data >data) root->left=deleteNode(root->left,data); else if(root->data <data) root-=\"\">right=deleteNode(root->right,data); else if((root->data) == data) { if(!root->left && !root->right) root=NULL; else if(!root->left || !root->right) { Node *temp= ((root->left)?(root->left):(root->right)); root= temp; } else{ Node *temp=root->left; while(temp->right!=NULL) temp= temp->right; root->data=temp->data; root->left=deleteNode(root->left,temp->data); } } updateheight(root); int bl=balancefactor(root); if(bl>1 && balancefactor(root->left)>=0) root=LL(root); if(bl>1 && balancefactor(root->left)<0) root=LR(root); if(bl<-1 && balancefactor(root->right)<=0) root=RR(root); if(bl<-1 && balancefactor(root->right)>0) root=RL(root);" }, { "code": null, "e": 17383, "s": 17365, "text": " return root;}" }, { "code": null, "e": 17456, "s": 17383, "text": "Possibly your code doesn't work correctly for multiple test-cases (TCs)." }, { "code": null, "e": 17500, "s": 17456, "text": "The first test case where your code failed:" }, { "code": null, "e": 17507, "s": 17500, "text": "Input:" }, { "code": null, "e": 17582, "s": 17507, "text": "80 51 95 29 66 89 99 6 40 N 71 N 94 98126 95 80 89 98 99 66 29 51 71 40 94" }, { "code": null, "e": 17605, "s": 17582, "text": "Its Correct output is:" }, { "code": null, "e": 17610, "s": 17605, "text": "null" }, { "code": null, "e": 17637, "s": 17610, "text": "And Your Code's output is:" }, { "code": null, "e": 17691, "s": 17637, "text": "Unbalanced BST, inorder traversal : 29 40 51 66 71..." }, { "code": null, "e": 17693, "s": 17691, "text": "0" }, { "code": null, "e": 17709, "s": 17693, "text": "Kunwar Sadanand" }, { "code": null, "e": 17735, "s": 17709, "text": "This comment was deleted." }, { "code": null, "e": 17737, "s": 17735, "text": "0" }, { "code": null, "e": 17753, "s": 17737, "text": "Joya2 years ago" }, { "code": null, "e": 17758, "s": 17753, "text": "Joya" }, { "code": null, "e": 17808, "s": 17758, "text": "Get Clue with comment when you stuck at any point" }, { "code": null, "e": 17811, "s": 17808, "text": "+2" }, { "code": null, "e": 17842, "s": 17811, "text": "Pratiik Priyadarsan2 years ago" }, { "code": null, "e": 17862, "s": 17842, "text": "Pratiik Priyadarsan" }, { "code": null, "e": 18014, "s": 17862, "text": "Not an actual method to delete an element from an AVL tree. There will be rotations involved.But this is certainly a way to deal with the task at hand." }, { "code": null, "e": 18583, "s": 18014, "text": "void inorder(vector<int>&v,Node*root,const int data){ if(root){ inorder(v,root->left,data); if(root->data != data) v.push_back(root->data); inorder(v,root->right,data); }}Node* buildTree(vector<int>&v,int s,int e){ if(s>e) return NULL; int mid = (s+e)/2; Node* root = new Node(v[mid]); root->left = buildTree(v,s,mid-1); root->right = buildTree(v,mid+1,e); return root;}Node* deleteNode(Node* root, int data){//add code here, vector<int>v; inorder(v,root,data); return buildTree(v,0,v.size()-1);}" }, { "code": null, "e": 18585, "s": 18583, "text": "0" }, { "code": null, "e": 18608, "s": 18585, "text": "Kamal Meena2 years ago" }, { "code": null, "e": 18620, "s": 18608, "text": "Kamal Meena" }, { "code": null, "e": 18699, "s": 18620, "text": "Please Add Python compiler And Add more Que on Avl Tree or on red black tree" }, { "code": null, "e": 18701, "s": 18699, "text": "0" }, { "code": null, "e": 18731, "s": 18701, "text": "Animesh Srivastawa2 years ago" }, { "code": null, "e": 18750, "s": 18731, "text": "Animesh Srivastawa" }, { "code": null, "e": 21520, "s": 18750, "text": "can someone explain me what is wrong with my code ?void print(Node *root){ if(root == NULL) return; cout<<root->data<<\"--->\"<<root->height<<\" \"; print(root->left); print(root->right);}Node *inOrderSuc(Node *&parent, Node *root){ if(root == NULL) return NULL; if(root->left == NULL) return root; parent = root; return inOrderSuc(parent, root->left);}int calculateHeight(Node *root){ int l = root->left ? root->left->height : 1; int r = root->right ? root->right->height : 1; return max(l, r);}Node* deleteNode(Node* root, int data){//add code here, if(root == NULL) return NULL; if(root->data > data) root->left = deleteNode(root->left, data); else if(root->data < data) root->right = deleteNode(root->right, data); else if(root->data == data){ Node *tmp = root; if(!root->left || !root->right){ if(!root->left && !root->right){ delete(root); return NULL; } if(!root->left) root = root->right; else root = root->left; delete(tmp); } else{ Node *parent = root; Node *inOrder = inOrderSuc(parent, root->right); //Node *tmp = inOrder->right; cout<<inorder->data<<\" \"; if(parent == root) parent->right = inOrder->right; else parent->left = inOrder->right; inOrder->left = root->left; inOrder->right = root->right; root = inOrder; parent->height = calculateHeight(parent); root->right = deleteNode(root->right, -1); delete(tmp); } } if(root != NULL){ int l = root->left ? root->left->height : 1; int r = root->right ? root->right->height : 1; int diff = abs(l - r); if(diff > 1){ if(l > r){ // print(root); // cout<<endl; int=\"\" l1=\"root-\">left->left ? root->left->left->height : 1; int r1 = root->left->right ? root->left->right->height : 1; int diff2 = l1 - r1; if(diff2 < 0) root->left = leftRotate(root->left); root = rightRotate(root); } else{ int l1 = root->right->left ? root->right->left->height : 1; int r1 = root->right->right ? root->right->right->height : 1; int diff2 = l1 - r1; if(diff2 > 0) root->right = rightRotate(root->right); root = leftRotate(root); } } l = root->left ? root->left->height+1 : 1; r = root->right ? root->right->height+1: 1; root->height = max(l,r); print(root); cout<<endl; }=\"\" return=\"\" root;=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 21666, "s": 21520, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 21702, "s": 21666, "text": " Login to access your submissions. " }, { "code": null, "e": 21712, "s": 21702, "text": "\nProblem\n" }, { "code": null, "e": 21722, "s": 21712, "text": "\nContest\n" }, { "code": null, "e": 21785, "s": 21722, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 21933, "s": 21785, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 22141, "s": 21933, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 22247, "s": 22141, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
TensorFlow + Jupyter Notebook + Nvidia DIY Setup | by Choong Hong Cheng | Towards Data Science
Based on my first story, more detailed step by step setup using Xbuntu / Ubuntu 17.04. Note that we will be using a user that has sudo right instead of root directly. Install Nvidia driver repository sudo add-apt-repository ppa:graphics-drivers/ppasudo apt-get update sudo apt-get upgrade sudo apt-get install build-essential cmake g++ gfortran git pkg-config python-dev software-properties-common wget Install CUDA 8.0 from Nvidia, get both base installer and patch 2. CUDA will also install nvidia driver accordingly specific to the CUDA version sudo dpkg -i cuda-repo-ubuntu1604-8-0-local-*amd64.debsudo apt-get updatesudo apt-get install cuda Setup the CUDA environment for local user echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrcecho 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrcsource ~/.bashrc Test it using nvcc -V Finally install cuDNN, get it from Nvidia, this is for Tensorflow later. Get the right version for the current installed CUDA cd ~/Downloads/tar xvf cudnn*.tgzcd cudasudo cp */*.h /usr/local/cuda/include/sudo cp */libcudnn* /usr/local/cuda/lib64/sudo chmod a+r /usr/local/cuda/lib64/libcudnn* Grab the installer from Anaconda, using Python 3.6 and follow the installation instruction cd ~/Downloads/bash Anaconda3-4.4.0-Linux-x86_64.sh Normally I will install the Anaconda under /opt folder. If is install under home folder, we need to locate the environment folder after activated the environment source activate tf-gpuecho $PATH This is important in order to setup Jupyter Notebook later. Once we have Anaconda install, we going to create an environment for our Jupyter setup and install TensorFlow GPU conda create --name tf-gpu python=3.6source activate tf-gpupip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.3.0-cp36-cp36m-linux_x86_64.whl Once we install TensorFlow, we going install Jupyter, we going use conda to manage the packages for both Jupyter Notebook and shell runtime conda install jupyter notebook numpy pandas matplotlib Install any ddns client to able to update domain so we could connect back to our home server. We could use NoIP for this and it has linux client to update the domain. Make sure we stop current nginx before using letsencrypt instead of buying a SSL certificate because I am on cost saving sudo systemctl stop nginx Once the NGINX is stop, we could run initial letsencrypt command that will spin off it’s own internal server for verification process Clone letsencrypt using command, follow by setting up initial certificate sudo git clone https://github.com/letsencrypt/letsencrypt /opt/letsencryptsudo -H /opt/letsencrypt/letsencrypt-auto certonly [email protected] -d deeplearning.chclab.net -d jupyter-cpu.chclab.net -d jupyter-nvidia.chclab.net -d monitor.chclab.net Setup the cron job to run the certificate renew process 0 0 * * * /opt/letsencrypt/letsencrypt-auto renew --quiet Create a shell script to start Jupyter Notebook at ~/start-tf-jupyter-gpu.sh This will use the conda environment called tf-gpu that we setup earlier. #!/bin/bashexport PATH=/home/chc/.conda/envs/tf-gpu/bin:$PATH/home/chc/.conda/envs/tf-gpu/bin/jupyter notebook --no-browser --NotebookApp.allow_origin='*' --notebook-dir='/home/chc/project' --NotebookApp.port=9999 Secure the Jupyter Notebook by using the following command, more information about this from this link jupyter notebook --generate-configjupyter notebook password Create a Systemctl service at sudo vi /etc/systemd/system/jupyter-gpu.service [Unit]Description=Service for jupyter cpu notebookAfter=local-fs.target network.target[Service]Type=simpleUser=chcGroup=chcExecStart=/home/chc/start-tf-jupyter-gpu.shRestart=alwaysSyslogIdentifier=jupyter cpu notebook[Install]WantedBy=multi-user.target Enable the service and try to run it sudo systemctl daemon-reloadsudo systemctl enable jupyter-gpu.servicesudo systemctl start jupyter-gpu.servicesudo systemctl status jupyter-gpu.service Install NGINX sudo apt-get install nginx Setup the following NGINX, for me is sudo vi /etc/nginx/conf.d/jupyter-nvidia.chclab.net.conf upstream notebook-tensorflow { server localhost:9999;}server { server_name jupyter-nvidia.chclab.net; listen 443 ssl; access_log off;ssl_certificate /etc/letsencrypt/live/deeplearning.chclab.net-0001/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/deeplearning.chclab.net-0001/privkey.pem;ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"; ssl_ecdh_curve secp384r1; ssl_session_cache shared:SSL:10m; ssl_session_tickets off; ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 5s; # disable HSTS header for now #add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"; add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff;ssl_dhparam /etc/ssl/certs/dhparam.pem;location / { proxy_pass http://notebook-tensorflow; proxy_set_header Host $host; }location ~ /api/kernels/ { proxy_pass http://notebook-tensorflow; proxy_set_header Host $host; # websocket support proxy_http_version 1.1; proxy_set_header Upgrade "websocket"; proxy_set_header Connection "Upgrade"; proxy_read_timeout 86400; } location ~ /terminals/ { proxy_pass http://notebook-tensorflow; proxy_set_header Host $host; # websocket support proxy_http_version 1.1; proxy_set_header Upgrade "websocket"; proxy_set_header Connection "Upgrade"; proxy_read_timeout 86400; }} Generate a strong dhparam file openssl dhparam -out /etc/ssl/certs/dhparam.pem 4096 Restart NGINX sudo systemctl restart nginx Finally there is how it look like using Jupyter Notebook
[ { "code": null, "e": 339, "s": 172, "text": "Based on my first story, more detailed step by step setup using Xbuntu / Ubuntu 17.04. Note that we will be using a user that has sudo right instead of root directly." }, { "code": null, "e": 372, "s": 339, "text": "Install Nvidia driver repository" }, { "code": null, "e": 577, "s": 372, "text": "sudo add-apt-repository ppa:graphics-drivers/ppasudo apt-get update sudo apt-get upgrade sudo apt-get install build-essential cmake g++ gfortran git pkg-config python-dev software-properties-common wget" }, { "code": null, "e": 722, "s": 577, "text": "Install CUDA 8.0 from Nvidia, get both base installer and patch 2. CUDA will also install nvidia driver accordingly specific to the CUDA version" }, { "code": null, "e": 821, "s": 722, "text": "sudo dpkg -i cuda-repo-ubuntu1604-8-0-local-*amd64.debsudo apt-get updatesudo apt-get install cuda" }, { "code": null, "e": 863, "s": 821, "text": "Setup the CUDA environment for local user" }, { "code": null, "e": 1018, "s": 863, "text": "echo 'export PATH=/usr/local/cuda/bin:$PATH' >> ~/.bashrcecho 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> ~/.bashrcsource ~/.bashrc" }, { "code": null, "e": 1032, "s": 1018, "text": "Test it using" }, { "code": null, "e": 1040, "s": 1032, "text": "nvcc -V" }, { "code": null, "e": 1166, "s": 1040, "text": "Finally install cuDNN, get it from Nvidia, this is for Tensorflow later. Get the right version for the current installed CUDA" }, { "code": null, "e": 1333, "s": 1166, "text": "cd ~/Downloads/tar xvf cudnn*.tgzcd cudasudo cp */*.h /usr/local/cuda/include/sudo cp */libcudnn* /usr/local/cuda/lib64/sudo chmod a+r /usr/local/cuda/lib64/libcudnn*" }, { "code": null, "e": 1424, "s": 1333, "text": "Grab the installer from Anaconda, using Python 3.6 and follow the installation instruction" }, { "code": null, "e": 1476, "s": 1424, "text": "cd ~/Downloads/bash Anaconda3-4.4.0-Linux-x86_64.sh" }, { "code": null, "e": 1532, "s": 1476, "text": "Normally I will install the Anaconda under /opt folder." }, { "code": null, "e": 1638, "s": 1532, "text": "If is install under home folder, we need to locate the environment folder after activated the environment" }, { "code": null, "e": 1671, "s": 1638, "text": "source activate tf-gpuecho $PATH" }, { "code": null, "e": 1731, "s": 1671, "text": "This is important in order to setup Jupyter Notebook later." }, { "code": null, "e": 1845, "s": 1731, "text": "Once we have Anaconda install, we going to create an environment for our Jupyter setup and install TensorFlow GPU" }, { "code": null, "e": 2046, "s": 1845, "text": "conda create --name tf-gpu python=3.6source activate tf-gpupip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.3.0-cp36-cp36m-linux_x86_64.whl" }, { "code": null, "e": 2186, "s": 2046, "text": "Once we install TensorFlow, we going install Jupyter, we going use conda to manage the packages for both Jupyter Notebook and shell runtime" }, { "code": null, "e": 2241, "s": 2186, "text": "conda install jupyter notebook numpy pandas matplotlib" }, { "code": null, "e": 2408, "s": 2241, "text": "Install any ddns client to able to update domain so we could connect back to our home server. We could use NoIP for this and it has linux client to update the domain." }, { "code": null, "e": 2529, "s": 2408, "text": "Make sure we stop current nginx before using letsencrypt instead of buying a SSL certificate because I am on cost saving" }, { "code": null, "e": 2555, "s": 2529, "text": "sudo systemctl stop nginx" }, { "code": null, "e": 2689, "s": 2555, "text": "Once the NGINX is stop, we could run initial letsencrypt command that will spin off it’s own internal server for verification process" }, { "code": null, "e": 2763, "s": 2689, "text": "Clone letsencrypt using command, follow by setting up initial certificate" }, { "code": null, "e": 3014, "s": 2763, "text": "sudo git clone https://github.com/letsencrypt/letsencrypt /opt/letsencryptsudo -H /opt/letsencrypt/letsencrypt-auto certonly [email protected] -d deeplearning.chclab.net -d jupyter-cpu.chclab.net -d jupyter-nvidia.chclab.net -d monitor.chclab.net" }, { "code": null, "e": 3070, "s": 3014, "text": "Setup the cron job to run the certificate renew process" }, { "code": null, "e": 3130, "s": 3070, "text": "0 0 * * * /opt/letsencrypt/letsencrypt-auto renew --quiet" }, { "code": null, "e": 3280, "s": 3130, "text": "Create a shell script to start Jupyter Notebook at ~/start-tf-jupyter-gpu.sh This will use the conda environment called tf-gpu that we setup earlier." }, { "code": null, "e": 3494, "s": 3280, "text": "#!/bin/bashexport PATH=/home/chc/.conda/envs/tf-gpu/bin:$PATH/home/chc/.conda/envs/tf-gpu/bin/jupyter notebook --no-browser --NotebookApp.allow_origin='*' --notebook-dir='/home/chc/project' --NotebookApp.port=9999" }, { "code": null, "e": 3597, "s": 3494, "text": "Secure the Jupyter Notebook by using the following command, more information about this from this link" }, { "code": null, "e": 3657, "s": 3597, "text": "jupyter notebook --generate-configjupyter notebook password" }, { "code": null, "e": 3735, "s": 3657, "text": "Create a Systemctl service at sudo vi /etc/systemd/system/jupyter-gpu.service" }, { "code": null, "e": 3988, "s": 3735, "text": "[Unit]Description=Service for jupyter cpu notebookAfter=local-fs.target network.target[Service]Type=simpleUser=chcGroup=chcExecStart=/home/chc/start-tf-jupyter-gpu.shRestart=alwaysSyslogIdentifier=jupyter cpu notebook[Install]WantedBy=multi-user.target" }, { "code": null, "e": 4025, "s": 3988, "text": "Enable the service and try to run it" }, { "code": null, "e": 4176, "s": 4025, "text": "sudo systemctl daemon-reloadsudo systemctl enable jupyter-gpu.servicesudo systemctl start jupyter-gpu.servicesudo systemctl status jupyter-gpu.service" }, { "code": null, "e": 4190, "s": 4176, "text": "Install NGINX" }, { "code": null, "e": 4217, "s": 4190, "text": "sudo apt-get install nginx" }, { "code": null, "e": 4311, "s": 4217, "text": "Setup the following NGINX, for me is sudo vi /etc/nginx/conf.d/jupyter-nvidia.chclab.net.conf" }, { "code": null, "e": 6132, "s": 4311, "text": "upstream notebook-tensorflow { server localhost:9999;}server { server_name jupyter-nvidia.chclab.net; listen 443 ssl; access_log off;ssl_certificate /etc/letsencrypt/live/deeplearning.chclab.net-0001/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/deeplearning.chclab.net-0001/privkey.pem;ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers \"EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH\"; ssl_ecdh_curve secp384r1; ssl_session_cache shared:SSL:10m; ssl_session_tickets off; ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s; resolver_timeout 5s; # disable HSTS header for now #add_header Strict-Transport-Security \"max-age=63072000; includeSubDomains; preload\"; add_header X-Frame-Options DENY; add_header X-Content-Type-Options nosniff;ssl_dhparam /etc/ssl/certs/dhparam.pem;location / { proxy_pass http://notebook-tensorflow; proxy_set_header Host $host; }location ~ /api/kernels/ { proxy_pass http://notebook-tensorflow; proxy_set_header Host $host; # websocket support proxy_http_version 1.1; proxy_set_header Upgrade \"websocket\"; proxy_set_header Connection \"Upgrade\"; proxy_read_timeout 86400; } location ~ /terminals/ { proxy_pass http://notebook-tensorflow; proxy_set_header Host $host; # websocket support proxy_http_version 1.1; proxy_set_header Upgrade \"websocket\"; proxy_set_header Connection \"Upgrade\"; proxy_read_timeout 86400; }}" }, { "code": null, "e": 6163, "s": 6132, "text": "Generate a strong dhparam file" }, { "code": null, "e": 6216, "s": 6163, "text": "openssl dhparam -out /etc/ssl/certs/dhparam.pem 4096" }, { "code": null, "e": 6230, "s": 6216, "text": "Restart NGINX" }, { "code": null, "e": 6259, "s": 6230, "text": "sudo systemctl restart nginx" } ]
Get All Factor Levels of DataFrame Column in R - GeeksforGeeks
17 May, 2021 The data frame columns in R can be factorized on the basis of its factor columns. The data frame factor columns are composed of factor levels. Factors are used to represent categorical data. Each of the factor is denoted by a level, computed in the lexicographic order of appearance of characters or strings in the encoded factor level vector. In this article we will discuss how to get all factor levels of dataframe column in R. The hardhat package in R is responsible for providing functionality for preprocessing, predicting, and validating input. It is used to construct modeling packages. Syntax: install.packages(“hardhat”) get_levels() method in this package is used to extract the levels from any factor columns in the specified data frame. The major advantage of this method is utilized in the extraction of the original factor levels from the predictors in the training set, which is the data frame, in this case. It takes as an argument only a data frame or data.table in R and returns the different columns mapped to the corresponding factor levels in the form of vectors, if and only if the data type is compatible. Syntax: get_levels(data_frame) The columns are leveled on the basis of factor levels. However, any duplicate entries are removed, since they fall at the same factor level. Example 1: R # getting required librarieslibrary("hardhat") # declaring data framedata_frame <- data.frame( col1 = letters[4:6], col3 = c("geeks","for","geeks")) print ("Original DataFrame")print (data_frame) print ("Factors")get_levels(data_frame) Output [1] “Original DataFrame” col1 col3 1 d geeks 2 e for 3 f geeks [1] “Factors” $col1 [1] “d” “e” “f” $col3 [1] “for” “geeks” Only the columns of the data frame which are of the factor type return output in the get_levels() method. The following program is used to understand the data type compatibility for the computation of factor levels of the columns in the data frame. Example 2: R # getting required librarieslibrary("hardhat") # declaring data framedata_frame <- data.frame(col1 = factor(c(2,4,6)), col2 = FALSE, col3 = LETTERS[1:3]) print ("Original DataFrame")print (data_frame) print ("Factors")get_levels(data_frame) Output col1 col2 col3 1 2 FALSE A 2 4 FALSE B 3 6 FALSE C [1] “Factors” $col1 [1] “2” “4” “6” $col3 [1] “A” “B” “C” In order to produce output factor(vec), where vec is the incompatible vector can be used while column declaration and definition. Picked R DataFrame-Programs R Factor-Programs R-DataFrame R-Factors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Data Visualization in R How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n17 May, 2021" }, { "code": null, "e": 25593, "s": 25162, "text": "The data frame columns in R can be factorized on the basis of its factor columns. The data frame factor columns are composed of factor levels. Factors are used to represent categorical data. Each of the factor is denoted by a level, computed in the lexicographic order of appearance of characters or strings in the encoded factor level vector. In this article we will discuss how to get all factor levels of dataframe column in R." }, { "code": null, "e": 25758, "s": 25593, "text": "The hardhat package in R is responsible for providing functionality for preprocessing, predicting, and validating input. It is used to construct modeling packages. " }, { "code": null, "e": 25766, "s": 25758, "text": "Syntax:" }, { "code": null, "e": 25794, "s": 25766, "text": "install.packages(“hardhat”)" }, { "code": null, "e": 26294, "s": 25794, "text": "get_levels() method in this package is used to extract the levels from any factor columns in the specified data frame. The major advantage of this method is utilized in the extraction of the original factor levels from the predictors in the training set, which is the data frame, in this case. It takes as an argument only a data frame or data.table in R and returns the different columns mapped to the corresponding factor levels in the form of vectors, if and only if the data type is compatible. " }, { "code": null, "e": 26302, "s": 26294, "text": "Syntax:" }, { "code": null, "e": 26325, "s": 26302, "text": "get_levels(data_frame)" }, { "code": null, "e": 26466, "s": 26325, "text": "The columns are leveled on the basis of factor levels. However, any duplicate entries are removed, since they fall at the same factor level." }, { "code": null, "e": 26477, "s": 26466, "text": "Example 1:" }, { "code": null, "e": 26479, "s": 26477, "text": "R" }, { "code": "# getting required librarieslibrary(\"hardhat\") # declaring data framedata_frame <- data.frame( col1 = letters[4:6], col3 = c(\"geeks\",\"for\",\"geeks\")) print (\"Original DataFrame\")print (data_frame) print (\"Factors\")get_levels(data_frame)", "e": 26721, "s": 26479, "text": null }, { "code": null, "e": 26728, "s": 26721, "text": "Output" }, { "code": null, "e": 26754, "s": 26728, "text": "[1] “Original DataFrame” " }, { "code": null, "e": 26767, "s": 26754, "text": " col1 col3 " }, { "code": null, "e": 26781, "s": 26767, "text": "1 d geeks " }, { "code": null, "e": 26795, "s": 26781, "text": "2 e for " }, { "code": null, "e": 26810, "s": 26795, "text": "3 f geeks " }, { "code": null, "e": 26825, "s": 26810, "text": "[1] “Factors” " }, { "code": null, "e": 26832, "s": 26825, "text": "$col1 " }, { "code": null, "e": 26850, "s": 26832, "text": "[1] “d” “e” “f” " }, { "code": null, "e": 26856, "s": 26850, "text": "$col3" }, { "code": null, "e": 26876, "s": 26856, "text": "[1] “for” “geeks”" }, { "code": null, "e": 27125, "s": 26876, "text": "Only the columns of the data frame which are of the factor type return output in the get_levels() method. The following program is used to understand the data type compatibility for the computation of factor levels of the columns in the data frame." }, { "code": null, "e": 27136, "s": 27125, "text": "Example 2:" }, { "code": null, "e": 27138, "s": 27136, "text": "R" }, { "code": "# getting required librarieslibrary(\"hardhat\") # declaring data framedata_frame <- data.frame(col1 = factor(c(2,4,6)), col2 = FALSE, col3 = LETTERS[1:3]) print (\"Original DataFrame\")print (data_frame) print (\"Factors\")get_levels(data_frame)", "e": 27407, "s": 27138, "text": null }, { "code": null, "e": 27414, "s": 27407, "text": "Output" }, { "code": null, "e": 27432, "s": 27414, "text": " col1 col2 col3 " }, { "code": null, "e": 27450, "s": 27432, "text": "1 2 FALSE A" }, { "code": null, "e": 27469, "s": 27450, "text": "2 4 FALSE B " }, { "code": null, "e": 27488, "s": 27469, "text": "3 6 FALSE C " }, { "code": null, "e": 27503, "s": 27488, "text": "[1] “Factors” " }, { "code": null, "e": 27510, "s": 27503, "text": "$col1 " }, { "code": null, "e": 27528, "s": 27510, "text": "[1] “2” “4” “6” " }, { "code": null, "e": 27535, "s": 27528, "text": "$col3 " }, { "code": null, "e": 27551, "s": 27535, "text": "[1] “A” “B” “C”" }, { "code": null, "e": 27682, "s": 27551, "text": "In order to produce output factor(vec), where vec is the incompatible vector can be used while column declaration and definition. " }, { "code": null, "e": 27689, "s": 27682, "text": "Picked" }, { "code": null, "e": 27710, "s": 27689, "text": "R DataFrame-Programs" }, { "code": null, "e": 27728, "s": 27710, "text": "R Factor-Programs" }, { "code": null, "e": 27740, "s": 27728, "text": "R-DataFrame" }, { "code": null, "e": 27750, "s": 27740, "text": "R-Factors" }, { "code": null, "e": 27761, "s": 27750, "text": "R Language" }, { "code": null, "e": 27772, "s": 27761, "text": "R Programs" }, { "code": null, "e": 27870, "s": 27772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27879, "s": 27870, "text": "Comments" }, { "code": null, "e": 27892, "s": 27879, "text": "Old Comments" }, { "code": null, "e": 27944, "s": 27892, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27982, "s": 27944, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28017, "s": 27982, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28075, "s": 28017, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28099, "s": 28075, "text": "Data Visualization in R" }, { "code": null, "e": 28157, "s": 28099, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28206, "s": 28157, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28249, "s": 28206, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28299, "s": 28249, "text": "How to filter R dataframe by multiple conditions?" } ]
What is TYPE_SCROLL_SENSITIVE ResultSet in JDBC?
This represents is a scrollable ResultSet i.e. the cursor moves in forward or backward directions. This type of ResultSet is sensitive to the changes that are made in the database i.e. the modifications done in the database are reflected in the ResultSet. Which means if we have established a connection with a database using a JDBC program and retrieved a ResultSet holding all the records in a table named SampleTable. Meanwhile, if we have added some more records to the table (after retrieving the ResultSet), these recent changes will be reflected in the ResultSet object we previously obtained. Following is an example which demonstrates how to create the TYPE_SCROLL_SENSITIVE result set. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class ScrollSensitive { public static void main(String[] args) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String url = "jdbc:mysql://localhost/testdb"; Connection con = DriverManager.getConnection(url, "root", "password"); //Creating a Statement object Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); stmt.setFetchSize(1); } }
[ { "code": null, "e": 1318, "s": 1062, "text": "This represents is a scrollable ResultSet i.e. the cursor moves in forward or backward directions. This type of ResultSet is sensitive to the changes that are made in the database i.e. the modifications done in the database are reflected in the ResultSet." }, { "code": null, "e": 1663, "s": 1318, "text": "Which means if we have established a connection with a database using a JDBC program and retrieved a ResultSet holding all the records in a table named SampleTable. Meanwhile, if we have added some more records to the table (after retrieving the ResultSet), these recent changes will be reflected in the ResultSet object we previously obtained." }, { "code": null, "e": 1758, "s": 1663, "text": "Following is an example which demonstrates how to create the TYPE_SCROLL_SENSITIVE result set." }, { "code": null, "e": 2430, "s": 1758, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class ScrollSensitive {\n public static void main(String[] args) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String url = \"jdbc:mysql://localhost/testdb\";\n Connection con = DriverManager.getConnection(url, \"root\", \"password\");\n //Creating a Statement object\n Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);\n stmt.setFetchSize(1);\n }\n}" } ]
Java Program to Compute the Sum of Numbers in a List Using Recursion
26 May, 2022 ArrayList is a part of the Collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. Illustration: Input : [1, 3, 9] Output : 13 Here the naive method can be to add up elements of List and maintain a counter in which sum is stored while traversing List. The step ahead method can be to convert the List to the array and do the same. Now more optimal method can be to use recursion while doing so in which subpart of List or array is automatically computed by recursion principles. Here this optimal approach is described and implemented as shown. Methods: Converting ArrayList to arrays and using recursion principles over arrays.Using ArrayList.add() method Converting ArrayList to arrays and using recursion principles over arrays. Using ArrayList.add() method Method 1: Converting ArrayList to arrays and using recursion principles over arrays. It is achieved by converting ArrayList to arrays and using recursion principles over arrays. Recursion in the list to array conversion and computing sum of elements using add() method. Approach: Take the elements of the list as input from the user.Convert the list into an array of the same size.Add the elements to it.Compute the sum of arrays using recursion principles. Take the elements of the list as input from the user. Convert the list into an array of the same size. Add the elements to it. Compute the sum of arrays using recursion principles. Example Java // Java Program to Compute Sum of Numbers in a List// by converting to arrays and applying recursion // Importing java input/output classesimport java.io.*;// Importing List and ArrayList class from// java.util packageimport java.util.ArrayList;import java.util.List; // Classpublic class GFG { // Method to calculate sum recursively public static int sumOfArray(Integer[] a, int n) { if (n == 0) return a[n]; else return a[n] + sumOfArray(a, n - 1); } // Method- main() public static void main(String[] args) { // Creating a List of Integer type // Declaring an object- 'al' List<Integer> al = new ArrayList<Integer>(); // Adding elements to the List // Custom inputs al.add(1); al.add(2); al.add(3); al.add(4); al.add(5); // Converting above List to array // using toArray() method Integer a[] = new Integer[al.size()]; al.toArray(a); // Display message System.out.print("Elements in List : "); // Printing array of objects // using for each loop for (Integer obj : a) { System.out.print(obj + " "); } // Recursion math to calculate sum snd // storing sum in a variable int sum = sumOfArray(a, a.length - 1); // Next line System.out.println(); // Print the sum returned above System.out.println("Sum of elements : " + sum); }} Elements in List : 1 2 3 4 5 Sum of elements : 15 Method 2: Using ArrayList.add() method This method appends the specified element to the end of this list Syntax: public boolean add(E element) ; Parameter: Object to be appended to this list. Return Type: It will always return a boolean true and the signature is as so because other classes in collections family need a return type. Exceptions: NA Example: Java // Java Program to Compute the Sum of Numbers in a List// using Recursion via ArrayList.add() method // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG{ // Declaring variables outside main class int sum = 0, j = 0; // Main driver method public static void main(String[]args) { /* // Taking the input from the user int n; Scanner s = new Scanner(System.in); // Display message System.out.print("Enter the no. of elements :"); // Reading integer elements using nextInt() method n = s.nextInt(); // Display message System.out.println("Enter all the elements you want:"); */ // Creating an object of List of Integer type List < Integer > list = new ArrayList < Integer > (); // Adding elements to object of List // Custom inputs to show sum list.add(10); list.add(90); list.add(30); list.add(40); list.add(70); list.add(100); list.add(0); System.out.println("Elements in List : " + list); /* // If input is through user than // For loop to add elements inside List for (int i = 0; i < n; i++) { // Adding integer elements in the list list.add(s.nextInt()); } */ // Converting List to Array Integer[] a = list.toArray(new Integer[list.size()]); // Initialising object of Main class GFG elem = new GFG(); // Finding sum of elements in array // via add() method using recursion int x = elem.add(a, a.length, 0); // Print the sum of array/elements initially in List System.out.println("Sum of elements in List :" + x); } // add() method to add elements in array // using recursion int add(Integer arr[], int n, int i) { if(i < n) { return arr[i] + add(arr, n, ++i); } else { return 0; } }} Elements in List : [10, 90, 30, 40, 70, 100, 0] Sum of elements in List :340 surinderdawra388 adnanirshad158 simmytarika5 simranarora5sos Java-Collections java-list Picked Java Java Programs Java Java-Collections 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 Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 54, "s": 26, "text": "\n26 May, 2022" }, { "code": null, "e": 354, "s": 54, "text": "ArrayList is a part of the Collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package. " }, { "code": null, "e": 368, "s": 354, "text": "Illustration:" }, { "code": null, "e": 401, "s": 368, "text": "Input : [1, 3, 9] \nOutput : 13" }, { "code": null, "e": 820, "s": 401, "text": "Here the naive method can be to add up elements of List and maintain a counter in which sum is stored while traversing List. The step ahead method can be to convert the List to the array and do the same. Now more optimal method can be to use recursion while doing so in which subpart of List or array is automatically computed by recursion principles. Here this optimal approach is described and implemented as shown. " }, { "code": null, "e": 829, "s": 820, "text": "Methods:" }, { "code": null, "e": 932, "s": 829, "text": "Converting ArrayList to arrays and using recursion principles over arrays.Using ArrayList.add() method" }, { "code": null, "e": 1007, "s": 932, "text": "Converting ArrayList to arrays and using recursion principles over arrays." }, { "code": null, "e": 1036, "s": 1007, "text": "Using ArrayList.add() method" }, { "code": null, "e": 1122, "s": 1036, "text": "Method 1: Converting ArrayList to arrays and using recursion principles over arrays. " }, { "code": null, "e": 1307, "s": 1122, "text": "It is achieved by converting ArrayList to arrays and using recursion principles over arrays. Recursion in the list to array conversion and computing sum of elements using add() method." }, { "code": null, "e": 1318, "s": 1307, "text": "Approach: " }, { "code": null, "e": 1496, "s": 1318, "text": "Take the elements of the list as input from the user.Convert the list into an array of the same size.Add the elements to it.Compute the sum of arrays using recursion principles." }, { "code": null, "e": 1550, "s": 1496, "text": "Take the elements of the list as input from the user." }, { "code": null, "e": 1599, "s": 1550, "text": "Convert the list into an array of the same size." }, { "code": null, "e": 1623, "s": 1599, "text": "Add the elements to it." }, { "code": null, "e": 1677, "s": 1623, "text": "Compute the sum of arrays using recursion principles." }, { "code": null, "e": 1685, "s": 1677, "text": "Example" }, { "code": null, "e": 1690, "s": 1685, "text": "Java" }, { "code": "// Java Program to Compute Sum of Numbers in a List// by converting to arrays and applying recursion // Importing java input/output classesimport java.io.*;// Importing List and ArrayList class from// java.util packageimport java.util.ArrayList;import java.util.List; // Classpublic class GFG { // Method to calculate sum recursively public static int sumOfArray(Integer[] a, int n) { if (n == 0) return a[n]; else return a[n] + sumOfArray(a, n - 1); } // Method- main() public static void main(String[] args) { // Creating a List of Integer type // Declaring an object- 'al' List<Integer> al = new ArrayList<Integer>(); // Adding elements to the List // Custom inputs al.add(1); al.add(2); al.add(3); al.add(4); al.add(5); // Converting above List to array // using toArray() method Integer a[] = new Integer[al.size()]; al.toArray(a); // Display message System.out.print(\"Elements in List : \"); // Printing array of objects // using for each loop for (Integer obj : a) { System.out.print(obj + \" \"); } // Recursion math to calculate sum snd // storing sum in a variable int sum = sumOfArray(a, a.length - 1); // Next line System.out.println(); // Print the sum returned above System.out.println(\"Sum of elements : \" + sum); }}", "e": 3189, "s": 1690, "text": null }, { "code": null, "e": 3241, "s": 3189, "text": "Elements in List : 1 2 3 4 5 \nSum of elements : 15" }, { "code": null, "e": 3280, "s": 3241, "text": "Method 2: Using ArrayList.add() method" }, { "code": null, "e": 3346, "s": 3280, "text": "This method appends the specified element to the end of this list" }, { "code": null, "e": 3354, "s": 3346, "text": "Syntax:" }, { "code": null, "e": 3386, "s": 3354, "text": "public boolean add(E element) ;" }, { "code": null, "e": 3433, "s": 3386, "text": "Parameter: Object to be appended to this list." }, { "code": null, "e": 3574, "s": 3433, "text": "Return Type: It will always return a boolean true and the signature is as so because other classes in collections family need a return type." }, { "code": null, "e": 3589, "s": 3574, "text": "Exceptions: NA" }, { "code": null, "e": 3598, "s": 3589, "text": "Example:" }, { "code": null, "e": 3603, "s": 3598, "text": "Java" }, { "code": "// Java Program to Compute the Sum of Numbers in a List// using Recursion via ArrayList.add() method // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG{ // Declaring variables outside main class int sum = 0, j = 0; // Main driver method public static void main(String[]args) { /* // Taking the input from the user int n; Scanner s = new Scanner(System.in); // Display message System.out.print(\"Enter the no. of elements :\"); // Reading integer elements using nextInt() method n = s.nextInt(); // Display message System.out.println(\"Enter all the elements you want:\"); */ // Creating an object of List of Integer type List < Integer > list = new ArrayList < Integer > (); // Adding elements to object of List // Custom inputs to show sum list.add(10); list.add(90); list.add(30); list.add(40); list.add(70); list.add(100); list.add(0); System.out.println(\"Elements in List : \" + list); /* // If input is through user than // For loop to add elements inside List for (int i = 0; i < n; i++) { // Adding integer elements in the list list.add(s.nextInt()); } */ // Converting List to Array Integer[] a = list.toArray(new Integer[list.size()]); // Initialising object of Main class GFG elem = new GFG(); // Finding sum of elements in array // via add() method using recursion int x = elem.add(a, a.length, 0); // Print the sum of array/elements initially in List System.out.println(\"Sum of elements in List :\" + x); } // add() method to add elements in array // using recursion int add(Integer arr[], int n, int i) { if(i < n) { return arr[i] + add(arr, n, ++i); } else { return 0; } }}", "e": 5427, "s": 3603, "text": null }, { "code": null, "e": 5504, "s": 5427, "text": "Elements in List : [10, 90, 30, 40, 70, 100, 0]\nSum of elements in List :340" }, { "code": null, "e": 5521, "s": 5504, "text": "surinderdawra388" }, { "code": null, "e": 5536, "s": 5521, "text": "adnanirshad158" }, { "code": null, "e": 5549, "s": 5536, "text": "simmytarika5" }, { "code": null, "e": 5565, "s": 5549, "text": "simranarora5sos" }, { "code": null, "e": 5582, "s": 5565, "text": "Java-Collections" }, { "code": null, "e": 5592, "s": 5582, "text": "java-list" }, { "code": null, "e": 5599, "s": 5592, "text": "Picked" }, { "code": null, "e": 5604, "s": 5599, "text": "Java" }, { "code": null, "e": 5618, "s": 5604, "text": "Java Programs" }, { "code": null, "e": 5623, "s": 5618, "text": "Java" }, { "code": null, "e": 5640, "s": 5623, "text": "Java-Collections" }, { "code": null, "e": 5738, "s": 5640, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5789, "s": 5738, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5820, "s": 5789, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5839, "s": 5820, "text": "Interfaces in Java" }, { "code": null, "e": 5869, "s": 5839, "text": "HashMap in Java with Examples" }, { "code": null, "e": 5887, "s": 5869, "text": "ArrayList in Java" }, { "code": null, "e": 5915, "s": 5887, "text": "Initializing a List in Java" }, { "code": null, "e": 5941, "s": 5915, "text": "Java Programming Examples" }, { "code": null, "e": 5985, "s": 5941, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 6019, "s": 5985, "text": "Convert Double to Integer in Java" } ]
Composite Method – Python Design Patterns
10 Feb, 2020 Composite Method is a Structural Design Pattern which describes a group of objects that is treated the same way as a single instance of the same type of the objects. The purpose of the Composite Method is to Compose objects into Tree type structures to represent the whole-partial hierarchies. One of the main advantages of using the Composite Method is that first, it allows you to compose the objects into the Tree Structure and then work with these structures as an individual object or an entity. Composite-Tree-Structure The operations you can perform on all the composite objects often have the least common denominator relationship. Participants-Composite-Method Component: Component helps in implementing the default behavior for the interface common to all classes as appropriate. It declares the interface of the objects in the composition and for accessing and managing its child components. Leaf: It defines the behavior for primitive objects in the composition. It represents the leaf object in the composition. Composite: It stores the child component and implements child related operations in the component interface. Client: It is used to manipulate the objects in the composition through the component interface. Imagine we are studying an organizational structure which consists of General Managers, Managers, and Developers. A General Manager may have many Managers working under him and a Manager may have many developers under him.Suppose, you have to determine the total salary of all the employees. So, How would you determine that ? An ordinary developer will definitely try the direct approach, go over each employee and calculate the total salary. Looks easy? not so when it comes to implementation. Because we have to know the classes of all the employees General Manager, Manager, and Developers.It seems even an impossible task to calculate through a direct approach in Tree-based structure. One of the best solutions to the above-described problem is using Composite Method by working with a common interface that declares a method for calculating the total salary.We will generally use the Composite Method whenever we have “composites that contain components, each of which could be a composite”. Composite-Running-Example """Here we attempt to make an organizational hierarchy with sub-organization, which may have subsequent sub-organizations, such as:GeneralManager [Composite] Manager1 [Composite] Developer11 [Leaf] Developer12 [Leaf] Manager2 [Composite] Developer21 [Leaf] Developer22 [Leaf]""" class LeafElement: '''Class representing objects at the bottom or Leaf of the hierarchy tree.''' def __init__(self, *args): ''''Takes the first positional argument and assigns to member variable "position".''' self.position = args[0] def showDetails(self): '''Prints the position of the child element.''' print("\t", end ="") print(self.position) class CompositeElement: '''Class representing objects at any level of the hierarchy tree except for the bottom or leaf level. Maintains the child objects by adding and removing them from the tree structure.''' def __init__(self, *args): '''Takes the first positional argument and assigns to member variable "position". Initializes a list of children elements.''' self.position = args[0] self.children = [] def add(self, child): '''Adds the supplied child element to the list of children elements "children".''' self.children.append(child) def remove(self, child): '''Removes the supplied child element from the list of children elements "children".''' self.children.remove(child) def showDetails(self): '''Prints the details of the component element first. Then, iterates over each of its children, prints their details by calling their showDetails() method.''' print(self.position) for child in self.children: print("\t", end ="") child.showDetails() """main method""" if __name__ == "__main__": topLevelMenu = CompositeElement("GeneralManager") subMenuItem1 = CompositeElement("Manager1") subMenuItem2 = CompositeElement("Manager2") subMenuItem11 = LeafElement("Developer11") subMenuItem12 = LeafElement("Developer12") subMenuItem21 = LeafElement("Developer21") subMenuItem22 = LeafElement("Developer22") subMenuItem1.add(subMenuItem11) subMenuItem1.add(subMenuItem12) subMenuItem2.add(subMenuItem22) subMenuItem2.add(subMenuItem22) topLevelMenu.add(subMenuItem1) topLevelMenu.add(subMenuItem2) topLevelMenu.showDetails() Output: GeneralManager Manager1 Developer11 Developer12 Manager2 Developer22 Developer22 Following is the general class diagram for the Composite Method: Class-diagram-Composite-Method Open/Closed Principle: As the introduction of new elements, classes and interfaces is allowed into the application without breaking the existing code of the client, it definitely follows the Open/Closed Principle Less Memory Consumption: Here we have to create less number of objects as compared to the ordinary method, which surely reduces the memory usage and also manages to keep us away from errors related to memory Improved Execution Time: Creating an object in Python doesn’t take much time but still we can reduce the execution time of our program by sharing objects. Flexibility: It provides flexibility of structure with manageable class or interface as it defines class hierarchies that contains primitive and complex objects. Restriction on the Components: Composite Method makes it harder to restrict the type of components of a composite. It is not preferred to use when you don’t want to represent a full or partial hierarchy of the objects. General Tree Structure: The Composite Method will produce the overall general tree, once the structure of the tree is defined. Type-System of Language: As it is not allowed to use the type-system of the programming language, our program must depend on the run-time checks to apply the constraints. Requirement of Nested Tree Structure: It is highly preferred to use Composite Method when you are need of producing the nested structure of tree which again include the leaves objects and other object containers. Graphics Editor: We can define a shape into types either it is simple for ex – a straight line or complex for ex – a rectangle. Since all the shapes have many common operations, such as rendering the shape to screen so composite pattern can be used to enable the program to deal with all shapes uniformly. Further read: Composite Method in Java python-design-pattern 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 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 Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Feb, 2020" }, { "code": null, "e": 322, "s": 28, "text": "Composite Method is a Structural Design Pattern which describes a group of objects that is treated the same way as a single instance of the same type of the objects. The purpose of the Composite Method is to Compose objects into Tree type structures to represent the whole-partial hierarchies." }, { "code": null, "e": 529, "s": 322, "text": "One of the main advantages of using the Composite Method is that first, it allows you to compose the objects into the Tree Structure and then work with these structures as an individual object or an entity." }, { "code": null, "e": 554, "s": 529, "text": "Composite-Tree-Structure" }, { "code": null, "e": 668, "s": 554, "text": "The operations you can perform on all the composite objects often have the least common denominator relationship." }, { "code": null, "e": 698, "s": 668, "text": "Participants-Composite-Method" }, { "code": null, "e": 931, "s": 698, "text": "Component: Component helps in implementing the default behavior for the interface common to all classes as appropriate. It declares the interface of the objects in the composition and for accessing and managing its child components." }, { "code": null, "e": 1053, "s": 931, "text": "Leaf: It defines the behavior for primitive objects in the composition. It represents the leaf object in the composition." }, { "code": null, "e": 1162, "s": 1053, "text": "Composite: It stores the child component and implements child related operations in the component interface." }, { "code": null, "e": 1259, "s": 1162, "text": "Client: It is used to manipulate the objects in the composition through the component interface." }, { "code": null, "e": 1586, "s": 1259, "text": "Imagine we are studying an organizational structure which consists of General Managers, Managers, and Developers. A General Manager may have many Managers working under him and a Manager may have many developers under him.Suppose, you have to determine the total salary of all the employees. So, How would you determine that ?" }, { "code": null, "e": 1950, "s": 1586, "text": "An ordinary developer will definitely try the direct approach, go over each employee and calculate the total salary. Looks easy? not so when it comes to implementation. Because we have to know the classes of all the employees General Manager, Manager, and Developers.It seems even an impossible task to calculate through a direct approach in Tree-based structure." }, { "code": null, "e": 2258, "s": 1950, "text": "One of the best solutions to the above-described problem is using Composite Method by working with a common interface that declares a method for calculating the total salary.We will generally use the Composite Method whenever we have “composites that contain components, each of which could be a composite”." }, { "code": null, "e": 2284, "s": 2258, "text": "Composite-Running-Example" }, { "code": "\"\"\"Here we attempt to make an organizational hierarchy with sub-organization, which may have subsequent sub-organizations, such as:GeneralManager [Composite] Manager1 [Composite] Developer11 [Leaf] Developer12 [Leaf] Manager2 [Composite] Developer21 [Leaf] Developer22 [Leaf]\"\"\" class LeafElement: '''Class representing objects at the bottom or Leaf of the hierarchy tree.''' def __init__(self, *args): ''''Takes the first positional argument and assigns to member variable \"position\".''' self.position = args[0] def showDetails(self): '''Prints the position of the child element.''' print(\"\\t\", end =\"\") print(self.position) class CompositeElement: '''Class representing objects at any level of the hierarchy tree except for the bottom or leaf level. Maintains the child objects by adding and removing them from the tree structure.''' def __init__(self, *args): '''Takes the first positional argument and assigns to member variable \"position\". Initializes a list of children elements.''' self.position = args[0] self.children = [] def add(self, child): '''Adds the supplied child element to the list of children elements \"children\".''' self.children.append(child) def remove(self, child): '''Removes the supplied child element from the list of children elements \"children\".''' self.children.remove(child) def showDetails(self): '''Prints the details of the component element first. Then, iterates over each of its children, prints their details by calling their showDetails() method.''' print(self.position) for child in self.children: print(\"\\t\", end =\"\") child.showDetails() \"\"\"main method\"\"\" if __name__ == \"__main__\": topLevelMenu = CompositeElement(\"GeneralManager\") subMenuItem1 = CompositeElement(\"Manager1\") subMenuItem2 = CompositeElement(\"Manager2\") subMenuItem11 = LeafElement(\"Developer11\") subMenuItem12 = LeafElement(\"Developer12\") subMenuItem21 = LeafElement(\"Developer21\") subMenuItem22 = LeafElement(\"Developer22\") subMenuItem1.add(subMenuItem11) subMenuItem1.add(subMenuItem12) subMenuItem2.add(subMenuItem22) subMenuItem2.add(subMenuItem22) topLevelMenu.add(subMenuItem1) topLevelMenu.add(subMenuItem2) topLevelMenu.showDetails()", "e": 4969, "s": 2284, "text": null }, { "code": null, "e": 4977, "s": 4969, "text": "Output:" }, { "code": null, "e": 5099, "s": 4977, "text": "GeneralManager\n Manager1\n Developer11\n Developer12\n Manager2\n Developer22\n Developer22\n" }, { "code": null, "e": 5164, "s": 5099, "text": "Following is the general class diagram for the Composite Method:" }, { "code": null, "e": 5195, "s": 5164, "text": "Class-diagram-Composite-Method" }, { "code": null, "e": 5408, "s": 5195, "text": "Open/Closed Principle: As the introduction of new elements, classes and interfaces is allowed into the application without breaking the existing code of the client, it definitely follows the Open/Closed Principle" }, { "code": null, "e": 5616, "s": 5408, "text": "Less Memory Consumption: Here we have to create less number of objects as compared to the ordinary method, which surely reduces the memory usage and also manages to keep us away from errors related to memory" }, { "code": null, "e": 5771, "s": 5616, "text": "Improved Execution Time: Creating an object in Python doesn’t take much time but still we can reduce the execution time of our program by sharing objects." }, { "code": null, "e": 5933, "s": 5771, "text": "Flexibility: It provides flexibility of structure with manageable class or interface as it defines class hierarchies that contains primitive and complex objects." }, { "code": null, "e": 6152, "s": 5933, "text": "Restriction on the Components: Composite Method makes it harder to restrict the type of components of a composite. It is not preferred to use when you don’t want to represent a full or partial hierarchy of the objects." }, { "code": null, "e": 6279, "s": 6152, "text": "General Tree Structure: The Composite Method will produce the overall general tree, once the structure of the tree is defined." }, { "code": null, "e": 6450, "s": 6279, "text": "Type-System of Language: As it is not allowed to use the type-system of the programming language, our program must depend on the run-time checks to apply the constraints." }, { "code": null, "e": 6663, "s": 6450, "text": "Requirement of Nested Tree Structure: It is highly preferred to use Composite Method when you are need of producing the nested structure of tree which again include the leaves objects and other object containers." }, { "code": null, "e": 6969, "s": 6663, "text": "Graphics Editor: We can define a shape into types either it is simple for ex – a straight line or complex for ex – a rectangle. Since all the shapes have many common operations, such as rendering the shape to screen so composite pattern can be used to enable the program to deal with all shapes uniformly." }, { "code": null, "e": 7008, "s": 6969, "text": "Further read: Composite Method in Java" }, { "code": null, "e": 7030, "s": 7008, "text": "python-design-pattern" }, { "code": null, "e": 7037, "s": 7030, "text": "Python" }, { "code": null, "e": 7135, "s": 7037, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7153, "s": 7135, "text": "Python Dictionary" }, { "code": null, "e": 7195, "s": 7153, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7217, "s": 7195, "text": "Enumerate() in Python" }, { "code": null, "e": 7243, "s": 7217, "text": "Python String | replace()" }, { "code": null, "e": 7275, "s": 7243, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 7304, "s": 7275, "text": "*args and **kwargs in Python" }, { "code": null, "e": 7331, "s": 7304, "text": "Python Classes and Objects" }, { "code": null, "e": 7361, "s": 7331, "text": "Iterate over a list in Python" }, { "code": null, "e": 7397, "s": 7361, "text": "Convert integer to string in Python" } ]
Implementation of file allocation methods using vectors
05 Oct, 2021 Prerequisite: File Allocation Methods Different File Allocation methods: 1. Contiguous File Allocation Methods: This is a type of allocation in which a file occupies contiguous blocks of a given memory. This type of allocation is fastest because we can access any part of the file just by adding it to the starting index of the file. However, this allocation is not useful when you have to insert a file whose size is greater than the greatest empty slot available. Below is the implementation of Contiguous File Allocation which follows First-Fit Allocation: C++ // C++ implementation of the Contiguous// File Allocation which follow First-Fit// algorithm#include <iostream>#include <vector>using namespace std; // File Classclass File {public: // Name of File string filename; // Size of file size_t size; // Partition no. is which part of // file is present at a particular // block of memory int partition;};class Block { // If Block is occupied // by a file or not bool occupied = false; // File of the block File file; public: // This function will set file into // current block and set occupied flag void set_file(File file) { this->file = file; occupied = true; } // This function will return // filename of given block string get_file_name() { return file.filename; } // This function will return // partition number of file int get_file_partition_no() { return file.partition; } // This function will return // if the block is empty or not bool is_empty() { return !occupied; } // This function will set the occupied // flag as false meaning that it will // free the given block void set_empty() { occupied = false; }}; // Function to return the number of// empty Blocks from given memoryint get_empty_count(vector<Block> memory){ int sum = 0; vector<Block>::iterator slot; // Count no. of empty blocks in // given memory for (slot = memory.begin(); slot != memory.end(); slot++) { sum += (*slot).is_empty(); } return sum;} // Function will return if the file// exists in a given memorybool file_exists(vector<Block> memory, string name){ vector<Block>::iterator slot; for (slot = memory.begin(); slot != memory.end(); slot++) { if (!(*slot).is_empty() && (*slot).get_file_name() == name) { return true; } } return false;} // Function will set the file in the memory// this will follow first fit allocationvoid set_contiguous_memory(vector<Block>* memory, vector<int>* index, File file){ bool avail = false; int i = 0, count = 0, main_index; vector<Block>::iterator slot; // Check if the file already exists if (file_exists((*memory), file.filename)) cout << "File already exists" << endl; else { // Iterate through full memory for (slot = (*memory).begin(); slot != (*memory).end(); slot++) { // Check if there are // contiguous Blocks available if ((*slot).is_empty()) { count++; // This if condition will note // the 1st index for each // Block empty if (count == 1) main_index = i; // Check if contiguous // Blocks are available, // it will set our flag // avail as true and break if (count == file.size) { avail = true; break; } } // Else if there is even a // single non-empty block // in between we will set // count as 0 else { count = 0; } i++; } // If our flag is set, // this condition will set // our file if (avail) { // Here starting index of // our given file will be // pushed in index page (*index).push_back(main_index); // Utilize count variable // again for setting file // partition count = 0; for (int i = main_index; i < main_index + file.size; i++) { file.partition = count; (*memory).at(i).set_file(file); count++; } cout << "File " << file.filename << " has been successfully" << " allocated" << endl; } else { cout << "The size of the file is" << " greater than" << endl; cout << "the greatest slot available" << " in contiguous memory" << endl; cout << "Hence, File " << file.filename << " cannot be allocated" << endl; } }} // Function to Delete file from memoryvoid delete_contiguous_mem(vector<Block>* memory, vector<int>* index_page, string file){ vector<int>::iterator slot; int index, i = 0, main_index; // Check if the file exist or not if (!file_exists((*memory), file)) cout << "File does not exist" << endl; else { // Iterate all the indexes for (slot = (*index_page).begin(); slot != (*index_page).end(); slot++) { // If specified file is found, // this condition will // set the value of index no. // in index and // main_index will have starting // location of // file in memory if ((*memory).at(*slot).get_file_name() == file) { index = i; main_index = (*slot); break; } i++; } // Iterate through the main index until // filename is similar to specified // filename and status of Block is // not empty i = main_index; while (i < (*memory).size() && (*memory).at(i).get_file_name() == file && !(*memory).at(i).is_empty()) { // Set the Block as empty (*memory).at(i).set_empty(); i++; } // Erase entry of file from index page (*index_page).erase((*index_page).begin() + index); cout << "File " << file << " has been successfully deleted" << endl; }} // Function to display main index pagevoid show_contiguous_index(vector<Block> memory, vector<int> index_page){ int max = 9, i, j; // Iterator vector<Block>::iterator slot; // File Name string fname; // Iterate through all index pages for (i = 0; i < index_page.size(); i++) { if (memory.at(index_page.at(i)) .get_file_name() .length() > max) { // Get the length of file max = memory.at(index_page .at(i)) .get_file_name() .length(); cout << "+" << string(max + 2, '-') << "+---------------+----" << "---------+-----------" << "-------+\n|" << string(max / 2 + max % 2 - 4, ' ') << "File Name" << string(max / 2 - 3, ' ') << "| Start Address | " << " End Address | Size" << " of the file |\n+" << string(max + 2, '-') << "+---------------+-------" << "------+------------------+" << endl; } } // Iterate index_pages for (i = 0; i < index_page.size(); i++) { cout << "|" << string(max / 2 + max % 2 - memory .at(index_page .at(i)) .get_file_name() .length() / 2 - memory .at(index_page .at(i)) .get_file_name() .length() % 2 + 1, ' ') << memory.at(index_page.at(i)) .get_file_name() << string(max / 2 - memory .at(index_page .at(i)) .get_file_name() .length() / 2 + 1, ' ') << "|" << string(8 - to_string(index_page .at(i)) .length() / 2 - to_string(index_page .at(i)) .length() % 2, ' ') << index_page.at(i) << string(7 - to_string(index_page .at(i)) .length() / 2, ' ') << "|"; j = index_page .at(i); fname = memory .at(j) .get_file_name(); // Till j is less than memory size while (j < memory.size() && !memory .at(j) .is_empty() && memory .at(j) .get_file_name() == fname) { j++; } j -= 1; // Print the index pages details cout << string(7 - to_string(j) .length() / 2 - to_string(j) .length() % 2, ' ') << j << string(6 - to_string(j) .length() / 2, ' ') << "|" << string(9 - to_string(j - index_page .at(i) + 1) .length() / 2 - to_string(j - index_page .at(i) + 1) .length() % 2, ' ') << j - index_page.at(i) + 1 << string(9 - to_string(j - index_page .at(i) + 1) .length() / 2, ' ') << "|" << endl; } cout << "+" << string(max + 2, '-') << "+---------------+------" << "-------+------------------+" << endl;} // Function to display index of each// partition of specified filevoid show_contiguous_indexes(vector<Block> memory, vector<int> index_page, string filename){ int index, i; // Iterator vector<int>::iterator slot; // If file exist then display file // index and partition if (file_exists(memory, filename)) { cout << "File Name = " << filename << "\n+------------------+----" << "--------------+"; cout << "\n| Current Location |" << " Partition Number |"; cout << "\n+------------------+-" << " -----------------+\n"; // Iterate through all the index for (slot = index_page.begin(); slot != index_page.end(); slot++) { if (memory.at(*slot).get_file_name() == filename) { index = (*slot); break; } } // Loop till memory size is greater than // index and file is allocated // in them while (index < memory.size() && memory .at(index) .get_file_name() == filename && !memory .at(index) .is_empty()) { cout << "|" << string(9 - to_string(index) .length() / 2 - to_string(index) .length() % 2, ' ') << index << string(9 - to_string(index) .length() / 2, ' ') << "|" << string(9 - to_string(memory .at(index) .get _file _partition _no()) .length() / 2 - to_string(memory .at(index) .get_file _partition _no()) .length() % 2, ' ') << memory .at(index) .get_file_partition_no() << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2, ' ') << "|" << endl; index++; } cout << "+------------------+" << "------------------+" << endl; } else cout << "File does not exist " << "in given memory" << endl;} // Driver Codeint main(){ // Declare memory of size 16 Blocks vector<Block> memory(16); // Declare index page vector<int> index_page; File temp; cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Set the data temp.filename = "home.txt"; temp.size = 5; set_contiguous_memory(&memory, &index_page, temp); temp.filename = "Report.docx"; temp.size = 6; set_contiguous_memory(&memory, &index_page, temp); temp.filename = "new_img.png"; temp.size = 3; set_contiguous_memory(&memory, &index_page, temp); temp.filename = "test.cpp"; temp.size = 2; set_contiguous_memory(&memory, &index_page, temp); cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Function call to show all the // memory allocation show_contiguous_index(memory, index_page); cout << "Now we will check each partition of"; cout << " Report.docx and test.cpp before" << endl; cout << "deleting them to see" << " which locations "; cout << "are going to be set free" << " as our slots" << endl; // Function call to show all the // memory allocation show_contiguous_indexes(memory, index_page, "Report.docx"); // Function call to show all the // memory allocation show_contiguous_indexes(memory, index_page, "test.cpp"); // Now delete Report.docx & test.cpp delete_contiguous_mem(&memory, &index_page, "Report.docx"); delete_contiguous_mem(&memory, &index_page, "test.cpp"); cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Function call to show all the // memory allocation show_contiguous_index(memory, index_page); // Creating hello.jpeg file now // and setting it to memory temp.filename = "hello.jpeg"; temp.size = 8; set_contiguous_memory(&memory, &index_page, temp); cout << "Check index page: " << endl; // Function call to show all the // memory allocation show_contiguous_index(memory, index_page);} Remaining memory :- 16 File home.txt has been successfully allocated File Report.docx has been successfully allocated File new_img.png has been successfully allocated File test.cpp has been successfully allocated Remaining memory :- 0 +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 0 | 4 | 5 | | Report.docx | 5 | 10 | 6 | | new_img.png | 11 | 13 | 3 | | test.cpp | 14 | 15 | 2 | +-------------+---------------+-------------+------------------+ Now we will check each partition of Report.docx and test.cpp before deleting them to see which locations are going to be set free as our slots File Name = Report.docx +------------------+------------------+ | Current Location | Partition Number | +------------------+------------------+ | 5 | 0 | | 6 | 1 | | 7 | 2 | | 8 | 3 | | 9 | 4 | | 10 | 5 | +------------------+------------------+ File Name = test.cpp +------------------+------------------+ | Current Location | Partition Number | +------------------+------------------+ | 14 | 0 | | 15 | 1 | +------------------+------------------+ File Report.docx has been successfully deleted File test.cpp has been successfully deleted Remaining memory:- 8 +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 0 | 4 | 5 | | new_img.png | 11 | 13 | 3 | +-------------+---------------+-------------+------------------+ The size of the file is greater than the greatest slot available in contiguous memory Hence, File hello.jpeg cannot be allocated Check index page: +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 0 | 4 | 5 | | new_img.png | 11 | 13 | 3 | +-------------+---------------+-------------+------------------+ 2. Indexed File Allocation Method: This is a type of allocation where we have 2 index pages, one is the main index page w.r.t all files and the other is a sub-indexed page which is w.r.t to a particular file. This type of allocation does not require a contiguous slot of memory since we are keeping track of each block individually. In the given program below, the vector of vectors is used for implementing the main index and sub-index. Below is the implementation for Indexed File Allocation Method: C++ // C++ implementation of the Indexed// File Allocation Method#include <iostream>#include <vector>using namespace std; // File Classclass File {public: // Name of File string filename; // Size of file size_t size; // Partition no. is which part of // file is present at a particular // block of memory int partition;}; // Block classclass Block { // If Block is occupied // by a file or not bool occupied = false; // File of the block File file; public: // This function will set file // into current block // and set occupied flag void set_file(File file) { this->file = file; occupied = true; } // This function will return // filename of given block string get_file_name() { return file.filename; } // This function will return // partition number of file int get_file_partition_no() { return file.partition; } // This function will return // if the block is empty or not bool is_empty() { return !occupied; } // This function will set the // occupied flag as false // meaning that it will free // the given block void set_empty() { occupied = false; }}; // Function to return the number of// empty Blocks from given memoryint get_empty_count(vector<Block> memory){ int sum = 0; vector<Block>::iterator slot; // count no. of empty blocks in // given memory for (slot = memory.begin(); slot != memory.end(); slot++) sum += (*slot).is_empty(); return sum;} // This function will generate random indexes// from empty memory slots to test indexingint generate_index(vector<Block> memory){ int index = -1; // Check if memory is full if (!get_empty_count(memory) == 0) { // Here it will generate index until // the memory block at generated // index is found to be empty do { index = rand() % memory.size(); index = abs(index); } while (!memory.at(index).is_empty()); } return index;} // This function will return if the file// exists in a given memorybool file_exists(vector<Block> memory, string name){ vector<Block>::iterator slot; for (slot = memory.begin(); slot != memory.end(); slot++) { if (!(*slot).is_empty() && (*slot).get_file_name() == name) { return true; } } return false;} // This function will set file in// memory and push index for each partition// and then push the file index to main// index vectorvoid set_indexed_memory(vector<Block>* memory, vector<vector<int> >* index_page, File file){ int index; // Declaration newpage to set the // index page for given file vector<int> newpage; // Check if file exists if (file_exists((*memory), file.filename)) cout << "File already exists" << endl; else { // Check if available memory is greater than // size of given file if (get_empty_count(*memory) >= file.size) { // Iterate till file size for (int i = 0; i < file.size; i++) { // Generate random empty index index = generate_index(*memory); // Set file partition file.partition = i; // Push the file to memory (*memory).at(index).set_file(file); // Push the index to newpage newpage.push_back(index); } // Push new index page into main // index page (*index_page).push_back(newpage); cout << "File " << file.filename << " has been successfully allocated" << endl; } else { cout << "Not enough available space" << endl; } }} // Function to delete a file from given// indexed memoryvoid delete_from_indexed_memory(vector<Block>* memory, vector<vector<int> >* index_page, string file){ vector<int>::iterator slot; vector<vector<int> >::iterator it; int index, i = 0; // Check if file exists if (file_exists((*memory), file)) { // Iterate main index for (it = (*index_page).begin(); it != (*index_page).end(); it++) { // Check for sub-index at // start location slot = (*it).begin(); // Check if it equals filename if ((*memory) .at(*slot) .get_file_name() == file) { // Set for index and break index = i; break; } i++; } // Set the memory flag as empty for (slot = (*index_page).at(index).begin(); slot != (*index_page).at(index).end(); slot++) (*memory).at(*slot).set_empty(); // Erase file index from main index page (*index_page) .erase((*index_page).begin() + index); cout << "File " << file << " has been successfully deleted" << endl; } else { cout << "File does not exist" << endl; }} // Function to display the main indexvoid show_indexed_index(vector<Block> memory, vector<vector<int> > index_page){ int max = 9; vector<Block>::iterator slot; vector<vector<int> >::iterator it; // Iterate over index pages for (it = index_page.begin(); it != index_page.end(); it++) { if (memory .at((*it) .at(0)) .get_file_name() .length() > max) { max = memory .at((*it) .at(0)) .get_file_name() .length(); cout << "+" << string(max + 2, '-') << "+---------------+----------" << "---+------------------+\n|" << string(max / 2 + max % 2 - 4, ' ') << "File Name" << string(max / 2 - 3, ' ') << "| Start Address | End Address" << " | Size of the file |\n+" << string(max + 2, '-') << "+---------------+------" << "-------+------------------+" << endl; } } // Iterate through all the index pages for (it = index_page.begin(); it != index_page.end(); it++) { cout << "|" << string(max / 2 + max % 2 - memory .at((*it) .at(0)) .get_file_name() .length() / 2 - memory .at((*it) .at(0)) .get_file_name() .length() % 2 + 1, ' ') << memory .at((*it) .at(0)) .get_file_name() << string(max / 2 - memory .at((*it) .at(0)) .get_file_name() .length() / 2 + 1, ' ') << "|" << string(8 - to_string((*it) .at(0)) .length() / 2 - to_string((*it) .at(0)) .length() % 2, ' ') << ((*it).at(0)) << string(7 - to_string((*it) .at(0)) .length() / 2, ' ') << "|" << string(7 - to_string((*it) .at((*it) .size() - 1)) .length() / 2 - to_string((*it) .at((*it) .size() - 1)) .length() % 2, ' ') << (*it) .at((*it).size() - 1) << string(6 - to_string((*it) .at((*it) .size() - 1)) .length() / 2, ' ') << "|" << string(9 - to_string((*it) .size()) .length() / 2 - to_string((*it) .size()) .length() % 2, ' ') << (*it).size() << string(9 - to_string((*it) .size()) .length() / 2, ' ') << "|" << endl; cout << "+" << string(max + 2, '-') << "+---------------+----------" << "---+------------------+" << endl; }} // Function to show each partition details// w.r.t filenamevoid show_indexed_indexes(vector<Block> memory, vector<vector<int> > index_page, string filename){ int index, i = 0, main_index; vector<vector<int> >::iterator slot; // Check if file exists if (file_exists(memory, filename)) { for (slot = index_page.begin(); slot != index_page.end(); slot++) { if (memory.at((*slot).at(0)).get_file_name() == filename) { main_index = i; break; } i++; } // Display File Details cout << "File Name = " << filename << endl; cout << "File page index at main index :- " << main_index << "\n+------------------+------------------+\n"; cout << "| Current Location | Partition Number |\n"; cout << "+------------------+------------------+\n"; for (i = 0; i < index_page.at(main_index).size(); i++) { index = index_page .at(main_index) .at(i); cout << "|" << string(9 - to_string(index) .length() / 2 - to_string(index) .length() % 2, ' ') << index << string(9 - to_string(index) .length() / 2, ' ') << "|" << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2 - to_string(memory .at(index) .get_file_partition_no()) .length() % 2, ' ') << memory .at(index) .get_file_partition_no() << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2, ' ') << "|" << endl; } cout << "+------------------+----" << "--------------+" << endl; } else { cout << "File does not exist" << endl; }} // Driver Codeint main(){ // Declare memory of size 16 Blocks vector<Block> memory(16); // Declare index page vector<vector<int> > index_page; File temp; cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Set the data temp.filename = "home.txt"; temp.size = 5; set_indexed_memory(&memory, &index_page, temp); temp.filename = "Report.docx"; temp.size = 6; set_indexed_memory(&memory, &index_page, temp); temp.filename = "new_img.png"; temp.size = 3; set_indexed_memory(&memory, &index_page, temp); temp.filename = "test.cpp"; temp.size = 2; set_indexed_memory(&memory, &index_page, temp); // Print the Remaining memory cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Print all the index memory show_indexed_index(memory, index_page); cout << "Now we will check each partition" << " for Report.docx and test.cpp" << " before deleting them" << endl; // Print all the index memory show_indexed_indexes(memory, index_page, "Report.docx"); // Print all the index memory show_indexed_indexes(memory, index_page, "test.cpp"); // Now delete Report.docx and test.cpp delete_from_indexed_memory(&memory, &index_page, "Report.docx"); delete_from_indexed_memory(&memory, &index_page, "test.cpp"); cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Print all the index memory show_indexed_index(memory, index_page); // Creating hello.jpeg file now // and setting it to memory temp.filename = "hello.jpeg"; temp.size = 8; set_indexed_memory(&memory, &index_page, temp); cout << "Check index page :- " << endl; // Print all the index memory show_indexed_index(memory, index_page); // Now we will see index for each partition of // hello.jpeg cout << "Remaining memory :- " << get_empty_count(memory) << endl; cout << "We will check each partition" << " for hello.jpeg to see "; cout << "if the locations of deleted files" << " are utilized or not" << endl; // Print all the index memory show_indexed_indexes(memory, index_page, "hello.jpeg"); memory.clear(); memory.shrink_to_fit(); index_page.clear(); index_page.shrink_to_fit(); return 0;} Remaining memory :- 16 File home.txt has been successfully allocated File Report.docx has been successfully allocated File new_img.png has been successfully allocated File test.cpp has been successfully allocated Remaining memory :- 0 +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 7 | 1 | 5 | +-------------+---------------+-------------+------------------+ | Report.docx | 15 | 2 | 6 | +-------------+---------------+-------------+------------------+ | new_img.png | 4 | 14 | 3 | +-------------+---------------+-------------+------------------+ | test.cpp | 5 | 0 | 2 | +-------------+---------------+-------------+------------------+ Now we will check each partition for Report.docx and test.cpp before deleting them File Name = Report.docx File page index at main index :- 1 +------------------+------------------+ | Current Location | Partition Number | +------------------+------------------+ | 15 | 0 | | 10 | 1 | | 12 | 2 | | 13 | 3 | | 11 | 4 | | 2 | 5 | +------------------+------------------+ File Name = test.cpp File page index at main index :- 3 +------------------+------------------+ | Current Location | Partition Number | +------------------+------------------+ | 5 | 0 | | 0 | 1 | +------------------+------------------+ File Report.docx has been successfully deleted File test.cpp has been successfully deleted Remaining memory :- 8 +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 7 | 1 | 5 | +-------------+---------------+-------------+------------------+ | new_img.png | 4 | 14 | 3 | +-------------+---------------+-------------+------------------+ File hello.jpeg has been successfully allocated Check index page :- +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 7 | 1 | 5 | +-------------+---------------+-------------+------------------+ | new_img.png | 4 | 14 | 3 | +-------------+---------------+-------------+------------------+ | hello.jpeg | 12 | 13 | 8 | +-------------+---------------+-------------+------------------+ Remaining memory :- 0 We will check each partition for hello.jpeg to see if the locations of deleted files are utilized or not File Name = hello.jpeg File page index at main index :- 2 +------------------+------------------+ | Current Location | Partition Number | +------------------+------------------+ | 12 | 0 | | 10 | 1 | | 11 | 2 | | 15 | 3 | | 0 | 4 | | 2 | 5 | | 5 | 6 | | 13 | 7 | +------------------+------------------+ 3. Linked File Allocation Method: This is a type of allocation where we linked all the partitions of a file to point to the memory location where the next partition of the file is placed. In the given program below, next will be allocated as -1 when the last partition is reached. Below is the implementation of Linked File Allocation Method: C++ // C++ implementation of the Linked// File Allocation Method#include <iostream>#include <vector>using namespace std; // File Classclass File {public: // Name of File string filename; // Size of file size_t size; // Partition no is which part of // file is present at a particular // block of memory int partition;}; // Block Classclass Block { // If Block is occupied // by a file or not bool occupied = false; // File of the block File file; // Location of next partition in given memory // By default, it is set to -1 // which indicates there is no next partition int next = -1; public: // This will set file into current block // and set occupied flag void set_file(File file) { this->file = file; occupied = true; } // This will return filename of given block string get_file_name() { return file.filename; } // Return partition number of file int get_file_partition_no() { return file.partition; } // Return if the block is empty or not bool is_empty() { return !occupied; } // This will set the occupied flag as false // meaning that it will free the memory void set_empty() { occupied = false; } // This function will set location of next // partition in given memory void set_next(int next) { this->next = next; } // This function will return location // of next partition int get_next() { return next; }}; // Function to return the number of// empty Blocks from given memoryint get_empty_count(vector<Block> memory){ int sum = 0; vector<Block>::iterator slot; // Count no. of empty blocks in given memory for (slot = memory.begin(); slot != memory.end(); slot++) sum += (*slot).is_empty(); // Return the empty count return sum;} // Function to generate random indexes// from empty memory slots to test indexingint generate_index(vector<Block> memory){ int index = -1; // Check if memory is full if (!get_empty_count(memory) == 0) { // Here it will generate index until // the memory block at generated // index is found to be empty do { index = rand() % memory.size(); index = abs(index); } while (!memory.at(index).is_empty()); } return index;} // This function will return if the file// exists in a given memorybool file_exists(vector<Block> memory, string name){ vector<Block>::iterator slot; for (slot = memory.begin(); slot != memory.end(); slot++) if (!(*slot).is_empty() && (*slot).get_file_name() == name) return true; return false;} // This function will set the file in memoryvoid set_linked_memory(vector<Block>* memory, vector<int>* index_page, File file){ int index = -1, prev = -1, i = 0; // Check if file exists already if (!file_exists((*memory), file.filename)) { // Check if memory is available // according to file size if (get_empty_count(*memory) >= file.size) { // Generate empty index index = generate_index(*memory); // Push 1st index to index page (*index_page).push_back(index); for (i = 0; i < file.size - 1; i++) { // Set partition file.partition = i; // Set file into memory (*memory).at(index).set_file(file); // Note down prev index before // generating next index prev = index; // Generate empty index index = generate_index(*memory); // Set the next location to generated // index in previous index (*memory).at(prev).set_next(index); } // Set last partition and file file.partition = file.size - 1; (*memory).at(index).set_file(file); cout << "File " << file.filename << " has been successfully allocated" << endl; } else cout << "Not enough available memory" << endl; } else cout << "File already exists in given memory" << endl;} // Function will delete the file from// memory specified by namevoid delete_from_linked_memory(vector<Block>* memory, vector<int>* index_page, string file){ int index, next, previous, main_index, i = 0; vector<int>::iterator slot; // Check if file exists if (file_exists((*memory), file)) { // Iterate through the index page // to find 1st partition for (slot = (*index_page).begin(); slot != (*index_page).end(); slot++) { // Check if file stored at index has // the same name we wish to delete if ((*memory) .at(*slot) .get_file_name() == file) { // Main index is w.r.t memory location main_index = (*slot); // index is w.r.t index page // entry location index = i; break; } i++; } // 1st partition i = main_index; // Check while next location comes as -1 while (i != -1 && (*memory) .at(i) .get_file_name() == file) { // set the Block free (*memory).at(i).set_empty(); // Note the location into previous previous = i; // get the next location i = (*memory).at(i).get_next(); // set -1 as next location into // previous location (*memory).at(previous).set_next(-1); } // Erase the entry of file from index // page as well (*index_page) .erase((*index_page) .begin() + index); cout << "File " << file << " has been successfully deleted" << endl; } else { cout << "File does not exist in given memory" << endl; }} // Function to display main index pagevoid show_linked_index(vector<Block> memory, vector<int> index){ int max = 9, i, count; // Iterator vector<int>::iterator slot; // File Name string fname; // Iterate through all index pages for (slot = index.begin(); slot != index.end(); slot++) { if (memory .at(*slot) .get_file_name() .length() > max) { max = memory .at(*slot) .get_file_name() .length(); cout << "+" << string(max + 2, '-') << "+---------------+---------" << "----+------------------+"; cout << "\n|" << string(max / 2 + max % 2 - 4, ' ') << "File Name" << string(max / 2 - 3, ' '); cout << "| Start Address | End Address" << " | Size of the file |\n+" << string(max + 2, '-'); cout << "+---------------+--------" << "-----+------------------+" << endl; } } // Iterate through index for (slot = index.begin(); slot != index.end(); slot++) { i = (*slot); fname = memory .at(i) .get_file_name(); count = 1; while (memory.at(i).get_next() != -1 && memory .at(i) .get_file_name() == fname) { i = memory.at(i).get_next(); count++; } cout << "|" << string(max / 2 + max % 2 - memory .at(*slot) .get_file_name() .length() / 2 - memory .at(*slot) .get_file_name() .length() % 2 + 1, ' ') << memory .at(*slot) .get_file_name() << string(max / 2 - memory.at(*slot).get_file_name().length() / 2 + 1, ' ') << "|" << string(8 - to_string(*slot) .length() / 2 - to_string(*slot) .length() % 2, ' ') << (*slot) << string(7 - to_string(*slot) .length() / 2, ' ') << "|" << string(7 - to_string(i) .length() / 2 - to_string(i) .length() % 2, ' ') << i << string(6 - to_string(i) .length() / 2, ' ') << "|" << string(9 - to_string(count) .length() / 2 - to_string(count) .length() % 2, ' ') << count << string(9 - to_string(count) .length() / 2, ' ') << "|" << endl; } cout << "+" << string(max + 2, '-') << "+---------------+----------" << "---+------------------+" << endl;} // Function to check all the partitions of file// w.r.t filename specifiedvoid show_linked_indexes(vector<Block> memory, vector<int> index_page, string filename){ int index; vector<int>::iterator slot; // If file exists if (file_exists(memory, filename)) { cout << "File Name = " << filename; cout << "\n+------------------+----------" << "--------+------------------+"; cout << "\n| Current Location |Next part" << " Location| Partition Number |"; cout << "\n+------------------+----------" << "--------+------------------+\n"; // Iterate through all index for (slot = index_page.begin(); slot != index_page.end(); slot++) { if (memory .at(*slot) .get_file_name() == filename) { index = (*slot); break; } } // Loop till index is not -1 while (index != -1) { cout << "|" << string(9 - to_string(index) .length() / 2 - to_string(index) .length() % 2, ' ') << index << string(9 - to_string(index) .length() / 2, ' ') << "|" << string(9 - to_string(memory .at(index) .get_next()) .length() / 2 - to_string(memory .at(index) .get_next()) .length() % 2, ' ') << memory .at(index) .get_next() << string(9 - to_string(memory .at(index) .get_next()) .length() / 2, ' ') << "|" << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2 - to_string(memory .at(index) .get_file_partition_no()) .length() % 2, ' ') << memory .at(index) .get_file_partition_no() << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2, ' ') << "|" << endl; index = memory .at(index) .get_next(); } cout << "+------------------+---------" << "---------+------------------+" << endl; } else { cout << "Given file does not exist" << " in given memory" << endl; }} // Driver Codeint main(){ // Declare memory of size 16 Blocks vector<Block> memory(16); // Declare index page vector<int> index_page; File temp; cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Set the data temp.filename = "home.txt"; temp.size = 5; set_linked_memory(&memory, &index_page, temp); temp.filename = "Report.docx"; temp.size = 6; set_linked_memory(&memory, &index_page, temp); temp.filename = "new_img.png"; temp.size = 3; set_linked_memory(&memory, &index_page, temp); temp.filename = "test.cpp"; temp.size = 2; set_linked_memory(&memory, &index_page temp); cout << "Files have been successfully set" << endl; cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Print all the linked index show_linked_index(memory, index_page); cout << "Now we will check index" << " of each partition of "; cout << "Report.docx and test.cpp" << " before deleting them" << endl; // Print all the linked index show_linked_indexes(memory, index_page, "Report.docx"); // Print all the linked index show_linked_indexes(memory, index_page, "test.cpp"); // Now delete Report.docx and test.cpp delete_from_linked_memory(&memory, &index_page, "Report.docx"); delete_from_linked_memory(&memory, &index_page, "test.cpp"); cout << "Remaining memory :- " << get_empty_count(memory) << endl; // Print all the linked index show_linked_index(memory, index_page); // Creating hello.jpeg file now // and setting it to memory temp.filename = "hello.jpeg"; temp.size = 8; // Set Linked memory set_linked_memory(&memory, &index_page, temp); cout << "Check index page :- " << endl; // Print all the linked index show_linked_index(memory, index_page); // Now we will see index for each partition // of hello.jpeg cout << "Remaining memory :- " << get_empty_count(memory) << endl; cout << "We will check each partition for" << " hello.jpeg "; cout << "to see if deleted locations are" << " utilized or not" << endl; // Print all the linked index show_linked_indexes(memory, index_page, "hello.jpeg"); memory.clear(); memory.shrink_to_fit(); index_page.clear(); index_page.shrink_to_fit(); return 0;} Remaining memory :- 16 File home.txt has been successfully allocated File Report.docx has been successfully allocated File new_img.png has been successfully allocated File test.cpp has been successfully allocated Files have been successfully set Remaining memory :- 0 +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 7 | 1 | 5 | | Report.docx | 15 | 2 | 6 | | new_img.png | 4 | 14 | 3 | | test.cpp | 5 | 0 | 2 | +-------------+---------------+-------------+------------------+ Now we will check index of each partition of Report.docx and test.cpp before deleting them File Name = Report.docx +------------------+------------------+------------------+ | Current Location |Next part Location| Partition Number | +------------------+------------------+------------------+ | 15 | 10 | 0 | | 10 | 12 | 1 | | 12 | 13 | 2 | | 13 | 11 | 3 | | 11 | 2 | 4 | | 2 | -1 | 5 | +------------------+------------------+------------------+ File Name = test.cpp +------------------+------------------+------------------+ | Current Location |Next part Location| Partition Number | +------------------+------------------+------------------+ | 5 | 0 | 0 | | 0 | -1 | 1 | +------------------+------------------+------------------+ File Report.docx has been successfully deleted File test.cpp has been successfully deleted Remaining memory :- 8 +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 7 | 1 | 5 | | new_img.png | 4 | 14 | 3 | +-------------+---------------+-------------+------------------+ File hello.jpeg has been successfully allocated Check index page :- +-------------+---------------+-------------+------------------+ | File Name | Start Address | End Address | Size of the file | +-------------+---------------+-------------+------------------+ | home.txt | 7 | 1 | 5 | | new_img.png | 4 | 14 | 3 | | hello.jpeg | 12 | 13 | 8 | +-------------+---------------+-------------+------------------+ Remaining memory :- 0 We will check each partition for hello.jpeg to see if deleted locations are utilized or not File Name = hello.jpeg +------------------+------------------+------------------+ | Current Location |Next part Location| Partition Number | +------------------+------------------+------------------+ | 12 | 10 | 0 | | 10 | 11 | 1 | | 11 | 15 | 2 | | 15 | 0 | 3 | | 0 | 2 | 4 | | 2 | 5 | 5 | | 5 | 13 | 6 | | 13 | -1 | 7 | +------------------+------------------+------------------+ surinderdawra388 cpp-vector C++ C++ Programs Operating Systems Write From Home Operating Systems CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Oct, 2021" }, { "code": null, "e": 93, "s": 54, "text": "Prerequisite: File Allocation Methods " }, { "code": null, "e": 128, "s": 93, "text": "Different File Allocation methods:" }, { "code": null, "e": 167, "s": 128, "text": "1. Contiguous File Allocation Methods:" }, { "code": null, "e": 522, "s": 167, "text": "This is a type of allocation in which a file occupies contiguous blocks of a given memory. This type of allocation is fastest because we can access any part of the file just by adding it to the starting index of the file. However, this allocation is not useful when you have to insert a file whose size is greater than the greatest empty slot available. " }, { "code": null, "e": 616, "s": 522, "text": "Below is the implementation of Contiguous File Allocation which follows First-Fit Allocation:" }, { "code": null, "e": 620, "s": 616, "text": "C++" }, { "code": "// C++ implementation of the Contiguous// File Allocation which follow First-Fit// algorithm#include <iostream>#include <vector>using namespace std; // File Classclass File {public: // Name of File string filename; // Size of file size_t size; // Partition no. is which part of // file is present at a particular // block of memory int partition;};class Block { // If Block is occupied // by a file or not bool occupied = false; // File of the block File file; public: // This function will set file into // current block and set occupied flag void set_file(File file) { this->file = file; occupied = true; } // This function will return // filename of given block string get_file_name() { return file.filename; } // This function will return // partition number of file int get_file_partition_no() { return file.partition; } // This function will return // if the block is empty or not bool is_empty() { return !occupied; } // This function will set the occupied // flag as false meaning that it will // free the given block void set_empty() { occupied = false; }}; // Function to return the number of// empty Blocks from given memoryint get_empty_count(vector<Block> memory){ int sum = 0; vector<Block>::iterator slot; // Count no. of empty blocks in // given memory for (slot = memory.begin(); slot != memory.end(); slot++) { sum += (*slot).is_empty(); } return sum;} // Function will return if the file// exists in a given memorybool file_exists(vector<Block> memory, string name){ vector<Block>::iterator slot; for (slot = memory.begin(); slot != memory.end(); slot++) { if (!(*slot).is_empty() && (*slot).get_file_name() == name) { return true; } } return false;} // Function will set the file in the memory// this will follow first fit allocationvoid set_contiguous_memory(vector<Block>* memory, vector<int>* index, File file){ bool avail = false; int i = 0, count = 0, main_index; vector<Block>::iterator slot; // Check if the file already exists if (file_exists((*memory), file.filename)) cout << \"File already exists\" << endl; else { // Iterate through full memory for (slot = (*memory).begin(); slot != (*memory).end(); slot++) { // Check if there are // contiguous Blocks available if ((*slot).is_empty()) { count++; // This if condition will note // the 1st index for each // Block empty if (count == 1) main_index = i; // Check if contiguous // Blocks are available, // it will set our flag // avail as true and break if (count == file.size) { avail = true; break; } } // Else if there is even a // single non-empty block // in between we will set // count as 0 else { count = 0; } i++; } // If our flag is set, // this condition will set // our file if (avail) { // Here starting index of // our given file will be // pushed in index page (*index).push_back(main_index); // Utilize count variable // again for setting file // partition count = 0; for (int i = main_index; i < main_index + file.size; i++) { file.partition = count; (*memory).at(i).set_file(file); count++; } cout << \"File \" << file.filename << \" has been successfully\" << \" allocated\" << endl; } else { cout << \"The size of the file is\" << \" greater than\" << endl; cout << \"the greatest slot available\" << \" in contiguous memory\" << endl; cout << \"Hence, File \" << file.filename << \" cannot be allocated\" << endl; } }} // Function to Delete file from memoryvoid delete_contiguous_mem(vector<Block>* memory, vector<int>* index_page, string file){ vector<int>::iterator slot; int index, i = 0, main_index; // Check if the file exist or not if (!file_exists((*memory), file)) cout << \"File does not exist\" << endl; else { // Iterate all the indexes for (slot = (*index_page).begin(); slot != (*index_page).end(); slot++) { // If specified file is found, // this condition will // set the value of index no. // in index and // main_index will have starting // location of // file in memory if ((*memory).at(*slot).get_file_name() == file) { index = i; main_index = (*slot); break; } i++; } // Iterate through the main index until // filename is similar to specified // filename and status of Block is // not empty i = main_index; while (i < (*memory).size() && (*memory).at(i).get_file_name() == file && !(*memory).at(i).is_empty()) { // Set the Block as empty (*memory).at(i).set_empty(); i++; } // Erase entry of file from index page (*index_page).erase((*index_page).begin() + index); cout << \"File \" << file << \" has been successfully deleted\" << endl; }} // Function to display main index pagevoid show_contiguous_index(vector<Block> memory, vector<int> index_page){ int max = 9, i, j; // Iterator vector<Block>::iterator slot; // File Name string fname; // Iterate through all index pages for (i = 0; i < index_page.size(); i++) { if (memory.at(index_page.at(i)) .get_file_name() .length() > max) { // Get the length of file max = memory.at(index_page .at(i)) .get_file_name() .length(); cout << \"+\" << string(max + 2, '-') << \"+---------------+----\" << \"---------+-----------\" << \"-------+\\n|\" << string(max / 2 + max % 2 - 4, ' ') << \"File Name\" << string(max / 2 - 3, ' ') << \"| Start Address | \" << \" End Address | Size\" << \" of the file |\\n+\" << string(max + 2, '-') << \"+---------------+-------\" << \"------+------------------+\" << endl; } } // Iterate index_pages for (i = 0; i < index_page.size(); i++) { cout << \"|\" << string(max / 2 + max % 2 - memory .at(index_page .at(i)) .get_file_name() .length() / 2 - memory .at(index_page .at(i)) .get_file_name() .length() % 2 + 1, ' ') << memory.at(index_page.at(i)) .get_file_name() << string(max / 2 - memory .at(index_page .at(i)) .get_file_name() .length() / 2 + 1, ' ') << \"|\" << string(8 - to_string(index_page .at(i)) .length() / 2 - to_string(index_page .at(i)) .length() % 2, ' ') << index_page.at(i) << string(7 - to_string(index_page .at(i)) .length() / 2, ' ') << \"|\"; j = index_page .at(i); fname = memory .at(j) .get_file_name(); // Till j is less than memory size while (j < memory.size() && !memory .at(j) .is_empty() && memory .at(j) .get_file_name() == fname) { j++; } j -= 1; // Print the index pages details cout << string(7 - to_string(j) .length() / 2 - to_string(j) .length() % 2, ' ') << j << string(6 - to_string(j) .length() / 2, ' ') << \"|\" << string(9 - to_string(j - index_page .at(i) + 1) .length() / 2 - to_string(j - index_page .at(i) + 1) .length() % 2, ' ') << j - index_page.at(i) + 1 << string(9 - to_string(j - index_page .at(i) + 1) .length() / 2, ' ') << \"|\" << endl; } cout << \"+\" << string(max + 2, '-') << \"+---------------+------\" << \"-------+------------------+\" << endl;} // Function to display index of each// partition of specified filevoid show_contiguous_indexes(vector<Block> memory, vector<int> index_page, string filename){ int index, i; // Iterator vector<int>::iterator slot; // If file exist then display file // index and partition if (file_exists(memory, filename)) { cout << \"File Name = \" << filename << \"\\n+------------------+----\" << \"--------------+\"; cout << \"\\n| Current Location |\" << \" Partition Number |\"; cout << \"\\n+------------------+-\" << \" -----------------+\\n\"; // Iterate through all the index for (slot = index_page.begin(); slot != index_page.end(); slot++) { if (memory.at(*slot).get_file_name() == filename) { index = (*slot); break; } } // Loop till memory size is greater than // index and file is allocated // in them while (index < memory.size() && memory .at(index) .get_file_name() == filename && !memory .at(index) .is_empty()) { cout << \"|\" << string(9 - to_string(index) .length() / 2 - to_string(index) .length() % 2, ' ') << index << string(9 - to_string(index) .length() / 2, ' ') << \"|\" << string(9 - to_string(memory .at(index) .get _file _partition _no()) .length() / 2 - to_string(memory .at(index) .get_file _partition _no()) .length() % 2, ' ') << memory .at(index) .get_file_partition_no() << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2, ' ') << \"|\" << endl; index++; } cout << \"+------------------+\" << \"------------------+\" << endl; } else cout << \"File does not exist \" << \"in given memory\" << endl;} // Driver Codeint main(){ // Declare memory of size 16 Blocks vector<Block> memory(16); // Declare index page vector<int> index_page; File temp; cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Set the data temp.filename = \"home.txt\"; temp.size = 5; set_contiguous_memory(&memory, &index_page, temp); temp.filename = \"Report.docx\"; temp.size = 6; set_contiguous_memory(&memory, &index_page, temp); temp.filename = \"new_img.png\"; temp.size = 3; set_contiguous_memory(&memory, &index_page, temp); temp.filename = \"test.cpp\"; temp.size = 2; set_contiguous_memory(&memory, &index_page, temp); cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Function call to show all the // memory allocation show_contiguous_index(memory, index_page); cout << \"Now we will check each partition of\"; cout << \" Report.docx and test.cpp before\" << endl; cout << \"deleting them to see\" << \" which locations \"; cout << \"are going to be set free\" << \" as our slots\" << endl; // Function call to show all the // memory allocation show_contiguous_indexes(memory, index_page, \"Report.docx\"); // Function call to show all the // memory allocation show_contiguous_indexes(memory, index_page, \"test.cpp\"); // Now delete Report.docx & test.cpp delete_contiguous_mem(&memory, &index_page, \"Report.docx\"); delete_contiguous_mem(&memory, &index_page, \"test.cpp\"); cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Function call to show all the // memory allocation show_contiguous_index(memory, index_page); // Creating hello.jpeg file now // and setting it to memory temp.filename = \"hello.jpeg\"; temp.size = 8; set_contiguous_memory(&memory, &index_page, temp); cout << \"Check index page: \" << endl; // Function call to show all the // memory allocation show_contiguous_index(memory, index_page);}", "e": 18186, "s": 620, "text": null }, { "code": null, "e": 20809, "s": 18186, "text": "Remaining memory :- 16\nFile home.txt has been successfully allocated\nFile Report.docx has been successfully allocated\nFile new_img.png has been successfully allocated\nFile test.cpp has been successfully allocated\nRemaining memory :- 0\n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 0 | 4 | 5 |\n| Report.docx | 5 | 10 | 6 |\n| new_img.png | 11 | 13 | 3 |\n| test.cpp | 14 | 15 | 2 |\n+-------------+---------------+-------------+------------------+\nNow we will check each partition of Report.docx and test.cpp before\ndeleting them to see which locations are going to be set free as our slots\nFile Name = Report.docx\n+------------------+------------------+\n| Current Location | Partition Number |\n+------------------+------------------+\n| 5 | 0 |\n| 6 | 1 |\n| 7 | 2 |\n| 8 | 3 |\n| 9 | 4 |\n| 10 | 5 |\n+------------------+------------------+\nFile Name = test.cpp\n+------------------+------------------+\n| Current Location | Partition Number |\n+------------------+------------------+\n| 14 | 0 |\n| 15 | 1 |\n+------------------+------------------+\nFile Report.docx has been successfully deleted\nFile test.cpp has been successfully deleted\nRemaining memory:- 8\n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 0 | 4 | 5 |\n| new_img.png | 11 | 13 | 3 |\n+-------------+---------------+-------------+------------------+\nThe size of the file is greater than\nthe greatest slot available in contiguous memory\nHence, File hello.jpeg cannot be allocated\nCheck index page: \n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 0 | 4 | 5 |\n| new_img.png | 11 | 13 | 3 |\n+-------------+---------------+-------------+------------------+" }, { "code": null, "e": 20846, "s": 20811, "text": "2. Indexed File Allocation Method:" }, { "code": null, "e": 21249, "s": 20846, "text": "This is a type of allocation where we have 2 index pages, one is the main index page w.r.t all files and the other is a sub-indexed page which is w.r.t to a particular file. This type of allocation does not require a contiguous slot of memory since we are keeping track of each block individually. In the given program below, the vector of vectors is used for implementing the main index and sub-index." }, { "code": null, "e": 21314, "s": 21249, "text": "Below is the implementation for Indexed File Allocation Method: " }, { "code": null, "e": 21318, "s": 21314, "text": "C++" }, { "code": "// C++ implementation of the Indexed// File Allocation Method#include <iostream>#include <vector>using namespace std; // File Classclass File {public: // Name of File string filename; // Size of file size_t size; // Partition no. is which part of // file is present at a particular // block of memory int partition;}; // Block classclass Block { // If Block is occupied // by a file or not bool occupied = false; // File of the block File file; public: // This function will set file // into current block // and set occupied flag void set_file(File file) { this->file = file; occupied = true; } // This function will return // filename of given block string get_file_name() { return file.filename; } // This function will return // partition number of file int get_file_partition_no() { return file.partition; } // This function will return // if the block is empty or not bool is_empty() { return !occupied; } // This function will set the // occupied flag as false // meaning that it will free // the given block void set_empty() { occupied = false; }}; // Function to return the number of// empty Blocks from given memoryint get_empty_count(vector<Block> memory){ int sum = 0; vector<Block>::iterator slot; // count no. of empty blocks in // given memory for (slot = memory.begin(); slot != memory.end(); slot++) sum += (*slot).is_empty(); return sum;} // This function will generate random indexes// from empty memory slots to test indexingint generate_index(vector<Block> memory){ int index = -1; // Check if memory is full if (!get_empty_count(memory) == 0) { // Here it will generate index until // the memory block at generated // index is found to be empty do { index = rand() % memory.size(); index = abs(index); } while (!memory.at(index).is_empty()); } return index;} // This function will return if the file// exists in a given memorybool file_exists(vector<Block> memory, string name){ vector<Block>::iterator slot; for (slot = memory.begin(); slot != memory.end(); slot++) { if (!(*slot).is_empty() && (*slot).get_file_name() == name) { return true; } } return false;} // This function will set file in// memory and push index for each partition// and then push the file index to main// index vectorvoid set_indexed_memory(vector<Block>* memory, vector<vector<int> >* index_page, File file){ int index; // Declaration newpage to set the // index page for given file vector<int> newpage; // Check if file exists if (file_exists((*memory), file.filename)) cout << \"File already exists\" << endl; else { // Check if available memory is greater than // size of given file if (get_empty_count(*memory) >= file.size) { // Iterate till file size for (int i = 0; i < file.size; i++) { // Generate random empty index index = generate_index(*memory); // Set file partition file.partition = i; // Push the file to memory (*memory).at(index).set_file(file); // Push the index to newpage newpage.push_back(index); } // Push new index page into main // index page (*index_page).push_back(newpage); cout << \"File \" << file.filename << \" has been successfully allocated\" << endl; } else { cout << \"Not enough available space\" << endl; } }} // Function to delete a file from given// indexed memoryvoid delete_from_indexed_memory(vector<Block>* memory, vector<vector<int> >* index_page, string file){ vector<int>::iterator slot; vector<vector<int> >::iterator it; int index, i = 0; // Check if file exists if (file_exists((*memory), file)) { // Iterate main index for (it = (*index_page).begin(); it != (*index_page).end(); it++) { // Check for sub-index at // start location slot = (*it).begin(); // Check if it equals filename if ((*memory) .at(*slot) .get_file_name() == file) { // Set for index and break index = i; break; } i++; } // Set the memory flag as empty for (slot = (*index_page).at(index).begin(); slot != (*index_page).at(index).end(); slot++) (*memory).at(*slot).set_empty(); // Erase file index from main index page (*index_page) .erase((*index_page).begin() + index); cout << \"File \" << file << \" has been successfully deleted\" << endl; } else { cout << \"File does not exist\" << endl; }} // Function to display the main indexvoid show_indexed_index(vector<Block> memory, vector<vector<int> > index_page){ int max = 9; vector<Block>::iterator slot; vector<vector<int> >::iterator it; // Iterate over index pages for (it = index_page.begin(); it != index_page.end(); it++) { if (memory .at((*it) .at(0)) .get_file_name() .length() > max) { max = memory .at((*it) .at(0)) .get_file_name() .length(); cout << \"+\" << string(max + 2, '-') << \"+---------------+----------\" << \"---+------------------+\\n|\" << string(max / 2 + max % 2 - 4, ' ') << \"File Name\" << string(max / 2 - 3, ' ') << \"| Start Address | End Address\" << \" | Size of the file |\\n+\" << string(max + 2, '-') << \"+---------------+------\" << \"-------+------------------+\" << endl; } } // Iterate through all the index pages for (it = index_page.begin(); it != index_page.end(); it++) { cout << \"|\" << string(max / 2 + max % 2 - memory .at((*it) .at(0)) .get_file_name() .length() / 2 - memory .at((*it) .at(0)) .get_file_name() .length() % 2 + 1, ' ') << memory .at((*it) .at(0)) .get_file_name() << string(max / 2 - memory .at((*it) .at(0)) .get_file_name() .length() / 2 + 1, ' ') << \"|\" << string(8 - to_string((*it) .at(0)) .length() / 2 - to_string((*it) .at(0)) .length() % 2, ' ') << ((*it).at(0)) << string(7 - to_string((*it) .at(0)) .length() / 2, ' ') << \"|\" << string(7 - to_string((*it) .at((*it) .size() - 1)) .length() / 2 - to_string((*it) .at((*it) .size() - 1)) .length() % 2, ' ') << (*it) .at((*it).size() - 1) << string(6 - to_string((*it) .at((*it) .size() - 1)) .length() / 2, ' ') << \"|\" << string(9 - to_string((*it) .size()) .length() / 2 - to_string((*it) .size()) .length() % 2, ' ') << (*it).size() << string(9 - to_string((*it) .size()) .length() / 2, ' ') << \"|\" << endl; cout << \"+\" << string(max + 2, '-') << \"+---------------+----------\" << \"---+------------------+\" << endl; }} // Function to show each partition details// w.r.t filenamevoid show_indexed_indexes(vector<Block> memory, vector<vector<int> > index_page, string filename){ int index, i = 0, main_index; vector<vector<int> >::iterator slot; // Check if file exists if (file_exists(memory, filename)) { for (slot = index_page.begin(); slot != index_page.end(); slot++) { if (memory.at((*slot).at(0)).get_file_name() == filename) { main_index = i; break; } i++; } // Display File Details cout << \"File Name = \" << filename << endl; cout << \"File page index at main index :- \" << main_index << \"\\n+------------------+------------------+\\n\"; cout << \"| Current Location | Partition Number |\\n\"; cout << \"+------------------+------------------+\\n\"; for (i = 0; i < index_page.at(main_index).size(); i++) { index = index_page .at(main_index) .at(i); cout << \"|\" << string(9 - to_string(index) .length() / 2 - to_string(index) .length() % 2, ' ') << index << string(9 - to_string(index) .length() / 2, ' ') << \"|\" << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2 - to_string(memory .at(index) .get_file_partition_no()) .length() % 2, ' ') << memory .at(index) .get_file_partition_no() << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2, ' ') << \"|\" << endl; } cout << \"+------------------+----\" << \"--------------+\" << endl; } else { cout << \"File does not exist\" << endl; }} // Driver Codeint main(){ // Declare memory of size 16 Blocks vector<Block> memory(16); // Declare index page vector<vector<int> > index_page; File temp; cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Set the data temp.filename = \"home.txt\"; temp.size = 5; set_indexed_memory(&memory, &index_page, temp); temp.filename = \"Report.docx\"; temp.size = 6; set_indexed_memory(&memory, &index_page, temp); temp.filename = \"new_img.png\"; temp.size = 3; set_indexed_memory(&memory, &index_page, temp); temp.filename = \"test.cpp\"; temp.size = 2; set_indexed_memory(&memory, &index_page, temp); // Print the Remaining memory cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Print all the index memory show_indexed_index(memory, index_page); cout << \"Now we will check each partition\" << \" for Report.docx and test.cpp\" << \" before deleting them\" << endl; // Print all the index memory show_indexed_indexes(memory, index_page, \"Report.docx\"); // Print all the index memory show_indexed_indexes(memory, index_page, \"test.cpp\"); // Now delete Report.docx and test.cpp delete_from_indexed_memory(&memory, &index_page, \"Report.docx\"); delete_from_indexed_memory(&memory, &index_page, \"test.cpp\"); cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Print all the index memory show_indexed_index(memory, index_page); // Creating hello.jpeg file now // and setting it to memory temp.filename = \"hello.jpeg\"; temp.size = 8; set_indexed_memory(&memory, &index_page, temp); cout << \"Check index page :- \" << endl; // Print all the index memory show_indexed_index(memory, index_page); // Now we will see index for each partition of // hello.jpeg cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; cout << \"We will check each partition\" << \" for hello.jpeg to see \"; cout << \"if the locations of deleted files\" << \" are utilized or not\" << endl; // Print all the index memory show_indexed_indexes(memory, index_page, \"hello.jpeg\"); memory.clear(); memory.shrink_to_fit(); index_page.clear(); index_page.shrink_to_fit(); return 0;}", "e": 37503, "s": 21318, "text": null }, { "code": null, "e": 41178, "s": 37503, "text": "Remaining memory :- 16\nFile home.txt has been successfully allocated\nFile Report.docx has been successfully allocated\nFile new_img.png has been successfully allocated\nFile test.cpp has been successfully allocated\nRemaining memory :- 0\n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 7 | 1 | 5 |\n+-------------+---------------+-------------+------------------+\n| Report.docx | 15 | 2 | 6 |\n+-------------+---------------+-------------+------------------+\n| new_img.png | 4 | 14 | 3 |\n+-------------+---------------+-------------+------------------+\n| test.cpp | 5 | 0 | 2 |\n+-------------+---------------+-------------+------------------+\nNow we will check each partition for Report.docx and test.cpp before deleting them\nFile Name = Report.docx\nFile page index at main index :- 1\n+------------------+------------------+\n| Current Location | Partition Number |\n+------------------+------------------+\n| 15 | 0 |\n| 10 | 1 |\n| 12 | 2 |\n| 13 | 3 |\n| 11 | 4 |\n| 2 | 5 |\n+------------------+------------------+\nFile Name = test.cpp\nFile page index at main index :- 3\n+------------------+------------------+\n| Current Location | Partition Number |\n+------------------+------------------+\n| 5 | 0 |\n| 0 | 1 |\n+------------------+------------------+\nFile Report.docx has been successfully deleted\nFile test.cpp has been successfully deleted\nRemaining memory :- 8\n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 7 | 1 | 5 |\n+-------------+---------------+-------------+------------------+\n| new_img.png | 4 | 14 | 3 |\n+-------------+---------------+-------------+------------------+\nFile hello.jpeg has been successfully allocated\nCheck index page :- \n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 7 | 1 | 5 |\n+-------------+---------------+-------------+------------------+\n| new_img.png | 4 | 14 | 3 |\n+-------------+---------------+-------------+------------------+\n| hello.jpeg | 12 | 13 | 8 |\n+-------------+---------------+-------------+------------------+\nRemaining memory :- 0\nWe will check each partition for hello.jpeg to see if the locations of deleted files are utilized or not\nFile Name = hello.jpeg\nFile page index at main index :- 2\n+------------------+------------------+\n| Current Location | Partition Number |\n+------------------+------------------+\n| 12 | 0 |\n| 10 | 1 |\n| 11 | 2 |\n| 15 | 3 |\n| 0 | 4 |\n| 2 | 5 |\n| 5 | 6 |\n| 13 | 7 |\n+------------------+------------------+" }, { "code": null, "e": 41214, "s": 41180, "text": "3. Linked File Allocation Method:" }, { "code": null, "e": 41461, "s": 41214, "text": "This is a type of allocation where we linked all the partitions of a file to point to the memory location where the next partition of the file is placed. In the given program below, next will be allocated as -1 when the last partition is reached." }, { "code": null, "e": 41523, "s": 41461, "text": "Below is the implementation of Linked File Allocation Method:" }, { "code": null, "e": 41527, "s": 41523, "text": "C++" }, { "code": "// C++ implementation of the Linked// File Allocation Method#include <iostream>#include <vector>using namespace std; // File Classclass File {public: // Name of File string filename; // Size of file size_t size; // Partition no is which part of // file is present at a particular // block of memory int partition;}; // Block Classclass Block { // If Block is occupied // by a file or not bool occupied = false; // File of the block File file; // Location of next partition in given memory // By default, it is set to -1 // which indicates there is no next partition int next = -1; public: // This will set file into current block // and set occupied flag void set_file(File file) { this->file = file; occupied = true; } // This will return filename of given block string get_file_name() { return file.filename; } // Return partition number of file int get_file_partition_no() { return file.partition; } // Return if the block is empty or not bool is_empty() { return !occupied; } // This will set the occupied flag as false // meaning that it will free the memory void set_empty() { occupied = false; } // This function will set location of next // partition in given memory void set_next(int next) { this->next = next; } // This function will return location // of next partition int get_next() { return next; }}; // Function to return the number of// empty Blocks from given memoryint get_empty_count(vector<Block> memory){ int sum = 0; vector<Block>::iterator slot; // Count no. of empty blocks in given memory for (slot = memory.begin(); slot != memory.end(); slot++) sum += (*slot).is_empty(); // Return the empty count return sum;} // Function to generate random indexes// from empty memory slots to test indexingint generate_index(vector<Block> memory){ int index = -1; // Check if memory is full if (!get_empty_count(memory) == 0) { // Here it will generate index until // the memory block at generated // index is found to be empty do { index = rand() % memory.size(); index = abs(index); } while (!memory.at(index).is_empty()); } return index;} // This function will return if the file// exists in a given memorybool file_exists(vector<Block> memory, string name){ vector<Block>::iterator slot; for (slot = memory.begin(); slot != memory.end(); slot++) if (!(*slot).is_empty() && (*slot).get_file_name() == name) return true; return false;} // This function will set the file in memoryvoid set_linked_memory(vector<Block>* memory, vector<int>* index_page, File file){ int index = -1, prev = -1, i = 0; // Check if file exists already if (!file_exists((*memory), file.filename)) { // Check if memory is available // according to file size if (get_empty_count(*memory) >= file.size) { // Generate empty index index = generate_index(*memory); // Push 1st index to index page (*index_page).push_back(index); for (i = 0; i < file.size - 1; i++) { // Set partition file.partition = i; // Set file into memory (*memory).at(index).set_file(file); // Note down prev index before // generating next index prev = index; // Generate empty index index = generate_index(*memory); // Set the next location to generated // index in previous index (*memory).at(prev).set_next(index); } // Set last partition and file file.partition = file.size - 1; (*memory).at(index).set_file(file); cout << \"File \" << file.filename << \" has been successfully allocated\" << endl; } else cout << \"Not enough available memory\" << endl; } else cout << \"File already exists in given memory\" << endl;} // Function will delete the file from// memory specified by namevoid delete_from_linked_memory(vector<Block>* memory, vector<int>* index_page, string file){ int index, next, previous, main_index, i = 0; vector<int>::iterator slot; // Check if file exists if (file_exists((*memory), file)) { // Iterate through the index page // to find 1st partition for (slot = (*index_page).begin(); slot != (*index_page).end(); slot++) { // Check if file stored at index has // the same name we wish to delete if ((*memory) .at(*slot) .get_file_name() == file) { // Main index is w.r.t memory location main_index = (*slot); // index is w.r.t index page // entry location index = i; break; } i++; } // 1st partition i = main_index; // Check while next location comes as -1 while (i != -1 && (*memory) .at(i) .get_file_name() == file) { // set the Block free (*memory).at(i).set_empty(); // Note the location into previous previous = i; // get the next location i = (*memory).at(i).get_next(); // set -1 as next location into // previous location (*memory).at(previous).set_next(-1); } // Erase the entry of file from index // page as well (*index_page) .erase((*index_page) .begin() + index); cout << \"File \" << file << \" has been successfully deleted\" << endl; } else { cout << \"File does not exist in given memory\" << endl; }} // Function to display main index pagevoid show_linked_index(vector<Block> memory, vector<int> index){ int max = 9, i, count; // Iterator vector<int>::iterator slot; // File Name string fname; // Iterate through all index pages for (slot = index.begin(); slot != index.end(); slot++) { if (memory .at(*slot) .get_file_name() .length() > max) { max = memory .at(*slot) .get_file_name() .length(); cout << \"+\" << string(max + 2, '-') << \"+---------------+---------\" << \"----+------------------+\"; cout << \"\\n|\" << string(max / 2 + max % 2 - 4, ' ') << \"File Name\" << string(max / 2 - 3, ' '); cout << \"| Start Address | End Address\" << \" | Size of the file |\\n+\" << string(max + 2, '-'); cout << \"+---------------+--------\" << \"-----+------------------+\" << endl; } } // Iterate through index for (slot = index.begin(); slot != index.end(); slot++) { i = (*slot); fname = memory .at(i) .get_file_name(); count = 1; while (memory.at(i).get_next() != -1 && memory .at(i) .get_file_name() == fname) { i = memory.at(i).get_next(); count++; } cout << \"|\" << string(max / 2 + max % 2 - memory .at(*slot) .get_file_name() .length() / 2 - memory .at(*slot) .get_file_name() .length() % 2 + 1, ' ') << memory .at(*slot) .get_file_name() << string(max / 2 - memory.at(*slot).get_file_name().length() / 2 + 1, ' ') << \"|\" << string(8 - to_string(*slot) .length() / 2 - to_string(*slot) .length() % 2, ' ') << (*slot) << string(7 - to_string(*slot) .length() / 2, ' ') << \"|\" << string(7 - to_string(i) .length() / 2 - to_string(i) .length() % 2, ' ') << i << string(6 - to_string(i) .length() / 2, ' ') << \"|\" << string(9 - to_string(count) .length() / 2 - to_string(count) .length() % 2, ' ') << count << string(9 - to_string(count) .length() / 2, ' ') << \"|\" << endl; } cout << \"+\" << string(max + 2, '-') << \"+---------------+----------\" << \"---+------------------+\" << endl;} // Function to check all the partitions of file// w.r.t filename specifiedvoid show_linked_indexes(vector<Block> memory, vector<int> index_page, string filename){ int index; vector<int>::iterator slot; // If file exists if (file_exists(memory, filename)) { cout << \"File Name = \" << filename; cout << \"\\n+------------------+----------\" << \"--------+------------------+\"; cout << \"\\n| Current Location |Next part\" << \" Location| Partition Number |\"; cout << \"\\n+------------------+----------\" << \"--------+------------------+\\n\"; // Iterate through all index for (slot = index_page.begin(); slot != index_page.end(); slot++) { if (memory .at(*slot) .get_file_name() == filename) { index = (*slot); break; } } // Loop till index is not -1 while (index != -1) { cout << \"|\" << string(9 - to_string(index) .length() / 2 - to_string(index) .length() % 2, ' ') << index << string(9 - to_string(index) .length() / 2, ' ') << \"|\" << string(9 - to_string(memory .at(index) .get_next()) .length() / 2 - to_string(memory .at(index) .get_next()) .length() % 2, ' ') << memory .at(index) .get_next() << string(9 - to_string(memory .at(index) .get_next()) .length() / 2, ' ') << \"|\" << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2 - to_string(memory .at(index) .get_file_partition_no()) .length() % 2, ' ') << memory .at(index) .get_file_partition_no() << string(9 - to_string(memory .at(index) .get_file_partition_no()) .length() / 2, ' ') << \"|\" << endl; index = memory .at(index) .get_next(); } cout << \"+------------------+---------\" << \"---------+------------------+\" << endl; } else { cout << \"Given file does not exist\" << \" in given memory\" << endl; }} // Driver Codeint main(){ // Declare memory of size 16 Blocks vector<Block> memory(16); // Declare index page vector<int> index_page; File temp; cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Set the data temp.filename = \"home.txt\"; temp.size = 5; set_linked_memory(&memory, &index_page, temp); temp.filename = \"Report.docx\"; temp.size = 6; set_linked_memory(&memory, &index_page, temp); temp.filename = \"new_img.png\"; temp.size = 3; set_linked_memory(&memory, &index_page, temp); temp.filename = \"test.cpp\"; temp.size = 2; set_linked_memory(&memory, &index_page temp); cout << \"Files have been successfully set\" << endl; cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Print all the linked index show_linked_index(memory, index_page); cout << \"Now we will check index\" << \" of each partition of \"; cout << \"Report.docx and test.cpp\" << \" before deleting them\" << endl; // Print all the linked index show_linked_indexes(memory, index_page, \"Report.docx\"); // Print all the linked index show_linked_indexes(memory, index_page, \"test.cpp\"); // Now delete Report.docx and test.cpp delete_from_linked_memory(&memory, &index_page, \"Report.docx\"); delete_from_linked_memory(&memory, &index_page, \"test.cpp\"); cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; // Print all the linked index show_linked_index(memory, index_page); // Creating hello.jpeg file now // and setting it to memory temp.filename = \"hello.jpeg\"; temp.size = 8; // Set Linked memory set_linked_memory(&memory, &index_page, temp); cout << \"Check index page :- \" << endl; // Print all the linked index show_linked_index(memory, index_page); // Now we will see index for each partition // of hello.jpeg cout << \"Remaining memory :- \" << get_empty_count(memory) << endl; cout << \"We will check each partition for\" << \" hello.jpeg \"; cout << \"to see if deleted locations are\" << \" utilized or not\" << endl; // Print all the linked index show_linked_indexes(memory, index_page, \"hello.jpeg\"); memory.clear(); memory.shrink_to_fit(); index_page.clear(); index_page.shrink_to_fit(); return 0;}", "e": 58926, "s": 41527, "text": null }, { "code": null, "e": 62666, "s": 58926, "text": "Remaining memory :- 16\nFile home.txt has been successfully allocated\nFile Report.docx has been successfully allocated\nFile new_img.png has been successfully allocated\nFile test.cpp has been successfully allocated\nFiles have been successfully set\nRemaining memory :- 0\n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 7 | 1 | 5 |\n| Report.docx | 15 | 2 | 6 |\n| new_img.png | 4 | 14 | 3 |\n| test.cpp | 5 | 0 | 2 |\n+-------------+---------------+-------------+------------------+\nNow we will check index of each partition of Report.docx and test.cpp before deleting them\nFile Name = Report.docx\n+------------------+------------------+------------------+\n| Current Location |Next part Location| Partition Number |\n+------------------+------------------+------------------+\n| 15 | 10 | 0 |\n| 10 | 12 | 1 |\n| 12 | 13 | 2 |\n| 13 | 11 | 3 |\n| 11 | 2 | 4 |\n| 2 | -1 | 5 |\n+------------------+------------------+------------------+\nFile Name = test.cpp\n+------------------+------------------+------------------+\n| Current Location |Next part Location| Partition Number |\n+------------------+------------------+------------------+\n| 5 | 0 | 0 |\n| 0 | -1 | 1 |\n+------------------+------------------+------------------+\nFile Report.docx has been successfully deleted\nFile test.cpp has been successfully deleted\nRemaining memory :- 8\n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 7 | 1 | 5 |\n| new_img.png | 4 | 14 | 3 |\n+-------------+---------------+-------------+------------------+\nFile hello.jpeg has been successfully allocated\nCheck index page :- \n+-------------+---------------+-------------+------------------+\n| File Name | Start Address | End Address | Size of the file |\n+-------------+---------------+-------------+------------------+\n| home.txt | 7 | 1 | 5 |\n| new_img.png | 4 | 14 | 3 |\n| hello.jpeg | 12 | 13 | 8 |\n+-------------+---------------+-------------+------------------+\nRemaining memory :- 0\nWe will check each partition for hello.jpeg to see if deleted locations are utilized or not\nFile Name = hello.jpeg\n+------------------+------------------+------------------+\n| Current Location |Next part Location| Partition Number |\n+------------------+------------------+------------------+\n| 12 | 10 | 0 |\n| 10 | 11 | 1 |\n| 11 | 15 | 2 |\n| 15 | 0 | 3 |\n| 0 | 2 | 4 |\n| 2 | 5 | 5 |\n| 5 | 13 | 6 |\n| 13 | -1 | 7 |\n+------------------+------------------+------------------+" }, { "code": null, "e": 62685, "s": 62668, "text": "surinderdawra388" }, { "code": null, "e": 62696, "s": 62685, "text": "cpp-vector" }, { "code": null, "e": 62700, "s": 62696, "text": "C++" }, { "code": null, "e": 62713, "s": 62700, "text": "C++ Programs" }, { "code": null, "e": 62731, "s": 62713, "text": "Operating Systems" }, { "code": null, "e": 62747, "s": 62731, "text": "Write From Home" }, { "code": null, "e": 62765, "s": 62747, "text": "Operating Systems" }, { "code": null, "e": 62769, "s": 62765, "text": "CPP" } ]
How to use Django Field Choices ?
03 Nov, 2019 Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only. Choices limits the input from the user to the particular values specified in models.py. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field. Choices can be any sequence object – not necessarily a list or tuple. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.For example, SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) Let us create a choices field with above semester in our django project named geeksforgeeks. from django.db import models # specifying choices SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"),) # declaring a Student Model class Student(models.Model): semester = models.CharField( max_length = 20, choices = SEMESTER_CHOICES, default = '1' ) Let us check in admin panel how semester is created.One can also collect your available choices into named groups that can be used for organizational purposes: MEDIA_CHOICES = [ ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ] The first element in each tuple is the name to apply to the group. The second element is an iterable of 2-tuples, with each 2-tuple containing a value and a human-readable name for an option. Grouped options may be combined with ungrouped options within a single list (such as the unknown option in this example).For each model field that has choices set, Django will add a method to retrieve the human-readable name for the field’s current value. See get_FOO_display() in the database API documentation. Django-models Python Django 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 Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Nov, 2019" }, { "code": null, "e": 659, "s": 54, "text": "Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only. Choices limits the input from the user to the particular values specified in models.py. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard text field. Choices can be any sequence object – not necessarily a list or tuple." }, { "code": null, "e": 798, "s": 659, "text": "The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name.For example," }, { "code": null, "e": 950, "s": 798, "text": "SEMESTER_CHOICES = (\n (\"1\", \"1\"),\n (\"2\", \"2\"),\n (\"3\", \"3\"),\n (\"4\", \"4\"),\n (\"5\", \"5\"),\n (\"6\", \"6\"),\n (\"7\", \"7\"),\n (\"8\", \"8\"),\n)\n" }, { "code": null, "e": 1043, "s": 950, "text": "Let us create a choices field with above semester in our django project named geeksforgeeks." }, { "code": "from django.db import models # specifying choices SEMESTER_CHOICES = ( (\"1\", \"1\"), (\"2\", \"2\"), (\"3\", \"3\"), (\"4\", \"4\"), (\"5\", \"5\"), (\"6\", \"6\"), (\"7\", \"7\"), (\"8\", \"8\"),) # declaring a Student Model class Student(models.Model): semester = models.CharField( max_length = 20, choices = SEMESTER_CHOICES, default = '1' )", "e": 1419, "s": 1043, "text": null }, { "code": null, "e": 1579, "s": 1419, "text": "Let us check in admin panel how semester is created.One can also collect your available choices into named groups that can be used for organizational purposes:" }, { "code": null, "e": 1813, "s": 1579, "text": "MEDIA_CHOICES = [\n ('Audio', (\n ('vinyl', 'Vinyl'),\n ('cd', 'CD'),\n )\n ),\n ('Video', (\n ('vhs', 'VHS Tape'),\n ('dvd', 'DVD'),\n )\n ),\n ('unknown', 'Unknown'),\n]\n" }, { "code": null, "e": 2318, "s": 1813, "text": "The first element in each tuple is the name to apply to the group. The second element is an iterable of 2-tuples, with each 2-tuple containing a value and a human-readable name for an option. Grouped options may be combined with ungrouped options within a single list (such as the unknown option in this example).For each model field that has choices set, Django will add a method to retrieve the human-readable name for the field’s current value. See get_FOO_display() in the database API documentation." }, { "code": null, "e": 2332, "s": 2318, "text": "Django-models" }, { "code": null, "e": 2346, "s": 2332, "text": "Python Django" }, { "code": null, "e": 2353, "s": 2346, "text": "Python" }, { "code": null, "e": 2451, "s": 2353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2469, "s": 2451, "text": "Python Dictionary" }, { "code": null, "e": 2511, "s": 2469, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2533, "s": 2511, "text": "Enumerate() in Python" }, { "code": null, "e": 2568, "s": 2533, "text": "Read a file line by line in Python" }, { "code": null, "e": 2594, "s": 2568, "text": "Python String | replace()" }, { "code": null, "e": 2626, "s": 2594, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2655, "s": 2626, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2685, "s": 2655, "text": "Iterate over a list in Python" }, { "code": null, "e": 2712, "s": 2685, "text": "Python Classes and Objects" } ]
How to check if a key exists in a HashMap in Java
11 Dec, 2018 Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: true Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10 Output: false Using Iterator (Not Efficient):Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(3, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); }}Output:HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks} Does key 2 exists: true Program 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use.// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { try { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(null, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); } catch (Exception e) { System.out.println(e); } }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks} java.lang.NullPointerException Using HashMap.containsKey method(Efficient):Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(null, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Check is key exists in the Map boolean isKeyPresent = map.containsKey(keyToBeChecked); // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks} Does key 2 exists: true Using Iterator (Not Efficient):Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(3, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); }}Output:HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks} Does key 2 exists: true Program 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use.// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { try { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(null, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); } catch (Exception e) { System.out.println(e); } }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks} java.lang.NullPointerException Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result. Get the HashMap and the Key Create an iterator to iterate over the HashMap using HashMap.iterate() method. Iterate over the HashMap using the Iterator.hasNext() method. While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method. If the key matches, set the flag as true. The flag value after iterating, contains the result. Below is the implementation of the above approach: Program 1: // Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(3, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); }} HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks} Does key 2 exists: true Program 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use. // Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { try { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(null, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); } catch (Exception e) { System.out.println(e); } }} HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks} java.lang.NullPointerException Using HashMap.containsKey method(Efficient):Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(null, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Check is key exists in the Map boolean isKeyPresent = map.containsKey(keyToBeChecked); // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks} Does key 2 exists: true Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result. Get the HashMap and the Key Check if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true. The flag value, contains the result. Below is the implementation of the above approach: Program 1: // Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, "Geeks"); map.put(2, "ForGeeks"); map.put(null, "GeeksForGeeks"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println("HashMap: " + map); // Check is key exists in the Map boolean isKeyPresent = map.containsKey(keyToBeChecked); // Print the result System.out.println("Does key " + keyToBeChecked + " exists: " + isKeyPresent); }} HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks} Does key 2 exists: true Java-Collections Java-HashMap Java-Map-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Interfaces in Java ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Stack Class in Java Introduction to Java Initialize an ArrayList in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Dec, 2018" }, { "code": null, "e": 152, "s": 54, "text": "Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not." }, { "code": null, "e": 162, "s": 152, "text": "Examples:" }, { "code": null, "e": 307, "s": 162, "text": "Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2\nOutput: true\n\nInput: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10\nOutput: false\n" }, { "code": null, "e": 5328, "s": 307, "text": "Using Iterator (Not Efficient):Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(3, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); }}Output:HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}\nDoes key 2 exists: true\nProgram 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use.// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { try { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(null, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); } catch (Exception e) { System.out.println(e); } }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}\njava.lang.NullPointerException\nUsing HashMap.containsKey method(Efficient):Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(null, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Check is key exists in the Map boolean isKeyPresent = map.containsKey(keyToBeChecked); // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}\nDoes key 2 exists: true\n" }, { "code": null, "e": 9118, "s": 5328, "text": "Using Iterator (Not Efficient):Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(3, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); }}Output:HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}\nDoes key 2 exists: true\nProgram 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use.// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { try { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(null, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); } catch (Exception e) { System.out.println(e); } }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}\njava.lang.NullPointerException\n" }, { "code": null, "e": 9545, "s": 9118, "text": "Get the HashMap and the KeyCreate an iterator to iterate over the HashMap using HashMap.iterate() method.Iterate over the HashMap using the Iterator.hasNext() method.While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.If the key matches, set the flag as true.The flag value after iterating, contains the result." }, { "code": null, "e": 9573, "s": 9545, "text": "Get the HashMap and the Key" }, { "code": null, "e": 9652, "s": 9573, "text": "Create an iterator to iterate over the HashMap using HashMap.iterate() method." }, { "code": null, "e": 9714, "s": 9652, "text": "Iterate over the HashMap using the Iterator.hasNext() method." }, { "code": null, "e": 9882, "s": 9714, "text": "While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method." }, { "code": null, "e": 9924, "s": 9882, "text": "If the key matches, set the flag as true." }, { "code": null, "e": 9977, "s": 9924, "text": "The flag value after iterating, contains the result." }, { "code": null, "e": 10028, "s": 9977, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 10039, "s": 10028, "text": "Program 1:" }, { "code": "// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(3, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); }}", "e": 11380, "s": 10039, "text": null }, { "code": null, "e": 11453, "s": 11380, "text": "HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}\nDoes key 2 exists: true\n" }, { "code": null, "e": 11649, "s": 11453, "text": "Program 2: To show why this method is not suggested. If the HashMap contains null values, then this method will throw NullPointerException. This makes this method a non suggestable method to use." }, { "code": "// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { try { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(null, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Get the iterator over the HashMap Iterator<Map.Entry<Integer, String> > iterator = map.entrySet().iterator(); // flag to store result boolean isKeyPresent = false; // Iterate over the HashMap while (iterator.hasNext()) { // Get the entry at this iteration Map.Entry<Integer, String> entry = iterator.next(); // Check if this key is the required key if (keyToBeChecked == entry.getKey()) { isKeyPresent = true; } } // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); } catch (Exception e) { System.out.println(e); } }}", "e": 13219, "s": 11649, "text": null }, { "code": null, "e": 13302, "s": 13219, "text": "HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}\njava.lang.NullPointerException\n" }, { "code": null, "e": 14534, "s": 13302, "text": "Using HashMap.containsKey method(Efficient):Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result.Below is the implementation of the above approach:Program 1:// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(null, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Check is key exists in the Map boolean isKeyPresent = map.containsKey(keyToBeChecked); // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); }}Output:HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}\nDoes key 2 exists: true\n" }, { "code": null, "e": 14720, "s": 14534, "text": "Get the HashMap and the KeyCheck if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true.The flag value, contains the result." }, { "code": null, "e": 14748, "s": 14720, "text": "Get the HashMap and the Key" }, { "code": null, "e": 14871, "s": 14748, "text": "Check if the key exists in the HashMap or not using HashMap.containsKey() method. If the key exists, set the flag as true." }, { "code": null, "e": 14908, "s": 14871, "text": "The flag value, contains the result." }, { "code": null, "e": 14959, "s": 14908, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 14970, "s": 14959, "text": "Program 1:" }, { "code": "// Java program to check if a key exists// in a HashMap or not import java.util.*; public class GFG { public static void main(String[] args) { // Create a HashMap HashMap<Integer, String> map = new HashMap<>(); // Populate the HashMap map.put(1, \"Geeks\"); map.put(2, \"ForGeeks\"); map.put(null, \"GeeksForGeeks\"); // Get the key to be removed int keyToBeChecked = 2; // Print the initial HashMap System.out.println(\"HashMap: \" + map); // Check is key exists in the Map boolean isKeyPresent = map.containsKey(keyToBeChecked); // Print the result System.out.println(\"Does key \" + keyToBeChecked + \" exists: \" + isKeyPresent); }}", "e": 15831, "s": 14970, "text": null }, { "code": null, "e": 15907, "s": 15831, "text": "HashMap: {null=GeeksForGeeks, 1=Geeks, 2=ForGeeks}\nDoes key 2 exists: true\n" }, { "code": null, "e": 15924, "s": 15907, "text": "Java-Collections" }, { "code": null, "e": 15937, "s": 15924, "text": "Java-HashMap" }, { "code": null, "e": 15955, "s": 15937, "text": "Java-Map-Programs" }, { "code": null, "e": 15960, "s": 15955, "text": "Java" }, { "code": null, "e": 15965, "s": 15960, "text": "Java" }, { "code": null, "e": 15982, "s": 15965, "text": "Java-Collections" }, { "code": null, "e": 16080, "s": 15982, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16131, "s": 16080, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 16150, "s": 16131, "text": "Interfaces in Java" }, { "code": null, "e": 16168, "s": 16150, "text": "ArrayList in Java" }, { "code": null, "e": 16183, "s": 16168, "text": "Stream In Java" }, { "code": null, "e": 16203, "s": 16183, "text": "Collections in Java" }, { "code": null, "e": 16227, "s": 16203, "text": "Singleton Class in Java" }, { "code": null, "e": 16259, "s": 16227, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 16279, "s": 16259, "text": "Stack Class in Java" }, { "code": null, "e": 16300, "s": 16279, "text": "Introduction to Java" } ]
static_cast in C++ | Type Casting operators
29 Aug, 2018 A Cast operator is an unary operator which forces one data type to be converted into another data type.C++ supports four types of casting: 1. Static Cast2. Dynamic Cast3. Const Cast4. Reinterpret Cast Static Cast: This is the simplest type of cast which can be used. It is a compile time cast.It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).For e.g. #include <iostream>using namespace std;int main(){ float f = 3.5; int a = f; // this is how you do in C int b = static_cast<int>(f); cout << b;} Output: 3 Now let’s make a few changes in the code. #include <iostream>using namespace std;int main(){ int a = 10; char c = 'a'; // pass at compile time, may fail at run time int* q = (int*)&c; int* p = static_cast<int*>(&c); return 0;} If you compile the code, you will get an error: [Error] invalid static_cast from type 'char*' to type 'int*' This means that even if you think you can some how typecast a particular object int another but its illegal, static_cast will not allow you to do this. Lets take another example of converting object to and from a class. #include <iostream>#include <string>using namespace std;class Int { int x; public: Int(int x_in = 0) : x{ x_in } { cout << "Conversion Ctor called" << endl; } operator string() { cout << "Conversion Operator" << endl; return to_string(x); }};int main(){ Int obj(3); string str = obj; obj = 20; string str2 = static_cast<string>(obj); obj = static_cast<Int>(30); return 0;} Run the above code: Conversion Ctor called Conversion Operator Conversion Ctor called Conversion Operator Conversion Ctor called Lets the try to understand the above output: When obj is created then constructor is called which in our case is also a Conversion Constructor(For C++14 rules are bit changed).When you create str out of obj, compiler will not thrown an error as we have defined the Conversion operator.When you make obj=20, you are actually calling the conversion constructor.When you make str2 out of static_cast, it is quite similar to string str=obj;, but with a tight type checking.When you write obj=static_cast<Int>(30), you are converting 30 into Int using static_cast. When obj is created then constructor is called which in our case is also a Conversion Constructor(For C++14 rules are bit changed). When you create str out of obj, compiler will not thrown an error as we have defined the Conversion operator. When you make obj=20, you are actually calling the conversion constructor. When you make str2 out of static_cast, it is quite similar to string str=obj;, but with a tight type checking. When you write obj=static_cast<Int>(30), you are converting 30 into Int using static_cast. Lets take example which involves Inheritance. #include <iostream>using namespace std;class Base {};class Derived : public Base {};int main(){ Derived d1; Base* b1 = (Base*)(&d1); // allowed Base* b2 = static_cast<Base*>(&d1); return 0;} The above code will compile without any error. We took address of d1 and explicitly casted it into Base and stored it in b1.We took address of d1 and used static_cast to cast it into Base and stored it in b2. We took address of d1 and explicitly casted it into Base and stored it in b1. We took address of d1 and used static_cast to cast it into Base and stored it in b2. As we know static_cast performs a tight type checking, let’s the changed code slightly to see it: #include <iostream>using namespace std;class Base {};class Derived : private Base { // Inherited private/protected not public};int main(){ Derived d1; Base* b1 = (Base*)(&d1); // allowed Base* b2 = static_cast<Base*>(&d1); return 0;} Try to compile the above code, What do you see?? Compilation Error!!!!!!! [Error] 'Base' is an inaccessible base of 'Derived' The above code will not compile even if you inherit as protected. So to use static_cast, inherit it as public. Use static_cast to cast ‘to and from’ void pointer. #include <iostream>int main(){ int i = 10; void* v = static_cast<void*>(&i); int* ip = static_cast<int*>(v); return 0;} cpp-advanced cpp-pointer C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Templates in C++ with Examples Inheritance in C++ Operator Overloading in C++ Socket Programming in C/C++ Polymorphism in C++ Queue in C++ Standard Template Library (STL) Virtual Function in C++ vector erase() and clear() in C++ C++ Classes and Objects
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Aug, 2018" }, { "code": null, "e": 193, "s": 54, "text": "A Cast operator is an unary operator which forces one data type to be converted into another data type.C++ supports four types of casting:" }, { "code": null, "e": 255, "s": 193, "text": "1. Static Cast2. Dynamic Cast3. Const Cast4. Reinterpret Cast" }, { "code": null, "e": 526, "s": 255, "text": "Static Cast: This is the simplest type of cast which can be used. It is a compile time cast.It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).For e.g." }, { "code": "#include <iostream>using namespace std;int main(){ float f = 3.5; int a = f; // this is how you do in C int b = static_cast<int>(f); cout << b;}", "e": 683, "s": 526, "text": null }, { "code": null, "e": 691, "s": 683, "text": "Output:" }, { "code": null, "e": 693, "s": 691, "text": "3" }, { "code": null, "e": 735, "s": 693, "text": "Now let’s make a few changes in the code." }, { "code": "#include <iostream>using namespace std;int main(){ int a = 10; char c = 'a'; // pass at compile time, may fail at run time int* q = (int*)&c; int* p = static_cast<int*>(&c); return 0;}", "e": 941, "s": 735, "text": null }, { "code": null, "e": 989, "s": 941, "text": "If you compile the code, you will get an error:" }, { "code": null, "e": 1050, "s": 989, "text": "[Error] invalid static_cast from type 'char*' to type 'int*'" }, { "code": null, "e": 1202, "s": 1050, "text": "This means that even if you think you can some how typecast a particular object int another but its illegal, static_cast will not allow you to do this." }, { "code": null, "e": 1270, "s": 1202, "text": "Lets take another example of converting object to and from a class." }, { "code": "#include <iostream>#include <string>using namespace std;class Int { int x; public: Int(int x_in = 0) : x{ x_in } { cout << \"Conversion Ctor called\" << endl; } operator string() { cout << \"Conversion Operator\" << endl; return to_string(x); }};int main(){ Int obj(3); string str = obj; obj = 20; string str2 = static_cast<string>(obj); obj = static_cast<Int>(30); return 0;}", "e": 1711, "s": 1270, "text": null }, { "code": null, "e": 1731, "s": 1711, "text": "Run the above code:" }, { "code": null, "e": 1840, "s": 1731, "text": "Conversion Ctor called\nConversion Operator\nConversion Ctor called\nConversion Operator\nConversion Ctor called" }, { "code": null, "e": 1885, "s": 1840, "text": "Lets the try to understand the above output:" }, { "code": null, "e": 2400, "s": 1885, "text": "When obj is created then constructor is called which in our case is also a Conversion Constructor(For C++14 rules are bit changed).When you create str out of obj, compiler will not thrown an error as we have defined the Conversion operator.When you make obj=20, you are actually calling the conversion constructor.When you make str2 out of static_cast, it is quite similar to string str=obj;, but with a tight type checking.When you write obj=static_cast<Int>(30), you are converting 30 into Int using static_cast." }, { "code": null, "e": 2532, "s": 2400, "text": "When obj is created then constructor is called which in our case is also a Conversion Constructor(For C++14 rules are bit changed)." }, { "code": null, "e": 2642, "s": 2532, "text": "When you create str out of obj, compiler will not thrown an error as we have defined the Conversion operator." }, { "code": null, "e": 2717, "s": 2642, "text": "When you make obj=20, you are actually calling the conversion constructor." }, { "code": null, "e": 2828, "s": 2717, "text": "When you make str2 out of static_cast, it is quite similar to string str=obj;, but with a tight type checking." }, { "code": null, "e": 2919, "s": 2828, "text": "When you write obj=static_cast<Int>(30), you are converting 30 into Int using static_cast." }, { "code": null, "e": 2965, "s": 2919, "text": "Lets take example which involves Inheritance." }, { "code": "#include <iostream>using namespace std;class Base {};class Derived : public Base {};int main(){ Derived d1; Base* b1 = (Base*)(&d1); // allowed Base* b2 = static_cast<Base*>(&d1); return 0;}", "e": 3170, "s": 2965, "text": null }, { "code": null, "e": 3217, "s": 3170, "text": "The above code will compile without any error." }, { "code": null, "e": 3379, "s": 3217, "text": "We took address of d1 and explicitly casted it into Base and stored it in b1.We took address of d1 and used static_cast to cast it into Base and stored it in b2." }, { "code": null, "e": 3457, "s": 3379, "text": "We took address of d1 and explicitly casted it into Base and stored it in b1." }, { "code": null, "e": 3542, "s": 3457, "text": "We took address of d1 and used static_cast to cast it into Base and stored it in b2." }, { "code": null, "e": 3640, "s": 3542, "text": "As we know static_cast performs a tight type checking, let’s the changed code slightly to see it:" }, { "code": "#include <iostream>using namespace std;class Base {};class Derived : private Base { // Inherited private/protected not public};int main(){ Derived d1; Base* b1 = (Base*)(&d1); // allowed Base* b2 = static_cast<Base*>(&d1); return 0;}", "e": 3886, "s": 3640, "text": null }, { "code": null, "e": 3960, "s": 3886, "text": "Try to compile the above code, What do you see?? Compilation Error!!!!!!!" }, { "code": null, "e": 4012, "s": 3960, "text": "[Error] 'Base' is an inaccessible base of 'Derived'" }, { "code": null, "e": 4123, "s": 4012, "text": "The above code will not compile even if you inherit as protected. So to use static_cast, inherit it as public." }, { "code": null, "e": 4175, "s": 4123, "text": "Use static_cast to cast ‘to and from’ void pointer." }, { "code": "#include <iostream>int main(){ int i = 10; void* v = static_cast<void*>(&i); int* ip = static_cast<int*>(v); return 0;}", "e": 4307, "s": 4175, "text": null }, { "code": null, "e": 4320, "s": 4307, "text": "cpp-advanced" }, { "code": null, "e": 4332, "s": 4320, "text": "cpp-pointer" }, { "code": null, "e": 4336, "s": 4332, "text": "C++" }, { "code": null, "e": 4340, "s": 4336, "text": "CPP" }, { "code": null, "e": 4438, "s": 4340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4465, "s": 4438, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 4496, "s": 4465, "text": "Templates in C++ with Examples" }, { "code": null, "e": 4515, "s": 4496, "text": "Inheritance in C++" }, { "code": null, "e": 4543, "s": 4515, "text": "Operator Overloading in C++" }, { "code": null, "e": 4571, "s": 4543, "text": "Socket Programming in C/C++" }, { "code": null, "e": 4591, "s": 4571, "text": "Polymorphism in C++" }, { "code": null, "e": 4636, "s": 4591, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 4660, "s": 4636, "text": "Virtual Function in C++" }, { "code": null, "e": 4694, "s": 4660, "text": "vector erase() and clear() in C++" } ]
How to fetch images from Node.js server ?
21 Nov, 2021 The images, CSS files, JavaScript files, and other files that the client downloads from the server are known as static files. These static files can be fetched with the use of the express framework and without the use of it. The methods that can be used to serve static files are discussed below. The image to be accessed (geeksforgeeks.png) is placed inside the images folder, as shown in the directory tree below: Directory Tree: server.js package.json package-lock.json nodemoules | -- * images | -- geeksforgeeks.png public | -- index.html Method 1: Using the Express framework: Using the express framework its built-in middleware function express.static() can be used to serve static files. Syntax: express.static(root, [options]) Parameters: This method accepts two parameters as mentioned above and described below: root: It specifies the directory from which the static files are to be served. Basically, all the static files reside in the public directory. options: It is used to specify other options which you can read more about here. Example: The following code is an example of how to get an image or other static files from the node server. Filename: server.js Javascript // Requiring moduleconst express = require('express'); // Creating express objectconst app = express(); // Defining port numberconst PORT = 3000; // Function to serve all static files// inside public directory.app.use(express.static('public')); app.use('/images', express.static('images')); // Server setupapp.listen(PORT, () => { console.log(`Running server on PORT ${PORT}...`);}) Steps to run the program: 1. Install express using the following command: npm install express 2. Run the server.js file using the following command: node server.js 3. Open any browser and to go http://localhost:3000/images/geeksforgeeks.png and you will see the following output: The output of the above command Method 2: Without using the express framework: To serve static files using the fundamentals of Node.js, we can follow these steps: Parse the incoming HTTP request, to know the requested path.Check if the path exists to respond to status as success or not found (optional).Get the extension of the file to set content-type.Serve the content-type in the header and serve the requested file in response. Parse the incoming HTTP request, to know the requested path. Check if the path exists to respond to status as success or not found (optional). Get the extension of the file to set content-type. Serve the content-type in the header and serve the requested file in response. Filename: server.js Javascript // Requiring modulesconst http = require("http");const fs = require("fs");const path = require("path");const url = require("url"); // Creating server to accept requesthttp.createServer((req, res) => { // Parsing the URL var request = url.parse(req.url, true); // Extracting the path of file var action = request.pathname; // Path Refinements var filePath = path.join(__dirname, action).split("%20").join(" "); // Checking if the path exists fs.exists(filePath, function (exists) { if (!exists) { res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 Not Found"); return; } // Extracting file extension var ext = path.extname(action); // Setting default Content-Type var contentType = "text/plain"; // Checking if the extension of // image is '.png' if (ext === ".png") { contentType = "image/png"; } // Setting the headers res.writeHead(200, { "Content-Type": contentType }); // Reading the file fs.readFile(filePath, function (err, content) { // Serving the image res.end(content); }); });}) // Listening to the PORT: 3000.listen(3000, "127.0.0.1"); Steps to run the program: 1. Install express using the following command: npm install express 2. Run the server.js file using the following command: node server.js 3. Open any browser and to go http://localhost:3000/images/geeksforgeeks.png and you will see the following output: The output of the above command mridulmanochagfg simmytarika5 surinderdawra388 NodeJS-Questions Picked Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Nov, 2021" }, { "code": null, "e": 350, "s": 53, "text": "The images, CSS files, JavaScript files, and other files that the client downloads from the server are known as static files. These static files can be fetched with the use of the express framework and without the use of it. The methods that can be used to serve static files are discussed below." }, { "code": null, "e": 469, "s": 350, "text": "The image to be accessed (geeksforgeeks.png) is placed inside the images folder, as shown in the directory tree below:" }, { "code": null, "e": 485, "s": 469, "text": "Directory Tree:" }, { "code": null, "e": 603, "s": 485, "text": "server.js\npackage.json\npackage-lock.json\nnodemoules\n | -- *\nimages\n | -- geeksforgeeks.png\npublic\n | -- index.html" }, { "code": null, "e": 756, "s": 603, "text": "Method 1: Using the Express framework: Using the express framework its built-in middleware function express.static() can be used to serve static files. " }, { "code": null, "e": 764, "s": 756, "text": "Syntax:" }, { "code": null, "e": 796, "s": 764, "text": "express.static(root, [options])" }, { "code": null, "e": 883, "s": 796, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 1026, "s": 883, "text": "root: It specifies the directory from which the static files are to be served. Basically, all the static files reside in the public directory." }, { "code": null, "e": 1107, "s": 1026, "text": "options: It is used to specify other options which you can read more about here." }, { "code": null, "e": 1216, "s": 1107, "text": "Example: The following code is an example of how to get an image or other static files from the node server." }, { "code": null, "e": 1236, "s": 1216, "text": "Filename: server.js" }, { "code": null, "e": 1247, "s": 1236, "text": "Javascript" }, { "code": "// Requiring moduleconst express = require('express'); // Creating express objectconst app = express(); // Defining port numberconst PORT = 3000; // Function to serve all static files// inside public directory.app.use(express.static('public')); app.use('/images', express.static('images')); // Server setupapp.listen(PORT, () => { console.log(`Running server on PORT ${PORT}...`);})", "e": 1648, "s": 1247, "text": null }, { "code": null, "e": 1674, "s": 1648, "text": "Steps to run the program:" }, { "code": null, "e": 1722, "s": 1674, "text": "1. Install express using the following command:" }, { "code": null, "e": 1742, "s": 1722, "text": "npm install express" }, { "code": null, "e": 1797, "s": 1742, "text": "2. Run the server.js file using the following command:" }, { "code": null, "e": 1812, "s": 1797, "text": "node server.js" }, { "code": null, "e": 1930, "s": 1814, "text": "3. Open any browser and to go http://localhost:3000/images/geeksforgeeks.png and you will see the following output:" }, { "code": null, "e": 1962, "s": 1930, "text": "The output of the above command" }, { "code": null, "e": 2093, "s": 1962, "text": "Method 2: Without using the express framework: To serve static files using the fundamentals of Node.js, we can follow these steps:" }, { "code": null, "e": 2363, "s": 2093, "text": "Parse the incoming HTTP request, to know the requested path.Check if the path exists to respond to status as success or not found (optional).Get the extension of the file to set content-type.Serve the content-type in the header and serve the requested file in response." }, { "code": null, "e": 2424, "s": 2363, "text": "Parse the incoming HTTP request, to know the requested path." }, { "code": null, "e": 2506, "s": 2424, "text": "Check if the path exists to respond to status as success or not found (optional)." }, { "code": null, "e": 2557, "s": 2506, "text": "Get the extension of the file to set content-type." }, { "code": null, "e": 2636, "s": 2557, "text": "Serve the content-type in the header and serve the requested file in response." }, { "code": null, "e": 2656, "s": 2636, "text": "Filename: server.js" }, { "code": null, "e": 2667, "s": 2656, "text": "Javascript" }, { "code": "// Requiring modulesconst http = require(\"http\");const fs = require(\"fs\");const path = require(\"path\");const url = require(\"url\"); // Creating server to accept requesthttp.createServer((req, res) => { // Parsing the URL var request = url.parse(req.url, true); // Extracting the path of file var action = request.pathname; // Path Refinements var filePath = path.join(__dirname, action).split(\"%20\").join(\" \"); // Checking if the path exists fs.exists(filePath, function (exists) { if (!exists) { res.writeHead(404, { \"Content-Type\": \"text/plain\" }); res.end(\"404 Not Found\"); return; } // Extracting file extension var ext = path.extname(action); // Setting default Content-Type var contentType = \"text/plain\"; // Checking if the extension of // image is '.png' if (ext === \".png\") { contentType = \"image/png\"; } // Setting the headers res.writeHead(200, { \"Content-Type\": contentType }); // Reading the file fs.readFile(filePath, function (err, content) { // Serving the image res.end(content); }); });}) // Listening to the PORT: 3000.listen(3000, \"127.0.0.1\");", "e": 3999, "s": 2667, "text": null }, { "code": null, "e": 4025, "s": 3999, "text": "Steps to run the program:" }, { "code": null, "e": 4073, "s": 4025, "text": "1. Install express using the following command:" }, { "code": null, "e": 4093, "s": 4073, "text": "npm install express" }, { "code": null, "e": 4148, "s": 4093, "text": "2. Run the server.js file using the following command:" }, { "code": null, "e": 4163, "s": 4148, "text": "node server.js" }, { "code": null, "e": 4279, "s": 4163, "text": "3. Open any browser and to go http://localhost:3000/images/geeksforgeeks.png and you will see the following output:" }, { "code": null, "e": 4311, "s": 4279, "text": "The output of the above command" }, { "code": null, "e": 4328, "s": 4311, "text": "mridulmanochagfg" }, { "code": null, "e": 4341, "s": 4328, "text": "simmytarika5" }, { "code": null, "e": 4358, "s": 4341, "text": "surinderdawra388" }, { "code": null, "e": 4375, "s": 4358, "text": "NodeJS-Questions" }, { "code": null, "e": 4382, "s": 4375, "text": "Picked" }, { "code": null, "e": 4406, "s": 4382, "text": "Technical Scripter 2020" }, { "code": null, "e": 4414, "s": 4406, "text": "Node.js" }, { "code": null, "e": 4433, "s": 4414, "text": "Technical Scripter" }, { "code": null, "e": 4450, "s": 4433, "text": "Web Technologies" } ]
Ruby | Loops (for, while, do..while, until)
05 Jul, 2021 Looping in programming languages is a feature which clears the way for the execution of a set of instructions or functions repeatedly when some of the condition evaluates to true or false. Ruby provides the different types of loop to handle the condition based situation in the program to make the programmers task simpler. The loops in Ruby are : while loop for loop do..while loop until loop while Loop The condition which is to be tested, given at the beginning of the loop and all statements are executed until the given boolean condition satisfies. When the condition becomes false, the control will be out from the while loop. It is also known as Entry Controlled Loop because the condition to be tested is present at the beginning of the loop body. So basically, while loop is used when the number of iterations is not fixed in a program. Syntax: while conditional [do] # code to be executed end Note: A while loop’s conditional is separated from code by the reserved word do, a newline, backslash(\), or a semicolon(;).Flowchart: Example: Ruby # Ruby program to illustrate 'while' loop # variable xx = 4 # using while loop# here conditional is x i.e. 4while x >= 1 # statements to be executed puts "GeeksforGeeks" x = x - 1 # while loop ends hereend Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks for Loop “for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers. It is also known as Entry Controlled Loop because the condition to be tested is present at the beginning of the loop body.Syntax: for variable_name[, variable...] in expression [do] # code to be executed end for: A special Ruby keyword which indicates the beginning of the loop.variable_name: This is a variable name that serves as the reference to the current iteration of the loop. in: This is a special Ruby keyword that is primarily used in for loop.expression: It executes code once for each element in expression. Here expression can be range or array variable.do: This indicates the beginning of the block of code to be repeatedly executed. do is optional.end: This keyword represents the ending of ‘for‘ loop block which started from ‘do‘ keyword.Example 1: Ruby # Ruby program to illustrate 'for'# loop using range as expression i = "Sudo Placements" # using for loop with the rangefor a in 1..5 do puts i end Output: Sudo Placements Sudo Placements Sudo Placements Sudo Placements Sudo Placements Output: 1 2 3 4 5 Explanation: Here, we have defined the range 1..5. Range Operators create a range of successive values consisting of a start, end, and range of values in between. The (..) creates a range including the last term. The statement for a in 1..5 will allow a to take values in the range from 1 to 5 (including 5).Example 2: Ruby # Ruby program to illustrate 'for'# loop using array as expression # arrayarr = ["GFG", "G4G", "Geeks", "Sudo"] # using for loopfor i in arr do puts i end Output: GFG G4G Geeks Sudo do..while Loop do while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e it will execute the loop body one time for sure. It is a Exit-Controlled loop because it tests the condition which presents at the end of the loop body. Syntax: loop do # code to be executed break if Boolean_Expression end Here, Boolean_Expression will result in either a true or false output which is created using comparing operators (>, =, <=, !=, ==). You can also use multiple boolean expressions within the parentheses (Boolean_Expressions) which will be connected through logical operators (&&, ||, !).Example: Ruby # Ruby program to illustrate 'do..while'loop # starting of do..while looploop do puts "GeeksforGeeks" val = '7' # using boolean expressions if val == '7' break end # ending of ruby do..while loopend Output: GeeksforGeeks until Loop Ruby until loop will executes the statements or code till the given condition evaluates to true. Basically it’s just opposite to the while loop which executes until the given condition evaluates to false. An until statement’s conditional is separated from code by the reserved word do, a newline, or a semicolon.Syntax: until conditional [do] # code to be executed end Example: Ruby # Ruby program to illustrate 'until' loop var = 7 # using until loop# here do is optionaluntil var == 11 do # code to be executed puts var * 10 var = var + 1 # here loop endsend Output: 70 80 90 100 sagar0719kumar Ruby-Basics Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Global Variable in Ruby Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Hash delete() function Ruby | unless Statement and unless Modifier Ruby | Data Types Ruby For Beginners Ruby | String capitalize() Method
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2021" }, { "code": null, "e": 401, "s": 52, "text": "Looping in programming languages is a feature which clears the way for the execution of a set of instructions or functions repeatedly when some of the condition evaluates to true or false. Ruby provides the different types of loop to handle the condition based situation in the program to make the programmers task simpler. The loops in Ruby are : " }, { "code": null, "e": 412, "s": 401, "text": "while loop" }, { "code": null, "e": 421, "s": 412, "text": "for loop" }, { "code": null, "e": 436, "s": 421, "text": "do..while loop" }, { "code": null, "e": 447, "s": 436, "text": "until loop" }, { "code": null, "e": 460, "s": 449, "text": "while Loop" }, { "code": null, "e": 910, "s": 460, "text": "The condition which is to be tested, given at the beginning of the loop and all statements are executed until the given boolean condition satisfies. When the condition becomes false, the control will be out from the while loop. It is also known as Entry Controlled Loop because the condition to be tested is present at the beginning of the loop body. So basically, while loop is used when the number of iterations is not fixed in a program. Syntax: " }, { "code": null, "e": 962, "s": 910, "text": "while conditional [do]\n\n # code to be executed\n\nend" }, { "code": null, "e": 1098, "s": 962, "text": "Note: A while loop’s conditional is separated from code by the reserved word do, a newline, backslash(\\), or a semicolon(;).Flowchart: " }, { "code": null, "e": 1108, "s": 1098, "text": "Example: " }, { "code": null, "e": 1113, "s": 1108, "text": "Ruby" }, { "code": "# Ruby program to illustrate 'while' loop # variable xx = 4 # using while loop# here conditional is x i.e. 4while x >= 1 # statements to be executed puts \"GeeksforGeeks\" x = x - 1 # while loop ends hereend", "e": 1323, "s": 1113, "text": null }, { "code": null, "e": 1332, "s": 1323, "text": "Output: " }, { "code": null, "e": 1388, "s": 1332, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks" }, { "code": null, "e": 1399, "s": 1390, "text": "for Loop" }, { "code": null, "e": 1757, "s": 1399, "text": "“for” loop has similar functionality as while loop but with different syntax. for loop is preferred when the number of times loop statements are to be executed is known beforehand. It iterates over a specific range of numbers. It is also known as Entry Controlled Loop because the condition to be tested is present at the beginning of the loop body.Syntax: " }, { "code": null, "e": 1840, "s": 1757, "text": "for variable_name[, variable...] in expression [do]\n\n # code to be executed\n\nend" }, { "code": null, "e": 2399, "s": 1840, "text": "for: A special Ruby keyword which indicates the beginning of the loop.variable_name: This is a variable name that serves as the reference to the current iteration of the loop. in: This is a special Ruby keyword that is primarily used in for loop.expression: It executes code once for each element in expression. Here expression can be range or array variable.do: This indicates the beginning of the block of code to be repeatedly executed. do is optional.end: This keyword represents the ending of ‘for‘ loop block which started from ‘do‘ keyword.Example 1: " }, { "code": null, "e": 2404, "s": 2399, "text": "Ruby" }, { "code": "# Ruby program to illustrate 'for'# loop using range as expression i = \"Sudo Placements\" # using for loop with the rangefor a in 1..5 do puts i end", "e": 2558, "s": 2404, "text": null }, { "code": null, "e": 2568, "s": 2558, "text": "Output: " }, { "code": null, "e": 2648, "s": 2568, "text": "Sudo Placements\nSudo Placements\nSudo Placements\nSudo Placements\nSudo Placements" }, { "code": null, "e": 2658, "s": 2648, "text": "Output: " }, { "code": null, "e": 2668, "s": 2658, "text": "1\n2\n3\n4\n5" }, { "code": null, "e": 2988, "s": 2668, "text": "Explanation: Here, we have defined the range 1..5. Range Operators create a range of successive values consisting of a start, end, and range of values in between. The (..) creates a range including the last term. The statement for a in 1..5 will allow a to take values in the range from 1 to 5 (including 5).Example 2: " }, { "code": null, "e": 2993, "s": 2988, "text": "Ruby" }, { "code": "# Ruby program to illustrate 'for'# loop using array as expression # arrayarr = [\"GFG\", \"G4G\", \"Geeks\", \"Sudo\"] # using for loopfor i in arr do puts i end", "e": 3155, "s": 2993, "text": null }, { "code": null, "e": 3165, "s": 3155, "text": "Output: " }, { "code": null, "e": 3184, "s": 3165, "text": "GFG\nG4G\nGeeks\nSudo" }, { "code": null, "e": 3201, "s": 3186, "text": "do..while Loop" }, { "code": null, "e": 3492, "s": 3201, "text": "do while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e it will execute the loop body one time for sure. It is a Exit-Controlled loop because it tests the condition which presents at the end of the loop body. Syntax: " }, { "code": null, "e": 3558, "s": 3492, "text": "loop do\n\n # code to be executed\n\nbreak if Boolean_Expression\n\nend" }, { "code": null, "e": 3854, "s": 3558, "text": "Here, Boolean_Expression will result in either a true or false output which is created using comparing operators (>, =, <=, !=, ==). You can also use multiple boolean expressions within the parentheses (Boolean_Expressions) which will be connected through logical operators (&&, ||, !).Example: " }, { "code": null, "e": 3859, "s": 3854, "text": "Ruby" }, { "code": "# Ruby program to illustrate 'do..while'loop # starting of do..while looploop do puts \"GeeksforGeeks\" val = '7' # using boolean expressions if val == '7' break end # ending of ruby do..while loopend", "e": 4069, "s": 3859, "text": null }, { "code": null, "e": 4079, "s": 4069, "text": "Output: " }, { "code": null, "e": 4093, "s": 4079, "text": "GeeksforGeeks" }, { "code": null, "e": 4106, "s": 4095, "text": "until Loop" }, { "code": null, "e": 4428, "s": 4106, "text": "Ruby until loop will executes the statements or code till the given condition evaluates to true. Basically it’s just opposite to the while loop which executes until the given condition evaluates to false. An until statement’s conditional is separated from code by the reserved word do, a newline, or a semicolon.Syntax: " }, { "code": null, "e": 4480, "s": 4428, "text": "until conditional [do]\n\n # code to be executed\n\nend" }, { "code": null, "e": 4490, "s": 4480, "text": "Example: " }, { "code": null, "e": 4495, "s": 4490, "text": "Ruby" }, { "code": "# Ruby program to illustrate 'until' loop var = 7 # using until loop# here do is optionaluntil var == 11 do # code to be executed puts var * 10 var = var + 1 # here loop endsend", "e": 4679, "s": 4495, "text": null }, { "code": null, "e": 4689, "s": 4679, "text": "Output: " }, { "code": null, "e": 4702, "s": 4689, "text": "70\n80\n90\n100" }, { "code": null, "e": 4719, "s": 4704, "text": "sagar0719kumar" }, { "code": null, "e": 4731, "s": 4719, "text": "Ruby-Basics" }, { "code": null, "e": 4736, "s": 4731, "text": "Ruby" }, { "code": null, "e": 4834, "s": 4736, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4880, "s": 4834, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 4904, "s": 4880, "text": "Global Variable in Ruby" }, { "code": null, "e": 4947, "s": 4904, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 4969, "s": 4947, "text": "Ruby | Case Statement" }, { "code": null, "e": 5000, "s": 4969, "text": "Ruby | Array select() function" }, { "code": null, "e": 5030, "s": 5000, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 5074, "s": 5030, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 5092, "s": 5074, "text": "Ruby | Data Types" }, { "code": null, "e": 5111, "s": 5092, "text": "Ruby For Beginners" } ]
Python | Pandas dataframe.notna()
27 Aug, 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 dataframe.notna() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the same size as that of the object on which it is applied, indicating whether each individual value is a na value or not. All of the non-missing values gets mapped to true and missing values get mapped to false. Note : Characters such as empty strings ” or numpy.inf are not considered NA values. (unless you set pandas.options.mode.use_inf_as_na = True). Syntax: DataFrame.notna()Returns : Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value Example #1: Use notna() function to find all the non-missing value in the dataframe. Python3 # importing pandas as pdimport pandas as pd # Creating the first dataframedf = pd.DataFrame({"A":[14, 4, 5, 4, 1], "B":[5, 2, 54, 3, 2], "C":[20, 20, 7, 3, 8], "D":[14, 3, 6, 2, 6]}) # Print the dataframedf Let’s use the dataframe.notna() function to find all the non-missing values in the dataframe. Python3 # find non-na valuesdf.notna() Output : As we can see in the output, all the non-missing values in the dataframe has been mapped to true. There is no false value as there is no missing value in the dataframe. Example #2: Use notna() function to find the non-missing values, when there are missing values in the dataframe. Python3 # importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({"A":[12, 4, 5, None, 1], "B":[7, 2, 54, 3, None], "C":[20, 16, 11, 3, 8], "D":[14, 3, None, 2, 6]}) # find non-missing valuesdf.notna() Output : As we can see in the output, cells which were having na values were mapped as false and all the cells which were having non-missing values were mapped as true. Python | Pandas dataframe.notna() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.notna() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:23•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KJ8cm4HtQc0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> anikakapoor 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 Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Aug, 2021" }, { "code": null, "e": 759, "s": 54, "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 dataframe.notna() function detects existing/ non-missing values in the dataframe. The function returns a boolean object having the same size as that of the object on which it is applied, indicating whether each individual value is a na value or not. All of the non-missing values gets mapped to true and missing values get mapped to false. Note : Characters such as empty strings ” or numpy.inf are not considered NA values. (unless you set pandas.options.mode.use_inf_as_na = True). " }, { "code": null, "e": 899, "s": 759, "text": "Syntax: DataFrame.notna()Returns : Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value " }, { "code": null, "e": 985, "s": 899, "text": "Example #1: Use notna() function to find all the non-missing value in the dataframe. " }, { "code": null, "e": 993, "s": 985, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first dataframedf = pd.DataFrame({\"A\":[14, 4, 5, 4, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 20, 7, 3, 8], \"D\":[14, 3, 6, 2, 6]}) # Print the dataframedf", "e": 1254, "s": 993, "text": null }, { "code": null, "e": 1350, "s": 1254, "text": "Let’s use the dataframe.notna() function to find all the non-missing values in the dataframe. " }, { "code": null, "e": 1358, "s": 1350, "text": "Python3" }, { "code": "# find non-na valuesdf.notna()", "e": 1389, "s": 1358, "text": null }, { "code": null, "e": 1400, "s": 1389, "text": "Output : " }, { "code": null, "e": 1684, "s": 1400, "text": "As we can see in the output, all the non-missing values in the dataframe has been mapped to true. There is no false value as there is no missing value in the dataframe. Example #2: Use notna() function to find the non-missing values, when there are missing values in the dataframe. " }, { "code": null, "e": 1692, "s": 1684, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframedf = pd.DataFrame({\"A\":[12, 4, 5, None, 1], \"B\":[7, 2, 54, 3, None], \"C\":[20, 16, 11, 3, 8], \"D\":[14, 3, None, 2, 6]}) # find non-missing valuesdf.notna()", "e": 1969, "s": 1692, "text": null }, { "code": null, "e": 1980, "s": 1969, "text": "Output : " }, { "code": null, "e": 2142, "s": 1980, "text": "As we can see in the output, cells which were having na values were mapped as false and all the cells which were having non-missing values were mapped as true. " }, { "code": null, "e": 3026, "s": 2142, "text": "Python | Pandas dataframe.notna() | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPython | Pandas dataframe.notna() | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:23•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=KJ8cm4HtQc0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 3040, "s": 3028, "text": "anikakapoor" }, { "code": null, "e": 3064, "s": 3040, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3096, "s": 3064, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 3110, "s": 3096, "text": "Python-pandas" }, { "code": null, "e": 3117, "s": 3110, "text": "Python" }, { "code": null, "e": 3215, "s": 3117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3233, "s": 3215, "text": "Python Dictionary" }, { "code": null, "e": 3275, "s": 3233, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3297, "s": 3275, "text": "Enumerate() in Python" }, { "code": null, "e": 3332, "s": 3297, "text": "Read a file line by line in Python" }, { "code": null, "e": 3358, "s": 3332, "text": "Python String | replace()" }, { "code": null, "e": 3390, "s": 3358, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3419, "s": 3390, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3446, "s": 3419, "text": "Python Classes and Objects" }, { "code": null, "e": 3476, "s": 3446, "text": "Iterate over a list in Python" } ]
How to insert DATE in MySQL table with TRIGGERS?
Let us first create a table − mysql> create table DemoTable1584 -> ( -> DueDate datetime -> ); Query OK, 0 rows affected (1.79 sec) Here is the query to insert DATE in a MySQL − mysql> create trigger insertDate before insert on DemoTable1584 -> for each row set new.DueDate=curdate(); Query OK, 0 rows affected (0.22 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1584 values(); Query OK, 1 row affected (0.66 sec) mysql> insert into DemoTable1584 values(); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1584 values(); Query OK, 1 row affected (0.07 sec) Display all records from the table using select statement − mysql> select * from DemoTable1584; This will produce the following output − +---------------------+ | DueDate | +---------------------+ | 2019-10-18 00:00:00 | | 2019-10-18 00:00:00 | | 2019-10-18 00:00:00 | +---------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1217, "s": 1187, "text": "Let us first create a table −" }, { "code": null, "e": 1328, "s": 1217, "text": "mysql> create table DemoTable1584\n -> (\n -> DueDate datetime\n -> );\nQuery OK, 0 rows affected (1.79 sec)" }, { "code": null, "e": 1374, "s": 1328, "text": "Here is the query to insert DATE in a MySQL −" }, { "code": null, "e": 1522, "s": 1374, "text": "mysql> create trigger insertDate before insert on DemoTable1584\n -> for each row set new.DueDate=curdate();\nQuery OK, 0 rows affected (0.22 sec)" }, { "code": null, "e": 1578, "s": 1522, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1815, "s": 1578, "text": "mysql> insert into DemoTable1584 values();\nQuery OK, 1 row affected (0.66 sec)\nmysql> insert into DemoTable1584 values();\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1584 values();\nQuery OK, 1 row affected (0.07 sec)" }, { "code": null, "e": 1875, "s": 1815, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1911, "s": 1875, "text": "mysql> select * from DemoTable1584;" }, { "code": null, "e": 1952, "s": 1911, "text": "This will produce the following output −" }, { "code": null, "e": 2145, "s": 1952, "text": "+---------------------+\n| DueDate |\n+---------------------+\n| 2019-10-18 00:00:00 |\n| 2019-10-18 00:00:00 |\n| 2019-10-18 00:00:00 |\n+---------------------+\n3 rows in set (0.00 sec)" } ]
NHibernate - Getting Started
In this chapter, we will look at how to start a simple example using NHibernate. We will be building a simple console application. To create a console application, we will use Visual Studio 2015, which contains all of the features you need to create, test your application using the NHibernate package. Following are the steps to create a project using project templates available in the Visual Studio. Step 1 − Open the Visual studio and click File → New → Project menu option. Step 2 − A new Project dialog opens. Step 3 − From the left pane, select Templates → Visual C# → Windows. Step 4 − In the middle pane, select Console Application. Step 5 − Enter the project name, ‘NHibernateDemoApp’, in the Name field and click Ok to continue. Step 6 − Once the project is created by Visual Studio, you will see a number of files displayed in the Solution Explorer window. As you know that we have created a simple console application project, now we need to include the NHibernate package to our console project. Go to the Tools menu and select NuGet Package Manager → Package Manager Console, it will open the Package Manager Console window. Specify the command shown in the above Package Manager Console window and press enter, it will download all the NHibernate dependencies and create references to all of the required assemblies. Once the installation is finished, you will see the message as shown in the following image. Now that we have NHibernate added, we can now start implementation. So, we are going to start out by mapping a very simple table called Student, which simply has an integer primary key called ID and a FirstName and LastName column. We need a class to represent this student, so let’s create a new class called Student by right clicking on the project in the solution explorer and then select Add → Class which will open the Add New Item dialog box. Enter Student.cs in the name field, click the Add button. In this Student class, we need to have our integer primary key called ID, and we need to create this string, FirstName and LastName fields as shown in the following complete implementation of Student class. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NHibernateDemoApp { class Student { public virtual int ID { get; set; } public virtual string LastName { get; set; } public virtual string FirstMidName { get; set; } } } When dealing with models in NHibernate application, it is easiest to make all of your fields virtual. So this is our simple NHibernate model that we will use and will map this to the back end database. Now let’s go to the Main method in the Program class and create a new NHibernate configuration object. The first thing that we need to provide is the connection string. This is a database specific connection string and the easiest way to find the connection string is that right click on the database in SQL Server Object Explorer and select Properties. It will open the Properties Window, now scroll down and you will see the Connection String field in the Properties window. Copy the Connection string and specify in your code. Following is the implementation of Main method in which we need configuration for NHibernate. using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using System; using System.Linq; using System.Reflection; namespace NHibernateDemoApp { class Program { static void Main(string[] args) { var cfg = new Configuration(); String Data Source = asia13797\\sqlexpress; String Initial Catalog = NHibernateDemoDB; String Integrated Security = True; String Connect Timeout = 15; String Encrypt = False; String TrustServerCertificate = False; String ApplicationIntent = ReadWrite; String MultiSubnetFailover = False; cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source + Initial Catalog + Integrated Security + Connect Timeout + Encrypt + TrustServerCertificate + ApplicationIntent + MultiSubnetFailover"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); }); cfg.AddAssembly(Assembly.GetExecutingAssembly()); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { //perform database logic tx.Commit(); } Console.ReadLine(); } } } } After the connection string, we need to supply a driver, which is the SQLClientDriver and then we also need to provide it a dialect, which version of SQL Server, and we are going to use MS SQL 2008. NHibernate now knows how to connect to the database. The other thing we need to do is to provide it a list of models that we will map. We can do this by adding an assembly, so by specifying the Assembly.GetExecutingAssembly and this is where program will find mapping files. Mapping files tell NHibernate how to go from C# classes into database tables. SessionFactory compiles all the metadata necessary for initializing NHibernate. SessionFactory can be used to build sessions, which are roughly analogous to database connections. So the appropriate way is to use it in the using block. I can say var session equals sessionFactory.OpenSession and I'm going to want to do this inside of its transaction. Once the session is opened, we can tell the session to begin a new transaction and we can then perform some logic in here. So perform some database logic and finally commit that transaction.
[ { "code": null, "e": 2770, "s": 2467, "text": "In this chapter, we will look at how to start a simple example using NHibernate. We will be building a simple console application. To create a console application, we will use Visual Studio 2015, which contains all of the features you need to create, test your application using the NHibernate package." }, { "code": null, "e": 2870, "s": 2770, "text": "Following are the steps to create a project using project templates available in the Visual Studio." }, { "code": null, "e": 2946, "s": 2870, "text": "Step 1 − Open the Visual studio and click File → New → Project menu option." }, { "code": null, "e": 2983, "s": 2946, "text": "Step 2 − A new Project dialog opens." }, { "code": null, "e": 3052, "s": 2983, "text": "Step 3 − From the left pane, select Templates → Visual C# → Windows." }, { "code": null, "e": 3109, "s": 3052, "text": "Step 4 − In the middle pane, select Console Application." }, { "code": null, "e": 3207, "s": 3109, "text": "Step 5 − Enter the project name, ‘NHibernateDemoApp’, in the Name field and click Ok to continue." }, { "code": null, "e": 3336, "s": 3207, "text": "Step 6 − Once the project is created by Visual Studio, you will see a number of files displayed in the Solution Explorer window." }, { "code": null, "e": 3477, "s": 3336, "text": "As you know that we have created a simple console application project, now we need to include the NHibernate package to our console project." }, { "code": null, "e": 3607, "s": 3477, "text": "Go to the Tools menu and select NuGet Package Manager → Package Manager Console, it will open the Package Manager Console window." }, { "code": null, "e": 3893, "s": 3607, "text": "Specify the command shown in the above Package Manager Console window and press enter, it will download all the NHibernate dependencies and create references to all of the required assemblies. Once the installation is finished, you will see the message as shown in the following image." }, { "code": null, "e": 4125, "s": 3893, "text": "Now that we have NHibernate added, we can now start implementation. So, we are going to start out by mapping a very simple table called Student, which simply has an integer primary key called ID and a FirstName and LastName column." }, { "code": null, "e": 4342, "s": 4125, "text": "We need a class to represent this student, so let’s create a new class called Student by right clicking on the project in the solution explorer and then select Add → Class which will open the Add New Item dialog box." }, { "code": null, "e": 4607, "s": 4342, "text": "Enter Student.cs in the name field, click the Add button. In this Student class, we need to have our integer primary key called ID, and we need to create this string, FirstName and LastName fields as shown in the following complete implementation of Student class." }, { "code": null, "e": 4942, "s": 4607, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace NHibernateDemoApp { \n \n class Student { \n public virtual int ID { get; set; } \n public virtual string LastName { get; set; } \n public virtual string FirstMidName { get; set; } \n } \n}" }, { "code": null, "e": 5144, "s": 4942, "text": "When dealing with models in NHibernate application, it is easiest to make all of your fields virtual. So this is our simple NHibernate model that we will use and will map this to the back end database." }, { "code": null, "e": 5247, "s": 5144, "text": "Now let’s go to the Main method in the Program class and create a new NHibernate configuration object." }, { "code": null, "e": 5498, "s": 5247, "text": "The first thing that we need to provide is the connection string. This is a database specific connection string and the easiest way to find the connection string is that right click on the database in SQL Server Object Explorer and select Properties." }, { "code": null, "e": 5621, "s": 5498, "text": "It will open the Properties Window, now scroll down and you will see the Connection String field in the Properties window." }, { "code": null, "e": 5768, "s": 5621, "text": "Copy the Connection string and specify in your code. Following is the implementation of Main method in which we need configuration for NHibernate." }, { "code": null, "e": 7189, "s": 5768, "text": "using NHibernate.Cfg;\nusing NHibernate.Dialect;\nusing NHibernate.Driver;\n\nusing System;\nusing System.Linq;\nusing System.Reflection;\n\nnamespace NHibernateDemoApp {\n\n class Program {\n \n static void Main(string[] args) {\n var cfg = new Configuration();\n\t\t\t\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\n\t\t\t\n cfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\";\n \n \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>();\n });\n \n cfg.AddAssembly(Assembly.GetExecutingAssembly());\n \n var sefact = cfg.BuildSessionFactory(); \n \n using (var session = sefact.OpenSession()) {\n \n using (var tx = session.BeginTransaction()) {\n //perform database logic \n tx.Commit();\n }\n \n Console.ReadLine(); \n } \n } \n } \n}" }, { "code": null, "e": 7388, "s": 7189, "text": "After the connection string, we need to supply a driver, which is the SQLClientDriver and then we also need to provide it a dialect, which version of SQL Server, and we are going to use MS SQL 2008." }, { "code": null, "e": 7523, "s": 7388, "text": "NHibernate now knows how to connect to the database. The other thing we need to do is to provide it a list of models that we will map." }, { "code": null, "e": 7741, "s": 7523, "text": "We can do this by adding an assembly, so by specifying the Assembly.GetExecutingAssembly and this is where program will find mapping files. Mapping files tell NHibernate how to go from C# classes into database tables." }, { "code": null, "e": 8092, "s": 7741, "text": "SessionFactory compiles all the metadata necessary for initializing NHibernate. SessionFactory can be used to build sessions, which are roughly analogous to database connections. So the appropriate way is to use it in the using block. I can say var session equals sessionFactory.OpenSession and I'm going to want to do this inside of its transaction." } ]
Program to convert List of String to List of Integer in Java
11 Dec, 2018 The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes. Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the list of String.Convert List of String to Stream of String. This is done using List.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into List of Integer. This is done using Collectors.toList().Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return listOfString.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5"); // Print the list of String System.out.println("List of String: " + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList( listOfString, Integer::parseInt); // Print the list of Integer System.out.println("List of Integer: " + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Using Guava’s List.transform():Algorithm:Get the list of String.Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation.Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return Lists.transform(listOfString, function); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5"); // Print the list of String System.out.println("List of String: " + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList(listOfString, Integer::parseInt); // Print the list of Integer System.out.println("List of Integer: " + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] My Personal Notes arrow_drop_upSave Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the list of String.Convert List of String to Stream of String. This is done using List.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into List of Integer. This is done using Collectors.toList().Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return listOfString.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5"); // Print the list of String System.out.println("List of String: " + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList( listOfString, Integer::parseInt); // Print the list of Integer System.out.println("List of Integer: " + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Java 8 Stream API can be used to convert List to List. Algorithm: Get the list of String.Convert List of String to Stream of String. This is done using List.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into List of Integer. This is done using Collectors.toList().Return/Print the list of String. Get the list of String. Convert List of String to Stream of String. This is done using List.stream(). Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression. Collect Stream of Integer into List of Integer. This is done using Collectors.toList(). Return/Print the list of String. Program: // Java Program to convert// List<String> to List<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return listOfString.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5"); // Print the list of String System.out.println("List of String: " + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList( listOfString, Integer::parseInt); // Print the list of Integer System.out.println("List of Integer: " + listOfInteger); }} List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Using Guava’s List.transform():Algorithm:Get the list of String.Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation.Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return Lists.transform(listOfString, function); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5"); // Print the list of String System.out.println("List of String: " + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList(listOfString, Integer::parseInt); // Print the list of Integer System.out.println("List of Integer: " + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Algorithm: Get the list of String.Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation.Return/Print the list of String. Get the list of String. Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation. Return/Print the list of String. Program: // Java Program to convert// List<String> to List<Integer> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return Lists.transform(listOfString, function); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5"); // Print the list of String System.out.println("List of String: " + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList(listOfString, Integer::parseInt); // Print the list of Integer System.out.println("List of Integer: " + listOfInteger); }} List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5] Java - util package java-list Java-List-Programs java-stream Java-Stream-programs Java-String-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Dec, 2018" }, { "code": null, "e": 368, "s": 54, "text": "The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes." }, { "code": null, "e": 3581, "s": 368, "text": "Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the list of String.Convert List of String to Stream of String. This is done using List.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into List of Integer. This is done using Collectors.toList().Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return listOfString.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\"); // Print the list of String System.out.println(\"List of String: \" + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList( listOfString, Integer::parseInt); // Print the list of Integer System.out.println(\"List of Integer: \" + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\nUsing Guava’s List.transform():Algorithm:Get the list of String.Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation.Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return Lists.transform(listOfString, function); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\"); // Print the list of String System.out.println(\"List of String: \" + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList(listOfString, Integer::parseInt); // Print the list of Integer System.out.println(\"List of Integer: \" + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 5306, "s": 3581, "text": "Using Java 8 Stream API: A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.Java 8 Stream API can be used to convert List to List.Algorithm:Get the list of String.Convert List of String to Stream of String. This is done using List.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into List of Integer. This is done using Collectors.toList().Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return listOfString.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\"); // Print the list of String System.out.println(\"List of String: \" + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList( listOfString, Integer::parseInt); // Print the list of Integer System.out.println(\"List of Integer: \" + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 5361, "s": 5306, "text": "Java 8 Stream API can be used to convert List to List." }, { "code": null, "e": 5372, "s": 5361, "text": "Algorithm:" }, { "code": null, "e": 5730, "s": 5372, "text": "Get the list of String.Convert List of String to Stream of String. This is done using List.stream().Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression.Collect Stream of Integer into List of Integer. This is done using Collectors.toList().Return/Print the list of String." }, { "code": null, "e": 5754, "s": 5730, "text": "Get the list of String." }, { "code": null, "e": 5832, "s": 5754, "text": "Convert List of String to Stream of String. This is done using List.stream()." }, { "code": null, "e": 5971, "s": 5832, "text": "Convert Stream of String to Stream of Integer. This is done using Stream.map() and passing Integer.parseInt() method as lambda expression." }, { "code": null, "e": 6059, "s": 5971, "text": "Collect Stream of Integer into List of Integer. This is done using Collectors.toList()." }, { "code": null, "e": 6092, "s": 6059, "text": "Return/Print the list of String." }, { "code": null, "e": 6101, "s": 6092, "text": "Program:" }, { "code": "// Java Program to convert// List<String> to List<Integer> in Java 8 import java.util.*;import java.util.stream.*;import java.util.function.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return listOfString.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\"); // Print the list of String System.out.println(\"List of String: \" + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList( listOfString, Integer::parseInt); // Print the list of Integer System.out.println(\"List of Integer: \" + listOfInteger); }}", "e": 7183, "s": 6101, "text": null }, { "code": null, "e": 7249, "s": 7183, "text": "List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 8703, "s": 7249, "text": "Using Guava’s List.transform():Algorithm:Get the list of String.Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation.Return/Print the list of String.Program:// Java Program to convert// List<String> to List<Integer> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return Lists.transform(listOfString, function); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\"); // Print the list of String System.out.println(\"List of String: \" + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList(listOfString, Integer::parseInt); // Print the list of Integer System.out.println(\"List of Integer: \" + listOfInteger); }}Output:List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 8714, "s": 8703, "text": "Algorithm:" }, { "code": null, "e": 8930, "s": 8714, "text": "Get the list of String.Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation.Return/Print the list of String." }, { "code": null, "e": 8954, "s": 8930, "text": "Get the list of String." }, { "code": null, "e": 9115, "s": 8954, "text": "Convert List of String to List of Integer using Lists.transform(). This is done using passing Integer.parseInt() method as lambda expression for transformation." }, { "code": null, "e": 9148, "s": 9115, "text": "Return/Print the list of String." }, { "code": null, "e": 9157, "s": 9148, "text": "Program:" }, { "code": "// Java Program to convert// List<String> to List<Integer> in Java 8 import com.google.common.base.Function;import com.google.common.collect.Lists;import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <T, U> List<U> convertStringListToIntList(List<T> listOfString, Function<T, U> function) { return Lists.transform(listOfString, function); } public static void main(String args[]) { // Create a list of String List<String> listOfString = Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\"); // Print the list of String System.out.println(\"List of String: \" + listOfString); // Convert List of String to list of Integer List<Integer> listOfInteger = convertStringListToIntList(listOfString, Integer::parseInt); // Print the list of Integer System.out.println(\"List of Integer: \" + listOfInteger); }}", "e": 10275, "s": 9157, "text": null }, { "code": null, "e": 10341, "s": 10275, "text": "List of String: [1, 2, 3, 4, 5]\nList of Integer: [1, 2, 3, 4, 5]\n" }, { "code": null, "e": 10361, "s": 10341, "text": "Java - util package" }, { "code": null, "e": 10371, "s": 10361, "text": "java-list" }, { "code": null, "e": 10390, "s": 10371, "text": "Java-List-Programs" }, { "code": null, "e": 10402, "s": 10390, "text": "java-stream" }, { "code": null, "e": 10423, "s": 10402, "text": "Java-Stream-programs" }, { "code": null, "e": 10444, "s": 10423, "text": "Java-String-Programs" }, { "code": null, "e": 10449, "s": 10444, "text": "Java" }, { "code": null, "e": 10463, "s": 10449, "text": "Java Programs" }, { "code": null, "e": 10468, "s": 10463, "text": "Java" } ]
How to Install Numpy on MacOS?
22 Sep, 2021 In this article, we will learn how to install Numpy in Python on MacOS. NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. Follow the below steps to install the Numpy package on macOS using pip: Step 1: Install the latest Python3 in MacOS Step 2: Check if pip3 and python3 are correctly installed. python3 --version pip3 --version Step 3: Upgrade your pip to avoid errors during installation. pip3 install --upgrade pip Step 4: Enter the following command to install Numpy using pip3. pip3 install numpy Follow the below steps to install the Numpy package on macOS using the setup.py file: Step 1: Download the latest source package of Numpy for python3 from here. curl https://files.pythonhosted.org/packages/3a/be/650f9c091ef71cb01d735775d554e068752d3ff63d7943b26316dc401749/numpy-1.21.2.zip > numpy.tar.gz Step 2: Extract the downloaded package using the following command. tar -xzvf numpy.tar.gz Step 3: Go inside the folder and Enter the following command to install the package. Note: You must have developer tools for XCode MacOS installed in your system cd numpy-1.21.2 python3 setup.py install Make the following import in your python terminal to verify if the installation has been done properly: import numpy If there is any error while importing the module then is not installed properly. Blogathon-2021 how-to-install Picked Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 316, "s": 28, "text": "In this article, we will learn how to install Numpy in Python on MacOS. NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays." }, { "code": null, "e": 388, "s": 316, "text": "Follow the below steps to install the Numpy package on macOS using pip:" }, { "code": null, "e": 432, "s": 388, "text": "Step 1: Install the latest Python3 in MacOS" }, { "code": null, "e": 491, "s": 432, "text": "Step 2: Check if pip3 and python3 are correctly installed." }, { "code": null, "e": 524, "s": 491, "text": "python3 --version\npip3 --version" }, { "code": null, "e": 586, "s": 524, "text": "Step 3: Upgrade your pip to avoid errors during installation." }, { "code": null, "e": 613, "s": 586, "text": "pip3 install --upgrade pip" }, { "code": null, "e": 679, "s": 613, "text": "Step 4: Enter the following command to install Numpy using pip3." }, { "code": null, "e": 699, "s": 679, "text": "pip3 install numpy " }, { "code": null, "e": 785, "s": 699, "text": "Follow the below steps to install the Numpy package on macOS using the setup.py file:" }, { "code": null, "e": 860, "s": 785, "text": "Step 1: Download the latest source package of Numpy for python3 from here." }, { "code": null, "e": 1004, "s": 860, "text": "curl https://files.pythonhosted.org/packages/3a/be/650f9c091ef71cb01d735775d554e068752d3ff63d7943b26316dc401749/numpy-1.21.2.zip > numpy.tar.gz" }, { "code": null, "e": 1072, "s": 1004, "text": "Step 2: Extract the downloaded package using the following command." }, { "code": null, "e": 1095, "s": 1072, "text": "tar -xzvf numpy.tar.gz" }, { "code": null, "e": 1180, "s": 1095, "text": "Step 3: Go inside the folder and Enter the following command to install the package." }, { "code": null, "e": 1257, "s": 1180, "text": "Note: You must have developer tools for XCode MacOS installed in your system" }, { "code": null, "e": 1298, "s": 1257, "text": "cd numpy-1.21.2\npython3 setup.py install" }, { "code": null, "e": 1402, "s": 1298, "text": "Make the following import in your python terminal to verify if the installation has been done properly:" }, { "code": null, "e": 1415, "s": 1402, "text": "import numpy" }, { "code": null, "e": 1496, "s": 1415, "text": "If there is any error while importing the module then is not installed properly." }, { "code": null, "e": 1511, "s": 1496, "text": "Blogathon-2021" }, { "code": null, "e": 1526, "s": 1511, "text": "how-to-install" }, { "code": null, "e": 1533, "s": 1526, "text": "Picked" }, { "code": null, "e": 1543, "s": 1533, "text": "Blogathon" }, { "code": null, "e": 1550, "s": 1543, "text": "How To" }, { "code": null, "e": 1569, "s": 1550, "text": "Installation Guide" } ]
How to break a loop in JavaScript?
The break statement is used to break a loop and continue executing the code, which is after the loop. You can try to run the following code to break a loop in JavaScript Live Demo <!DOCTYPE html> <html> <body> <p id="test"></p> <script> var text = ""; var i; for (i = 0; i < 5; i++) { if (i === 2) { break; } text += "Value: " + i + "<br>"; } document.getElementById("test").innerHTML = text; </script> </body> </html> Value: 0 Value: 1
[ { "code": null, "e": 1164, "s": 1062, "text": "The break statement is used to break a loop and continue executing the code, which is after the loop." }, { "code": null, "e": 1232, "s": 1164, "text": "You can try to run the following code to break a loop in JavaScript" }, { "code": null, "e": 1242, "s": 1232, "text": "Live Demo" }, { "code": null, "e": 1603, "s": 1242, "text": "<!DOCTYPE html>\n<html>\n <body>\n <p id=\"test\"></p>\n <script>\n var text = \"\";\n var i;\n\n for (i = 0; i < 5; i++) {\n if (i === 2) {\n break;\n }\n text += \"Value: \" + i + \"<br>\";\n }\n document.getElementById(\"test\").innerHTML = text;\n </script>\n </body>\n\n</html>" }, { "code": null, "e": 1621, "s": 1603, "text": "Value: 0\nValue: 1" } ]
Sequential Digits in C++
Suppose we have an integer, that has sequential digits if and only if each digit in the number is one more than the previous digit. We have to find a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. So if the low = 100 and high = 300, then the output will be [123,234] To solve this, we will follow these steps − create one array res for i in range 1 to nfor j := 1, until j + i – 1 <= 9x := 0for k in range 0 to i – 1x := 10x + (j + k)if low < x and x <= high, then insert x into ans for j := 1, until j + i – 1 <= 9x := 0for k in range 0 to i – 1x := 10x + (j + k)if low < x and x <= high, then insert x into ans x := 0 for k in range 0 to i – 1x := 10x + (j + k) x := 10x + (j + k) if low < x and x <= high, then insert x into ans return ans Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> sequentialDigits(int low, int high) { vector <int> ans; for(int i = 1; i <= 9; i++){ for(int j = 1; j + i - 1 <= 9; j++){ int x = 0; for(int k = 0; k < i; k++){ x = (x*10) + (j + k); } if(low <= x && x <= high){ ans.push_back(x); } } } return ans; } }; main(){ Solution ob; print_vector(ob.sequentialDigits(500, 5000)); } 500 5000 [567, 678, 789, 1234, 2345, 3456, 4567, ]
[ { "code": null, "e": 1378, "s": 1062, "text": "Suppose we have an integer, that has sequential digits if and only if each digit in the number is one more than the previous digit. We have to find a sorted list of all the integers in the range [low, high] inclusive that have sequential digits. So if the low = 100 and high = 300, then the output will be [123,234]" }, { "code": null, "e": 1422, "s": 1378, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1443, "s": 1422, "text": "create one array res" }, { "code": null, "e": 1594, "s": 1443, "text": "for i in range 1 to nfor j := 1, until j + i – 1 <= 9x := 0for k in range 0 to i – 1x := 10x + (j + k)if low < x and x <= high, then insert x into ans" }, { "code": null, "e": 1724, "s": 1594, "text": "for j := 1, until j + i – 1 <= 9x := 0for k in range 0 to i – 1x := 10x + (j + k)if low < x and x <= high, then insert x into ans" }, { "code": null, "e": 1731, "s": 1724, "text": "x := 0" }, { "code": null, "e": 1775, "s": 1731, "text": "for k in range 0 to i – 1x := 10x + (j + k)" }, { "code": null, "e": 1794, "s": 1775, "text": "x := 10x + (j + k)" }, { "code": null, "e": 1843, "s": 1794, "text": "if low < x and x <= high, then insert x into ans" }, { "code": null, "e": 1854, "s": 1843, "text": "return ans" }, { "code": null, "e": 1924, "s": 1854, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1935, "s": 1924, "text": " Live Demo" }, { "code": null, "e": 2631, "s": 1935, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\n public:\n vector<int> sequentialDigits(int low, int high) {\n vector <int> ans;\n for(int i = 1; i <= 9; i++){\n for(int j = 1; j + i - 1 <= 9; j++){\n int x = 0;\n for(int k = 0; k < i; k++){\n x = (x*10) + (j + k);\n }\n if(low <= x && x <= high){\n ans.push_back(x);\n }\n }\n }\n return ans;\n }\n};\nmain(){\n Solution ob;\n print_vector(ob.sequentialDigits(500, 5000));\n}" }, { "code": null, "e": 2640, "s": 2631, "text": "500\n5000" }, { "code": null, "e": 2682, "s": 2640, "text": "[567, 678, 789, 1234, 2345, 3456, 4567, ]" } ]
How to Assign Default Value for Struct Field in Golang?
22 Jun, 2020 Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Example 1: // Golang program to assign// default values to a struct // using constructor functionpackage main import ( "fmt") // declaring a student structtype Student struct{ // declaring struct variables name string marks int64 age int64} // constructor functionfunc(std *Student) fill_defaults(){ // setting default values // if no values present if std.name == "" { std.name = "ABC" } if std.marks == 0 { std.marks = 40 } if std.age == 0 { std.age = 18 }} // main functionfunc main() { // creating a struct where // only the name is initialised std1 := Student{name: "Vani"} // printing the struct // with no default values fmt.Println(std1) // this will assign default values // to non-initialised valiables // in struct std1 std1.fill_defaults() // printing after assigning // defaults to struct variables fmt.Println(std1) // creating a struct where // age and marks are initialised std2 := Student{age: 19, marks: 78} // assigning default name std2.fill_defaults() // printing after assigning // default name to struct fmt.Println(std2) } Output: {Vani 0 0} {Vani 40 18} {ABC 78 19} Another way of assigning default values to structs is by using tags. Tags can only be used for string values only and can be implemented by using single quotes(”). Example 2: // Golang program to assign// default values to a struct // using tags package main import ( "fmt" "reflect") // declaring a person structtype Person struct { // setting the default value // of name to "geek" name string `default:"geek"` } func default_tag(p Person) string { // TypeOf returns type of // interface value passed to it typ := reflect.TypeOf(p) // checking if null string if p.name == "" { // returns the struct field // with the given parameter "name" f, _ := typ.FieldByName("name") // returns the value associated // with key in the tag string // and returns empty string if // no such key in tag p.name = f.Tag.Get("default") } return fmt.Sprintf("%s", p.name)} // main functionfunc main(){ // prints out the default name fmt.Println("Default name is:", default_tag(Person{}))} Output: Default name is: geek Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Golang Maps Interfaces in Golang Data Types in Go Slices in Golang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang? How to Trim a String in Golang? Pointers in Golang Channel in Golang How to iterate over an Array using for loop in Golang?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 235, "s": 28, "text": "Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members." }, { "code": null, "e": 246, "s": 235, "text": "Example 1:" }, { "code": "// Golang program to assign// default values to a struct // using constructor functionpackage main import ( \"fmt\") // declaring a student structtype Student struct{ // declaring struct variables name string marks int64 age int64} // constructor functionfunc(std *Student) fill_defaults(){ // setting default values // if no values present if std.name == \"\" { std.name = \"ABC\" } if std.marks == 0 { std.marks = 40 } if std.age == 0 { std.age = 18 }} // main functionfunc main() { // creating a struct where // only the name is initialised std1 := Student{name: \"Vani\"} // printing the struct // with no default values fmt.Println(std1) // this will assign default values // to non-initialised valiables // in struct std1 std1.fill_defaults() // printing after assigning // defaults to struct variables fmt.Println(std1) // creating a struct where // age and marks are initialised std2 := Student{age: 19, marks: 78} // assigning default name std2.fill_defaults() // printing after assigning // default name to struct fmt.Println(std2) }", "e": 1475, "s": 246, "text": null }, { "code": null, "e": 1483, "s": 1475, "text": "Output:" }, { "code": null, "e": 1520, "s": 1483, "text": "{Vani 0 0}\n{Vani 40 18}\n{ABC 78 19}\n" }, { "code": null, "e": 1684, "s": 1520, "text": "Another way of assigning default values to structs is by using tags. Tags can only be used for string values only and can be implemented by using single quotes(”)." }, { "code": null, "e": 1695, "s": 1684, "text": "Example 2:" }, { "code": "// Golang program to assign// default values to a struct // using tags package main import ( \"fmt\" \"reflect\") // declaring a person structtype Person struct { // setting the default value // of name to \"geek\" name string `default:\"geek\"` } func default_tag(p Person) string { // TypeOf returns type of // interface value passed to it typ := reflect.TypeOf(p) // checking if null string if p.name == \"\" { // returns the struct field // with the given parameter \"name\" f, _ := typ.FieldByName(\"name\") // returns the value associated // with key in the tag string // and returns empty string if // no such key in tag p.name = f.Tag.Get(\"default\") } return fmt.Sprintf(\"%s\", p.name)} // main functionfunc main(){ // prints out the default name fmt.Println(\"Default name is:\", default_tag(Person{}))}", "e": 2650, "s": 1695, "text": null }, { "code": null, "e": 2658, "s": 2650, "text": "Output:" }, { "code": null, "e": 2681, "s": 2658, "text": "Default name is: geek\n" }, { "code": null, "e": 2696, "s": 2681, "text": "Golang-Program" }, { "code": null, "e": 2703, "s": 2696, "text": "Picked" }, { "code": null, "e": 2715, "s": 2703, "text": "Go Language" }, { "code": null, "e": 2813, "s": 2715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2825, "s": 2813, "text": "Golang Maps" }, { "code": null, "e": 2846, "s": 2825, "text": "Interfaces in Golang" }, { "code": null, "e": 2863, "s": 2846, "text": "Data Types in Go" }, { "code": null, "e": 2880, "s": 2863, "text": "Slices in Golang" }, { "code": null, "e": 2934, "s": 2880, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 2963, "s": 2934, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 2995, "s": 2963, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 3014, "s": 2995, "text": "Pointers in Golang" }, { "code": null, "e": 3032, "s": 3014, "text": "Channel in Golang" } ]
How to read a hash with an “&” sign in the URL ?
31 Dec, 2019 It’s a very common situation in web development where users want to extract or read information from any URL. In the case of the unavailability of the server-side code, the programmer can make use of JavaScript or jQuery to read information. To read the URL with an & sign, we can use the split() function. By that function, we can easily get the URL parameter as a string. The programmer can retrieve the parameter string and store it in a variable by using JavaScript. Syntax: var q = url.split('?')[1]; Here URL is any example URL string. To get URL query string parameters. If the URL has many parameters in the query string, the following code snippet will guide you to parse and store in variables that can be accessed. var vars = [], hash; var q = url.split('?')[1]; var fullParameter = q; if(q != undefined) { q = q.split('&'); for(var i = 0; i < q.length; i++) { hash = q[i].split('='); vars.push(hash[1]); vars[hash[0]] = hash[1]; } // Get hash parameter var hashParameter = hash[1]; var hashstr= hashParameter.split('#')[1]; alert("# Parameter :" + hashstr); } To use any parameters, the user can access the value by parameter name. For example, if the URL contains the query string “?var1=name&var=surname&var3=address?, the user can access the value for “var1” using: alert(vars['var1']); Below example illustrates the above approach: Example: This example reads URL parameters which includes hash along with "&" sign in the given URL. <!DOCTYPE html><html> <head> <title> How to read a hash with an & sign in the URL? </title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Get parameters and anchor of URL using jQuery </b> <p> Click on the button below to read parameters for any URL </p> <button id="btn"> Read hash with & sign: </button> <div style="height:10px;"></div> <div id="Ampdiv"></div> <script> var url = 'http://www.geeksforgeeks.com/search?var1=term&var2=english#results'; $('#btn').click(function() { readHash(url); }); function readHash(url) { var vars = [], hash; var q = url.split('?')[1]; var fullParameter = q; if (q != undefined) { q = q.split('&'); for (var i = 0; i < q.length; i++) { hash = q[i].split('='); vars.push(hash[1]); vars[hash[0]] = hash[1]; } // Get hash parameter var hashParameter = hash[1]; var hashstr = hashParameter.split('#')[1]; alert("# Parameter :" + hashstr); } $("#Ampdiv").text(fullParameter); } </script></body> </html> Output: Before clicking the button: After clicking the button: jQuery-Misc Picked JQuery 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": "\n31 Dec, 2019" }, { "code": null, "e": 499, "s": 28, "text": "It’s a very common situation in web development where users want to extract or read information from any URL. In the case of the unavailability of the server-side code, the programmer can make use of JavaScript or jQuery to read information. To read the URL with an & sign, we can use the split() function. By that function, we can easily get the URL parameter as a string. The programmer can retrieve the parameter string and store it in a variable by using JavaScript." }, { "code": null, "e": 507, "s": 499, "text": "Syntax:" }, { "code": null, "e": 534, "s": 507, "text": "var q = url.split('?')[1];" }, { "code": null, "e": 754, "s": 534, "text": "Here URL is any example URL string. To get URL query string parameters. If the URL has many parameters in the query string, the following code snippet will guide you to parse and store in variables that can be accessed." }, { "code": null, "e": 1212, "s": 754, "text": "var vars = [], hash;\nvar q = url.split('?')[1];\nvar fullParameter = q;\n \nif(q != undefined) {\n q = q.split('&');\n \n for(var i = 0; i < q.length; i++) {\n hash = q[i].split('=');\n vars.push(hash[1]);\n vars[hash[0]] = hash[1]; \n }\n \n // Get hash parameter\n var hashParameter = hash[1];\n var hashstr= hashParameter.split('#')[1];\n alert(\"# Parameter :\" + hashstr);\n}\n" }, { "code": null, "e": 1421, "s": 1212, "text": "To use any parameters, the user can access the value by parameter name. For example, if the URL contains the query string “?var1=name&var=surname&var3=address?, the user can access the value for “var1” using:" }, { "code": null, "e": 1442, "s": 1421, "text": "alert(vars['var1']);" }, { "code": null, "e": 1488, "s": 1442, "text": "Below example illustrates the above approach:" }, { "code": null, "e": 1589, "s": 1488, "text": "Example: This example reads URL parameters which includes hash along with \"&\" sign in the given URL." }, { "code": "<!DOCTYPE html><html> <head> <title> How to read a hash with an & sign in the URL? </title> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Get parameters and anchor of URL using jQuery </b> <p> Click on the button below to read parameters for any URL </p> <button id=\"btn\"> Read hash with & sign: </button> <div style=\"height:10px;\"></div> <div id=\"Ampdiv\"></div> <script> var url = 'http://www.geeksforgeeks.com/search?var1=term&var2=english#results'; $('#btn').click(function() { readHash(url); }); function readHash(url) { var vars = [], hash; var q = url.split('?')[1]; var fullParameter = q; if (q != undefined) { q = q.split('&'); for (var i = 0; i < q.length; i++) { hash = q[i].split('='); vars.push(hash[1]); vars[hash[0]] = hash[1]; } // Get hash parameter var hashParameter = hash[1]; var hashstr = hashParameter.split('#')[1]; alert(\"# Parameter :\" + hashstr); } $(\"#Ampdiv\").text(fullParameter); } </script></body> </html>", "e": 3064, "s": 1589, "text": null }, { "code": null, "e": 3072, "s": 3064, "text": "Output:" }, { "code": null, "e": 3100, "s": 3072, "text": "Before clicking the button:" }, { "code": null, "e": 3127, "s": 3100, "text": "After clicking the button:" }, { "code": null, "e": 3139, "s": 3127, "text": "jQuery-Misc" }, { "code": null, "e": 3146, "s": 3139, "text": "Picked" }, { "code": null, "e": 3153, "s": 3146, "text": "JQuery" }, { "code": null, "e": 3170, "s": 3153, "text": "Web Technologies" }, { "code": null, "e": 3197, "s": 3170, "text": "Web technologies Questions" } ]
Form a Spiral Matrix from the given Array
26 Nov, 2021 Given an array, the task is to form a spiral matrix Examples: Input: arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; Output: 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Input: arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; Output: 1 2 3 4 5 6 14 15 16 17 18 7 13 12 11 10 9 8 Approach: This problem is just the reverse of this problem “Print a given matrix in spiral form“. The approach to do so is: Traverse the given array and pick each element one by one. Fill each of this element in the spiral matrix order. Spiral matrix order is maintained with the help of 4 loops – left, right, top, and bottom. Each loop prints its corresponding row/column in the spiral matrix. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to form a Spiral Matrix// from the given Array #include <bits/stdc++.h>using namespace std; #define R 3#define C 6 // Function to form the spiral matrixvoid formSpiralMatrix(int arr[], int mat[R][C]){ int top = 0, bottom = R - 1, left = 0, right = C - 1; int index = 0; while (1) { if (left > right) break; // print top row for (int i = left; i <= right; i++) mat[top][i] = arr[index++]; top++; if (top > bottom) break; // print right column for (int i = top; i <= bottom; i++) mat[i][right] = arr[index++]; right--; if (left > right) break; // print bottom row for (int i = right; i >= left; i--) mat[bottom][i] = arr[index++]; bottom--; if (top > bottom) break; // print left column for (int i = bottom; i >= top; i--) mat[i][left] = arr[index++]; left++; }} // Function to print the spiral matrixvoid printSpiralMatrix(int mat[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << mat[i][j] << " "; cout << '\n'; }} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; int mat[R][C]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); return 0;} // Java program to form a Spiral Matrix// from the given Arrayclass GFG{ static final int R = 3 ; static final int C = 6; // Function to form the spiral matrix static void formSpiralMatrix(int arr[], int mat[][]) { int top = 0, bottom = R - 1, left = 0, right = C - 1; int index = 0; while (true) { if (left > right) break; // print top row for (int i = left; i <= right; i++) mat[top][i] = arr[index++]; top++; if (top > bottom) break; // print right column for (int i = top; i <= bottom; i++) mat[i][right] = arr[index++]; right--; if (left > right) break; // print bottom row for (int i = right; i >= left; i--) mat[bottom][i] = arr[index++]; bottom--; if (top > bottom) break; // print left column for (int i = bottom; i >= top; i--) mat[i][left] = arr[index++]; left++; } } // Function to print the spiral matrix static void printSpiralMatrix(int mat[][]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) System.out.print(mat[i][j] + " "); System.out.println(); } } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; int mat[][] = new int[R][C]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); }} // This code is contributed by kanugargng # Python program to form a Spiral Matrix# from the given Array R = 3 ;C = 6; # Function to form the spiral matrixdef formSpiralMatrix(arr, mat): top = 0; bottom = R - 1; left = 0; right = C - 1; index = 0; while (True): if(left > right): break; # print top row for i in range(left, right + 1): mat[top][i] = arr[index]; index += 1; top += 1; if (top > bottom): break; # print right column for i in range(top, bottom+1): mat[i][right] = arr[index]; index += 1; right -= 1; if (left > right): break; # print bottom row for i in range(right, left-1, -1): mat[bottom][i] = arr[index]; index += 1; bottom -= 1; if (top > bottom): break; # print left column for i in range(bottom, top-1, -1): mat[i][left] = arr[index]; index += 1; left += 1;# Function to print the spiral matrixdef printSpiralMatrix(mat): for i in range(R): for j in range(C): print(mat[i][j],end= " "); print(); # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]; mat= [[0 for i in range(C)] for j in range(R)]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); # This code contributed by PrinciRaj1992 // C# program to form a Spiral Matrix// from the given Arrayusing System; class GFG{ static readonly int R = 3; static readonly int C = 6; // Function to form the spiral matrix static void formSpiralMatrix(int []arr, int [,]mat) { int top = 0, bottom = R - 1, left = 0, right = C - 1; int index = 0; while (true) { if (left > right) break; // print top row for (int i = left; i <= right; i++) mat[top, i] = arr[index++]; top++; if (top > bottom) break; // print right column for (int i = top; i <= bottom; i++) mat[i, right] = arr[index++]; right--; if (left > right) break; // print bottom row for (int i = right; i >= left; i--) mat[bottom, i] = arr[index++]; bottom--; if (top > bottom) break; // print left column for (int i = bottom; i >= top; i--) mat[i, left] = arr[index++]; left++; } } // Function to print the spiral matrix static void printSpiralMatrix(int [,]mat) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) Console.Write(mat[i, j] + " "); Console.WriteLine(); } } // Driver code public static void Main (String[] args) { int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; int [,]mat = new int[R, C]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); }} // This code is contributed by 29AjayKumar <script> // Javascript program to form a Spiral Matrix// from the given Arrayconst R = 3;const C = 6; // Function to form the spiral matrixfunction formSpiralMatrix(arr, mat){ let top = 0, bottom = R - 1, left = 0, right = C - 1; let index = 0; while (1) { if (left > right) break; // Print top row for(let i = left; i <= right; i++) mat[top][i] = arr[index++]; top++; if (top > bottom) break; // Print right column for (let i = top; i <= bottom; i++) mat[i][right] = arr[index++]; right--; if (left > right) break; // print bottom row for (let i = right; i >= left; i--) mat[bottom][i] = arr[index++]; bottom--; if (top > bottom) break; // Print left column for(let i = bottom; i >= top; i--) mat[i][left] = arr[index++]; left++; }} // Function to print the spiral matrixfunction printSpiralMatrix(mat){ for(let i = 0; i < R; i++) { for(let j = 0; j < C; j++) document.write(mat[i][j] + " "); document.write("<br>"); }} // Driver codelet arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]; let mat = new Array(R);for(let i = 0; i < R; i++) mat[i] = new Array(C); formSpiralMatrix(arr, mat);printSpiralMatrix(mat); // This code is contributed by subham348 </script> 1 2 3 4 5 6 14 15 16 17 18 7 13 12 11 10 9 8 kanugargng 29AjayKumar princiraj1992 subham348 ankita_saini spiral Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Traverse a given Matrix using Recursion Find median in row wise sorted matrix Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Python program to add two Matrices Find a specific pair in Matrix Common elements in all rows of a given matrix Find shortest safe route in a path with landmines Flood fill Algorithm - how to implement fill() in paint?
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Nov, 2021" }, { "code": null, "e": 107, "s": 54, "text": "Given an array, the task is to form a spiral matrix " }, { "code": null, "e": 118, "s": 107, "text": "Examples: " }, { "code": null, "e": 435, "s": 118, "text": "Input:\narr[] = { 1, 2, 3, 4, 5,\n 6, 7, 8, 9, 10,\n 11, 12, 13, 14, 15, 16 };\nOutput:\n 1 2 3 4\n 12 13 14 5\n 11 16 15 6\n 10 9 8 7\n\nInput:\narr[] = { 1, 2, 3, 4, 5, 6,\n 7, 8, 9, 10, 11, 12,\n 13, 14, 15, 16, 17, 18 };\nOutput:\n1 2 3 4 5 6 \n14 15 16 17 18 7 \n13 12 11 10 9 8" }, { "code": null, "e": 560, "s": 435, "text": "Approach: This problem is just the reverse of this problem “Print a given matrix in spiral form“. The approach to do so is: " }, { "code": null, "e": 619, "s": 560, "text": "Traverse the given array and pick each element one by one." }, { "code": null, "e": 673, "s": 619, "text": "Fill each of this element in the spiral matrix order." }, { "code": null, "e": 764, "s": 673, "text": "Spiral matrix order is maintained with the help of 4 loops – left, right, top, and bottom." }, { "code": null, "e": 832, "s": 764, "text": "Each loop prints its corresponding row/column in the spiral matrix." }, { "code": null, "e": 884, "s": 832, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 888, "s": 884, "text": "C++" }, { "code": null, "e": 893, "s": 888, "text": "Java" }, { "code": null, "e": 901, "s": 893, "text": "Python3" }, { "code": null, "e": 904, "s": 901, "text": "C#" }, { "code": null, "e": 915, "s": 904, "text": "Javascript" }, { "code": "// C++ program to form a Spiral Matrix// from the given Array #include <bits/stdc++.h>using namespace std; #define R 3#define C 6 // Function to form the spiral matrixvoid formSpiralMatrix(int arr[], int mat[R][C]){ int top = 0, bottom = R - 1, left = 0, right = C - 1; int index = 0; while (1) { if (left > right) break; // print top row for (int i = left; i <= right; i++) mat[top][i] = arr[index++]; top++; if (top > bottom) break; // print right column for (int i = top; i <= bottom; i++) mat[i][right] = arr[index++]; right--; if (left > right) break; // print bottom row for (int i = right; i >= left; i--) mat[bottom][i] = arr[index++]; bottom--; if (top > bottom) break; // print left column for (int i = bottom; i >= top; i--) mat[i][left] = arr[index++]; left++; }} // Function to print the spiral matrixvoid printSpiralMatrix(int mat[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << mat[i][j] << \" \"; cout << '\\n'; }} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; int mat[R][C]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); return 0;}", "e": 2373, "s": 915, "text": null }, { "code": "// Java program to form a Spiral Matrix// from the given Arrayclass GFG{ static final int R = 3 ; static final int C = 6; // Function to form the spiral matrix static void formSpiralMatrix(int arr[], int mat[][]) { int top = 0, bottom = R - 1, left = 0, right = C - 1; int index = 0; while (true) { if (left > right) break; // print top row for (int i = left; i <= right; i++) mat[top][i] = arr[index++]; top++; if (top > bottom) break; // print right column for (int i = top; i <= bottom; i++) mat[i][right] = arr[index++]; right--; if (left > right) break; // print bottom row for (int i = right; i >= left; i--) mat[bottom][i] = arr[index++]; bottom--; if (top > bottom) break; // print left column for (int i = bottom; i >= top; i--) mat[i][left] = arr[index++]; left++; } } // Function to print the spiral matrix static void printSpiralMatrix(int mat[][]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) System.out.print(mat[i][j] + \" \"); System.out.println(); } } // Driver code public static void main (String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; int mat[][] = new int[R][C]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); }} // This code is contributed by kanugargng", "e": 4229, "s": 2373, "text": null }, { "code": "# Python program to form a Spiral Matrix# from the given Array R = 3 ;C = 6; # Function to form the spiral matrixdef formSpiralMatrix(arr, mat): top = 0; bottom = R - 1; left = 0; right = C - 1; index = 0; while (True): if(left > right): break; # print top row for i in range(left, right + 1): mat[top][i] = arr[index]; index += 1; top += 1; if (top > bottom): break; # print right column for i in range(top, bottom+1): mat[i][right] = arr[index]; index += 1; right -= 1; if (left > right): break; # print bottom row for i in range(right, left-1, -1): mat[bottom][i] = arr[index]; index += 1; bottom -= 1; if (top > bottom): break; # print left column for i in range(bottom, top-1, -1): mat[i][left] = arr[index]; index += 1; left += 1;# Function to print the spiral matrixdef printSpiralMatrix(mat): for i in range(R): for j in range(C): print(mat[i][j],end= \" \"); print(); # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]; mat= [[0 for i in range(C)] for j in range(R)]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); # This code contributed by PrinciRaj1992", "e": 5709, "s": 4229, "text": null }, { "code": "// C# program to form a Spiral Matrix// from the given Arrayusing System; class GFG{ static readonly int R = 3; static readonly int C = 6; // Function to form the spiral matrix static void formSpiralMatrix(int []arr, int [,]mat) { int top = 0, bottom = R - 1, left = 0, right = C - 1; int index = 0; while (true) { if (left > right) break; // print top row for (int i = left; i <= right; i++) mat[top, i] = arr[index++]; top++; if (top > bottom) break; // print right column for (int i = top; i <= bottom; i++) mat[i, right] = arr[index++]; right--; if (left > right) break; // print bottom row for (int i = right; i >= left; i--) mat[bottom, i] = arr[index++]; bottom--; if (top > bottom) break; // print left column for (int i = bottom; i >= top; i--) mat[i, left] = arr[index++]; left++; } } // Function to print the spiral matrix static void printSpiralMatrix(int [,]mat) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) Console.Write(mat[i, j] + \" \"); Console.WriteLine(); } } // Driver code public static void Main (String[] args) { int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }; int [,]mat = new int[R, C]; formSpiralMatrix(arr, mat); printSpiralMatrix(mat); }} // This code is contributed by 29AjayKumar", "e": 7611, "s": 5709, "text": null }, { "code": "<script> // Javascript program to form a Spiral Matrix// from the given Arrayconst R = 3;const C = 6; // Function to form the spiral matrixfunction formSpiralMatrix(arr, mat){ let top = 0, bottom = R - 1, left = 0, right = C - 1; let index = 0; while (1) { if (left > right) break; // Print top row for(let i = left; i <= right; i++) mat[top][i] = arr[index++]; top++; if (top > bottom) break; // Print right column for (let i = top; i <= bottom; i++) mat[i][right] = arr[index++]; right--; if (left > right) break; // print bottom row for (let i = right; i >= left; i--) mat[bottom][i] = arr[index++]; bottom--; if (top > bottom) break; // Print left column for(let i = bottom; i >= top; i--) mat[i][left] = arr[index++]; left++; }} // Function to print the spiral matrixfunction printSpiralMatrix(mat){ for(let i = 0; i < R; i++) { for(let j = 0; j < C; j++) document.write(mat[i][j] + \" \"); document.write(\"<br>\"); }} // Driver codelet arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ]; let mat = new Array(R);for(let i = 0; i < R; i++) mat[i] = new Array(C); formSpiralMatrix(arr, mat);printSpiralMatrix(mat); // This code is contributed by subham348 </script>", "e": 9163, "s": 7611, "text": null }, { "code": null, "e": 9216, "s": 9163, "text": "1 2 3 4 5 6 \n14 15 16 17 18 7 \n13 12 11 10 9 8" }, { "code": null, "e": 9229, "s": 9218, "text": "kanugargng" }, { "code": null, "e": 9241, "s": 9229, "text": "29AjayKumar" }, { "code": null, "e": 9255, "s": 9241, "text": "princiraj1992" }, { "code": null, "e": 9265, "s": 9255, "text": "subham348" }, { "code": null, "e": 9278, "s": 9265, "text": "ankita_saini" }, { "code": null, "e": 9285, "s": 9278, "text": "spiral" }, { "code": null, "e": 9292, "s": 9285, "text": "Matrix" }, { "code": null, "e": 9299, "s": 9292, "text": "Matrix" }, { "code": null, "e": 9397, "s": 9299, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9435, "s": 9397, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 9475, "s": 9435, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 9513, "s": 9475, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 9554, "s": 9513, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 9580, "s": 9554, "text": "A Boolean Matrix Question" }, { "code": null, "e": 9615, "s": 9580, "text": "Python program to add two Matrices" }, { "code": null, "e": 9646, "s": 9615, "text": "Find a specific pair in Matrix" }, { "code": null, "e": 9692, "s": 9646, "text": "Common elements in all rows of a given matrix" }, { "code": null, "e": 9742, "s": 9692, "text": "Find shortest safe route in a path with landmines" } ]
JavaScript - Nested Functions
Prior to JavaScript 1.2, function definition was allowed only in top level global code, but JavaScript 1.2 allows function definitions to be nested within other functions as well. Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement. As we'll discuss later in the next chapter, function literals (another feature introduced in JavaScript 1.2) may appear within any JavaScript expression, which means that they can appear within if and other statements. Try the following example to learn how to implement nested functions. <html> <head> <script type = "text/javascript"> <!-- function hypotenuse(a, b) { function square(x) { return x*x; } return Math.sqrt(square(a) + square(b)); } function secondFunction() { var result; result = hypotenuse(1,2); document.write ( result ); } //--> </script> </head> <body> <p>Click the following button to call the function</p> <form> <input type = "button" onclick = "secondFunction()" value = "Call Function"> </form> <p>Use different parameters inside the function and then try...</p> </body> </html> Click the following button to call the function Use different parameters inside the function and then try...
[ { "code": null, "e": 2988, "s": 2600, "text": "Prior to JavaScript 1.2, function definition was allowed only in top level global code, but JavaScript 1.2 allows function definitions to be nested within other functions as well. Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement." }, { "code": null, "e": 3207, "s": 2988, "text": "As we'll discuss later in the next chapter, function literals (another feature introduced in JavaScript 1.2) may appear within any JavaScript expression, which means that they can appear within if and other statements." }, { "code": null, "e": 3277, "s": 3207, "text": "Try the following example to learn how to implement nested functions." }, { "code": null, "e": 4009, "s": 3277, "text": "<html>\n <head>\n <script type = \"text/javascript\">\n <!--\n function hypotenuse(a, b) {\n function square(x) { return x*x; }\n return Math.sqrt(square(a) + square(b));\n }\n function secondFunction() {\n var result;\n result = hypotenuse(1,2);\n document.write ( result );\n }\n //-->\n </script>\n </head>\n \n <body>\n <p>Click the following button to call the function</p>\n \n <form>\n <input type = \"button\" onclick = \"secondFunction()\" value = \"Call Function\">\n </form>\n \n <p>Use different parameters inside the function and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 4057, "s": 4009, "text": "Click the following button to call the function" } ]
Groovy - Quick Guide
Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0. Groovy has the following features − Support for both static and dynamic typing. Support for operator overloading. Native syntax for lists and associative arrays. Native support for regular expressions. Native support for various markup languages such as XML and HTML. Groovy is simple for Java developers since the syntax for Java and Groovy are very similar. You can use existing Java libraries. Groovy extends the java.lang.Object. The official website for Groovy is http://www.groovy-lang.org/ There are a variety of ways to get the Groovy environment setup. Binary download and installation − Go to the link www.groovy-lang.org/download.html to get the Windows Installer section. Click on this option to start the download of the Groovy installer. Once you launch the installer, follow the steps given below to complete the installation. Step 1 − Select the language installer. Step 2 − Click the Next button in the next screen. Step 3 − Click the ‘I Agree’ button. Step 4 − Accept the default components and click the Next button. Step 5 − Choose the appropriate destination folder and then click the Next button. Step 6 − Click the Install button to start the installation. Step 7 − Once the installation is complete, click the Next button to start the configuration. Step 8 − Choose the default options and click the Next button. Step 9 − Accept the default file associations and click the Next button. Step 10 − Click the Finish button to complete the installation. Once the above steps are followed, you can then start the groovy shell which is part of the Groovy installation that helps in testing our different aspects of the Groovy language without the need of having a full-fledged integrated development environment for Groovy. This can be done by running the command groovysh from the command prompt. If you want to include the groovy binaries as part of you maven or gradle build, you can add the following lines 'org.codehaus.groovy:groovy:2.4.5' <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>2.4.5</version> In order to understand the basic syntax of Groovy, let’s first look at a simple Hello World program. Creating your first hello world program is as simple as just entering the following code line − class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } } When we run the above program, we will get the following result − Hello World The import statement can be used to import the functionality of other libraries which can be used in your code. This is done by using the import keyword. The following example shows how to use a simple import of the MarkupBuilder class which is probably one of the most used classes for creating HTML or XML markup. import groovy.xml.MarkupBuilder def xml = new MarkupBuilder() By default, Groovy includes the following libraries in your code, so you don’t need to explicitly import them. import java.lang.* import java.util.* import java.io.* import java.net.* import groovy.lang.* import groovy.util.* import java.math.BigInteger import java.math.BigDecimal A token is either a keyword, an identifier, a constant, a string literal, or a symbol. println(“Hello World”); In the above code line, there are two tokens, the first is the keyword println and the next is the string literal of “Hello World”. Comments are used to document your code. Comments in Groovy can be single line or multiline. Single line comments are identified by using the // at any position in the line. An example is shown below − class Example { static void main(String[] args) { // Using a simple println statement to print output to the console println('Hello World'); } } Multiline comments are identified with /* in the beginning and */ to identify the end of the multiline comment. class Example { static void main(String[] args) { /* This program is the first program This program shows how to display hello world */ println('Hello World'); } } Unlike in the Java programming language, it is not mandatory to have semicolons after the end of every statement, It is optional. class Example { static void main(String[] args) { def x = 5 println('Hello World'); } } If you execute the above program, both statements in the main method don't generate any error. Identifiers are used to define variables, functions or other user defined variables. Identifiers start with a letter, a dollar or an underscore. They cannot start with a number. Here are some examples of valid identifiers − def employeename def student1 def student_name where def is a keyword used in Groovy to define an identifier. Here is a code example of how an identifier can be used in our Hello World program. class Example { static void main(String[] args) { // One can see the use of a semi-colon after each statement def x = 5; println('Hello World'); } } In the above example, the variable x is used as an identifier. Keywords as the name suggest are special words which are reserved in the Groovy Programming language. The following table lists the keywords which are defined in Groovy. Whitespace is the term used in a programming language such as Java and Groovy to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement. For example, in the following code example, there is a white space between the keyword def and the variable x. This is so that the compiler knows that def is the keyword which needs to be used and that x should be the variable name that needs to be defined. def x = 5; A literal is a notation for representing a fixed value in groovy. The groovy language has notations for integers, floating-point numbers, characters and strings. Here are some of the examples of literals in the Groovy programming language − 12 1.45 ‘a’ “aa” In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory to store the value associated with the variable. You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Groovy offers a wide variety of built-in data types. Following is a list of data types which are defined in Groovy − byte − This is used to represent a byte value. An example is 2. byte − This is used to represent a byte value. An example is 2. short − This is used to represent a short number. An example is 10. short − This is used to represent a short number. An example is 10. int − This is used to represent whole numbers. An example is 1234. int − This is used to represent whole numbers. An example is 1234. long − This is used to represent a long number. An example is 10000090. long − This is used to represent a long number. An example is 10000090. float − This is used to represent 32-bit floating point numbers. An example is 12.34. float − This is used to represent 32-bit floating point numbers. An example is 12.34. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. char − This defines a single character literal. An example is ‘a’. char − This defines a single character literal. An example is ‘a’. Boolean − This represents a Boolean value which can either be true or false. Boolean − This represents a Boolean value which can either be true or false. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. The following table shows the maximum allowed values for the numerical and decimal literals. Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed − java.lang.Byte java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double In addition, the following classes can be used for supporting arbitrary precision arithmetic − The following code example showcases how the different built-in data types can be used − class Example { static void main(String[] args) { //Example of a int datatype int x = 5; //Example of a long datatype long y = 100L; //Example of a floating point datatype float a = 10.56f; //Example of a double datatype double b = 10.5e40; //Example of a BigInteger datatype BigInteger bi = 30g; //Example of a BigDecimal datatype BigDecimal bd = 3.5g; println(x); println(y); println(a); println(b); println(bi); println(bd); } } When we run the above program, we will get the following result − 5 100 10.56 1.05E41 30 3.5 Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser. There are following basic types of variable in Groovy as explained in the previous chapter − byte − This is used to represent a byte value. An example is 2. byte − This is used to represent a byte value. An example is 2. short − This is used to represent a short number. An example is 10. short − This is used to represent a short number. An example is 10. int − This is used to represent whole numbers. An example is 1234. int − This is used to represent whole numbers. An example is 1234. long − This is used to represent a long number. An example is 10000090. long − This is used to represent a long number. An example is 10000090. float − This is used to represent 32-bit floating point numbers. An example is 12.34. float − This is used to represent 32-bit floating point numbers. An example is 12.34. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565. char − This defines a single character literal. An example is ‘a’. char − This defines a single character literal. An example is ‘a’. Boolean − This represents a Boolean value which can either be true or false. Boolean − This represents a Boolean value which can either be true or false. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. Groovy also allows for additional types of variables such as arrays, structures and classes which we will see in the subsequent chapters. A variable declaration tells the compiler where and how much to create the storage for the variable. Following is an example of variable declaration − class Example { static void main(String[] args) { // x is defined as a variable String x = "Hello"; // The value of the variable is printed to the console println(x); } } When we run the above program, we will get the following result − Hello The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Groovy, just like Java is a case-sensitive programming language. class Example { static void main(String[] args) { // Defining a variable in lowercase int x = 5; // Defining a variable in uppercase int X = 6; // Defining a variable with the underscore in it's name def _Name = "Joe"; println(x); println(X); println(_Name); } } When we run the above program, we will get the following result − 5 6 Joe We can see that x and X are two different variables because of case sensitivity and in the third case, we can see that _Name begins with an underscore. You can print the current value of a variable with the println function. The following example shows how this can be achieved. class Example { static void main(String[] args) { //Initializing 2 variables int x = 5; int X = 6; //Printing the value of the variables to the console println("The value of x is " + x + "The value of X is " + X); } } When we run the above program, we will get the following result − The value of x is 5 The value of X is 6 An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Groovy has the following types of operators − Arithmetic operators Relational operators Logical operators Bitwise operators Assignment operators The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy − Show Example int x = 5; x++; x will give 6 int x = 5; x--; x will give 4 Relational operators allow of the comparison of objects. Following are the relational operators available in Groovy − Show Example Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy − Show Example Groovy provides four bitwise operators. Following are the bitwise operators available in Groovy − Show Example & This is the bitwise “and” operator | This is the bitwise “or” operator ^ This is the bitwise “xor” or Exclusive or operator ~ This is the bitwise negation operator Here is the truth table showcasing these operators. The Groovy language also provides assignment operators. Following are the assignment operators available in Groovy − Show Example def A = 5 A+=3 Output will be 8 def A = 5 A-=3 Output will be 2 def A = 5 A*=3 Output will be 15 def A = 6 A/=3 Output will be 2 def A = 5 A%=3 Output will be 2 Groovy supports the concept of ranges and provides a notation of range operators with the help of the .. notation. A simple example of the range operator is given below. def range = 0..5 This just defines a simple range of integers, stored into a local variable called range with a lower bound of 0 and an upper bound of 5. The following code snippet shows how the various operators can be used. class Example { static void main(String[] args) { def range = 5..10; println(range); println(range.get(2)); } } When we run the above program, we will get the following result − From the println statement, you can see that the entire range of numbers which are defined in the range statement are displayed. The get statement is used to get an object from the range defined which takes in an index value as the parameter. [5, 6, 7, 8, 9, 10] 7 The following table lists all groovy operators in order of precedence. ++ -- + - pre increment/decrement, unary plus, unary minus * / % multiply, div, modulo + - addition, subtraction == != <=> equals, not equals, compare to & binary/bitwise and ^ binary/bitwise xor | binary/bitwise or && logical and || logical or = **= *= /= %= += -= <<= >>= >>>= &= ^= |= Various assignment operators So far, we have seen statements which have been executed one after the other in a sequential manner. Additionally, statements are provided in Groovy to alter the flow of control in a program’s logic. They are then classified into flow of control statements which we will see in detail. The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed. The for statement is used to iterate through a set of values. The for-in statement is used to iterate through a set of values. The break statement is used to alter the flow of control inside loops and switch statements. The continue statement complements the break statement. Its use is restricted to while and for loops. Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true, it then executes the statements. The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true it then executes the statements thereafter and stops before the else condition and exits out of the loop. If the condition is false it then executes the statements in the else statement block and then exits the loop. Sometimes there is a requirement to have multiple if statement embedded inside of each other. Sometimes the nested if-else statement is so common and is used so often that an easier statement was designed called the switch statement. It is also possible to have a nested set of switch statements. A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It’s not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added. By default, if no visibility modifier is provided, the method is public. The simplest type of a method is one with no parameters as the one shown below − def methodName() { //Method code } Following is an example of simple method class Example { static def DisplayName() { println("This is how methods work in groovy"); println("This is an example of a simple method"); } static void main(String[] args) { DisplayName(); } } In the above example, DisplayName is a simple method which consists of two println statements which are used to output some text to the console. In our static main method, we are just calling the DisplayName method. The output of the above method would be − This is how methods work in groovy This is an example of a simple method A method is more generally useful if its behavior is determined by the value of one or more parameters. We can transfer values to the called method using method parameters. Note that the parameter names must differ from each other. The simplest type of a method with parameters as the one shown below − def methodName(parameter1, parameter2, parameter3) { // Method code goes here } Following is an example of simple method with parameters class Example { static void sum(int a,int b) { int c = a+b; println(c); } static void main(String[] args) { sum(10,5); } } In this example, we are creating a sum method with 2 parameters, a and b. Both parameters are of type int. We are then calling the sum method from our main method and passing the values to the variables a and b. The output of the above method would be the value 15. There is also a provision in Groovy to specify default values for parameters within methods. If no values are passed to the method for the parameters, the default ones are used. If both nondefault and default parameters are used, then it has to be noted that the default parameters should be defined at the end of the parameter list. Following is an example of simple method with parameters − def someMethod(parameter1, parameter2 = 0, parameter3 = 0) { // Method code goes here } Let’s look at the same example we looked at before for the addition of two numbers and create a method which has one default and another non-default parameter − class Example { static void sum(int a,int b = 5) { int c = a+b; println(c); } static void main(String[] args) { sum(6); } } In this example, we are creating a sum method with two parameters, a and b. Both parameters are of type int. The difference between this example and the previous example is that in this case we are specifying a default value for b as 5. So when we call the sum method from our main method, we have the option of just passing one value which is 6 and this will be assigned to the parameter a within the sum method. The output of the above method would be the value 11. class Example { static void sum(int a,int b = 5) { int c = a+b; println(c); } static void main(String[] args) { sum(6,6); } } We can also call the sum method by passing 2 values, in our example above we are passing 2 values of 6. The second value of 6 will actually replace the default value which is assigned to the parameter b. The output of the above method would be the value 12. Methods can also return values back to the calling program. This is required in modern-day programming language wherein a method does some sort of computation and then returns the desired value to the calling method. Following is an example of simple method with a return value. class Example { static int sum(int a,int b = 5) { int c = a+b; return c; } static void main(String[] args) { println(sum(6)); } } In our above example, note that this time we are specifying a return type for our method sum which is of the type int. In the method we are using the return statement to send the sum value to the calling main program. Since the value of the method is now available to the main method, we are using the println function to display the value in the console. The output of the above method would be the value 11. Methods are normally implemented inside classes within Groovy just like the Java language. A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. The class objects exhibit the properties and behaviors defined by its class. So the behaviors are defined by creating methods inside of the class. We will see classes in more detail in a later chapter but Following is an example of a method implementation in a class. In our previous examples we defined our method as static methods which meant that we could access those methods directly from the class. The next example of methods is instance methods wherein the methods are accessed by creating objects of the class. Again we will see classes in a later chapter, for now we will demonstrate how to use methods. Following is an example of how methods can be implemented. class Example { int x; public int getX() { return x; } public void setX(int pX) { x = pX; } static void main(String[] args) { Example ex = new Example(); ex.setX(100); println(ex.getX()); } } In our above example, note that this time we are specifying no static attribute for our class methods. In our main function we are actually creating an instance of the Example class and then invoking the method of the ‘ex’ object. The output of the above method would be the value 100. Groovy provides the facility just like java to have local and global parameters. In the following example, lx is a local parameter which has a scope only within the function of getX() and x is a global property which can be accessed inside the entire Example class. If we try to access the variable lx outside of the getX() function, we will get an error. class Example { static int x = 100; public static int getX() { int lx = 200; println(lx); return x; } static void main(String[] args) { println(getX()); } } When we run the above program, we will get the following result. 200 100 Just like in Java, groovy can access its instance members using the this keyword. The following example shows how when we use the statement this.x, it refers to its instance and sets the value of x accordingly. class Example { int x = 100; public int getX() { this.x = 200; return x; } static void main(String[] args) { Example ex = new Example(); println(ex.getX()); } } When we run the above program, we will get the result of 200 printed on the console. Groovy provides a number of helper methods when working with I/O. Groovy provides easier classes to provide the following functionalities for files. Reading files Writing to files Traversing file trees Reading and writing data objects to files In addition to this, you can always use the normal Java classes listed below for File I/O operations. java.io.File java.io.InputStream java.io.OutputStream java.io.Reader java.io.Writer The following example will output all the lines of a text file in Groovy. The method eachLine is in-built in the File class in Groovy for the purpose of ensuring that each line of the text file is read. import java.io.File class Example { static void main(String[] args) { new File("E:/Example.txt").eachLine { line -> println "line : $line"; } } } The File class is used to instantiate a new object which takes the file name as the parameter. It then takes the function of eachLine, puts it to a variable called line and prints it accordingly. If the file contains the following lines, they will be printed. line : Example1 line : Example2 If you want to get the entire contents of the file as a string, you can use the text property of the file class. The following example shows how this can be done. class Example { static void main(String[] args) { File file = new File("E:/Example.txt") println file.text } } If the file contains the following lines, they will be printed. line : Example1 line : Example2 If you want to write to files, you need to use the writer class to output text to a file. The following example shows how this can be done. import java.io.File class Example { static void main(String[] args) { new File('E:/','Example.txt').withWriter('utf-8') { writer -> writer.writeLine 'Hello World' } } } If you open the file Example.txt, you will see the words “Hello World” printed to the file. If you want to get the size of the file one can use the length property of the file class to get the size of the file. The following example shows how this can be done. class Example { static void main(String[] args) { File file = new File("E:/Example.txt") println "The file ${file.absolutePath} has ${file.length()} bytes" } } The above code would show the size of the file in bytes. If you want to see if a path is a file or a directory, one can use the isFile and isDirectory option of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { def file = new File('E:/') println "File? ${file.isFile()}" println "Directory? ${file.isDirectory()}" } } The above code would show the following output − File? false Directory? True If you want to create a new directory you can use the mkdir function of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { def file = new File('E:/Directory') file.mkdir() } } The directory E:\Directory will be created if it does not exist. If you want to delete a file you can use the delete function of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { def file = new File('E:/Example.txt') file.delete() } } The file will be deleted if it exists. Groovy also provides the functionality to copy the contents from one file to another. The following example shows how this can be done. class Example { static void main(String[] args) { def src = new File("E:/Example.txt") def dst = new File("E:/Example1.txt") dst << src.text } } The file Example1.txt will be created and all of the contents of the file Example.txt will be copied to this file. Groovy also provides the functionality to list the drives and files in a drive. The following example shows how the drives on a machine can be displayed by using the listRoots function of the File class. class Example { static void main(String[] args) { def rootFiles = new File("test").listRoots() rootFiles.each { file -> println file.absolutePath } } } Depending on the drives available on your machine, the output could vary. On a standard machine the output would be similar to the following one − C:\ D:\ The following example shows how to list the files in a particular directory by using the eachFile function of the File class. class Example { static void main(String[] args) { new File("E:/Temp").eachFile() { file->println file.getAbsolutePath() } } } The output would display all of the files in the directory E:\Temp If you want to recursively display all of files in a directory and its subdirectories, then you would use the eachFileRecurse function of the File class. The following example shows how this can be done. class Example { static void main(String[] args) { new File("E:/temp").eachFileRecurse() { file -> println file.getAbsolutePath() } } } The output would display all of the files in the directory E:\Temp and in its subdirectories if they exist. Groovy is an “optionally” typed language, and that distinction is an important one when understanding the fundamentals of the language. When compared to Java, which is a “strongly” typed language, whereby the compiler knows all of the types for every variable and can understand and honor contracts at compile time. This means that method calls are able to be determined at compile time. When writing code in Groovy, developers are given the flexibility to provide a type or not. This can offer some simplicity in implementation and, when leveraged properly, can service your application in a robust and dynamic way. In Groovy, optional typing is done via the ‘def’ keyword. Following is an example of the usage of the def method − class Example { static void main(String[] args) { // Example of an Integer using def def a = 100; println(a); // Example of an float using def def b = 100.10; println(b); // Example of an Double using def def c = 100.101; println(c); // Example of an String using def def d = "HelloWorld"; println(d); } } From the above program, we can see that we have not declared the individual variables as Integer, float, double, or string even though they contain these types of values. When we run the above program, we will get the following result − 100 100.10 100.101 HelloWorld Optional typing can be a powerful utility during development, but can lead to problems in maintainability during the later stages of development when the code becomes too vast and complex. To get a handle on how you can utilize optional typing in Groovy without getting your codebase into an unmaintainable mess, it is best to embrace the philosophy of “duck typing” in your applications. If we re-write the above code using duck typing, it would look like the one given below. The variable names are given names which resemble more often than not the type they represent which makes the code more understandable. class Example { static void main(String[] args) { // Example of an Integer using def def aint = 100; println(aint); // Example of an float using def def bfloat = 100.10; println(bfloat); // Example of an Double using def def cDouble = 100.101; println(cDouble); // Example of an String using def def dString = "HelloWorld"; println(dString); } } In Groovy, Numbers are actually represented as object’s, all of them being an instance of the class Integer. To make an object do something, we need to invoke one of the methods declared in its class. Groovy supports integer and floating point numbers. An integer is a value that does not include a fraction. A floating-point number is a decimal value that includes a decimal fraction. An Example of numbers in Groovy is shown below − Integer x = 5; Float y = 1.25; Where x is of the type Integer and y is the float. The reason why numbers in groovy are defined as objects is generally because there are requirements to perform operations on numbers. The concept of providing a class over primitive types is known as wrapper classes. By default the following wrapper classes are provided in Groovy. The object of the wrapper class contains or wraps its respective primitive data type. The process of converting a primitive data types into object is called boxing, and this is taken care by the compiler. The process of converting the object back to its corresponding primitive type is called unboxing. Following is an example of boxing and unboxing − class Example { static void main(String[] args) { Integer x = 5,y = 10,z = 0; // The the values of 5,10 and 0 are boxed into Integer types // The values of x and y are unboxed and the addition is performed z = x+y; println(z); } } The output of the above program would be 15. In the above example, the values of 5, 10, and 0 are first boxed into the Integer variables x, y and z accordingly. And then the when the addition of x and y is performed the values are unboxed from their Integer types. Since the Numbers in Groovy are represented as classes, following are the list of methods available. This method takes on the Number as the parameter and returns a primitive type based on the method which is invoked. The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers. The method determines whether the Number object that invokes the method is equal to the object that is passed as argument. The valueOf method returns the relevant Number Object holding the value of the argument passed. The method is used to get a String object representing the value of the Number Object. This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two. The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte. The method ceil gives the smallest integer that is greater than or equal to the argument. The method floor gives the largest integer that is less than or equal to the argument. The method rint returns the integer that is closest in value to the argument. The method round returns the closest long or int, as given by the methods return type. The method gives the smaller of the two arguments. The argument can be int, float, long, double. The method gives the maximum of the two arguments. The argument can be int, float, long, double. The method returns the base of the natural logarithms, e, to the power of the argument. The method returns the natural logarithm of the argument. The method returns the value of the first argument raised to the power of the second argument. The method returns the square root of the argument. The method returns the sine of the specified double value. The method returns the cosine of the specified double value. The method returns the tangent of the specified double value. The method returns the arcsine of the specified double value. The method returns the arccosine of the specified double value. The method returns the arctangent of the specified double value. The method Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta. The method converts the argument value to degrees. The method converts the argument value to radians. The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic. A String literal is constructed in Groovy by enclosing the string text in quotations. Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes (’), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines. Following is an example of the usage of strings in Groovy − class Example { static void main(String[] args) { String a = 'Hello Single'; String b = "Hello Double"; String c = "'Hello Triple" + "Multiple lines'"; println(a); println(b); println(c); } } When we run the above program, we will get the following result − Hello Single Hello Double 'Hello TripleMultiple lines' Strings in Groovy are an ordered sequences of characters. The individual character in a string can be accessed by its position. This is given by an index position. String indices start at zero and end at one less than the length of the string. Groovy also permits negative indices to count back from the end of the string. Following is an example of the usage of string indexing in Groovy − class Example { static void main(String[] args) { String sample = "Hello world"; println(sample[4]); // Print the 5 character in the string //Print the 1st character in the string starting from the back println(sample[-1]); println(sample[1..2]);//Prints a string starting from Index 1 to 2 println(sample[4..2]);//Prints a string starting from Index 4 back to 2 } } When we run the above program, we will get the following result − o d el oll First let’s learn the basic string operations in groovy. They are given below. The concatenation of strings can be done by the simple ‘+’ operator. The repetition of strings can be done by the simple ‘*’ operator. The length of the string determined by the length() method of the string. Here is the list of methods supported by String class. Returns a new String of length numberOfChars consisting of the recipient padded on the left and right with space characters. Compares two strings lexicographically, ignoring case differences. Concatenates the specified String to the end of this String. Processes each regex group (see next section) matched substring of the given String. Tests whether this string ends with the specified suffix. Compares this String to another String, ignoring case considerations. It returns string value at the index position Returns the index within this String of the first occurrence of the specified substring. It outputs whether a String matches the given regular expression. Removes the value part of the String. This method is called by the ++ operator for the class String. It increments the last character in the given String. Pad the String with the spaces appended to the left. Pad the String with the spaces appended to the right. Appends a String This method is called by the -- operator for the CharSequence. Replaces all occurrences of a captured group by the result of a closure on that text. Creates a new String which is the reverse of this String. Splits this String around matches of the given regular expression. Returns a new String that is a substring of this String. Converts all of the characters in this String to upper case. Converts all of the characters in this String to lower case. A range is shorthand for specifying a sequence of values. A Range is denoted by the first and last values in the sequence, and Range can be inclusive or exclusive. An inclusive Range includes all the values from the first to the last, while an exclusive Range includes all values except the last. Here are some examples of Range literals − 1..10 - An example of an inclusive Range 1..<10 - An example of an exclusive Range ‘a’..’x’ – Ranges can also consist of characters 10..1 – Ranges can also be in descending order ‘x’..’a’ – Ranges can also consist of characters and be in descending order. Following are the various methods available for ranges. Checks if a range contains a specific value Returns the element at the specified position in this Range. Get the lower value of this Range. Get the upper value of this Range. Is this a reversed Range, iterating backwards Returns the number of elements in this Range. Returns a view of the portion of this Range between the specified fromIndex, inclusive, and toIndex, exclusive The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets. To process the data in a list, we must be able to access individual elements. Groovy Lists are indexed using the indexing operator []. List indices start at zero, which refers to the first element. Following are some example of lists − [11, 12, 13, 14] – A list of integer values [‘Angular’, ‘Groovy’, ‘Java’] – A list of Strings [1, 2, [3, 4], 5] – A nested list [‘Groovy’, 21, 2.11] – A heterogeneous list of object references [ ] – An empty list In this chapter, we will discuss the list methods available in Groovy. Append the new value to the end of this List. Returns true if this List contains the specified value. Returns the element at the specified position in this List. Returns true if this List contains no elements Creates a new List composed of the elements of the original without those specified in the collection. Creates a new List composed of the elements of the original together with those specified in the collection. Removes the last item from this List Removes the element at the specified position in this List. Create a new List that is the reverse the elements of the original List Obtains the number of elements in this List. Returns a sorted copy of the original List. A Map (also known as an associative array, dictionary, table, and hash) is an unordered collection of object references. The elements in a Map collection are accessed by a key value. The keys used in a Map can be of any class. When we insert into a Map collection, two values are required: the key and the value. Following are some examples of maps − [‘TopicName’ : ‘Lists’, ‘Author’ : ‘Raghav’] – Collections of key value pairs which has TopicName as the key and their respective values. [‘TopicName’ : ‘Lists’, ‘Author’ : ‘Raghav’] – Collections of key value pairs which has TopicName as the key and their respective values. [ : ] – An Empty map. [ : ] – An Empty map. In this chapter, we will discuss the map methods available in Groovy. Does this Map contain this key? Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return null. Obtain a Set of the keys in this Map. Associates the specified value with the specified key in this Map. If this Map previously contained a mapping for this key, the old value is replaced by the specified value. Returns the number of key-value mappings in this Map. Returns a collection view of the values contained in this Map. The class Date represents a specific instant in time, with millisecond precision. The Date class has two constructors as shown below. public Date() Parameters − None. Return Value Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. Following is an example of the usage of this method − class Example { static void main(String[] args) { Date date = new Date(); // display time and date using toString() System.out.println(date.toString()); } } When we run the above program, we will get the following result. The following output will give you the current date and time − Thu Dec 10 21:31:15 GST 2015 public Date(long millisec) Parameters Millisec – The number of millisecconds to specify since the standard base time. Return Value − Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT. Following is an example of the usage of this method − class Example { static void main(String[] args) { Date date = new Date(100); // display time and date using toString() System.out.println(date.toString()); } } When we run the above program, we will get the following result − Thu Jan 01 04:00:00 GST 1970 Following are the given methods of the Date class. In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used − A year y is represented by the integer y - 1900. A year y is represented by the integer y - 1900. A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December. A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December. A date (day of month) is represented by an integer from 1 to 31 in the usual manner. A date (day of month) is represented by an integer from 1 to 31 in the usual manner. An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12. An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12. A minute is represented by an integer from 0 to 59 in the usual manner. A minute is represented by an integer from 0 to 59 in the usual manner. A second is represented by an integer from 0 to 61. A second is represented by an integer from 0 to 61. Tests if this date is after the specified date. Compares two dates for equality. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object. Compares two Dates for ordering. Converts this Date object to a String Tests if this date is before the specified date. Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison. For example we can create a regular expression object as shown below − def regex = ~'Groovy' When the Groovy operator =~ appears as a predicate (expression returning a Boolean) in if and while statements (see Chapter 8), the String operand on the left is matched against the regular expression operand on the right. Hence, each of the following delivers the value true. When defining regular expression, the following special characters can be used − There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($). There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($). Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once. Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once. The metacharacter { and } is used to match a specific number of instances of the preceding character. The metacharacter { and } is used to match a specific number of instances of the preceding character. In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character. In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character. A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below 'Groovy' =~ 'Groovy' 'Groovy' =~ 'oo' 'Groovy' ==~ 'Groovy' 'Groovy' ==~ 'oo' 'Groovy' =~ '∧G' ‘Groovy' =~ 'G$' ‘Groovy' =~ 'Gro*vy' 'Groovy' =~ 'Gro{2}vy' Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application. Exceptions are broadly classified into the following categories − Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time. One classical case is the FileNotFoundException. Suppose you had the following codein your application which reads from a file in E drive. class Example { static void main(String[] args) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } } if the File (file.txt) is not there in the E drive then the following exception will be raised. Caught: java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified). java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified). Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. One classical case is the ArrayIndexOutOfBoundsException which happens when you try to access an index of an array which is greater than the length of the array. Following is a typical example of this sort of mistake. class Example { static void main(String[] args) { def arr = new int[3]; arr[5] = 5; } } When the above code is executed the following exception will be raised. Caught: java.lang.ArrayIndexOutOfBoundsException: 5 java.lang.ArrayIndexOutOfBoundsException: 5 Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. These are errors which the program can never recover from and will cause the program to crash. The following diagram shows how the hierarchy of exceptions in Groovy is organized. It’s all based on the hierarchy defined in Java. A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. try { //Protected code } catch(ExceptionName e1) { //Catch block } All of your code which could raise an exception is placed in the Protected code block. In the catch block, you can write custom code to handle your exception so that the application can recover from the exception. Let’s look at an example of the similar code we saw above for accessing an array with an index value which is greater than the size of the array. But this time let’s wrap our code in a try/catch block. class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; } catch(Exception ex) { println("Catching the exception"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − Catching the exception Let's move on after the exception From the above code, we wrap out faulty code in the try block. In the catch block we are just catching our exception and outputting a message that an exception has occurred. One can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception raised you would write code to handle it accordingly. Let’s modify our above code to catch the ArrayIndexOutOfBoundsException specifically. Following is the code snippet. class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; }catch(ArrayIndexOutOfBoundsException ex) { println("Catching the Array out of Bounds exception"); }catch(Exception ex) { println("Catching the exception"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − Catching the Aray out of Bounds exception Let's move on after the exception From the above code you can see that the ArrayIndexOutOfBoundsException catch block is caught first because it means the criteria of the exception. The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. The syntax for this block is given below. try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } finally { //The finally block always executes. } Let’s modify our above code and add the finally block of code. Following is the code snippet. class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; } catch(ArrayIndexOutOfBoundsException ex) { println("Catching the Array out of Bounds exception"); }catch(Exception ex) { println("Catching the exception"); } finally { println("The final block"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − Catching the Array out of Bounds exception The final block Let's move on after the exception Following are the Exception methods available in Groovy − Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. Returns the cause of the exception as represented by a Throwable object. Returns the name of the class concatenated with the result of getMessage() Prints the result of toString() along with the stack trace to System.err, the error output stream. Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. Following is the code example using some of the methods given above − class Example { static void main(String[] args) { try { def arr = new int[3]; arr[5] = 5; }catch(ArrayIndexOutOfBoundsException ex) { println(ex.toString()); println(ex.getMessage()); println(ex.getStackTrace()); } catch(Exception ex) { println("Catching the exception"); }finally { println("The final block"); } println("Let's move on after the exception"); } } When we run the above program, we will get the following result − java.lang.ArrayIndexOutOfBoundsException: 5 5 [org.codehaus.groovy.runtime.dgmimpl.arrays.IntegerArrayPutAtMetaMethod$MyPojoMetaMet hodSite.call(IntegerArrayPutAtMetaMethod.java:75), org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) , org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) , org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) , Example.main(Sample:8), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) , java.lang.reflect.Method.invoke(Method.java:606), org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93), groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325), groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1443), org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:893), groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:287), groovy.lang.GroovyShell.run(GroovyShell.java:524), groovy.lang.GroovyShell.run(GroovyShell.java:513), groovy.ui.GroovyMain.processOnce(GroovyMain.java:652), groovy.ui.GroovyMain.run(GroovyMain.java:384), groovy.ui.GroovyMain.process(GroovyMain.java:370), groovy.ui.GroovyMain.processArgs(GroovyMain.java:129), groovy.ui.GroovyMain.main(GroovyMain.java:109), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) , java.lang.reflect.Method.invoke(Method.java:606), org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109), org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method), sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57), sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) , java.lang.reflect.Method.invoke(Method.java:606), com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)] The final block Let's move on after the exception In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain. A class in Groovy declares the state (data) and the behavior of objects defined by that class. Hence, a Groovy class describes both the instance fields and methods for that class. Following is an example of a class in Groovy. The name of the class is Student which has two fields – StudentID and StudentName. In the main function, we are creating an object of this class and assigning values to the StudentID and StudentName of the object. class Student { int StudentID; String StudentName; static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.StudentName = "Joe" } } In any programming language, it always a practice to hide the instance members with the private keyword and instead provide getter and setter methods to set and get the values of the instance variables accordingly. The following example shows how this can be done. class Student { private int StudentID; private String StudentName; void setStudentID(int pID) { StudentID = pID; } void setStudentName(String pName) { StudentName = pName; } int getStudentID() { return this.StudentID; } String getStudentName() { return this.StudentName; } static void main(String[] args) { Student st = new Student(); st.setStudentID(1); st.setStudentName("Joe"); println(st.getStudentID()); println(st.getStudentName()); } } When we run the above program, we will get the following result − 1 Joe Note the following key points about the above program − In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class. In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class. Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName) Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName) It’s normally a natural to include more methods inside of the class which actually does some sort of functionality for the class. In our student example, let’s add instance members of Marks1, Marks2 and Marks3 to denote the marks of the student in 3 subjects. We will then add a new instance method which will calculate the total marks of the student. Following is how the code would look like. In the following example, the method Total is an additional Instance method which has some logic built into it. class Student { int StudentID; String StudentName; int Marks1; int Marks2; int Marks3; int Total() { return Marks1+Marks2+Marks3; } static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.StudentName="Joe"; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 30; println(st.Total()); } } When we run the above program, we will get the following result − 60 One can also create multiple objects of a class. Following is the example of how this can be achieved. In here we are creating 3 objects (st, st1 and st2) and calling their instance members and instance methods accordingly. class Student { int StudentID; String StudentName; int Marks1; int Marks2; int Marks3; int Total() { return Marks1+Marks2+Marks3; } static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.StudentName = "Joe"; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 30; println(st.Total()); Student st1 = new Student(); st.StudentID = 1; st.StudentName = "Joe"; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 40; println(st.Total()); Student st3 = new Student(); st.StudentID = 1; st.StudentName = "Joe"; st.Marks1 = 10; st.Marks2 = 20; st.Marks3 = 50; println(st.Total()); } } When we run the above program, we will get the following result − 60 70 80 Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). extends is the keyword used to inherit the properties of a class. Given below is the syntax of extends keyword. In the following example we are doing the following things − Creating a class called Person. This class has one instance member called name. Creating a class called Person. This class has one instance member called name. Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class. Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class. In the Student class constructor, we are calling the base class constructor. In the Student class constructor, we are calling the base class constructor. In our Student class, we are adding 2 additional instance members of StudentID and Marks1. In our Student class, we are adding 2 additional instance members of StudentID and Marks1. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; st.name = "Joe"; println(st.name); } } class Person { public String name; public Person() {} } class Student extends Person { int StudentID int Marks1; public Student() { super(); } } When we run the above program, we will get the following result − Joe Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes. Following is an example of an Outer and Inner class. In the following example we are doing the following things − Creating an class called Outer which will be our outer class. Defining a string called name in our Outer class. Creating an Inner or nested class inside of our Outer class. Note that in the inner class we are able to access the name instance member defined in the Outer class. class Example { static void main(String[] args) { Outer outobj = new Outer(); outobj.name = "Joe"; outobj.callInnerMethod() } } class Outer { String name; def callInnerMethod() { new Inner().methodA() } class Inner { def methodA() { println(name); } } } When we run the above program, we will get the following result − Joe Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses. Abstract classes must be declared with abstract keyword. Abstract methods must also be declared with abstract keyword. In the following example, note that the Person class is now made into an abstract class and cannot be instantiated. Also note that there is an abstract method called DisplayMarks in the abstract class which has no implementation details. In the student class it is mandatory to add the implementation details. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; st.name="Joe"; println(st.name); println(st.DisplayMarks()); } } abstract class Person { public String name; public Person() { } abstract void DisplayMarks(); } class Student extends Person { int StudentID int Marks1; public Student() { super(); } void DisplayMarks() { println(Marks1); } } When we run the above program, we will get the following result − Joe 10 null An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the methods implementation. An interface needs to be declared using the interface keyword. An interface only defines method signatures. Methods of an interface are always public. It is an error to use protected or private methods in interfaces. Following is an example of an interface in groovy. In the following example we are doing the following things − Creating an interface called Marks and creating an interface method called DisplayMarks. Creating an interface called Marks and creating an interface method called DisplayMarks. In the class definition, we are using the implements keyword to implement the interface. In the class definition, we are using the implements keyword to implement the interface. Because we are implementing the interface we have to provide the implementation for the DisplayMarks method. Because we are implementing the interface we have to provide the implementation for the DisplayMarks method. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; println(st.DisplayMarks()); } } interface Marks { void DisplayMarks(); } class Student implements Marks { int StudentID int Marks1; void DisplayMarks() { println(Marks1); } } When we run the above program, we will get the following result − 10 null Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types. The collections classes such as the List class can be generalized so that only collections of that type are accepted in the application. An example of the generalized ArrayList is shown below. What the following statement does is that it only accepts list items which are of the type string − List<String> list = new ArrayList<String>(); In the following code example, we are doing the following − Creating a Generalized ArrayList collection which will hold only Strings. Add 3 strings to the list. For each item in the list, printing the value of the strings. class Example { static void main(String[] args) { // Creating a generic List collection List<String> list = new ArrayList<String>(); list.add("First String"); list.add("Second String"); list.add("Third String"); for(String str : list) { println(str); } } } The output of the above program would be − First String Second String Third String The entire class can also be generalized. This makes the class more flexible in accepting any types and working accordingly with those types. Let’s look at an example of how we can accomplish this. In the following program, we are carrying out the following steps − We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T> We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T> The generic class has simple getter and setter methods to work with the member variable defined in the class. The generic class has simple getter and setter methods to work with the member variable defined in the class. In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String. In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String. class Example { static void main(String[] args) { // Creating a generic List collection ListType<String> lststr = new ListType<>(); lststr.set("First String"); println(lststr.get()); ListType<Integer> lstint = new ListType<>(); lstint.set(1); println(lstint.get()); } } public class ListType<T> { private T localt; public T get() { return this.localt; } public void set(T plocal) { this.localt = plocal; } } The output of the above program would be − First String 1 Traits are a structural construct of the language which allow − Composition of behaviors. Runtime implementation of interfaces. Compatibility with static type checking/compilation They can be seen as interfaces carrying both default implementations and state. A trait is defined using the trait keyword. An example of a trait is given below − trait Marks { void DisplayMarks() { println("Display Marks"); } } One can then use the implement keyword to implement the trait in the similar way as interfaces. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; println(st.DisplayMarks()); } } trait Marks { void DisplayMarks() { println("Display Marks"); } } class Student implements Marks { int StudentID int Marks1; } Traits may implement interfaces, in which case the interfaces are declared using the implements keyword. An example of a trait implementing an interface is given below. In the following example the following key points can be noted. An interface Total is defined with the method DisplayTotal. An interface Total is defined with the method DisplayTotal. The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method. The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; st.Marks1 = 10; println(st.DisplayMarks()); println(st.DisplayTotal()); } } interface Total { void DisplayTotal() } trait Marks implements Total { void DisplayMarks() { println("Display Marks"); } void DisplayTotal() { println("Display Total"); } } class Student implements Marks { int StudentID int Marks1; } The output of the above program would be − Display Marks Display Total A trait may define properties. An example of a trait with a property is given below. In the following example, the Marks1 of type integer is a property. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); println(st.DisplayTotal()); } interface Total { void DisplayTotal() } trait Marks implements Total { int Marks1; void DisplayMarks() { this.Marks1 = 10; println(this.Marks1); } void DisplayTotal() { println("Display Total"); } } class Student implements Marks { int StudentID } } The output of the above program would be − 10 Display Total Traits can be used to implement multiple inheritance in a controlled way, avoiding the diamond issue. In the following code example, we have defined two traits – Marks and Total. Our Student class implements both traits. Since the student class extends both traits, it is able to access the both of the methods – DisplayMarks and DisplayTotal. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); println(st.DisplayTotal()); } } trait Marks { void DisplayMarks() { println("Marks1"); } } trait Total { void DisplayTotal() { println("Total"); } } class Student implements Marks,Total { int StudentID } The output of the above program would be − Total Marks1 Traits may extend another trait, in which case you must use the extends keyword. In the following code example, we are extending the Total trait with the Marks trait. class Example { static void main(String[] args) { Student st = new Student(); st.StudentID = 1; println(st.DisplayMarks()); } } trait Marks { void DisplayMarks() { println("Marks1"); } } trait Total extends Marks { void DisplayMarks() { println("Total"); } } class Student implements Total { int StudentID } The output of the above program would be − Total A closure is a short anonymous block of code. It just normally spans a few lines of code. A method can even take the block of code as a parameter. They are anonymous in nature. Following is an example of a simple closure and what it looks like. class Example { static void main(String[] args) { def clos = {println "Hello World"}; clos.call(); } } In the above example, the code line - {println "Hello World"} is known as a closure. The code block referenced by this identifier can be executed with the call statement. When we run the above program, we will get the following result − Hello World Closures can also contain formal parameters to make them more useful just like methods in Groovy. class Example { static void main(String[] args) { def clos = {param->println "Hello ${param}"}; clos.call("World"); } } In the above code example, notice the use of the ${param } which causes the closure to take a parameter. When calling the closure via the clos.call statement we now have the option to pass a parameter to the closure. When we run the above program, we will get the following result − Hello World The next illustration repeats the previous example and produces the same result, but shows that an implicit single parameter referred to as it can be used. Here ‘it’ is a keyword in Groovy. class Example { static void main(String[] args) { def clos = {println "Hello ${it}"}; clos.call("World"); } } When we run the above program, we will get the following result − Hello World More formally, closures can refer to variables at the time the closure is defined. Following is an example of how this can be achieved. class Example { static void main(String[] args) { def str1 = "Hello"; def clos = {param -> println "${str1} ${param}"} clos.call("World"); // We are now changing the value of the String str1 which is referenced in the closure str1 = "Welcome"; clos.call("World"); } } In the above example, in addition to passing a parameter to the closure, we are also defining a variable called str1. The closure also takes on the variable along with the parameter. When we run the above program, we will get the following result − Hello World Welcome World Closures can also be used as parameters to methods. In Groovy, a lot of the inbuilt methods for data types such as Lists and collections have closures as a parameter type. The following example shows how a closure can be sent to a method as a parameter. class Example { def static Display(clo) { // This time the $param parameter gets replaced by the string "Inner" clo.call("Inner"); } static void main(String[] args) { def str1 = "Hello"; def clos = { param -> println "${str1} ${param}" } clos.call("World"); // We are now changing the value of the String str1 which is referenced in the closure str1 = "Welcome"; clos.call("World"); // Passing our closure to a method Example.Display(clos); } } In the above example, We are defining a static method called Display which takes a closure as an argument. We are defining a static method called Display which takes a closure as an argument. We are then defining a closure in our main method and passing it to our Display method as a parameter. We are then defining a closure in our main method and passing it to our Display method as a parameter. When we run the above program, we will get the following result − Hello World Welcome World Welcome Inner Several List, Map, and String methods accept a closure as an argument. Let’s look at example of how closures can be used in these data types. The following example shows how closures can be used with Lists. In the following example we are first defining a simple list of values. The list collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each element of the list. class Example { static void main(String[] args) { def lst = [11, 12, 13, 14]; lst.each {println it} } } When we run the above program, we will get the following result − 11 12 13 14 The following example shows how closures can be used with Maps. In the following example we are first defining a simple Map of key value items. The map collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each key-value pair of the map. class Example { static void main(String[] args) { def mp = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] mp.each {println it} mp.each {println "${it.key} maps to: ${it.value}"} } } When we run the above program, we will get the following result − TopicName = Maps TopicDescription = Methods in Maps TopicName maps to: Maps TopicDescription maps to: Methods in Maps Often, we may wish to iterate across the members of a collection and apply some logic only when the element meets some criterion. This is readily handled with a conditional statement in the closure. class Example { static void main(String[] args) { def lst = [1,2,3,4]; lst.each {println it} println("The list will only display those numbers which are divisible by 2") lst.each{num -> if(num % 2 == 0) println num} } } The above example shows the conditional if(num % 2 == 0) expression being used in the closure which is used to check if each item in the list is divisible by 2. When we run the above program, we will get the following result − 1 2 3 4 The list will only display those numbers which are divisible by 2. 2 4 The closures themselves provide some methods. The find method finds the first value in a collection that matches some criterion. It finds all values in the receiving object matching the closure condition. Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element. The method collect iterates through a collection, converting each element into a new value using the closure as the transformer. Annotations are a form of metadata wherein they provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate. Annotations are mainly used for the following reasons − Information for the compiler − Annotations can be used by the compiler to detect errors or suppress warnings. Information for the compiler − Annotations can be used by the compiler to detect errors or suppress warnings. Compile-time and deployment-time processing − Software tools can process annotation information to generate code, XML files, and so forth. Compile-time and deployment-time processing − Software tools can process annotation information to generate code, XML files, and so forth. Runtime processing − Some annotations are available to be examined at runtime. Runtime processing − Some annotations are available to be examined at runtime. In Groovy, a basic annotation looks as follows − @interface - The at sign character (@) indicates to the compiler that what follows is an annotation. An annotation may define members in the form of methods without bodies and an optional default value. Annotation’s can be applied to the following types − An example of an Annotation for a string is given below − @interface Simple { String str1() default "HelloWorld"; } enum DayOfWeek { mon, tue, wed, thu, fri, sat, sun } @interface Scheduled { DayOfWeek dayOfWeek() } @interface Simple {} @Simple class User { String username int age } def user = new User(username: "Joe",age:1); println(user.age); println(user.username); When an annotation is used, it is required to set at least all members that do not have a default value. An example is given below. When the annotation Example is used after being defined, it needs to have a value assigned to it. @interface Example { int status() } @Example(status = 1) A good feature of annotations in Groovy is that you can use a closure as an annotation value also. Therefore annotations may be used with a wide variety of expressions. An example is given below on this. The annotation Onlyif is created based on a class value. Then the annotation is applied to two methods which posts different messages to the result variable based on the value of the number variable. @interface OnlyIf { Class value() } @OnlyIf({ number<=6 }) void Version6() { result << 'Number greater than 6' } @OnlyIf({ number>=6 }) void Version7() { result << 'Number greater than 6' } This is quite a useful feature of annotations in groovy. There may comes times wherein you might have multiple annotations for a method as the one shown below. Sometimes this can become messy to have multiple annotations. @Procedure @Master class MyMasterProcedure {} In such a case you can define a meta-annotation which clubs multiple annotations together and the apply the meta annotation to the method. So for the above example you can fist define the collection of annotation using the AnnotationCollector. import groovy.transform.AnnotationCollector @Procedure @Master @AnnotationCollector Once this is done, you can apply the following meta-annotator to the method − import groovy.transform.AnnotationCollector @Procedure @Master @AnnotationCollector @MasterProcedure class MyMasterProcedure {} XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications. The Extensible Markup Language XML is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQLbased backbone. The Groovy language also provides a rich support of the XML language. The two most basic XML classes used are − XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node. XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node. XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. For all our XML code examples, let's use the following simple XML file movies.xml for construction of the XML file and reading the file subsequently. <collection shelf = "New Arrivals"> <movie title = "Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title = "Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title = "Trigun"> <type>Anime, Action</type> <format>DVD</format> <year>1986</year> <rating>PG</rating> <stars>10</stars> <description>Vash the Stam pede!</description> </movie> <movie title = "Ishtar"> <type>Comedy</type> <format>VHS</format> <year>1987</year> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom </description> </movie> </collection> public MarkupBuilder() The MarkupBuilder is used to construct the entire XML document. The XML document is created by first creating an object of the XML document class. Once the object is created, a pseudomethod can be called to create the various elements of the XML document. Let’s look at an example of how to create one block, that is, one movie element from the above XML document − import groovy.xml.MarkupBuilder class Example { static void main(String[] args) { def mB = new MarkupBuilder() // Compose the builder mB.collection(shelf : 'New Arrivals') { movie(title : 'Enemy Behind') type('War, Thriller') format('DVD') year('2003') rating('PG') stars(10) description('Talk about a US-Japan war') } } } In the above example, the following things need to be noted − mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection> mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection> movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element. movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element. A closure is provided to the pseudomethod to create the remaining elements of the XML document. A closure is provided to the pseudomethod to create the remaining elements of the XML document. The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream When we run the above program, we will get the following result − <collection shelf = 'New Arrivals'> <movie title = 'Enemy Behind' /> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> </collection> In order to create the entire XML document, the following things need to be done. A map entry needs to be created to store the different values of the elements. For each element of the map, we are assigning the value to each element. import groovy.xml.MarkupBuilder class Example { static void main(String[] args) { def mp = [1 : ['Enemy Behind', 'War, Thriller','DVD','2003', 'PG', '10','Talk about a US-Japan war'], 2 : ['Transformers','Anime, Science Fiction','DVD','1989', 'R', '8','A scientific fiction'], 3 : ['Trigun','Anime, Action','DVD','1986', 'PG', '10','Vash the Stam pede'], 4 : ['Ishtar','Comedy','VHS','1987', 'PG', '2','Viewable boredom ']] def mB = new MarkupBuilder() // Compose the builder def MOVIEDB = mB.collection('shelf': 'New Arrivals') { mp.each { sd -> mB.movie('title': sd.value[0]) { type(sd.value[1]) format(sd.value[2]) year(sd.value[3]) rating(sd.value[4]) stars(sd.value[4]) description(sd.value[5]) } } } } } When we run the above program, we will get the following result − <collection shelf = 'New Arrivals'> <movie title = 'Enemy Behind'> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>PG</stars> <description>10</description> </movie> <movie title = 'Transformers'> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>R</stars> <description>8</description> </movie> <movie title = 'Trigun'> <type>Anime, Action</type> <format>DVD</format> <year>1986</year> <rating>PG</rating> <stars>PG</stars> <description>10</description> </movie> <movie title = 'Ishtar'> <type>Comedy</type> <format>VHS</format> <year>1987</year> <rating>PG</rating> <stars>PG</stars> <description>2</description> </movie> </collection> The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing. public XmlParser() throws ParserConfigurationException, SAXException The following codeshows an example of how the XML parser can be used to read an XML document. Let’s assume we have the same document called Movies.xml and we wanted to parse the XML document and display a proper output to the user. The following codeis a snippet of how we can traverse through the entire content of the XML document and display a proper response to the user. import groovy.xml.MarkupBuilder import groovy.util.* class Example { static void main(String[] args) { def parser = new XmlParser() def doc = parser.parse("D:\\Movies.xml"); doc.movie.each{ bk-> print("Movie Name:") println "${bk['@title']}" print("Movie Type:") println "${bk.type[0].text()}" print("Movie Format:") println "${bk.format[0].text()}" print("Movie year:") println "${bk.year[0].text()}" print("Movie rating:") println "${bk.rating[0].text()}" print("Movie stars:") println "${bk.stars[0].text()}" print("Movie description:") println "${bk.description[0].text()}" println("*******************************") } } } When we run the above program, we will get the following result − Movie Name:Enemy Behind Movie Type:War, Thriller Movie Format:DVD Movie year:2003 Movie rating:PG Movie stars:10 Movie description:Talk about a US-Japan war ******************************* Movie Name:Transformers Movie Type:Anime, Science Fiction Movie Format:DVD Movie year:1989 Movie rating:R Movie stars:8 Movie description:A schientific fiction ******************************* Movie Name:Trigun Movie Type:Anime, Action Movie Format:DVD Movie year:1986 Movie rating:PG Movie stars:10 Movie description:Vash the Stam pede! ******************************* Movie Name:Ishtar Movie Type:Comedy Movie Format:VHS Movie year:1987 Movie rating:PG Movie stars:2 Movie description:Viewable boredom The important things to note about the above code. An object of the class XmlParser is being formed so that it can be used to parse the XML document. An object of the class XmlParser is being formed so that it can be used to parse the XML document. The parser is given the location of the XML file. The parser is given the location of the XML file. For each movie element, we are using a closure to browse through each child node and display the relevant information. For each movie element, we are using a closure to browse through each child node and display the relevant information. For the movie element itself, we are using the @ symbol to display the title attribute attached to the movie element. JMX is the defacto standard which is used for monitoring all applications which have anything to do with the Java virual environment. Given that Groovy sits directly on top of Java, Groovy can leverage the tremendous amount of work already done for JMX with Java. One can use the standard classes available in java.lang.management for carrying out the monitoring of the JVM. The following code example shows how this can be done. import java.lang.management.* def os = ManagementFactory.operatingSystemMXBean println """OPERATING SYSTEM: \tOS architecture = $os.arch \tOS name = $os.name \tOS version = $os.version \tOS processors = $os.availableProcessors """ def rt = ManagementFactory.runtimeMXBean println """RUNTIME: \tRuntime name = $rt.name \tRuntime spec name = $rt.specName \tRuntime vendor = $rt.specVendor \tRuntime spec version = $rt.specVersion \tRuntime management spec version = $rt.managementSpecVersion """ def mem = ManagementFactory.memoryMXBean def heapUsage = mem.heapMemoryUsage def nonHeapUsage = mem.nonHeapMemoryUsage println """MEMORY: HEAP STORAGE: \tMemory committed = $heapUsage.committed \tMemory init = $heapUsage.init \tMemory max = $heapUsage.max \tMemory used = $heapUsage.used NON-HEAP STORAGE: \tNon-heap memory committed = $nonHeapUsage.committed \tNon-heap memory init = $nonHeapUsage.init \tNon-heap memory max = $nonHeapUsage.max \tNon-heap memory used = $nonHeapUsage.used """ println "GARBAGE COLLECTION:" ManagementFactory.garbageCollectorMXBeans.each { gc -> println "\tname = $gc.name" println "\t\tcollection count = $gc.collectionCount" println "\t\tcollection time = $gc.collectionTime" String[] mpoolNames = gc.memoryPoolNames mpoolNames.each { mpoolName -> println "\t\tmpool name = $mpoolName" } } When the code is executed, the output will vary depending on the system on which the code is run. A sample of the output is given below. OPERATING SYSTEM: OS architecture = x86 OS name = Windows 7 OS version = 6.1 OS processors = 4 RUNTIME: Runtime name = 5144@Babuli-PC Runtime spec name = Java Virtual Machine Specification Runtime vendor = Oracle Corporation Runtime spec version = 1.7 Runtime management spec version = 1.2 MEMORY: HEAP STORAGE: Memory committed = 16252928 Memory init = 16777216 Memory max = 259522560 Memory used = 7355840 NON-HEAP STORAGE: Non-heap memory committed = 37715968 Non-heap memory init = 35815424 Non-heap memory max = 123731968 Non-heap memory used = 18532232 GARBAGE COLLECTION: name = Copy collection count = 15 collection time = 47 mpool name = Eden Space mpool name = Survivor Space name = MarkSweepCompact collection count = 0 collection time = 0 mpool name = Eden Space mpool name = Survivor Space mpool name = Tenured Gen mpool name = Perm Gen mpool name = Perm Gen [shared-ro] mpool name = Perm Gen [shared-rw] In order to monitor tomcat, the following parameter should be set when tomcat is started − set JAVA_OPTS = -Dcom.sun.management.jmxremote Dcom.sun.management.jmxremote.port = 9004\ -Dcom.sun.management.jmxremote.authenticate=false Dcom.sun.management.jmxremote.ssl = false The following code uses JMX to discover the available MBeans in the running Tomcat, determine which are the web modules and extract the processing time for each web module. import groovy.swing.SwingBuilder import javax.management.ObjectName import javax.management.remote.JMXConnectorFactory as JmxFactory import javax.management.remote.JMXServiceURL as JmxUrl import javax.swing.WindowConstants as WC import org.jfree.chart.ChartFactory import org.jfree.data.category.DefaultCategoryDataset as Dataset import org.jfree.chart.plot.PlotOrientation as Orientation def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi' def server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection def serverInfo = new GroovyMBean(server, 'Catalina:type = Server').serverInfo println "Connected to: $serverInfo" def query = new ObjectName('Catalina:*') String[] allNames = server.queryNames(query, null) def modules = allNames.findAll { name -> name.contains('j2eeType=WebModule') }.collect{ new GroovyMBean(server, it) } println "Found ${modules.size()} web modules. Processing ..." def dataset = new Dataset() modules.each { m -> println m.name() dataset.addValue m.processingTime, 0, m.path } This chapter covers how to we can use the Groovy language for parsing and producing JSON objects. JsonSlurper JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String. JsonOutput This method is responsible for serialising Groovy objects into JSON strings. JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String. def slurper = new JsonSlurper() JSON slurper parses text or reader content into a data structure of lists and maps. The JsonSlurper class comes with a couple of variants for parser implementations. Sometimes you may have different requirements when it comes to parsing certain strings. Let’s take an instance wherein one needs to read the JSON which is returned from the response from a web server. In such a case it’s beneficial to use the parser JsonParserLax variant. This parsee allows comments in the JSON text as well as no quote strings etc. To specify this sort of parser you need to use JsonParserType.LAX parser type when defining an object of the JsonSlurper. Let’s see an example of this given below. The example is for getting JSON data from a web server using the http module. For this type of traversal, the best option is to have the parser type set to JsonParserLax variant. http.request( GET, TEXT ) { headers.Accept = 'application/json' headers.'User-Agent' = USER_AGENT response.success = { res, rd -> def jsonText = rd.text //Setting the parser type to JsonParserLax def parser = new JsonSlurper().setType(JsonParserType.LAX) def jsonResp = parser.parseText(jsonText) } } Similarly the following additional parser types are available in Groovy − The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as "chopping") and operates on them individually. The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as "chopping") and operates on them individually. The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. JsonFastParser is also known as the index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It just keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible. The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. JsonFastParser is also known as the index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It just keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible. The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called "character windowing" to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics. The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called "character windowing" to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics. Let’s have a look at some examples of how we can use the JsonSlurper class. import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def object = jsonSlurper.parseText('{ "name": "John", "ID" : "1"}') println(object.name); println(object.ID); } } In the above example, we are − First creating an instance of the JsonSlurper class First creating an instance of the JsonSlurper class We are then using the parseText function of the JsonSlurper class to parse some JSON text. We are then using the parseText function of the JsonSlurper class to parse some JSON text. When we get the object, you can see that we can actually access the values in the JSON string via the key. When we get the object, you can see that we can actually access the values in the JSON string via the key. The output of the above program is given below − John 1 Let’s take a look at another example of the JsonSlurper parsing method. In the following example, we are pasing a list of integers. You will notice from The following codethat we are able to use the List method of each and pass a closure to it. import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() Object lst = jsonSlurper.parseText('{ "List": [2, 3, 4, 5] }') lst.each { println it } } } The output of the above program is given below − List=[2, 3, 4, 5] The JSON parser also supports the primitive data types of string, number, object, true, false and null. The JsonSlurper class converts these JSON types into corresponding Groovy types. The following example shows how to use the JsonSlurper to parse a JSON string. And here you can see that the JsonSlurper is able to parse the individual items into their respective primitive types. import groovy.json.JsonSlurper class Example { static void main(String[] args) { def jsonSlurper = new JsonSlurper() def obj = jsonSlurper.parseText ''' {"Integer": 12, "fraction": 12.55, "double": 12e13}''' println(obj.Integer); println(obj.fraction); println(obj.double); } } The output of the above program is given below − 12 12.55 1.2E+14 Now let’s talk about how to print output in Json. This can be done by the JsonOutput method. This method is responsible for serialising Groovy objects into JSON strings. Static string JsonOutput.toJson(datatype obj) Parameters − The parameters can be an object of a datatype – Number, Boolean, character,String, Date, Map, closure etc. Return type − The return type is a json string. Following is a simple example of how this can be achieved. import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([name: 'John', ID: 1]) println(output); } } The output of the above program is given below − {"name":"John","ID":1} The JsonOutput can also be used for plain old groovy objects. In the following example, you can see that we are actually passing objects of the type Student to the JsonOutput method. import groovy.json.JsonOutput class Example { static void main(String[] args) { def output = JsonOutput.toJson([ new Student(name: 'John',ID:1), new Student(name: 'Mark',ID:2)]) println(output); } } class Student { String name int ID; } The output of the above program is given below − [{"name":"John","ID":1},{"name":"Mark","ID":2}] Groovy allows one to omit parentheses around the arguments of a method call for top-level statements. This is known as the "command chain" feature. This extension works by allowing one to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls. If a call is executed as a b c d, this will actually be equivalent to a(b).c(d). DSL or Domain specific language is meant to simplify the code written in Groovy in such a way that it becomes easily understandable for the common user. The following example shows what exactly is meant by having a domain specific language. def lst = [1,2,3,4] print lst The above code shows a list of numbers being printed to the console using the println statement. In a domain specific language the commands would be as − Given the numbers 1,2,3,4 Display all the numbers So the above example shows the transformation of the programming language to meet the needs of a domain specific language. Let’s look at a simple example of how we can implement DSLs in Groovy − class EmailDsl { String toText String fromText String body /** * This method accepts a closure which is essentially the DSL. Delegate the * closure methods to * the DSL class so the calls can be processed */ def static make(closure) { EmailDsl emailDsl = new EmailDsl() // any method called in closure will be delegated to the EmailDsl class closure.delegate = emailDsl closure() } /** * Store the parameter as a variable and use it later to output a memo */ def to(String toText) { this.toText = toText } def from(String fromText) { this.fromText = fromText } def body(String bodyText) { this.body = bodyText } } EmailDsl.make { to "Nirav Assar" from "Barack Obama" body "How are things? We are doing well. Take care" } When we run the above program, we will get the following result − How are things? We are doing well. Take care The following needs to be noted about the above code implementation − A static method is used that accepts a closure. This is mostly a hassle free way to implement a DSL. A static method is used that accepts a closure. This is mostly a hassle free way to implement a DSL. In the email example, the class EmailDsl has a make method. It creates an instance and delegates all calls in the closure to the instance. This is the mechanism where the "to", and "from" sections end up executing methods inside the EmailDsl class. In the email example, the class EmailDsl has a make method. It creates an instance and delegates all calls in the closure to the instance. This is the mechanism where the "to", and "from" sections end up executing methods inside the EmailDsl class. Once the to() method is called, we store the text in the instance for formatting later on. Once the to() method is called, we store the text in the instance for formatting later on. We can now call the EmailDSL method with an easy language that is easy to understand for end users. We can now call the EmailDSL method with an easy language that is easy to understand for end users. Groovy’s groovy-sql module provides a higher-level abstraction over the current Java’s JDBC technology. The Groovy sql API supports a wide variety of databases, some of which are shown below. HSQLDB Oracle SQL Server MySQL MongoDB In our example, we are going to use MySQL DB as an example. In order to use MySQL with Groovy, the first thing to do is to download the MySQL jdbc jar file from the mysql site. The format of the MySQL will be shown below. mysql-connector-java-5.1.38-bin Then ensure to add the above jar file to the classpath in your workstation. Before connecting to a MySQL database, make sure of the followings − You have created a database TESTDB. You have created a table EMPLOYEE in TESTDB. This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. User ID "testuser" and password "test123" are set to access TESTDB. Ensure you have downloaded the mysql jar file and added the file to your classpath. You have gone through MySQL tutorial to understand MySQL Basics The following example shows how to connect with MySQL database "TESTDB". import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') // Executing the query SELECT VERSION which gets the version of the database // Also using the eachROW method to fetch the result from the database sql.eachRow('SELECT VERSION()'){ row -> println row[0] } sql.close() } } While running this script, it is producing the following result − 5.7.10-log The Sql.newInstance method is used to establish a connection to the database. The next step after connecting to the database is to create the tables in our database. The following example shows how to create a table in the database using Groovy. The execute method of the Sql class is used to execute statements against the database. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') def sqlstr = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" sql.execute(sqlstr); sql.close() } } It is required when you want to create your records into a database table. The following example will insert a record in the employee table. The code is placed in a try catch block so that if the record is executed successfully, the transaction is committed to the database. If the transaction fails, a rollback is done. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def sqlstr = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } Suppose if you wanted to just select certain rows based on a criteria. The following codeshows how you can add a parameter placeholder to search for values. The above example can also be written to take in parameters as shown in the following code. The $ symbol is used to define a parameter which can then be replaced by values when the sql statement is executed. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def firstname = "Mac" def lastname ="Mohan" def age = 20 def sex = "M" def income = 2000 def sqlstr = "INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES " + "(${firstname}, ${lastname}, ${age}, ${sex}, ${income} )" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") } catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } READ Operation on any database means to fetch some useful information from the database. Once our database connection is established, you are ready to make a query into this database. The read operation is performed by using the eachRow method of the sql class. eachRow(GString gstring, Closure closure) Performs the given SQL query calling the given Closure with each row of the result set. Parameters Gstring − The sql statement which needs to be executed. Gstring − The sql statement which needs to be executed. Closure − The closure statement to process the rows retrived from the read operation. Performs the given SQL query calling the given Closure with each row of the result set. Closure − The closure statement to process the rows retrived from the read operation. Performs the given SQL query calling the given Closure with each row of the result set. The following code example shows how to fetch all the records from the employee table. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test123', 'com.mysql.jdbc.Driver') sql.eachRow('select * from employee') { tp -> println([tp.FIRST_NAME,tp.LAST_NAME,tp.age,tp.sex,tp.INCOME]) } sql.close() } } The output from the above program would be − [Mac, Mohan, 20, M, 2000.0] UPDATE Operation on any database means to update one or more records, which are already available in the database. The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one year. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args){ // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test@123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def sqlstr = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20. import java.sql.*; import groovy.sql.Sql class Example { static void main(String[] args) { // Creating a connection to the database def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', 'test@123', 'com.mysql.jdbc.Driver') sql.connection.autoCommit = false def sqlstr = "DELETE FROM EMPLOYEE WHERE AGE > 20" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() } } Transactions are a mechanism that ensures data consistency. Transactions have the following four properties − Atomicity − Either a transaction completes or nothing happens at all. Atomicity − Either a transaction completes or nothing happens at all. Consistency − A transaction must start in a consistent state and leave the system in a consistent state. Consistency − A transaction must start in a consistent state and leave the system in a consistent state. Isolation − Intermediate results of a transaction are not visible outside the current transaction. Isolation − Intermediate results of a transaction are not visible outside the current transaction. Durability − Once a transaction was committed, the effects are persistent, even after a system failure. Durability − Once a transaction was committed, the effects are persistent, even after a system failure. Here is a simple example of how to implement transactions. We have already seen this example from our previous topic of the DELETE operation. def sqlstr = "DELETE FROM EMPLOYEE WHERE AGE > 20" try { sql.execute(sqlstr); sql.commit() println("Successfully committed") }catch(Exception ex) { sql.rollback() println("Transaction rollback") } sql.close() The commit operation is what tells the database to proceed ahead with the operation and finalize all changes to the database. In our above example, this is achieved by the following statement − sql.commit() If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback method. In our above example, this is achieved by the following statement − sql.rollback() To disconnect Database connection, use the close method. sql.close() During the process of software development, sometimes developers spend a lot of time in creating Data structures, domain classes, XML, GUI Layouts, Output streams etc.And sometimes the code used to create these specific requirements results in the repitition of the same snippet of code in many places. This is where Groovy builders come into play. Groovy has builders which can be used to create standard objects and structures. These builders saves time as developer dont need to write their own code to create these builders. In the couse of this chapter we will look at the different builders available in groovy. In groovy one can also create graphical user interfaces using the swing builders available in groovy. The main class for developing swing components is the SwingBuilder class. This class has many methods for creating graphical components such as − JFrame − This is for creating the frame element. JFrame − This is for creating the frame element. JTextField − This is used for creating the textfield component. JTextField − This is used for creating the textfield component. Let’s look at a simple example of how to create a Swing application using the SwingBuilder class. In the following example, you can see the following points − You need to import the groovy.swing.SwingBuilder and the javax.swing.* classes. You need to import the groovy.swing.SwingBuilder and the javax.swing.* classes. All of the componets displayed in the Swing application are part of the SwingBuilder class. All of the componets displayed in the Swing application are part of the SwingBuilder class. For the frame itself, you can specify the initial location and size of the frame. You can also specify the title of the frame. For the frame itself, you can specify the initial location and size of the frame. You can also specify the title of the frame. You need to set the Visibility property to true in order for the frame to be shown. You need to set the Visibility property to true in order for the frame to be shown. import groovy.swing.SwingBuilder import javax.swing.* // Create a builder def myapp = new SwingBuilder() // Compose the builder def myframe = myapp.frame(title : 'Tutorials Point', location : [200, 200], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE { label(text : 'Hello world') } // The following statement is used for displaying the form frame.setVisible(true) The output of the above program is given below. The following output shows a JFrame along with a JLabel with a text of Hello World. Let’s look at our next example for creating an input screen with textboxes. In the following example, we want to create a form which has text boxes for Student name, subject and School Name. In the following example, you can see the following key points − We are defining a layout for our controls on the screen. In this case we are using the Grid Layout. We are using an alignment property for our labels. We are using the textField method for displaying textboxes on the screen. import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* // Create a builder def myapp = new SwingBuilder() // Compose the builder def myframe = myapp.frame(title : 'Tutorials Point', location : [200, 200], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) { panel(layout: new GridLayout(3, 2, 5, 5)) { label(text : 'Student Name:', horizontalAlignment : JLabel.RIGHT) textField(text : '', columns : 10) label(text : 'Subject Name:', horizontalAlignment : JLabel.RIGHT) textField(text : '', columns : 10) label(text : 'School Name:', horizontalAlignment : JLabel.RIGHT) textField(text : '', columns : 10) } } // The following statement is used for displaying the form myframe.setVisible(true) The output of the above program is given below − Now let’s look at event handlers. Event handlers are used for button to perform some sort of processing when a button is pressed. Each button pseudomethod call includes the actionPerformed parameter. This represents a code block presented as a closure. Let’s look at our next example for creating a screen with 2 buttons. When either button is pressed a corresponding message is sent to the console screen. In the following example, you can see the following key points − For each button defined, we are using the actionPerformed method and defining a closure to send some output to the console when the button is clicked. For each button defined, we are using the actionPerformed method and defining a closure to send some output to the console when the button is clicked. import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* def myapp = new SwingBuilder() def buttonPanel = { myapp.panel(constraints : BorderLayout.SOUTH) { button(text : 'Option A', actionPerformed : { println 'Option A chosen' }) button(text : 'Option B', actionPerformed : { println 'Option B chosen' }) } } def mainPanel = { myapp.panel(layout : new BorderLayout()) { label(text : 'Which Option do you want', horizontalAlignment : JLabel.CENTER, constraints : BorderLayout.CENTER) buttonPanel() } } def myframe = myapp.frame(title : 'Tutorials Point', location : [100, 100], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE){ mainPanel() } myframe.setVisible(true) The output of the above program is given below. When you click on either button, the required message is sent to the console log screen. Another variation of the above example is to define methods which can can act as handlers. In the following example we are defining 2 handlers of DisplayA and DisplayB. import groovy.swing.SwingBuilder import javax.swing.* import java.awt.* def myapp = new SwingBuilder() def DisplayA = { println("Option A") } def DisplayB = { println("Option B") } def buttonPanel = { myapp.panel(constraints : BorderLayout.SOUTH) { button(text : 'Option A', actionPerformed : DisplayA) button(text : 'Option B', actionPerformed : DisplayB) } } def mainPanel = { myapp.panel(layout : new BorderLayout()) { label(text : 'Which Option do you want', horizontalAlignment : JLabel.CENTER, constraints : BorderLayout.CENTER) buttonPanel() } } def myframe = myapp.frame(title : 'Tutorials Point', location : [100, 100], size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) { mainPanel() } myframe.setVisible(true) The output of the above program would remain the same as the earlier example. The DOM builder can be used for parsing HTML, XHTML and XML and converting it into a W3C DOM tree. The following example shows how the DOM builder can be used. String records = ''' <library> <Student> <StudentName division = 'A'>Joe</StudentName> <StudentID>1</StudentID> </Student> <Student> <StudentName division = 'B'>John</StudentName> <StudentID>2</StudentID> </Student> <Student> <StudentName division = 'C'>Mark</StudentName> <StudentID>3</StudentID> </Student> </library>''' def rd = new StringReader(records) def doc = groovy.xml.DOMBuilder.parse(rd) The JsonBuilder is used for creating json type objects. The following example shows how the Json builder can be used. def builder = new groovy.json.JsonBuilder() def root = builder.students { student { studentname 'Joe' studentid '1' Marks( Subject1: 10, Subject2: 20, Subject3:30, ) } } println(builder.toString()); The output of the above program is given below. The output clearlt shows that the Jsonbuilder was able to build the json object out of a structed set of nodes. {"students":{"student":{"studentname":"Joe","studentid":"1","Marks":{"Subject1":10, "S ubject2":20,"Subject3":30}}}} The jsonbuilder can also take in a list and convert it to a json object. The following example shows how this can be accomplished. def builder = new groovy.json.JsonBuilder() def lst = builder([1, 2, 3]) println(builder.toString()); The output of the above program is given below. [1,2,3] The jsonBuilder can also be used for classes. The following example shows how objects of a class can become inputs to the json builder. def builder = new groovy.json.JsonBuilder() class Student { String name } def studentlist = [new Student (name: "Joe"), new Student (name: "Mark"), new Student (name: "John")] builder studentlist, { Student student ->name student.name} println(builder) The output of the above program is given below. [{"name":"Joe"},{"name":"Mark"},{"name":"John"}] NodeBuilder is used for creating nested trees of Node objects for handling arbitrary data. An example of the usage of a Nodebuilder is shown below. def nodeBuilder = new NodeBuilder() def studentlist = nodeBuilder.userlist { user(id: '1', studentname: 'John', Subject: 'Chemistry') user(id: '2', studentname: 'Joe', Subject: 'Maths') user(id: '3', studentname: 'Mark', Subject: 'Physics') } println(studentlist) FileTreeBuilder is a builder for generating a file directory structure from a specification. Following is an example of how the FileTreeBuilder can be used. tmpDir = File.createTempDir() def fileTreeBuilder = new FileTreeBuilder(tmpDir) fileTreeBuilder.dir('main') { dir('submain') { dir('Tutorial') { file('Sample.txt', 'println "Hello World"') } } } From the execution of the above code a file called sample.txt will be created in the folder main/submain/Tutorial. And the sample.txt file will have the text of “Hello World”. The Groovy shell known as groovysh can be easily used to evaluate groovy expressions, define classes and run simple programs. The command line shell gets installed when Groovy is installed. Following are the command line options available in Groovy − The following snapshot shows a simple example of an expression being executed in the Groovy shell. In the following example we are just printing “Hello World” in the groovy shell. It is very easy to define a class in the command prompt, create a new object and invoke a method on the class. The following example shows how this can be implemented. In the following example, we are creating a simple Student class with a simple method. In the command prompt itself, we are creating an object of the class and calling the Display method. It is very easy to define a method in the command prompt and invoke the method. Note that the method is defined using the def type. Also note that we have included a parameter called name which then gets substituted with the actual value when the Display method is called. The following example shows how this can be implemented. The shell has a number of different commands, which provide rich access to the shell’s environment. Following is the list of them and what they do. :help (:h ) Display this help message ? (:? ) Alias to: :help :exit (:x ) Exit the shell :quit (:q ) Alias to: :exit import (:i ) Import a class into the namespace :display (:d ) Display the current buffer :clear (:c ) Clear the buffer and reset the prompt counter :show (:S ) Show variables, classes or imports :inspect (:n ) Inspect a variable or the last result with the GUI object browser :purge (:p ) Purge variables, classes, imports or preferences :edit (:e ) Edit the current buffer :load (:l ) Load a file or URL into the buffer . (:. ) Alias to: :load .save (:s ) Save the current buffer to a file .record (:r ) Record the current session to a file :alias (:a ) Create an alias :set (:= ) Set (or list) preferences :register (:rc) Registers a new command with the shell :doc (:D ) Opens a browser window displaying the doc for the argument :history (:H ) Display, manage and recall edit-line history The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods. JUnit is an open-source testing framework that is the accepted industry standard for the automated unit testing of Java code. Fortunately, the JUnit framework can be easily used for testing Groovy classes. All that is required is to extend the GroovyTestCase class that is part of the standard Groovy environment. The Groovy test case class is based on the Junit test case. Let assume we have the following class defined in a an application class file − class Example { static void main(String[] args) { Student mst = new Student(); mst.name = "Joe"; mst.ID = 1; println(mst.Display()) } } public class Student { String name; int ID; String Display() { return name +ID; } } The output of the above program is given below. Joe1 And now suppose we wanted to write a test case for the Student class. A typical test case would look like the one below. The following points need to be noted about the following code − The test case class extends the GroovyTestCase class We are using the assert statement to ensure that the Display method returns the right string. class StudentTest extends GroovyTestCase { void testDisplay() { def stud = new Student(name : 'Joe', ID : '1') def expected = 'Joe1' assertToString(stud.Display(), expected) } } Normally as the number of unit tests increases, it would become difficult to keep on executing all the test cases one by one. Hence Groovy provides a facility to create a test suite that can encapsulate all test cases into one logicial unit. The following codesnippet shows how this can be achieved. The following things should be noted about the code − The GroovyTestSuite is used to encapsulate all test cases into one. The GroovyTestSuite is used to encapsulate all test cases into one. In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing. In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing. import groovy.util.GroovyTestSuite import junit.framework.Test import junit.textui.TestRunner class AllTests { static Test suite() { def allTests = new GroovyTestSuite() allTests.addTestSuite(StudentTest.class) allTests.addTestSuite(EmployeeTest.class) return allTests } } TestRunner.run(AllTests.suite()) Groovy’s template engine operates like a mail merge (the automatic addition of names and addresses from a database to letters and envelopes in order to facilitate sending mail, especially advertising, to many addresses) but it is much more general. If you take the simple example below, we are first defining a name variable to hold the string “Groovy”. In the println statement, we are using $ symbol to define a parameter or template where a value can be inserted. def name = "Groovy" println "This Tutorial is about ${name}" If the above code is executed in groovy, the following output will be shown. The output clearly shows that the $name was replaced by the value which was assigned by the def statement. Following is an example of the SimpleTemplateEngine that allows you to use JSP-like scriptlets and EL expressions in your template in order to generate parametrized text. The templating engine allows you to bind a list of parameters and their values so that they can be replaced in the string which has the defined placeholders. def text ='This Tutorial focuses on $TutorialName. In this tutorial you will learn about $Topic' def binding = ["TutorialName":"Groovy", "Topic":"Templates"] def engine = new groovy.text.SimpleTemplateEngine() def template = engine.createTemplate(text).make(binding) println template If the above code is executed in groovy, the following output will be shown. Let’s now use the templating feature for an XML file. As a first step let’s add the following code to a file called Student.template. In the following file you will notice that we have not added the actual values for the elements, but placeholders. So $name,$is and $subject are all put as placeholders which will need to replaced at runtime. <Student> <name>${name}</name> <ID>${id}</ID> <subject>${subject}</subject> </Student> Now let’s add our Groovy script code to add the functionality which can be used to replace the above template with actual values. The following things should be noted about the following code. The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values. The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values. import groovy.text.* import java.io.* def file = new File("D:/Student.template") def binding = ['name' : 'Joe', 'id' : 1, 'subject' : 'Physics'] def engine = new SimpleTemplateEngine() def template = engine.createTemplate(file) def writable = template.make(binding) println writable If the above code is executed in groovy, the following output will be shown. From the output it can be seen that the values are successfully replaced in the relevant placeholders. <Student> <name>Joe</name> <ID>1</ID> <subject>Physics</subject> </Student> The StreamingTemplateEngine engine is another templating engine available in Groovy. This is kind of equivalent to the SimpleTemplateEngine, but creates the template using writeable closures making it more scalable for large templates. Specifically this template engine can handle strings larger than 64k. Following is an example of how StreamingTemplateEngine are used − def text = '''This Tutorial is <% out.print TutorialName %> The Topic name is ${TopicName}''' def template = new groovy.text.StreamingTemplateEngine().createTemplate(text) def binding = [TutorialName : "Groovy", TopicName : "Templates",] String response = template.make(binding) println(response) If the above code is executed in groovy, the following output will be shown. This Tutorial is Groovy The Topic name is Templates The XmlTemplateEngine is used in templating scenarios where both the template source and the expected output are intended to be XML. Templates use the normal ${expression} and $variable notations to insert an arbitrary expression into the template. Following is an example of how XMLTemplateEngine is used. def binding = [StudentName: 'Joe', id: 1, subject: 'Physics'] def engine = new groovy.text.XmlTemplateEngine() def text = '''\ <document xmlns:gsp='http://groovy.codehaus.org/2005/gsp'> <Student> <name>${StudentName}</name> <ID>${id}</ID> <subject>${subject}</subject> </Student> </document> ''' def template = engine.createTemplate(text).make(binding) println template.toString() If the above code is executed in groovy, the following output will be shown Joe 1 Physics Meta object programming or MOP can be used to invoke methods dynamically and also create classes and methods on the fly. So what does this mean? Let’s consider a class called Student, which is kind of an empty class with no member variables or methods. Suppose if you had to invoke the following statements on this class. Def myStudent = new Student() myStudent.Name = ”Joe”; myStudent.Display() Now in meta object programming, even though the class does not have the member variable Name or the method Display(), the above code will still work. How can this work? Well, for this to work out, one has to implement the GroovyInterceptable interface to hook into the execution process of Groovy. Following are the methods available for this interface. Public interface GroovyInterceptable { Public object invokeMethod(String methodName, Object args) Public object getproperty(String propertyName) Public object setProperty(String propertyName, Object newValue) Public MetaClass getMetaClass() Public void setMetaClass(MetaClass metaClass) } So in the above interface description, suppose if you had to implement the invokeMethod(), it would be called for every method which either exists or does not exist. So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code. The class Student has no member variable called Name or ID defined. The class Student has no member variable called Name or ID defined. The class Student implements the GroovyInterceptable interface. The class Student implements the GroovyInterceptable interface. There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly. There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly. The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime. The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime. class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = "Joe"; mst.ID = 1; println(mst.Name); println(mst.ID); } } class Student implements GroovyInterceptable { protected dynamicProps=[:] void setProperty(String pName,val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } } The output of the following code would be − Joe 1 So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code − The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not. The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not. class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = "Joe"; mst.ID = 1; println(mst.Name); println(mst.ID); mst.AddMarks(); } } class Student implements GroovyInterceptable { protected dynamicProps = [:] void setProperty(String pName, val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } def invokeMethod(String name, Object args) { return "called invokeMethod $name $args" } } The output of the following codewould be shown below. Note that there is no error of missing Method Exception even though the method Display does not exist. Joe 1 This functionality is related to the MetaClass implementation. In the default implementation you can access fields without invoking their getters and setters. The following example shows how by using the metaClass function we are able to change the value of the private variables in the class. class Example { static void main(String[] args) { Student mst = new Student(); println mst.getName() mst.metaClass.setAttribute(mst, 'name', 'Mark') println mst.getName() } } class Student { private String name = "Joe"; public String getName() { return this.name; } } The output of the following code would be − Joe Mark Groovy supports the concept of methodMissing. This method differs from invokeMethod in that it is only invoked in case of a failed method dispatch, when no method can be found for the given name and/or the given arguments. The following example shows how the methodMissing can be used. class Example { static void main(String[] args) { Student mst = new Student(); mst.Name = "Joe"; mst.ID = 1; println(mst.Name); println(mst.ID); mst.AddMarks(); } } class Student implements GroovyInterceptable { protected dynamicProps = [:] void setProperty(String pName, val) { dynamicProps[pName] = val } def getProperty(String pName) { dynamicProps[pName] } def methodMissing(String name, def args) { println "Missing method" } } The output of the following code would be −
[ { "code": null, "e": 2584, "s": 2372, "text": "Groovy is an object oriented language which is based on Java platform. Groovy 1.0 was released in January 2, 2007 with Groovy 2.4 as the current major release. Groovy is distributed via the Apache License v 2.0." }, { "code": null, "e": 2620, "s": 2584, "text": "Groovy has the following features −" }, { "code": null, "e": 2664, "s": 2620, "text": "Support for both static and dynamic typing." }, { "code": null, "e": 2698, "s": 2664, "text": "Support for operator overloading." }, { "code": null, "e": 2746, "s": 2698, "text": "Native syntax for lists and associative arrays." }, { "code": null, "e": 2786, "s": 2746, "text": "Native support for regular expressions." }, { "code": null, "e": 2852, "s": 2786, "text": "Native support for various markup languages such as XML and HTML." }, { "code": null, "e": 2944, "s": 2852, "text": "Groovy is simple for Java developers since the syntax for Java and Groovy are very similar." }, { "code": null, "e": 2981, "s": 2944, "text": "You can use existing Java libraries." }, { "code": null, "e": 3018, "s": 2981, "text": "Groovy extends the java.lang.Object." }, { "code": null, "e": 3081, "s": 3018, "text": "The official website for Groovy is http://www.groovy-lang.org/" }, { "code": null, "e": 3146, "s": 3081, "text": "There are a variety of ways to get the Groovy environment setup." }, { "code": null, "e": 3337, "s": 3146, "text": "Binary download and installation − Go to the link www.groovy-lang.org/download.html to get the Windows Installer section. Click on this option to start the download of the Groovy installer." }, { "code": null, "e": 3427, "s": 3337, "text": "Once you launch the installer, follow the steps given below to complete the installation." }, { "code": null, "e": 3467, "s": 3427, "text": "Step 1 − Select the language installer." }, { "code": null, "e": 3518, "s": 3467, "text": "Step 2 − Click the Next button in the next screen." }, { "code": null, "e": 3555, "s": 3518, "text": "Step 3 − Click the ‘I Agree’ button." }, { "code": null, "e": 3621, "s": 3555, "text": "Step 4 − Accept the default components and click the Next button." }, { "code": null, "e": 3704, "s": 3621, "text": "Step 5 − Choose the appropriate destination folder and then click the Next button." }, { "code": null, "e": 3765, "s": 3704, "text": "Step 6 − Click the Install button to start the installation." }, { "code": null, "e": 3859, "s": 3765, "text": "Step 7 − Once the installation is complete, click the Next button to start the configuration." }, { "code": null, "e": 3922, "s": 3859, "text": "Step 8 − Choose the default options and click the Next button." }, { "code": null, "e": 3995, "s": 3922, "text": "Step 9 − Accept the default file associations and click the Next button." }, { "code": null, "e": 4059, "s": 3995, "text": "Step 10 − Click the Finish button to complete the installation." }, { "code": null, "e": 4401, "s": 4059, "text": "Once the above steps are followed, you can then start the groovy shell which is part of the Groovy installation that helps in testing our different aspects of the Groovy language without the need of having a full-fledged integrated development environment for Groovy. This can be done by running the command groovysh from the command prompt." }, { "code": null, "e": 4514, "s": 4401, "text": "If you want to include the groovy binaries as part of you maven or gradle build, you can add the following lines" }, { "code": null, "e": 4550, "s": 4514, "text": "'org.codehaus.groovy:groovy:2.4.5'\n" }, { "code": null, "e": 4649, "s": 4550, "text": "<groupId>org.codehaus.groovy</groupId> \n<artifactId>groovy</artifactId> \n<version>2.4.5</version>" }, { "code": null, "e": 4750, "s": 4649, "text": "In order to understand the basic syntax of Groovy, let’s first look at a simple Hello World program." }, { "code": null, "e": 4846, "s": 4750, "text": "Creating your first hello world program is as simple as just entering the following code line −" }, { "code": null, "e": 5009, "s": 4846, "text": "class Example {\n static void main(String[] args) {\n // Using a simple println statement to print output to the console\n println('Hello World');\n }\n}" }, { "code": null, "e": 5075, "s": 5009, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 5088, "s": 5075, "text": "Hello World\n" }, { "code": null, "e": 5242, "s": 5088, "text": "The import statement can be used to import the functionality of other libraries which can be used in your code. This is done by using the import keyword." }, { "code": null, "e": 5404, "s": 5242, "text": "The following example shows how to use a simple import of the MarkupBuilder class which is probably one of the most used classes for creating HTML or XML markup." }, { "code": null, "e": 5468, "s": 5404, "text": "import groovy.xml.MarkupBuilder \ndef xml = new MarkupBuilder() " }, { "code": null, "e": 5579, "s": 5468, "text": "By default, Groovy includes the following libraries in your code, so you don’t need to explicitly import them." }, { "code": null, "e": 5759, "s": 5579, "text": "import java.lang.* \nimport java.util.* \nimport java.io.* \nimport java.net.* \n\nimport groovy.lang.* \nimport groovy.util.* \n\nimport java.math.BigInteger \nimport java.math.BigDecimal" }, { "code": null, "e": 5846, "s": 5759, "text": "A token is either a keyword, an identifier, a constant, a string literal, or a symbol." }, { "code": null, "e": 5870, "s": 5846, "text": "println(“Hello World”);" }, { "code": null, "e": 6002, "s": 5870, "text": "In the above code line, there are two tokens, the first is the keyword println and the next is the string literal of “Hello World”." }, { "code": null, "e": 6095, "s": 6002, "text": "Comments are used to document your code. Comments in Groovy can be single line or multiline." }, { "code": null, "e": 6204, "s": 6095, "text": "Single line comments are identified by using the // at any position in the line. An example is shown below −" }, { "code": null, "e": 6367, "s": 6204, "text": "class Example {\n static void main(String[] args) {\n // Using a simple println statement to print output to the console\n println('Hello World');\n }\n}" }, { "code": null, "e": 6479, "s": 6367, "text": "Multiline comments are identified with /* in the beginning and */ to identify the end of the multiline comment." }, { "code": null, "e": 6667, "s": 6479, "text": "class Example {\n static void main(String[] args) {\n /* This program is the first program\n This program shows how to display hello world */\n println('Hello World');\n }\n}" }, { "code": null, "e": 6797, "s": 6667, "text": "Unlike in the Java programming language, it is not mandatory to have semicolons after the end of every statement, It is optional." }, { "code": null, "e": 6905, "s": 6797, "text": "class Example {\n static void main(String[] args) {\n def x = 5\n println('Hello World'); \n }\n}" }, { "code": null, "e": 7000, "s": 6905, "text": "If you execute the above program, both statements in the main method don't generate any error." }, { "code": null, "e": 7224, "s": 7000, "text": "Identifiers are used to define variables, functions or other user defined variables. Identifiers start with a letter, a dollar or an underscore. They cannot start with a number. Here are some examples of valid identifiers −" }, { "code": null, "e": 7273, "s": 7224, "text": "def employeename \ndef student1 \ndef student_name" }, { "code": null, "e": 7336, "s": 7273, "text": "where def is a keyword used in Groovy to define an identifier." }, { "code": null, "e": 7420, "s": 7336, "text": "Here is a code example of how an identifier can be used in our Hello World program." }, { "code": null, "e": 7594, "s": 7420, "text": "class Example {\n static void main(String[] args) {\n // One can see the use of a semi-colon after each statement\n def x = 5;\n println('Hello World'); \n }\n}" }, { "code": null, "e": 7657, "s": 7594, "text": "In the above example, the variable x is used as an identifier." }, { "code": null, "e": 7827, "s": 7657, "text": "Keywords as the name suggest are special words which are reserved in the Groovy Programming language. The following table lists the keywords which are defined in Groovy." }, { "code": null, "e": 8093, "s": 7827, "text": "Whitespace is the term used in a programming language such as Java and Groovy to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement." }, { "code": null, "e": 8351, "s": 8093, "text": "For example, in the following code example, there is a white space between the keyword def and the variable x. This is so that the compiler knows that def is the keyword which needs to be used and that x should be the variable name that needs to be defined." }, { "code": null, "e": 8362, "s": 8351, "text": "def x = 5;" }, { "code": null, "e": 8603, "s": 8362, "text": "A literal is a notation for representing a fixed value in groovy. The groovy language has notations for integers, floating-point numbers, characters and strings. Here are some of the examples of literals in the Groovy programming language −" }, { "code": null, "e": 8624, "s": 8603, "text": "12 \n1.45 \n‘a’ \n“aa”\n" }, { "code": null, "e": 8920, "s": 8624, "text": "In any programming language, you need to use various variables to store various types of information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory to store the value associated with the variable." }, { "code": null, "e": 9186, "s": 8920, "text": "You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory." }, { "code": null, "e": 9303, "s": 9186, "text": "Groovy offers a wide variety of built-in data types. Following is a list of data types which are defined in Groovy −" }, { "code": null, "e": 9367, "s": 9303, "text": "byte − This is used to represent a byte value. An example is 2." }, { "code": null, "e": 9431, "s": 9367, "text": "byte − This is used to represent a byte value. An example is 2." }, { "code": null, "e": 9499, "s": 9431, "text": "short − This is used to represent a short number. An example is 10." }, { "code": null, "e": 9567, "s": 9499, "text": "short − This is used to represent a short number. An example is 10." }, { "code": null, "e": 9634, "s": 9567, "text": "int − This is used to represent whole numbers. An example is 1234." }, { "code": null, "e": 9701, "s": 9634, "text": "int − This is used to represent whole numbers. An example is 1234." }, { "code": null, "e": 9773, "s": 9701, "text": "long − This is used to represent a long number. An example is 10000090." }, { "code": null, "e": 9845, "s": 9773, "text": "long − This is used to represent a long number. An example is 10000090." }, { "code": null, "e": 9931, "s": 9845, "text": "float − This is used to represent 32-bit floating point numbers. An example is 12.34." }, { "code": null, "e": 10017, "s": 9931, "text": "float − This is used to represent 32-bit floating point numbers. An example is 12.34." }, { "code": null, "e": 10189, "s": 10017, "text": "double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565." }, { "code": null, "e": 10361, "s": 10189, "text": "double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565." }, { "code": null, "e": 10428, "s": 10361, "text": "char − This defines a single character literal. An example is ‘a’." }, { "code": null, "e": 10495, "s": 10428, "text": "char − This defines a single character literal. An example is ‘a’." }, { "code": null, "e": 10572, "s": 10495, "text": "Boolean − This represents a Boolean value which can either be true or false." }, { "code": null, "e": 10649, "s": 10572, "text": "Boolean − This represents a Boolean value which can either be true or false." }, { "code": null, "e": 10767, "s": 10649, "text": "String − These are text literals which are represented in the form of chain of characters. For example “Hello World”." }, { "code": null, "e": 10885, "s": 10767, "text": "String − These are text literals which are represented in the form of chain of characters. For example “Hello World”." }, { "code": null, "e": 10978, "s": 10885, "text": "The following table shows the maximum allowed values for the numerical and decimal literals." }, { "code": null, "e": 11102, "s": 10978, "text": "Types In addition to the primitive types, the following object types (sometimes referred to as wrapper types) are allowed −" }, { "code": null, "e": 11117, "s": 11102, "text": "java.lang.Byte" }, { "code": null, "e": 11133, "s": 11117, "text": "java.lang.Short" }, { "code": null, "e": 11151, "s": 11133, "text": "java.lang.Integer" }, { "code": null, "e": 11166, "s": 11151, "text": "java.lang.Long" }, { "code": null, "e": 11182, "s": 11166, "text": "java.lang.Float" }, { "code": null, "e": 11199, "s": 11182, "text": "java.lang.Double" }, { "code": null, "e": 11294, "s": 11199, "text": "In addition, the following classes can be used for supporting arbitrary precision arithmetic −" }, { "code": null, "e": 11383, "s": 11294, "text": "The following code example showcases how the different built-in data types can be used −" }, { "code": null, "e": 11968, "s": 11383, "text": "class Example { \n static void main(String[] args) { \n //Example of a int datatype \n int x = 5; \n\t\t\n //Example of a long datatype \n long y = 100L; \n\t\t\n //Example of a floating point datatype \n float a = 10.56f; \n\t\t\n //Example of a double datatype \n double b = 10.5e40; \n\t\t\n //Example of a BigInteger datatype \n BigInteger bi = 30g; \n\t\t\n //Example of a BigDecimal datatype \n BigDecimal bd = 3.5g; \n\t\t\n println(x); \n println(y); \n println(a); \n println(b); \n println(bi); \n println(bd); \n } \n}" }, { "code": null, "e": 12034, "s": 11968, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 12067, "s": 12034, "text": "5 \n100 \n10.56 \n1.05E41 \n30 \n3.5\n" }, { "code": null, "e": 12352, "s": 12067, "text": "Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use \"def\" in replacement. This is required by the Groovy parser." }, { "code": null, "e": 12445, "s": 12352, "text": "There are following basic types of variable in Groovy as explained in the previous chapter −" }, { "code": null, "e": 12509, "s": 12445, "text": "byte − This is used to represent a byte value. An example is 2." }, { "code": null, "e": 12573, "s": 12509, "text": "byte − This is used to represent a byte value. An example is 2." }, { "code": null, "e": 12641, "s": 12573, "text": "short − This is used to represent a short number. An example is 10." }, { "code": null, "e": 12709, "s": 12641, "text": "short − This is used to represent a short number. An example is 10." }, { "code": null, "e": 12776, "s": 12709, "text": "int − This is used to represent whole numbers. An example is 1234." }, { "code": null, "e": 12843, "s": 12776, "text": "int − This is used to represent whole numbers. An example is 1234." }, { "code": null, "e": 12915, "s": 12843, "text": "long − This is used to represent a long number. An example is 10000090." }, { "code": null, "e": 12987, "s": 12915, "text": "long − This is used to represent a long number. An example is 10000090." }, { "code": null, "e": 13073, "s": 12987, "text": "float − This is used to represent 32-bit floating point numbers. An example is 12.34." }, { "code": null, "e": 13159, "s": 13073, "text": "float − This is used to represent 32-bit floating point numbers. An example is 12.34." }, { "code": null, "e": 13330, "s": 13159, "text": "double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565." }, { "code": null, "e": 13501, "s": 13330, "text": "double − This is used to represent 64-bit floating point numbers which are longer decimal number representations which may be required at times. An example is 12.3456565." }, { "code": null, "e": 13568, "s": 13501, "text": "char − This defines a single character literal. An example is ‘a’." }, { "code": null, "e": 13635, "s": 13568, "text": "char − This defines a single character literal. An example is ‘a’." }, { "code": null, "e": 13712, "s": 13635, "text": "Boolean − This represents a Boolean value which can either be true or false." }, { "code": null, "e": 13789, "s": 13712, "text": "Boolean − This represents a Boolean value which can either be true or false." }, { "code": null, "e": 13908, "s": 13789, "text": "String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. " }, { "code": null, "e": 14027, "s": 13908, "text": "String − These are text literals which are represented in the form of chain of characters. For example “Hello World”. " }, { "code": null, "e": 14165, "s": 14027, "text": "Groovy also allows for additional types of variables such as arrays, structures and classes which we will see in the subsequent chapters." }, { "code": null, "e": 14266, "s": 14165, "text": "A variable declaration tells the compiler where and how much to create the storage for the variable." }, { "code": null, "e": 14316, "s": 14266, "text": "Following is an example of variable declaration −" }, { "code": null, "e": 14524, "s": 14316, "text": "class Example { \n static void main(String[] args) { \n // x is defined as a variable \n String x = \"Hello\";\n\t\t\n // The value of the variable is printed to the console \n println(x);\n }\n}" }, { "code": null, "e": 14590, "s": 14524, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 14597, "s": 14590, "text": "Hello\n" }, { "code": null, "e": 14853, "s": 14597, "text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Groovy, just like Java is a case-sensitive programming language." }, { "code": null, "e": 15200, "s": 14853, "text": "class Example { \n static void main(String[] args) { \n // Defining a variable in lowercase \n int x = 5;\n\t \n // Defining a variable in uppercase \n int X = 6; \n\t \n // Defining a variable with the underscore in it's name \n def _Name = \"Joe\"; \n\t\t\n println(x); \n println(X); \n println(_Name); \n } \n}" }, { "code": null, "e": 15266, "s": 15200, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 15278, "s": 15266, "text": "5 \n6 \nJoe \n" }, { "code": null, "e": 15430, "s": 15278, "text": "We can see that x and X are two different variables because of case sensitivity and in the third case, we can see that _Name begins with an underscore." }, { "code": null, "e": 15557, "s": 15430, "text": "You can print the current value of a variable with the println function. The following example shows how this can be achieved." }, { "code": null, "e": 15823, "s": 15557, "text": "class Example { \n static void main(String[] args) { \n //Initializing 2 variables \n int x = 5; \n int X = 6; \n\t \n //Printing the value of the variables to the console \n println(\"The value of x is \" + x + \"The value of X is \" + X); \n }\n}" }, { "code": null, "e": 15889, "s": 15823, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 15931, "s": 15889, "text": "The value of x is 5 The value of X is 6 \n" }, { "code": null, "e": 16038, "s": 15931, "text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations." }, { "code": null, "e": 16084, "s": 16038, "text": "Groovy has the following types of operators −" }, { "code": null, "e": 16105, "s": 16084, "text": "Arithmetic operators" }, { "code": null, "e": 16126, "s": 16105, "text": "Relational operators" }, { "code": null, "e": 16144, "s": 16126, "text": "Logical operators" }, { "code": null, "e": 16162, "s": 16144, "text": "Bitwise operators" }, { "code": null, "e": 16183, "s": 16162, "text": "Assignment operators" }, { "code": null, "e": 16326, "s": 16183, "text": "The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy −" }, { "code": null, "e": 16339, "s": 16326, "text": "Show Example" }, { "code": null, "e": 16350, "s": 16339, "text": "int x = 5;" }, { "code": null, "e": 16355, "s": 16350, "text": "x++;" }, { "code": null, "e": 16369, "s": 16355, "text": "x will give 6" }, { "code": null, "e": 16380, "s": 16369, "text": "int x = 5;" }, { "code": null, "e": 16385, "s": 16380, "text": "x--;" }, { "code": null, "e": 16399, "s": 16385, "text": "x will give 4" }, { "code": null, "e": 16517, "s": 16399, "text": "Relational operators allow of the comparison of objects. Following are the relational operators available in Groovy −" }, { "code": null, "e": 16530, "s": 16517, "text": "Show Example" }, { "code": null, "e": 16648, "s": 16530, "text": "Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy −" }, { "code": null, "e": 16661, "s": 16648, "text": "Show Example" }, { "code": null, "e": 16759, "s": 16661, "text": "Groovy provides four bitwise operators. Following are the bitwise operators available in Groovy −" }, { "code": null, "e": 16772, "s": 16759, "text": "Show Example" }, { "code": null, "e": 16774, "s": 16772, "text": "&" }, { "code": null, "e": 16809, "s": 16774, "text": "This is the bitwise “and” operator" }, { "code": null, "e": 16811, "s": 16809, "text": "|" }, { "code": null, "e": 16845, "s": 16811, "text": "This is the bitwise “or” operator" }, { "code": null, "e": 16847, "s": 16845, "text": "^" }, { "code": null, "e": 16898, "s": 16847, "text": "This is the bitwise “xor” or Exclusive or operator" }, { "code": null, "e": 16900, "s": 16898, "text": "~" }, { "code": null, "e": 16938, "s": 16900, "text": "This is the bitwise negation operator" }, { "code": null, "e": 16990, "s": 16938, "text": "Here is the truth table showcasing these operators." }, { "code": null, "e": 17107, "s": 16990, "text": "The Groovy language also provides assignment operators. Following are the assignment operators available in Groovy −" }, { "code": null, "e": 17120, "s": 17107, "text": "Show Example" }, { "code": null, "e": 17130, "s": 17120, "text": "def A = 5" }, { "code": null, "e": 17135, "s": 17130, "text": "A+=3" }, { "code": null, "e": 17152, "s": 17135, "text": "Output will be 8" }, { "code": null, "e": 17162, "s": 17152, "text": "def A = 5" }, { "code": null, "e": 17167, "s": 17162, "text": "A-=3" }, { "code": null, "e": 17184, "s": 17167, "text": "Output will be 2" }, { "code": null, "e": 17194, "s": 17184, "text": "def A = 5" }, { "code": null, "e": 17199, "s": 17194, "text": "A*=3" }, { "code": null, "e": 17217, "s": 17199, "text": "Output will be 15" }, { "code": null, "e": 17227, "s": 17217, "text": "def A = 6" }, { "code": null, "e": 17232, "s": 17227, "text": "A/=3" }, { "code": null, "e": 17249, "s": 17232, "text": "Output will be 2" }, { "code": null, "e": 17259, "s": 17249, "text": "def A = 5" }, { "code": null, "e": 17264, "s": 17259, "text": "A%=3" }, { "code": null, "e": 17281, "s": 17264, "text": "Output will be 2" }, { "code": null, "e": 17451, "s": 17281, "text": "Groovy supports the concept of ranges and provides a notation of range operators with the help of the .. notation. A simple example of the range operator is given below." }, { "code": null, "e": 17470, "s": 17451, "text": "def range = 0..5 \n" }, { "code": null, "e": 17607, "s": 17470, "text": "This just defines a simple range of integers, stored into a local variable called range with a lower bound of 0 and an upper bound of 5." }, { "code": null, "e": 17679, "s": 17607, "text": "The following code snippet shows how the various operators can be used." }, { "code": null, "e": 17821, "s": 17679, "text": "class Example { \n static void main(String[] args) { \n def range = 5..10; \n println(range); \n println(range.get(2)); \n } \n}" }, { "code": null, "e": 17887, "s": 17821, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 18016, "s": 17887, "text": "From the println statement, you can see that the entire range of numbers which are defined in the range statement are displayed." }, { "code": null, "e": 18130, "s": 18016, "text": "The get statement is used to get an object from the range defined which takes in an index value as the parameter." }, { "code": null, "e": 18154, "s": 18130, "text": "[5, 6, 7, 8, 9, 10] \n7\n" }, { "code": null, "e": 18225, "s": 18154, "text": "The following table lists all groovy operators in order of precedence." }, { "code": null, "e": 18241, "s": 18225, "text": "++ -- + -" }, { "code": null, "e": 18290, "s": 18241, "text": "pre increment/decrement, unary plus, unary minus" }, { "code": null, "e": 18300, "s": 18290, "text": "* / %" }, { "code": null, "e": 18322, "s": 18300, "text": "multiply, div, modulo" }, { "code": null, "e": 18328, "s": 18322, "text": "+ -" }, { "code": null, "e": 18350, "s": 18328, "text": "addition, subtraction" }, { "code": null, "e": 18364, "s": 18350, "text": "== != <=>" }, { "code": null, "e": 18395, "s": 18364, "text": "equals, not equals, compare to" }, { "code": null, "e": 18397, "s": 18395, "text": "&" }, { "code": null, "e": 18416, "s": 18397, "text": "binary/bitwise and" }, { "code": null, "e": 18418, "s": 18416, "text": "^" }, { "code": null, "e": 18437, "s": 18418, "text": "binary/bitwise xor" }, { "code": null, "e": 18439, "s": 18437, "text": "|" }, { "code": null, "e": 18457, "s": 18439, "text": "binary/bitwise or" }, { "code": null, "e": 18460, "s": 18457, "text": "&&" }, { "code": null, "e": 18472, "s": 18460, "text": "logical and" }, { "code": null, "e": 18475, "s": 18472, "text": "||" }, { "code": null, "e": 18486, "s": 18475, "text": "logical or" }, { "code": null, "e": 18553, "s": 18486, "text": "= **= *= /= %= += -= <<= >>= >>>= &= ^= |=" }, { "code": null, "e": 18582, "s": 18553, "text": "Various assignment operators" }, { "code": null, "e": 18868, "s": 18582, "text": "So far, we have seen statements which have been executed one after the other in a sequential manner. Additionally, statements are provided in Groovy to alter the flow of control in a program’s logic. They are then classified into flow of control statements which we will see in detail." }, { "code": null, "e": 19043, "s": 18868, "text": "The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed." }, { "code": null, "e": 19105, "s": 19043, "text": "The for statement is used to iterate through a set of values." }, { "code": null, "e": 19170, "s": 19105, "text": "The for-in statement is used to iterate through a set of values." }, { "code": null, "e": 19263, "s": 19170, "text": "The break statement is used to alter the flow of control inside loops and switch statements." }, { "code": null, "e": 19365, "s": 19263, "text": "The continue statement complements the break statement. Its use is restricted to while and for loops." }, { "code": null, "e": 19680, "s": 19365, "text": "Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false." }, { "code": null, "e": 19837, "s": 19680, "text": "The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true, it then executes the statements." }, { "code": null, "e": 20177, "s": 19837, "text": "The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true it then executes the statements thereafter and stops before the else condition and exits out of the loop. If the condition is false it then executes the statements in the else statement block and then exits the loop." }, { "code": null, "e": 20271, "s": 20177, "text": "Sometimes there is a requirement to have multiple if statement embedded inside of each other." }, { "code": null, "e": 20411, "s": 20271, "text": "Sometimes the nested if-else statement is so common and is used so often that an easier statement was designed called the switch statement." }, { "code": null, "e": 20474, "s": 20411, "text": "It is also possible to have a nested set of switch statements." }, { "code": null, "e": 20817, "s": 20474, "text": "A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It’s not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added. By default, if no visibility modifier is provided, the method is public." }, { "code": null, "e": 20898, "s": 20817, "text": "The simplest type of a method is one with no parameters as the one shown below −" }, { "code": null, "e": 20938, "s": 20898, "text": "def methodName() { \n //Method code \n}" }, { "code": null, "e": 20979, "s": 20938, "text": "Following is an example of simple method" }, { "code": null, "e": 21208, "s": 20979, "text": "class Example {\n static def DisplayName() {\n println(\"This is how methods work in groovy\");\n println(\"This is an example of a simple method\");\n } \n\t\n static void main(String[] args) {\n DisplayName();\n } \n}" }, { "code": null, "e": 21466, "s": 21208, "text": "In the above example, DisplayName is a simple method which consists of two println statements which are used to output some text to the console. In our static main method, we are just calling the DisplayName method. The output of the above method would be −" }, { "code": null, "e": 21541, "s": 21466, "text": "This is how methods work in groovy \nThis is an example of a simple method\n" }, { "code": null, "e": 21773, "s": 21541, "text": "A method is more generally useful if its behavior is determined by the value of one or more parameters. We can transfer values to the called method using method parameters. Note that the parameter names must differ from each other." }, { "code": null, "e": 21844, "s": 21773, "text": "The simplest type of a method with parameters as the one shown below −" }, { "code": null, "e": 21929, "s": 21844, "text": "def methodName(parameter1, parameter2, parameter3) { \n // Method code goes here \n}" }, { "code": null, "e": 21986, "s": 21929, "text": "Following is an example of simple method with parameters" }, { "code": null, "e": 22144, "s": 21986, "text": "class Example {\n static void sum(int a,int b) {\n int c = a+b;\n println(c);\n } \n\t\n static void main(String[] args) {\n sum(10,5);\n } \n}" }, { "code": null, "e": 22356, "s": 22144, "text": "In this example, we are creating a sum method with 2 parameters, a and b. Both parameters are of type int. We are then calling the sum method from our main method and passing the values to the variables a and b." }, { "code": null, "e": 22410, "s": 22356, "text": "The output of the above method would be the value 15." }, { "code": null, "e": 22744, "s": 22410, "text": "There is also a provision in Groovy to specify default values for parameters within methods. If no values are passed to the method for the parameters, the default ones are used. If both nondefault and default parameters are used, then it has to be noted that the default parameters should be defined at the end of the parameter list." }, { "code": null, "e": 22803, "s": 22744, "text": "Following is an example of simple method with parameters −" }, { "code": null, "e": 22897, "s": 22803, "text": "def someMethod(parameter1, parameter2 = 0, parameter3 = 0) { \n // Method code goes here \n} " }, { "code": null, "e": 23058, "s": 22897, "text": "Let’s look at the same example we looked at before for the addition of two numbers and create a method which has one default and another non-default parameter −" }, { "code": null, "e": 23221, "s": 23058, "text": "class Example { \n static void sum(int a,int b = 5) { \n int c = a+b; \n println(c); \n } \n\t\n static void main(String[] args) {\n sum(6); \n } \n}" }, { "code": null, "e": 23635, "s": 23221, "text": "In this example, we are creating a sum method with two parameters, a and b. Both parameters are of type int. The difference between this example and the previous example is that in this case we are specifying a default value for b as 5. So when we call the sum method from our main method, we have the option of just passing one value which is 6 and this will be assigned to the parameter a within the sum method." }, { "code": null, "e": 23689, "s": 23635, "text": "The output of the above method would be the value 11." }, { "code": null, "e": 23849, "s": 23689, "text": "class Example {\n static void sum(int a,int b = 5) {\n int c = a+b;\n println(c);\n } \n\t\n static void main(String[] args) {\n sum(6,6);\n } \n}" }, { "code": null, "e": 24053, "s": 23849, "text": "We can also call the sum method by passing 2 values, in our example above we are passing 2 values of 6. The second value of 6 will actually replace the default value which is assigned to the parameter b." }, { "code": null, "e": 24107, "s": 24053, "text": "The output of the above method would be the value 12." }, { "code": null, "e": 24324, "s": 24107, "text": "Methods can also return values back to the calling program. This is required in modern-day programming language wherein a method does some sort of computation and then returns the desired value to the calling method." }, { "code": null, "e": 24386, "s": 24324, "text": "Following is an example of simple method with a return value." }, { "code": null, "e": 24550, "s": 24386, "text": "class Example {\n static int sum(int a,int b = 5) {\n int c = a+b;\n return c;\n } \n\t\n static void main(String[] args) {\n println(sum(6));\n } \n}" }, { "code": null, "e": 24906, "s": 24550, "text": "In our above example, note that this time we are specifying a return type for our method sum which is of the type int. In the method we are using the return statement to send the sum value to the calling main program. Since the value of the method is now available to the main method, we are using the println function to display the value in the console." }, { "code": null, "e": 24960, "s": 24906, "text": "The output of the above method would be the value 11." }, { "code": null, "e": 25322, "s": 24960, "text": "Methods are normally implemented inside classes within Groovy just like the Java language. A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. The class objects exhibit the properties and behaviors defined by its class. So the behaviors are defined by creating methods inside of the class." }, { "code": null, "e": 25789, "s": 25322, "text": "We will see classes in more detail in a later chapter but Following is an example of a method implementation in a class. In our previous examples we defined our method as static methods which meant that we could access those methods directly from the class. The next example of methods is instance methods wherein the methods are accessed by creating objects of the class. Again we will see classes in a later chapter, for now we will demonstrate how to use methods." }, { "code": null, "e": 25848, "s": 25789, "text": "Following is an example of how methods can be implemented." }, { "code": null, "e": 26110, "s": 25848, "text": "class Example { \n int x; \n\t\n public int getX() { \n return x; \n } \n\t\n public void setX(int pX) { \n x = pX; \n } \n\t\n static void main(String[] args) { \n Example ex = new Example(); \n ex.setX(100); \n println(ex.getX()); \n } \n}" }, { "code": null, "e": 26341, "s": 26110, "text": "In our above example, note that this time we are specifying no static attribute for our class methods. In our main function we are actually creating an instance of the Example class and then invoking the method of the ‘ex’ object." }, { "code": null, "e": 26396, "s": 26341, "text": "The output of the above method would be the value 100." }, { "code": null, "e": 26752, "s": 26396, "text": "Groovy provides the facility just like java to have local and global parameters. In the following example, lx is a local parameter which has a scope only within the function of getX() and x is a global property which can be accessed inside the entire Example class. If we try to access the variable lx outside of the getX() function, we will get an error." }, { "code": null, "e": 26963, "s": 26752, "text": "class Example { \n static int x = 100; \n\t\n public static int getX() { \n int lx = 200; \n println(lx); \n return x; \n } \n\t\n static void main(String[] args) { \n println(getX()); \n } \n}" }, { "code": null, "e": 27028, "s": 26963, "text": "When we run the above program, we will get the following result." }, { "code": null, "e": 27038, "s": 27028, "text": "200 \n100\n" }, { "code": null, "e": 27249, "s": 27038, "text": "Just like in Java, groovy can access its instance members using the this keyword. The following example shows how when we use the statement this.x, it refers to its instance and sets the value of x accordingly." }, { "code": null, "e": 27460, "s": 27249, "text": "class Example { \n int x = 100; \n\t\n public int getX() { \n this.x = 200; \n return x; \n } \n\t\n static void main(String[] args) {\n Example ex = new Example(); \n println(ex.getX());\n }\n}" }, { "code": null, "e": 27545, "s": 27460, "text": "When we run the above program, we will get the result of 200 printed on the console." }, { "code": null, "e": 27694, "s": 27545, "text": "Groovy provides a number of helper methods when working with I/O. Groovy provides easier classes to provide the following functionalities for files." }, { "code": null, "e": 27708, "s": 27694, "text": "Reading files" }, { "code": null, "e": 27725, "s": 27708, "text": "Writing to files" }, { "code": null, "e": 27747, "s": 27725, "text": "Traversing file trees" }, { "code": null, "e": 27789, "s": 27747, "text": "Reading and writing data objects to files" }, { "code": null, "e": 27891, "s": 27789, "text": "In addition to this, you can always use the normal Java classes listed below for File I/O operations." }, { "code": null, "e": 27904, "s": 27891, "text": "java.io.File" }, { "code": null, "e": 27924, "s": 27904, "text": "java.io.InputStream" }, { "code": null, "e": 27945, "s": 27924, "text": "java.io.OutputStream" }, { "code": null, "e": 27960, "s": 27945, "text": "java.io.Reader" }, { "code": null, "e": 27975, "s": 27960, "text": "java.io.Writer" }, { "code": null, "e": 28178, "s": 27975, "text": "The following example will output all the lines of a text file in Groovy. The method eachLine is in-built in the File class in Groovy for the purpose of ensuring that each line of the text file is read." }, { "code": null, "e": 28359, "s": 28178, "text": "import java.io.File \nclass Example { \n static void main(String[] args) { \n new File(\"E:/Example.txt\").eachLine { \n line -> println \"line : $line\"; \n } \n } \n}" }, { "code": null, "e": 28555, "s": 28359, "text": "The File class is used to instantiate a new object which takes the file name as the parameter. It then takes the function of eachLine, puts it to a variable called line and prints it accordingly." }, { "code": null, "e": 28619, "s": 28555, "text": "If the file contains the following lines, they will be printed." }, { "code": null, "e": 28652, "s": 28619, "text": "line : Example1\nline : Example2\n" }, { "code": null, "e": 28815, "s": 28652, "text": "If you want to get the entire contents of the file as a string, you can use the text property of the file class. The following example shows how this can be done." }, { "code": null, "e": 28949, "s": 28815, "text": "class Example { \n static void main(String[] args) { \n File file = new File(\"E:/Example.txt\") \n println file.text \n } \n}" }, { "code": null, "e": 29013, "s": 28949, "text": "If the file contains the following lines, they will be printed." }, { "code": null, "e": 29047, "s": 29013, "text": "line : Example1 \nline : Example2\n" }, { "code": null, "e": 29187, "s": 29047, "text": "If you want to write to files, you need to use the writer class to output text to a file. The following example shows how this can be done." }, { "code": null, "e": 29391, "s": 29187, "text": "import java.io.File \nclass Example { \n static void main(String[] args) { \n new File('E:/','Example.txt').withWriter('utf-8') { \n writer -> writer.writeLine 'Hello World' \n } \n } \n}" }, { "code": null, "e": 29483, "s": 29391, "text": "If you open the file Example.txt, you will see the words “Hello World” printed to the file." }, { "code": null, "e": 29652, "s": 29483, "text": "If you want to get the size of the file one can use the length property of the file class to get the size of the file. The following example shows how this can be done." }, { "code": null, "e": 29831, "s": 29652, "text": "class Example {\n static void main(String[] args) {\n File file = new File(\"E:/Example.txt\")\n println \"The file ${file.absolutePath} has ${file.length()} bytes\"\n } \n}" }, { "code": null, "e": 29888, "s": 29831, "text": "The above code would show the size of the file in bytes." }, { "code": null, "e": 30058, "s": 29888, "text": "If you want to see if a path is a file or a directory, one can use the isFile and isDirectory option of the File class. The following example shows how this can be done." }, { "code": null, "e": 30245, "s": 30058, "text": "class Example { \n static void main(String[] args) { \n def file = new File('E:/') \n println \"File? ${file.isFile()}\" \n println \"Directory? ${file.isDirectory()}\" \n } \n}" }, { "code": null, "e": 30294, "s": 30245, "text": "The above code would show the following output −" }, { "code": null, "e": 30324, "s": 30294, "text": "File? false \nDirectory? True\n" }, { "code": null, "e": 30462, "s": 30324, "text": "If you want to create a new directory you can use the mkdir function of the File class. The following example shows how this can be done." }, { "code": null, "e": 30584, "s": 30462, "text": "class Example {\n static void main(String[] args) {\n def file = new File('E:/Directory')\n file.mkdir()\n } \n}" }, { "code": null, "e": 30649, "s": 30584, "text": "The directory E:\\Directory will be created if it does not exist." }, { "code": null, "e": 30779, "s": 30649, "text": "If you want to delete a file you can use the delete function of the File class. The following example shows how this can be done." }, { "code": null, "e": 30904, "s": 30779, "text": "class Example {\n static void main(String[] args) {\n def file = new File('E:/Example.txt')\n file.delete()\n } \n}" }, { "code": null, "e": 30943, "s": 30904, "text": "The file will be deleted if it exists." }, { "code": null, "e": 31079, "s": 30943, "text": "Groovy also provides the functionality to copy the contents from one file to another. The following example shows how this can be done." }, { "code": null, "e": 31249, "s": 31079, "text": "class Example {\n static void main(String[] args) {\n def src = new File(\"E:/Example.txt\")\n def dst = new File(\"E:/Example1.txt\")\n dst << src.text\n } \n}" }, { "code": null, "e": 31364, "s": 31249, "text": "The file Example1.txt will be created and all of the contents of the file Example.txt will be copied to this file." }, { "code": null, "e": 31444, "s": 31364, "text": "Groovy also provides the functionality to list the drives and files in a drive." }, { "code": null, "e": 31568, "s": 31444, "text": "The following example shows how the drives on a machine can be displayed by using the listRoots function of the File class." }, { "code": null, "e": 31758, "s": 31568, "text": "class Example { \n static void main(String[] args) { \n def rootFiles = new File(\"test\").listRoots() \n rootFiles.each { \n file -> println file.absolutePath \n }\n }\n}" }, { "code": null, "e": 31905, "s": 31758, "text": "Depending on the drives available on your machine, the output could vary. On a standard machine the output would be similar to the following one −" }, { "code": null, "e": 31915, "s": 31905, "text": "C:\\ \nD:\\\n" }, { "code": null, "e": 32041, "s": 31915, "text": "The following example shows how to list the files in a particular directory by using the eachFile function of the File class." }, { "code": null, "e": 32197, "s": 32041, "text": "class Example {\n static void main(String[] args) {\n new File(\"E:/Temp\").eachFile() { \n file->println file.getAbsolutePath()\n }\n } \n}" }, { "code": null, "e": 32264, "s": 32197, "text": "The output would display all of the files in the directory E:\\Temp" }, { "code": null, "e": 32468, "s": 32264, "text": "If you want to recursively display all of files in a directory and its subdirectories, then you would use the eachFileRecurse function of the File class. The following example shows how this can be done." }, { "code": null, "e": 32632, "s": 32468, "text": "class Example { \n static void main(String[] args) {\n new File(\"E:/temp\").eachFileRecurse() {\n file -> println file.getAbsolutePath()\n }\n }\n} " }, { "code": null, "e": 32740, "s": 32632, "text": "The output would display all of the files in the directory E:\\Temp and in its subdirectories if they exist." }, { "code": null, "e": 33129, "s": 32740, "text": "Groovy is an “optionally” typed language, and that distinction is an important one when understanding the fundamentals of the language. When compared to Java, which is a “strongly” typed language, whereby the compiler knows all of the types for every variable and can understand and honor contracts at compile time. This means that method calls are able to be determined at compile time." }, { "code": null, "e": 33358, "s": 33129, "text": "When writing code in Groovy, developers are given the flexibility to provide a type or not. This can offer some simplicity in implementation and, when leveraged properly, can service your application in a robust and dynamic way." }, { "code": null, "e": 33473, "s": 33358, "text": "In Groovy, optional typing is done via the ‘def’ keyword. Following is an example of the usage of the def method −" }, { "code": null, "e": 33881, "s": 33473, "text": "class Example { \n static void main(String[] args) { \n // Example of an Integer using def \n def a = 100; \n println(a); \n\t\t\n // Example of an float using def \n def b = 100.10; \n println(b); \n\t\t\n // Example of an Double using def \n def c = 100.101; \n println(c);\n\t\t\n // Example of an String using def \n def d = \"HelloWorld\"; \n println(d); \n } \n} " }, { "code": null, "e": 34052, "s": 33881, "text": "From the above program, we can see that we have not declared the individual variables as Integer, float, double, or string even though they contain these types of values." }, { "code": null, "e": 34118, "s": 34052, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 34151, "s": 34118, "text": "100 \n100.10 \n100.101\nHelloWorld\n" }, { "code": null, "e": 34340, "s": 34151, "text": "Optional typing can be a powerful utility during development, but can lead to problems in maintainability during the later stages of development when the code becomes too vast and complex." }, { "code": null, "e": 34540, "s": 34340, "text": "To get a handle on how you can utilize optional typing in Groovy without getting your codebase into an unmaintainable mess, it is best to embrace the philosophy of “duck typing” in your applications." }, { "code": null, "e": 34765, "s": 34540, "text": "If we re-write the above code using duck typing, it would look like the one given below. The variable names are given names which resemble more often than not the type they represent which makes the code more understandable." }, { "code": null, "e": 35212, "s": 34765, "text": "class Example { \n static void main(String[] args) { \n // Example of an Integer using def \n def aint = 100; \n println(aint); \n\t\t\n // Example of an float using def \n def bfloat = 100.10; \n println(bfloat); \n\t\t\n // Example of an Double using def \n def cDouble = 100.101; \n println(cDouble);\n\t\t\n // Example of an String using def \n def dString = \"HelloWorld\"; \n println(dString); \n } \n}" }, { "code": null, "e": 35413, "s": 35212, "text": "In Groovy, Numbers are actually represented as object’s, all of them being an instance of the class Integer. To make an object do something, we need to invoke one of the methods declared in its class." }, { "code": null, "e": 35465, "s": 35413, "text": "Groovy supports integer and floating point numbers." }, { "code": null, "e": 35521, "s": 35465, "text": "An integer is a value that does not include a fraction." }, { "code": null, "e": 35598, "s": 35521, "text": "A floating-point number is a decimal value that includes a decimal fraction." }, { "code": null, "e": 35647, "s": 35598, "text": "An Example of numbers in Groovy is shown below −" }, { "code": null, "e": 35681, "s": 35647, "text": "Integer x = 5; \nFloat y = 1.25; \n" }, { "code": null, "e": 35732, "s": 35681, "text": "Where x is of the type Integer and y is the float." }, { "code": null, "e": 35949, "s": 35732, "text": "The reason why numbers in groovy are defined as objects is generally because there are requirements to perform operations on numbers. The concept of providing a class over primitive types is known as wrapper classes." }, { "code": null, "e": 36014, "s": 35949, "text": "By default the following wrapper classes are provided in Groovy." }, { "code": null, "e": 36317, "s": 36014, "text": "The object of the wrapper class contains or wraps its respective primitive data type. The process of converting a primitive data types into object is called boxing, and this is taken care by the compiler. The process of converting the object back to its corresponding primitive type is called unboxing." }, { "code": null, "e": 36366, "s": 36317, "text": "Following is an example of boxing and unboxing −" }, { "code": null, "e": 36641, "s": 36366, "text": "class Example { \n static void main(String[] args) {\n Integer x = 5,y = 10,z = 0; \n\t\t\n // The the values of 5,10 and 0 are boxed into Integer types \n // The values of x and y are unboxed and the addition is performed \n z = x+y; \n println(z);\n }\n}" }, { "code": null, "e": 36906, "s": 36641, "text": "The output of the above program would be 15. In the above example, the values of 5, 10, and 0 are first boxed into the Integer variables x, y and z accordingly. And then the when the addition of x and y is performed the values are unboxed from their Integer types." }, { "code": null, "e": 37007, "s": 36906, "text": "Since the Numbers in Groovy are represented as classes, following are the list of methods available." }, { "code": null, "e": 37123, "s": 37007, "text": "This method takes on the Number as the parameter and returns a primitive type based on the method which is invoked." }, { "code": null, "e": 37250, "s": 37123, "text": "The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers." }, { "code": null, "e": 37373, "s": 37250, "text": "The method determines whether the Number object that invokes the method is equal to the object that is passed as argument." }, { "code": null, "e": 37469, "s": 37373, "text": "The valueOf method returns the relevant Number Object holding the value of the argument passed." }, { "code": null, "e": 37556, "s": 37469, "text": "The method is used to get a String object representing the value of the Number Object." }, { "code": null, "e": 37692, "s": 37556, "text": "This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two." }, { "code": null, "e": 37804, "s": 37692, "text": "The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte." }, { "code": null, "e": 37894, "s": 37804, "text": "The method ceil gives the smallest integer that is greater than or equal to the argument." }, { "code": null, "e": 37981, "s": 37894, "text": "The method floor gives the largest integer that is less than or equal to the argument." }, { "code": null, "e": 38059, "s": 37981, "text": "The method rint returns the integer that is closest in value to the argument." }, { "code": null, "e": 38146, "s": 38059, "text": "The method round returns the closest long or int, as given by the methods return type." }, { "code": null, "e": 38243, "s": 38146, "text": "The method gives the smaller of the two arguments. The argument can be int, float, long, double." }, { "code": null, "e": 38340, "s": 38243, "text": "The method gives the maximum of the two arguments. The argument can be int, float, long, double." }, { "code": null, "e": 38428, "s": 38340, "text": "The method returns the base of the natural logarithms, e, to the power of the argument." }, { "code": null, "e": 38486, "s": 38428, "text": "The method returns the natural logarithm of the argument." }, { "code": null, "e": 38581, "s": 38486, "text": "The method returns the value of the first argument raised to the power of the second argument." }, { "code": null, "e": 38633, "s": 38581, "text": "The method returns the square root of the argument." }, { "code": null, "e": 38692, "s": 38633, "text": "The method returns the sine of the specified double value." }, { "code": null, "e": 38753, "s": 38692, "text": "The method returns the cosine of the specified double value." }, { "code": null, "e": 38815, "s": 38753, "text": "The method returns the tangent of the specified double value." }, { "code": null, "e": 38877, "s": 38815, "text": "The method returns the arcsine of the specified double value." }, { "code": null, "e": 38941, "s": 38877, "text": "The method returns the arccosine of the specified double value." }, { "code": null, "e": 39006, "s": 38941, "text": "The method returns the arctangent of the specified double value." }, { "code": null, "e": 39107, "s": 39006, "text": "The method Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta." }, { "code": null, "e": 39158, "s": 39107, "text": "The method converts the argument value to degrees." }, { "code": null, "e": 39209, "s": 39158, "text": "The method converts the argument value to radians." }, { "code": null, "e": 39371, "s": 39209, "text": "The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic." }, { "code": null, "e": 39457, "s": 39371, "text": "A String literal is constructed in Groovy by enclosing the string text in quotations." }, { "code": null, "e": 39692, "s": 39457, "text": "Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes (’), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines." }, { "code": null, "e": 39752, "s": 39692, "text": "Following is an example of the usage of strings in Groovy −" }, { "code": null, "e": 39997, "s": 39752, "text": "class Example { \n static void main(String[] args) { \n String a = 'Hello Single'; \n String b = \"Hello Double\"; \n String c = \"'Hello Triple\" + \"Multiple lines'\";\n\t\t\n println(a); \n println(b); \n println(c); \n } \n}" }, { "code": null, "e": 40063, "s": 39997, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 40121, "s": 40063, "text": "Hello Single \nHello Double \n'Hello TripleMultiple lines'\n" }, { "code": null, "e": 40285, "s": 40121, "text": "Strings in Groovy are an ordered sequences of characters. The individual character in a string can be accessed by its position. This is given by an index position." }, { "code": null, "e": 40444, "s": 40285, "text": "String indices start at zero and end at one less than the length of the string. Groovy also permits negative indices to count back from the end of the string." }, { "code": null, "e": 40512, "s": 40444, "text": "Following is an example of the usage of string indexing in Groovy −" }, { "code": null, "e": 40939, "s": 40512, "text": "class Example { \n static void main(String[] args) { \n String sample = \"Hello world\"; \n println(sample[4]); // Print the 5 character in the string\n\t\t\n //Print the 1st character in the string starting from the back \n println(sample[-1]); \n println(sample[1..2]);//Prints a string starting from Index 1 to 2 \n println(sample[4..2]);//Prints a string starting from Index 4 back to 2 \n \n } \n}" }, { "code": null, "e": 41005, "s": 40939, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 41021, "s": 41005, "text": "o \nd \nel \noll \n" }, { "code": null, "e": 41100, "s": 41021, "text": "First let’s learn the basic string operations in groovy. They are given below." }, { "code": null, "e": 41169, "s": 41100, "text": "The concatenation of strings can be done by the simple ‘+’ operator." }, { "code": null, "e": 41235, "s": 41169, "text": "The repetition of strings can be done by the simple ‘*’ operator." }, { "code": null, "e": 41309, "s": 41235, "text": "The length of the string determined by the length() method of the string." }, { "code": null, "e": 41364, "s": 41309, "text": "Here is the list of methods supported by String class." }, { "code": null, "e": 41489, "s": 41364, "text": "Returns a new String of length numberOfChars consisting of the recipient padded on the left and right with space characters." }, { "code": null, "e": 41556, "s": 41489, "text": "Compares two strings lexicographically, ignoring case differences." }, { "code": null, "e": 41617, "s": 41556, "text": "Concatenates the specified String to the end of this String." }, { "code": null, "e": 41702, "s": 41617, "text": "Processes each regex group (see next section) matched substring of the given String." }, { "code": null, "e": 41760, "s": 41702, "text": "Tests whether this string ends with the specified suffix." }, { "code": null, "e": 41830, "s": 41760, "text": "Compares this String to another String, ignoring case considerations." }, { "code": null, "e": 41876, "s": 41830, "text": "It returns string value at the index position" }, { "code": null, "e": 41965, "s": 41876, "text": "Returns the index within this String of the first occurrence of the specified substring." }, { "code": null, "e": 42031, "s": 41965, "text": "It outputs whether a String matches the given regular expression." }, { "code": null, "e": 42069, "s": 42031, "text": "Removes the value part of the String." }, { "code": null, "e": 42186, "s": 42069, "text": "This method is called by the ++ operator for the class String. It increments the last character in the given String." }, { "code": null, "e": 42239, "s": 42186, "text": "Pad the String with the spaces appended to the left." }, { "code": null, "e": 42293, "s": 42239, "text": "Pad the String with the spaces appended to the right." }, { "code": null, "e": 42310, "s": 42293, "text": "Appends a String" }, { "code": null, "e": 42373, "s": 42310, "text": "This method is called by the -- operator for the CharSequence." }, { "code": null, "e": 42459, "s": 42373, "text": "Replaces all occurrences of a captured group by the result of a closure on that text." }, { "code": null, "e": 42517, "s": 42459, "text": "Creates a new String which is the reverse of this String." }, { "code": null, "e": 42584, "s": 42517, "text": "Splits this String around matches of the given regular expression." }, { "code": null, "e": 42641, "s": 42584, "text": "Returns a new String that is a substring of this String." }, { "code": null, "e": 42702, "s": 42641, "text": "Converts all of the characters in this String to upper case." }, { "code": null, "e": 42763, "s": 42702, "text": "Converts all of the characters in this String to lower case." }, { "code": null, "e": 43103, "s": 42763, "text": "A range is shorthand for specifying a sequence of values. A Range is denoted by the first and last values in the sequence, and Range can be inclusive or exclusive. An inclusive Range includes all the values from the first to the last, while an exclusive Range includes all values except the last. Here are some examples of Range literals −" }, { "code": null, "e": 43145, "s": 43103, "text": "1..10 - An example of an inclusive Range" }, { "code": null, "e": 43187, "s": 43145, "text": "1..<10 - An example of an exclusive Range" }, { "code": null, "e": 43236, "s": 43187, "text": "‘a’..’x’ – Ranges can also consist of characters" }, { "code": null, "e": 43283, "s": 43236, "text": "10..1 – Ranges can also be in descending order" }, { "code": null, "e": 43360, "s": 43283, "text": "‘x’..’a’ – Ranges can also consist of characters and be in descending order." }, { "code": null, "e": 43416, "s": 43360, "text": "Following are the various methods available for ranges." }, { "code": null, "e": 43460, "s": 43416, "text": "Checks if a range contains a specific value" }, { "code": null, "e": 43521, "s": 43460, "text": "Returns the element at the specified position in this Range." }, { "code": null, "e": 43556, "s": 43521, "text": "Get the lower value of this Range." }, { "code": null, "e": 43591, "s": 43556, "text": "Get the upper value of this Range." }, { "code": null, "e": 43637, "s": 43591, "text": "Is this a reversed Range, iterating backwards" }, { "code": null, "e": 43683, "s": 43637, "text": "Returns the number of elements in this Range." }, { "code": null, "e": 43794, "s": 43683, "text": "Returns a view of the portion of this Range between the specified fromIndex, inclusive, and toIndex, exclusive" }, { "code": null, "e": 44128, "s": 43794, "text": "The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. A List literal is presented as a series of objects separated by commas and enclosed in square brackets." }, { "code": null, "e": 44326, "s": 44128, "text": "To process the data in a list, we must be able to access individual elements. Groovy Lists are indexed using the indexing operator []. List indices start at zero, which refers to the first element." }, { "code": null, "e": 44364, "s": 44326, "text": "Following are some example of lists −" }, { "code": null, "e": 44408, "s": 44364, "text": "[11, 12, 13, 14] – A list of integer values" }, { "code": null, "e": 44458, "s": 44408, "text": "[‘Angular’, ‘Groovy’, ‘Java’] – A list of Strings" }, { "code": null, "e": 44492, "s": 44458, "text": "[1, 2, [3, 4], 5] – A nested list" }, { "code": null, "e": 44557, "s": 44492, "text": "[‘Groovy’, 21, 2.11] – A heterogeneous list of object references" }, { "code": null, "e": 44577, "s": 44557, "text": "[ ] – An empty list" }, { "code": null, "e": 44648, "s": 44577, "text": "In this chapter, we will discuss the list methods available in Groovy." }, { "code": null, "e": 44694, "s": 44648, "text": "Append the new value to the end of this List." }, { "code": null, "e": 44750, "s": 44694, "text": "Returns true if this List contains the specified value." }, { "code": null, "e": 44810, "s": 44750, "text": "Returns the element at the specified position in this List." }, { "code": null, "e": 44857, "s": 44810, "text": "Returns true if this List contains no elements" }, { "code": null, "e": 44960, "s": 44857, "text": "Creates a new List composed of the elements of the original without those specified in the collection." }, { "code": null, "e": 45069, "s": 44960, "text": "Creates a new List composed of the elements of the original together with those specified in the collection." }, { "code": null, "e": 45106, "s": 45069, "text": "Removes the last item from this List" }, { "code": null, "e": 45166, "s": 45106, "text": "Removes the element at the specified position in this List." }, { "code": null, "e": 45238, "s": 45166, "text": "Create a new List that is the reverse the elements of the original List" }, { "code": null, "e": 45283, "s": 45238, "text": "Obtains the number of elements in this List." }, { "code": null, "e": 45327, "s": 45283, "text": "Returns a sorted copy of the original List." }, { "code": null, "e": 45640, "s": 45327, "text": "A Map (also known as an associative array, dictionary, table, and hash) is an unordered collection of object references. The elements in a Map collection are accessed by a key value. The keys used in a Map can be of any class. When we insert into a Map collection, two values are required: the key and the value." }, { "code": null, "e": 45678, "s": 45640, "text": "Following are some examples of maps −" }, { "code": null, "e": 45816, "s": 45678, "text": "[‘TopicName’ : ‘Lists’, ‘Author’ : ‘Raghav’] – Collections of key value pairs which has TopicName as the key and their respective values." }, { "code": null, "e": 45954, "s": 45816, "text": "[‘TopicName’ : ‘Lists’, ‘Author’ : ‘Raghav’] – Collections of key value pairs which has TopicName as the key and their respective values." }, { "code": null, "e": 45976, "s": 45954, "text": "[ : ] – An Empty map." }, { "code": null, "e": 45998, "s": 45976, "text": "[ : ] – An Empty map." }, { "code": null, "e": 46068, "s": 45998, "text": "In this chapter, we will discuss the map methods available in Groovy." }, { "code": null, "e": 46100, "s": 46068, "text": "Does this Map contain this key?" }, { "code": null, "e": 46228, "s": 46100, "text": "Look up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then return null." }, { "code": null, "e": 46266, "s": 46228, "text": "Obtain a Set of the keys in this Map." }, { "code": null, "e": 46440, "s": 46266, "text": "Associates the specified value with the specified key in this Map. If this Map previously contained a mapping for this key, the old value is replaced by the specified value." }, { "code": null, "e": 46494, "s": 46440, "text": "Returns the number of key-value mappings in this Map." }, { "code": null, "e": 46557, "s": 46494, "text": "Returns a collection view of the values contained in this Map." }, { "code": null, "e": 46691, "s": 46557, "text": "The class Date represents a specific instant in time, with millisecond precision. The Date class has two constructors as shown below." }, { "code": null, "e": 46706, "s": 46691, "text": "public Date()\n" }, { "code": null, "e": 46725, "s": 46706, "text": "Parameters − None." }, { "code": null, "e": 46738, "s": 46725, "text": "Return Value" }, { "code": null, "e": 46876, "s": 46738, "text": "Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond." }, { "code": null, "e": 46930, "s": 46876, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 47125, "s": 46930, "text": "class Example { \n static void main(String[] args) { \n Date date = new Date(); \n \n // display time and date using toString() \n System.out.println(date.toString()); \n } \n} " }, { "code": null, "e": 47253, "s": 47125, "text": "When we run the above program, we will get the following result. The following output will give you the current date and time −" }, { "code": null, "e": 47283, "s": 47253, "text": "Thu Dec 10 21:31:15 GST 2015\n" }, { "code": null, "e": 47311, "s": 47283, "text": "public Date(long millisec)\n" }, { "code": null, "e": 47322, "s": 47311, "text": "Parameters" }, { "code": null, "e": 47402, "s": 47322, "text": "Millisec – The number of millisecconds to specify since the standard base time." }, { "code": null, "e": 47599, "s": 47402, "text": "Return Value − Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as \"the epoch\", namely January 1, 1970, 00:00:00 GMT." }, { "code": null, "e": 47653, "s": 47599, "text": "Following is an example of the usage of this method −" }, { "code": null, "e": 47845, "s": 47653, "text": "class Example {\n static void main(String[] args) {\n Date date = new Date(100);\n \n // display time and date using toString()\n System.out.println(date.toString());\n } \n}" }, { "code": null, "e": 47911, "s": 47845, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 47941, "s": 47911, "text": "Thu Jan 01 04:00:00 GST 1970\n" }, { "code": null, "e": 48140, "s": 47941, "text": "Following are the given methods of the Date class. In all methods of class Date that accept or return year, month, date, hours, minutes, and seconds values, the following representations are used −" }, { "code": null, "e": 48189, "s": 48140, "text": "A year y is represented by the integer y - 1900." }, { "code": null, "e": 48238, "s": 48189, "text": "A year y is represented by the integer y - 1900." }, { "code": null, "e": 48353, "s": 48238, "text": "A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December." }, { "code": null, "e": 48468, "s": 48353, "text": "A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December." }, { "code": null, "e": 48553, "s": 48468, "text": "A date (day of month) is represented by an integer from 1 to 31 in the usual manner." }, { "code": null, "e": 48638, "s": 48553, "text": "A date (day of month) is represented by an integer from 1 to 31 in the usual manner." }, { "code": null, "e": 48784, "s": 48638, "text": "An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12." }, { "code": null, "e": 48930, "s": 48784, "text": "An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12." }, { "code": null, "e": 49002, "s": 48930, "text": "A minute is represented by an integer from 0 to 59 in the usual manner." }, { "code": null, "e": 49074, "s": 49002, "text": "A minute is represented by an integer from 0 to 59 in the usual manner." }, { "code": null, "e": 49126, "s": 49074, "text": "A second is represented by an integer from 0 to 61." }, { "code": null, "e": 49178, "s": 49126, "text": "A second is represented by an integer from 0 to 61." }, { "code": null, "e": 49226, "s": 49178, "text": "Tests if this date is after the specified date." }, { "code": null, "e": 49415, "s": 49226, "text": "Compares two dates for equality. The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object." }, { "code": null, "e": 49448, "s": 49415, "text": "Compares two Dates for ordering." }, { "code": null, "e": 49486, "s": 49448, "text": "Converts this Date object to a String" }, { "code": null, "e": 49535, "s": 49486, "text": "Tests if this date is before the specified date." }, { "code": null, "e": 49639, "s": 49535, "text": "Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object." }, { "code": null, "e": 49752, "s": 49639, "text": "Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT." }, { "code": null, "e": 49984, "s": 49752, "text": "A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison." }, { "code": null, "e": 50055, "s": 49984, "text": "For example we can create a regular expression object as shown below −" }, { "code": null, "e": 50078, "s": 50055, "text": "def regex = ~'Groovy'\n" }, { "code": null, "e": 50355, "s": 50078, "text": "When the Groovy operator =~ appears as a predicate (expression returning a Boolean) in if and while statements (see Chapter 8), the String operand on the left is matched against the regular expression operand on the right. Hence, each of the following delivers the value true." }, { "code": null, "e": 50436, "s": 50355, "text": "When defining regular expression, the following special characters can be used −" }, { "code": null, "e": 50568, "s": 50436, "text": "There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($)." }, { "code": null, "e": 50700, "s": 50568, "text": "There are two special positional characters that are used to denote the beginning and end of a line: caret (∧) and dollar sign ($)." }, { "code": null, "e": 50958, "s": 50700, "text": "Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once." }, { "code": null, "e": 51216, "s": 50958, "text": "Regular expressions can also include quantifiers. The plus sign (+) represents one or more times, applied to the preceding element of the expression. The asterisk (*) is used to represent zero or more occurrences. The question mark (?) denotes zero or once." }, { "code": null, "e": 51318, "s": 51216, "text": "The metacharacter { and } is used to match a specific number of instances of the preceding character." }, { "code": null, "e": 51420, "s": 51318, "text": "The metacharacter { and } is used to match a specific number of instances of the preceding character." }, { "code": null, "e": 51541, "s": 51420, "text": "In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character." }, { "code": null, "e": 51662, "s": 51541, "text": "In a regular expression, the period symbol (.) can represent any character. This is described as the wildcard character." }, { "code": null, "e": 52133, "s": 51662, "text": "A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below" }, { "code": null, "e": 52604, "s": 52133, "text": "A regular expression may include character classes. A set of characters can be given as a simple sequence of characters enclosed in the metacharacters [and] as in [aeiou]. For letter or number ranges, you can use a dash separator as in [a–z] or [a–mA–M]. The complement of a character class is denoted by a leading caret within the square rackets as in [∧a–z] and represents all characters other than those specified. Some examples of Regular expressions are given below" }, { "code": null, "e": 52767, "s": 52604, "text": "'Groovy' =~ 'Groovy' \n'Groovy' =~ 'oo' \n'Groovy' ==~ 'Groovy' \n'Groovy' ==~ 'oo' \n'Groovy' =~ '∧G' \n‘Groovy' =~ 'G$' \n‘Groovy' =~ 'Gro*vy' 'Groovy' =~ 'Gro{2}vy'\n" }, { "code": null, "e": 52913, "s": 52767, "text": "Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained." }, { "code": null, "e": 53055, "s": 52913, "text": "Exception normally disrupts the normal flow of the application, which is the reason why we need to use Exception handling in our application." }, { "code": null, "e": 53121, "s": 53055, "text": "Exceptions are broadly classified into the following categories −" }, { "code": null, "e": 53330, "s": 53121, "text": "Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time." }, { "code": null, "e": 53539, "s": 53330, "text": "Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time." }, { "code": null, "e": 53678, "s": 53539, "text": "One classical case is the FileNotFoundException. Suppose you had the following codein your application which reads from a file in E drive." }, { "code": null, "e": 53827, "s": 53678, "text": "class Example {\n static void main(String[] args) {\n File file = new File(\"E://file.txt\");\n FileReader fr = new FileReader(file);\n } \n}" }, { "code": null, "e": 53924, "s": 53827, "text": "if the File (file.txt) is not there in the E drive then the following exception will be raised." }, { "code": null, "e": 54020, "s": 53924, "text": "Caught: java.io.FileNotFoundException: E:\\file.txt (The system cannot find the file specified)." }, { "code": null, "e": 54108, "s": 54020, "text": "java.io.FileNotFoundException: E:\\file.txt (The system cannot find the file specified)." }, { "code": null, "e": 54380, "s": 54108, "text": "Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime." }, { "code": null, "e": 54652, "s": 54380, "text": "Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime." }, { "code": null, "e": 54870, "s": 54652, "text": "One classical case is the ArrayIndexOutOfBoundsException which happens when you try to access an index of an array which is greater than the length of the array. Following is a typical example of this sort of mistake." }, { "code": null, "e": 54977, "s": 54870, "text": "class Example {\n static void main(String[] args) {\n def arr = new int[3];\n arr[5] = 5;\n } \n}" }, { "code": null, "e": 55050, "s": 54977, "text": "When the above code is executed the following exception will be raised." }, { "code": null, "e": 55102, "s": 55050, "text": "Caught: java.lang.ArrayIndexOutOfBoundsException: 5" }, { "code": null, "e": 55146, "s": 55102, "text": "java.lang.ArrayIndexOutOfBoundsException: 5" }, { "code": null, "e": 55241, "s": 55146, "text": "Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc." }, { "code": null, "e": 55336, "s": 55241, "text": "Error − Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc." }, { "code": null, "e": 55431, "s": 55336, "text": "These are errors which the program can never recover from and will cause the program to crash." }, { "code": null, "e": 55564, "s": 55431, "text": "The following diagram shows how the hierarchy of exceptions in Groovy is organized. It’s all based on the hierarchy defined in Java." }, { "code": null, "e": 55723, "s": 55564, "text": "A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception." }, { "code": null, "e": 55799, "s": 55723, "text": "try { \n //Protected code \n} catch(ExceptionName e1) {\n //Catch block \n}" }, { "code": null, "e": 55886, "s": 55799, "text": "All of your code which could raise an exception is placed in the Protected code block." }, { "code": null, "e": 56013, "s": 55886, "text": "In the catch block, you can write custom code to handle your exception so that the application can recover from the exception." }, { "code": null, "e": 56215, "s": 56013, "text": "Let’s look at an example of the similar code we saw above for accessing an array with an index value which is greater than the size of the array. But this time let’s wrap our code in a try/catch block." }, { "code": null, "e": 56476, "s": 56215, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n } catch(Exception ex) {\n println(\"Catching the exception\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n }\n}" }, { "code": null, "e": 56542, "s": 56476, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 56601, "s": 56542, "text": "Catching the exception \nLet's move on after the exception\n" }, { "code": null, "e": 56775, "s": 56601, "text": "From the above code, we wrap out faulty code in the try block. In the catch block we are just catching our exception and outputting a message that an exception has occurred." }, { "code": null, "e": 56961, "s": 56775, "text": "One can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception raised you would write code to handle it accordingly." }, { "code": null, "e": 57078, "s": 56961, "text": "Let’s modify our above code to catch the ArrayIndexOutOfBoundsException specifically. Following is the code snippet." }, { "code": null, "e": 57453, "s": 57078, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n }catch(ArrayIndexOutOfBoundsException ex) {\n println(\"Catching the Array out of Bounds exception\");\n }catch(Exception ex) {\n println(\"Catching the exception\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n } \n}" }, { "code": null, "e": 57519, "s": 57453, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 57597, "s": 57519, "text": "Catching the Aray out of Bounds exception \nLet's move on after the exception\n" }, { "code": null, "e": 57745, "s": 57597, "text": "From the above code you can see that the ArrayIndexOutOfBoundsException catch block is caught first because it means the criteria of the exception." }, { "code": null, "e": 57886, "s": 57745, "text": "The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception." }, { "code": null, "e": 58068, "s": 57886, "text": "Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. The syntax for this block is given below." }, { "code": null, "e": 58296, "s": 58068, "text": "try { \n //Protected code \n} catch(ExceptionType1 e1) { \n //Catch block \n} catch(ExceptionType2 e2) { \n //Catch block \n} catch(ExceptionType3 e3) { \n //Catch block \n} finally {\n //The finally block always executes. \n}\n" }, { "code": null, "e": 58390, "s": 58296, "text": "Let’s modify our above code and add the finally block of code. Following is the code snippet." }, { "code": null, "e": 58822, "s": 58390, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n } catch(ArrayIndexOutOfBoundsException ex) {\n println(\"Catching the Array out of Bounds exception\");\n }catch(Exception ex) {\n println(\"Catching the exception\");\n } finally {\n println(\"The final block\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n } \n} " }, { "code": null, "e": 58888, "s": 58822, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 58984, "s": 58888, "text": "Catching the Array out of Bounds exception \nThe final block \nLet's move on after the exception\n" }, { "code": null, "e": 59042, "s": 58984, "text": "Following are the Exception methods available in Groovy −" }, { "code": null, "e": 59166, "s": 59042, "text": "Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor." }, { "code": null, "e": 59239, "s": 59166, "text": "Returns the cause of the exception as represented by a Throwable object." }, { "code": null, "e": 59314, "s": 59239, "text": "Returns the name of the class concatenated with the result of getMessage()" }, { "code": null, "e": 59413, "s": 59314, "text": "Prints the result of toString() along with the stack trace to System.err, the error output stream." }, { "code": null, "e": 59624, "s": 59413, "text": "Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack." }, { "code": null, "e": 59756, "s": 59624, "text": "Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace." }, { "code": null, "e": 59826, "s": 59756, "text": "Following is the code example using some of the methods given above −" }, { "code": null, "e": 60300, "s": 59826, "text": "class Example {\n static void main(String[] args) {\n try {\n def arr = new int[3];\n arr[5] = 5;\n }catch(ArrayIndexOutOfBoundsException ex) {\n println(ex.toString());\n println(ex.getMessage());\n println(ex.getStackTrace()); \n } catch(Exception ex) {\n println(\"Catching the exception\");\n }finally {\n println(\"The final block\");\n }\n\t\t\n println(\"Let's move on after the exception\");\n } \n}" }, { "code": null, "e": 60366, "s": 60300, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 62668, "s": 60366, "text": "java.lang.ArrayIndexOutOfBoundsException: 5 \n5 \n[org.codehaus.groovy.runtime.dgmimpl.arrays.IntegerArrayPutAtMetaMethod$MyPojoMetaMet \nhodSite.call(IntegerArrayPutAtMetaMethod.java:75), \norg.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48) ,\norg.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113) ,\norg.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133) ,\nExample.main(Sample:8), sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),\nsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),\nsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,\njava.lang.reflect.Method.invoke(Method.java:606),\norg.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93),\ngroovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325),\ngroovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1443),\norg.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:893),\ngroovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:287),\ngroovy.lang.GroovyShell.run(GroovyShell.java:524),\ngroovy.lang.GroovyShell.run(GroovyShell.java:513),\ngroovy.ui.GroovyMain.processOnce(GroovyMain.java:652),\ngroovy.ui.GroovyMain.run(GroovyMain.java:384),\ngroovy.ui.GroovyMain.process(GroovyMain.java:370),\ngroovy.ui.GroovyMain.processArgs(GroovyMain.java:129),\ngroovy.ui.GroovyMain.main(GroovyMain.java:109),\nsun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),\nsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),\nsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,\njava.lang.reflect.Method.invoke(Method.java:606),\norg.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109),\norg.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131),\nsun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),\nsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),\nsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ,\njava.lang.reflect.Method.invoke(Method.java:606),\ncom.intellij.rt.execution.application.AppMain.main(AppMain.java:144)]\n \nThe final block \nLet's move on after the exception \n" }, { "code": null, "e": 63030, "s": 62668, "text": "In Groovy, as in any other Object-Oriented language, there is the concept of classes and objects to represent the objected oriented nature of the programming language. A Groovy class is a collection of data and the methods that operate on that data. Together, the data and methods of a class are used to represent some real world object from the problem domain." }, { "code": null, "e": 63210, "s": 63030, "text": "A class in Groovy declares the state (data) and the behavior of objects defined by that class. Hence, a Groovy class describes both the instance fields and methods for that class." }, { "code": null, "e": 63470, "s": 63210, "text": "Following is an example of a class in Groovy. The name of the class is Student which has two fields – StudentID and StudentName. In the main function, we are creating an object of this class and assigning values to the StudentID and StudentName of the object." }, { "code": null, "e": 63666, "s": 63470, "text": "class Student {\n int StudentID;\n String StudentName;\n\t\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\" \n } \n}" }, { "code": null, "e": 63931, "s": 63666, "text": "In any programming language, it always a practice to hide the instance members with the private keyword and instead provide getter and setter methods to set and get the values of the instance variables accordingly. The following example shows how this can be done." }, { "code": null, "e": 64478, "s": 63931, "text": "class Student {\n private int StudentID;\n private String StudentName;\n\t\n void setStudentID(int pID) {\n StudentID = pID;\n }\n\t\n void setStudentName(String pName) {\n StudentName = pName;\n }\n\t\n int getStudentID() {\n return this.StudentID;\n }\n\t\n String getStudentName() {\n return this.StudentName;\n }\n\t\n static void main(String[] args) {\n Student st = new Student();\n st.setStudentID(1);\n st.setStudentName(\"Joe\");\n\t\t\n println(st.getStudentID());\n println(st.getStudentName());\n } \n}" }, { "code": null, "e": 64544, "s": 64478, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 64553, "s": 64544, "text": "1 \nJoe \n" }, { "code": null, "e": 64609, "s": 64553, "text": "Note the following key points about the above program −" }, { "code": null, "e": 64747, "s": 64609, "text": "In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class." }, { "code": null, "e": 64885, "s": 64747, "text": "In the class both the studentID and studentName are marked as private which means that they cannot be accessed from outside of the class." }, { "code": null, "e": 65164, "s": 64885, "text": "Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName)" }, { "code": null, "e": 65443, "s": 65164, "text": "Each instance member has its own getter and setter method. The getter method returns the value of the instance variable, for example the method int getStudentID() and the setter method sets the value of the instance ID, for example the method - void setStudentName(String pName)" }, { "code": null, "e": 65838, "s": 65443, "text": "It’s normally a natural to include more methods inside of the class which actually does some sort of functionality for the class. In our student example, let’s add instance members of Marks1, Marks2 and Marks3 to denote the marks of the student in 3 subjects. We will then add a new instance method which will calculate the total marks of the student. Following is how the code would look like." }, { "code": null, "e": 65950, "s": 65838, "text": "In the following example, the method Total is an additional Instance method which has some logic built into it." }, { "code": null, "e": 66344, "s": 65950, "text": "class Student {\n int StudentID;\n String StudentName;\n\t\n int Marks1;\n int Marks2;\n int Marks3;\n\t\n int Total() {\n return Marks1+Marks2+Marks3;\n }\n\t\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.StudentName=\"Joe\";\n\t\t\n st.Marks1 = 10;\n st.Marks2 = 20;\n st.Marks3 = 30;\n\t\t\n println(st.Total());\n }\n}" }, { "code": null, "e": 66410, "s": 66344, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 66414, "s": 66410, "text": "60\n" }, { "code": null, "e": 66638, "s": 66414, "text": "One can also create multiple objects of a class. Following is the example of how this can be achieved. In here we are creating 3 objects (st, st1 and st2) and calling their instance members and instance methods accordingly." }, { "code": null, "e": 67431, "s": 66638, "text": "class Student {\n int StudentID;\n String StudentName;\n\t\n int Marks1;\n int Marks2;\n int Marks3;\n\t\n int Total() { \n return Marks1+Marks2+Marks3;\n } \n\t\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\";\n\t\t\n st.Marks1 = 10;\n st.Marks2 = 20;\n st.Marks3 = 30;\n\t\t\n println(st.Total()); \n \n Student st1 = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\";\n\t\t\n st.Marks1 = 10;\n st.Marks2 = 20;\n st.Marks3 = 40;\n\t\t\n println(st.Total()); \n \n Student st3 = new Student();\n st.StudentID = 1;\n st.StudentName = \"Joe\";\n\t\t\n st.Marks1 = 10; \n st.Marks2 = 20;\n st.Marks3 = 50;\n\t\t\n println(st.Total());\n } \n} " }, { "code": null, "e": 67497, "s": 67431, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 67510, "s": 67497, "text": "60 \n70 \n80 \n" }, { "code": null, "e": 67713, "s": 67510, "text": "Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order." }, { "code": null, "e": 67908, "s": 67713, "text": "The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class)." }, { "code": null, "e": 68081, "s": 67908, "text": "extends is the keyword used to inherit the properties of a class. Given below is the syntax of extends keyword. In the following example we are doing the following things −" }, { "code": null, "e": 68161, "s": 68081, "text": "Creating a class called Person. This class has one instance member called name." }, { "code": null, "e": 68241, "s": 68161, "text": "Creating a class called Person. This class has one instance member called name." }, { "code": null, "e": 68419, "s": 68241, "text": "Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class." }, { "code": null, "e": 68597, "s": 68419, "text": "Creating a class called Student which extends from the Person class. Note that the name instance member which is defined in the Person class gets inherited in the Student class." }, { "code": null, "e": 68674, "s": 68597, "text": "In the Student class constructor, we are calling the base class constructor." }, { "code": null, "e": 68751, "s": 68674, "text": "In the Student class constructor, we are calling the base class constructor." }, { "code": null, "e": 68842, "s": 68751, "text": "In our Student class, we are adding 2 additional instance members of StudentID and Marks1." }, { "code": null, "e": 68933, "s": 68842, "text": "In our Student class, we are adding 2 additional instance members of StudentID and Marks1." }, { "code": null, "e": 69307, "s": 68933, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n\t\t\n st.Marks1 = 10;\n st.name = \"Joe\";\n\t\t\n println(st.name);\n }\n} \n\nclass Person {\n public String name;\n public Person() {} \n} \n\nclass Student extends Person {\n int StudentID\n int Marks1;\n\t\n public Student() {\n super();\n } \n} " }, { "code": null, "e": 69373, "s": 69307, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 69378, "s": 69373, "text": "Joe\n" }, { "code": null, "e": 69664, "s": 69378, "text": "Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes." }, { "code": null, "e": 69778, "s": 69664, "text": "Following is an example of an Outer and Inner class. In the following example we are doing the following things −" }, { "code": null, "e": 69840, "s": 69778, "text": "Creating an class called Outer which will be our outer class." }, { "code": null, "e": 69890, "s": 69840, "text": "Defining a string called name in our Outer class." }, { "code": null, "e": 69951, "s": 69890, "text": "Creating an Inner or nested class inside of our Outer class." }, { "code": null, "e": 70055, "s": 69951, "text": "Note that in the inner class we are able to access the name instance member defined in the Outer class." }, { "code": null, "e": 70400, "s": 70055, "text": "class Example { \n static void main(String[] args) { \n Outer outobj = new Outer(); \n outobj.name = \"Joe\"; \n outobj.callInnerMethod() \n } \n} \n\nclass Outer { \n String name;\n\t\n def callInnerMethod() { \n new Inner().methodA() \n } \n\t\n class Inner {\n def methodA() { \n println(name); \n } \n } \n\t\n} " }, { "code": null, "e": 70466, "s": 70400, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 70471, "s": 70466, "text": "Joe\n" }, { "code": null, "e": 70869, "s": 70471, "text": "Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses. Abstract classes must be declared with abstract keyword. Abstract methods must also be declared with abstract keyword." }, { "code": null, "e": 71179, "s": 70869, "text": "In the following example, note that the Person class is now made into an abstract class and cannot be instantiated. Also note that there is an abstract method called DisplayMarks in the abstract class which has no implementation details. In the student class it is mandatory to add the implementation details." }, { "code": null, "e": 71699, "s": 71179, "text": "class Example { \n static void main(String[] args) { \n Student st = new Student(); \n st.StudentID = 1;\n\t\t\n st.Marks1 = 10; \n st.name=\"Joe\"; \n\t\t\n println(st.name); \n println(st.DisplayMarks()); \n } \n} \n\nabstract class Person { \n public String name; \n public Person() { } \n abstract void DisplayMarks();\n}\n \nclass Student extends Person { \n int StudentID \n int Marks1; \n\t\n public Student() { \n super(); \n } \n\t\n void DisplayMarks() { \n println(Marks1); \n } \n} " }, { "code": null, "e": 71765, "s": 71699, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 71780, "s": 71765, "text": "Joe \n10 \nnull\n" }, { "code": null, "e": 72184, "s": 71780, "text": "An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the methods implementation. An interface needs to be declared using the interface keyword. An interface only defines method signatures. Methods of an interface are always public. It is an error to use protected or private methods in interfaces." }, { "code": null, "e": 72296, "s": 72184, "text": "Following is an example of an interface in groovy. In the following example we are doing the following things −" }, { "code": null, "e": 72385, "s": 72296, "text": "Creating an interface called Marks and creating an interface method called DisplayMarks." }, { "code": null, "e": 72474, "s": 72385, "text": "Creating an interface called Marks and creating an interface method called DisplayMarks." }, { "code": null, "e": 72563, "s": 72474, "text": "In the class definition, we are using the implements keyword to implement the interface." }, { "code": null, "e": 72652, "s": 72563, "text": "In the class definition, we are using the implements keyword to implement the interface." }, { "code": null, "e": 72761, "s": 72652, "text": "Because we are implementing the interface we have to provide the implementation for the DisplayMarks method." }, { "code": null, "e": 72870, "s": 72761, "text": "Because we are implementing the interface we have to provide the implementation for the DisplayMarks method." }, { "code": null, "e": 73217, "s": 72870, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.Marks1 = 10;\n println(st.DisplayMarks());\n } \n} \n\ninterface Marks { \n void DisplayMarks(); \n} \n\nclass Student implements Marks {\n int StudentID\n int Marks1;\n\t\n void DisplayMarks() {\n println(Marks1);\n }\n}" }, { "code": null, "e": 73283, "s": 73217, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 73292, "s": 73283, "text": "10\nnull\n" }, { "code": null, "e": 73677, "s": 73292, "text": "Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types." }, { "code": null, "e": 73970, "s": 73677, "text": "The collections classes such as the List class can be generalized so that only collections of that type are accepted in the application. An example of the generalized ArrayList is shown below. What the following statement does is that it only accepts list items which are of the type string −" }, { "code": null, "e": 74015, "s": 73970, "text": "List<String> list = new ArrayList<String>();" }, { "code": null, "e": 74075, "s": 74015, "text": "In the following code example, we are doing the following −" }, { "code": null, "e": 74149, "s": 74075, "text": "Creating a Generalized ArrayList collection which will hold only Strings." }, { "code": null, "e": 74176, "s": 74149, "text": "Add 3 strings to the list." }, { "code": null, "e": 74238, "s": 74176, "text": "For each item in the list, printing the value of the strings." }, { "code": null, "e": 74556, "s": 74238, "text": "class Example {\n static void main(String[] args) {\n // Creating a generic List collection\n List<String> list = new ArrayList<String>();\n list.add(\"First String\");\n list.add(\"Second String\");\n list.add(\"Third String\");\n\t\t\n for(String str : list) {\n println(str);\n }\n } \n}" }, { "code": null, "e": 74599, "s": 74556, "text": "The output of the above program would be −" }, { "code": null, "e": 74642, "s": 74599, "text": "First String \nSecond String \nThird String\n" }, { "code": null, "e": 74840, "s": 74642, "text": "The entire class can also be generalized. This makes the class more flexible in accepting any types and working accordingly with those types. Let’s look at an example of how we can accomplish this." }, { "code": null, "e": 74908, "s": 74840, "text": "In the following program, we are carrying out the following steps −" }, { "code": null, "e": 75221, "s": 74908, "text": "We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T>" }, { "code": null, "e": 75534, "s": 75221, "text": "We are creating a class called ListType. Note the <T> keywords placed in front of the class definition. This tells the compiler that this class can accept any type. So when we declare an object of this class, we can specify a type during the the declaration and that type would be replaced in the placeholder <T>" }, { "code": null, "e": 75644, "s": 75534, "text": "The generic class has simple getter and setter methods to work with the member variable defined in the class." }, { "code": null, "e": 75754, "s": 75644, "text": "The generic class has simple getter and setter methods to work with the member variable defined in the class." }, { "code": null, "e": 75944, "s": 75754, "text": "In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String." }, { "code": null, "e": 76134, "s": 75944, "text": "In the main program, notice that we are able to declare objects of the ListType class, but of different types. The first one is of the type Integer and the second one is of the type String." }, { "code": null, "e": 76629, "s": 76134, "text": "class Example {\n static void main(String[] args) {\n // Creating a generic List collection \n ListType<String> lststr = new ListType<>();\n lststr.set(\"First String\");\n println(lststr.get()); \n\t\t\n ListType<Integer> lstint = new ListType<>();\n lstint.set(1);\n println(lstint.get());\n }\n} \n\npublic class ListType<T> {\n private T localt;\n\t\n public T get() {\n return this.localt;\n }\n\t\n public void set(T plocal) {\n this.localt = plocal;\n } \n}" }, { "code": null, "e": 76672, "s": 76629, "text": "The output of the above program would be −" }, { "code": null, "e": 76689, "s": 76672, "text": "First String \n1\n" }, { "code": null, "e": 76753, "s": 76689, "text": "Traits are a structural construct of the language which allow −" }, { "code": null, "e": 76779, "s": 76753, "text": "Composition of behaviors." }, { "code": null, "e": 76817, "s": 76779, "text": "Runtime implementation of interfaces." }, { "code": null, "e": 76869, "s": 76817, "text": "Compatibility with static type checking/compilation" }, { "code": null, "e": 76993, "s": 76869, "text": "They can be seen as interfaces carrying both default implementations and state. A trait is defined using the trait keyword." }, { "code": null, "e": 77032, "s": 76993, "text": "An example of a trait is given below −" }, { "code": null, "e": 77111, "s": 77032, "text": "trait Marks {\n void DisplayMarks() {\n println(\"Display Marks\");\n } \n}" }, { "code": null, "e": 77207, "s": 77111, "text": "One can then use the implement keyword to implement the trait in the similar way as interfaces." }, { "code": null, "e": 77535, "s": 77207, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.Marks1 = 10; \n println(st.DisplayMarks());\n } \n} \n\ntrait Marks { \n void DisplayMarks() {\n println(\"Display Marks\");\n } \n} \n\nclass Student implements Marks { \n int StudentID\n int Marks1;\n}" }, { "code": null, "e": 77640, "s": 77535, "text": "Traits may implement interfaces, in which case the interfaces are declared using the implements keyword." }, { "code": null, "e": 77768, "s": 77640, "text": "An example of a trait implementing an interface is given below. In the following example the following key points can be noted." }, { "code": null, "e": 77828, "s": 77768, "text": "An interface Total is defined with the method DisplayTotal." }, { "code": null, "e": 77888, "s": 77828, "text": "An interface Total is defined with the method DisplayTotal." }, { "code": null, "e": 78009, "s": 77888, "text": "The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method." }, { "code": null, "e": 78130, "s": 78009, "text": "The trait Marks implements the Total interface and hence needs to provide an implementation for the DisplayTotal method." }, { "code": null, "e": 78624, "s": 78130, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n st.Marks1 = 10;\n\t\t\n println(st.DisplayMarks());\n println(st.DisplayTotal());\n } \n} \n\ninterface Total {\n void DisplayTotal() \n} \n\ntrait Marks implements Total {\n void DisplayMarks() {\n println(\"Display Marks\");\n }\n\t\n void DisplayTotal() {\n println(\"Display Total\"); \n } \n} \n\nclass Student implements Marks { \n int StudentID\n int Marks1; \n} " }, { "code": null, "e": 78667, "s": 78624, "text": "The output of the above program would be −" }, { "code": null, "e": 78697, "s": 78667, "text": "Display Marks \nDisplay Total\n" }, { "code": null, "e": 78782, "s": 78697, "text": "A trait may define properties. An example of a trait with a property is given below." }, { "code": null, "e": 78850, "s": 78782, "text": "In the following example, the Marks1 of type integer is a property." }, { "code": null, "e": 79393, "s": 78850, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n\t\t\n println(st.DisplayMarks());\n println(st.DisplayTotal());\n } \n\t\n interface Total {\n void DisplayTotal() \n } \n\t\n trait Marks implements Total {\n int Marks1;\n\t\t\n void DisplayMarks() {\n this.Marks1 = 10;\n println(this.Marks1);\n }\n\t\t\n void DisplayTotal() {\n println(\"Display Total\");\n } \n } \n\t\n class Student implements Marks {\n int StudentID \n }\n} " }, { "code": null, "e": 79436, "s": 79393, "text": "The output of the above program would be −" }, { "code": null, "e": 79455, "s": 79436, "text": "10 \nDisplay Total\n" }, { "code": null, "e": 79799, "s": 79455, "text": "Traits can be used to implement multiple inheritance in a controlled way, avoiding the diamond issue. In the following code example, we have defined two traits – Marks and Total. Our Student class implements both traits. Since the student class extends both traits, it is able to access the both of the methods – DisplayMarks and DisplayTotal." }, { "code": null, "e": 80203, "s": 79799, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n\t\t\n println(st.DisplayMarks());\n println(st.DisplayTotal()); \n } \n} \n\ntrait Marks {\n void DisplayMarks() {\n println(\"Marks1\");\n } \n} \n\ntrait Total {\n void DisplayTotal() { \n println(\"Total\");\n } \n} \n\nclass Student implements Marks,Total {\n int StudentID \n} " }, { "code": null, "e": 80246, "s": 80203, "text": "The output of the above program would be −" }, { "code": null, "e": 80261, "s": 80246, "text": "Total \nMarks1\n" }, { "code": null, "e": 80428, "s": 80261, "text": "Traits may extend another trait, in which case you must use the extends keyword. In the following code example, we are extending the Total trait with the Marks trait." }, { "code": null, "e": 80798, "s": 80428, "text": "class Example {\n static void main(String[] args) {\n Student st = new Student();\n st.StudentID = 1;\n println(st.DisplayMarks());\n } \n} \n\ntrait Marks {\n void DisplayMarks() {\n println(\"Marks1\");\n } \n} \n\ntrait Total extends Marks {\n void DisplayMarks() {\n println(\"Total\");\n } \n} \n\nclass Student implements Total {\n int StudentID \n}" }, { "code": null, "e": 80841, "s": 80798, "text": "The output of the above program would be −" }, { "code": null, "e": 80848, "s": 80841, "text": "Total\n" }, { "code": null, "e": 81025, "s": 80848, "text": "A closure is a short anonymous block of code. It just normally spans a few lines of code. A method can even take the block of code as a parameter. They are anonymous in nature." }, { "code": null, "e": 81093, "s": 81025, "text": "Following is an example of a simple closure and what it looks like." }, { "code": null, "e": 81215, "s": 81093, "text": "class Example {\n static void main(String[] args) {\n def clos = {println \"Hello World\"};\n clos.call();\n } \n}" }, { "code": null, "e": 81387, "s": 81215, "text": "In the above example, the code line - {println \"Hello World\"} is known as a closure. The code block referenced by this identifier can be executed with the call statement." }, { "code": null, "e": 81453, "s": 81387, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 81466, "s": 81453, "text": "Hello World\n" }, { "code": null, "e": 81564, "s": 81466, "text": "Closures can also contain formal parameters to make them more useful just like methods in Groovy." }, { "code": null, "e": 81703, "s": 81564, "text": "class Example {\n static void main(String[] args) {\n def clos = {param->println \"Hello ${param}\"};\n clos.call(\"World\");\n } \n}" }, { "code": null, "e": 81920, "s": 81703, "text": "In the above code example, notice the use of the ${param } which causes the closure to take a parameter. When calling the closure via the clos.call statement we now have the option to pass a parameter to the closure." }, { "code": null, "e": 81986, "s": 81920, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 81999, "s": 81986, "text": "Hello World\n" }, { "code": null, "e": 82189, "s": 81999, "text": "The next illustration repeats the previous example and produces the same result, but shows that an implicit single parameter referred to as it can be used. Here ‘it’ is a keyword in Groovy." }, { "code": null, "e": 82318, "s": 82189, "text": "class Example {\n static void main(String[] args) {\n def clos = {println \"Hello ${it}\"};\n clos.call(\"World\");\n } \n}" }, { "code": null, "e": 82384, "s": 82318, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 82397, "s": 82384, "text": "Hello World\n" }, { "code": null, "e": 82533, "s": 82397, "text": "More formally, closures can refer to variables at the time the closure is defined. Following is an example of how this can be achieved." }, { "code": null, "e": 82852, "s": 82533, "text": "class Example { \n static void main(String[] args) {\n def str1 = \"Hello\";\n def clos = {param -> println \"${str1} ${param}\"}\n clos.call(\"World\");\n\t\t\n // We are now changing the value of the String str1 which is referenced in the closure\n str1 = \"Welcome\";\n clos.call(\"World\");\n } \n}" }, { "code": null, "e": 83035, "s": 82852, "text": "In the above example, in addition to passing a parameter to the closure, we are also defining a variable called str1. The closure also takes on the variable along with the parameter." }, { "code": null, "e": 83101, "s": 83035, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 83129, "s": 83101, "text": "Hello World \nWelcome World\n" }, { "code": null, "e": 83301, "s": 83129, "text": "Closures can also be used as parameters to methods. In Groovy, a lot of the inbuilt methods for data types such as Lists and collections have closures as a parameter type." }, { "code": null, "e": 83383, "s": 83301, "text": "The following example shows how a closure can be sent to a method as a parameter." }, { "code": null, "e": 83920, "s": 83383, "text": "class Example { \n def static Display(clo) {\n // This time the $param parameter gets replaced by the string \"Inner\" \n clo.call(\"Inner\");\n } \n\t\n static void main(String[] args) {\n def str1 = \"Hello\";\n def clos = { param -> println \"${str1} ${param}\" }\n clos.call(\"World\");\n\t\t\n // We are now changing the value of the String str1 which is referenced in the closure\n str1 = \"Welcome\";\n clos.call(\"World\");\n\t\t\n // Passing our closure to a method\n Example.Display(clos);\n } \n}" }, { "code": null, "e": 83942, "s": 83920, "text": "In the above example," }, { "code": null, "e": 84027, "s": 83942, "text": "We are defining a static method called Display which takes a closure as an argument." }, { "code": null, "e": 84112, "s": 84027, "text": "We are defining a static method called Display which takes a closure as an argument." }, { "code": null, "e": 84215, "s": 84112, "text": "We are then defining a closure in our main method and passing it to our Display method as a parameter." }, { "code": null, "e": 84318, "s": 84215, "text": "We are then defining a closure in our main method and passing it to our Display method as a parameter." }, { "code": null, "e": 84384, "s": 84318, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 84427, "s": 84384, "text": "Hello World \nWelcome World \nWelcome Inner\n" }, { "code": null, "e": 84569, "s": 84427, "text": "Several List, Map, and String methods accept a closure as an argument. Let’s look at example of how closures can be used in these data types." }, { "code": null, "e": 84870, "s": 84569, "text": "The following example shows how closures can be used with Lists. In the following example we are first defining a simple list of values. The list collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each element of the list." }, { "code": null, "e": 84993, "s": 84870, "text": "class Example {\n static void main(String[] args) {\n def lst = [11, 12, 13, 14];\n lst.each {println it}\n } \n}" }, { "code": null, "e": 85059, "s": 84993, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 85075, "s": 85059, "text": "11 \n12 \n13 \n14\n" }, { "code": null, "e": 85388, "s": 85075, "text": "The following example shows how closures can be used with Maps. In the following example we are first defining a simple Map of key value items. The map collection type then defines a function called .each. This function takes on a closure as a parameter and applies the closure to each key-value pair of the map." }, { "code": null, "e": 85624, "s": 85388, "text": "class Example {\n static void main(String[] args) {\n def mp = [\"TopicName\" : \"Maps\", \"TopicDescription\" : \"Methods in Maps\"] \n mp.each {println it}\n mp.each {println \"${it.key} maps to: ${it.value}\"}\n } \n}" }, { "code": null, "e": 85690, "s": 85624, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 85812, "s": 85690, "text": "TopicName = Maps \nTopicDescription = Methods in Maps \nTopicName maps to: Maps \nTopicDescription maps to: Methods in Maps\n" }, { "code": null, "e": 86011, "s": 85812, "text": "Often, we may wish to iterate across the members of a collection and apply some logic only when the element meets some criterion. This is readily handled with a conditional statement in the closure." }, { "code": null, "e": 86262, "s": 86011, "text": "class Example {\n static void main(String[] args) {\n def lst = [1,2,3,4];\n lst.each {println it}\n println(\"The list will only display those numbers which are divisible by 2\")\n lst.each{num -> if(num % 2 == 0) println num}\n } \n}" }, { "code": null, "e": 86423, "s": 86262, "text": "The above example shows the conditional if(num % 2 == 0) expression being used in the closure which is used to check if each item in the list is divisible by 2." }, { "code": null, "e": 86489, "s": 86423, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 86575, "s": 86489, "text": "1 \n2 \n3 \n4 \nThe list will only display those numbers which are divisible by 2.\n2 \n4 \n" }, { "code": null, "e": 86621, "s": 86575, "text": "The closures themselves provide some methods." }, { "code": null, "e": 86704, "s": 86621, "text": "The find method finds the first value in a collection that matches some criterion." }, { "code": null, "e": 86780, "s": 86704, "text": "It finds all values in the receiving object matching the closure condition." }, { "code": null, "e": 86909, "s": 86780, "text": "Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element." }, { "code": null, "e": 87038, "s": 86909, "text": "The method collect iterates through a collection, converting each element into a new value using the closure as the transformer." }, { "code": null, "e": 87233, "s": 87038, "text": "Annotations are a form of metadata wherein they provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate." }, { "code": null, "e": 87289, "s": 87233, "text": "Annotations are mainly used for the following reasons −" }, { "code": null, "e": 87399, "s": 87289, "text": "Information for the compiler − Annotations can be used by the compiler to detect errors or suppress warnings." }, { "code": null, "e": 87509, "s": 87399, "text": "Information for the compiler − Annotations can be used by the compiler to detect errors or suppress warnings." }, { "code": null, "e": 87648, "s": 87509, "text": "Compile-time and deployment-time processing − Software tools can process annotation information to generate code, XML files, and so forth." }, { "code": null, "e": 87787, "s": 87648, "text": "Compile-time and deployment-time processing − Software tools can process annotation information to generate code, XML files, and so forth." }, { "code": null, "e": 87866, "s": 87787, "text": "Runtime processing − Some annotations are available to be examined at runtime." }, { "code": null, "e": 87945, "s": 87866, "text": "Runtime processing − Some annotations are available to be examined at runtime." }, { "code": null, "e": 87994, "s": 87945, "text": "In Groovy, a basic annotation looks as follows −" }, { "code": null, "e": 88095, "s": 87994, "text": "@interface - The at sign character (@) indicates to the compiler that what follows is an annotation." }, { "code": null, "e": 88197, "s": 88095, "text": "An annotation may define members in the form of methods without bodies and an optional default value." }, { "code": null, "e": 88250, "s": 88197, "text": "Annotation’s can be applied to the following types −" }, { "code": null, "e": 88308, "s": 88250, "text": "An example of an Annotation for a string is given below −" }, { "code": null, "e": 88371, "s": 88308, "text": "@interface Simple { \n String str1() default \"HelloWorld\"; \n}" }, { "code": null, "e": 88477, "s": 88371, "text": "enum DayOfWeek { mon, tue, wed, thu, fri, sat, sun } \n@interface Scheduled {\n DayOfWeek dayOfWeek() \n} " }, { "code": null, "e": 88644, "s": 88477, "text": "@interface Simple {} \n@Simple \nclass User {\n String username\n int age\n}\n \ndef user = new User(username: \"Joe\",age:1); \nprintln(user.age); \nprintln(user.username);" }, { "code": null, "e": 88874, "s": 88644, "text": "When an annotation is used, it is required to set at least all members that do not have a default value. An example is given below. When the annotation Example is used after being defined, it needs to have a value assigned to it." }, { "code": null, "e": 88936, "s": 88874, "text": "@interface Example {\n int status() \n}\n\n@Example(status = 1)" }, { "code": null, "e": 89105, "s": 88936, "text": "A good feature of annotations in Groovy is that you can use a closure as an annotation value also. Therefore annotations may be used with a wide variety of expressions." }, { "code": null, "e": 89340, "s": 89105, "text": "An example is given below on this. The annotation Onlyif is created based on a class value. Then the annotation is applied to two methods which posts different messages to the result variable based on the value of the number variable." }, { "code": null, "e": 89549, "s": 89340, "text": "@interface OnlyIf {\n Class value() \n} \n\n@OnlyIf({ number<=6 }) \nvoid Version6() {\n result << 'Number greater than 6' \n} \n\n@OnlyIf({ number>=6 }) \nvoid Version7() {\n result << 'Number greater than 6' \n}" }, { "code": null, "e": 89771, "s": 89549, "text": "This is quite a useful feature of annotations in groovy. There may comes times wherein you might have multiple annotations for a method as the one shown below. Sometimes this can become messy to have multiple annotations." }, { "code": null, "e": 89820, "s": 89771, "text": "@Procedure \n@Master class \nMyMasterProcedure {} " }, { "code": null, "e": 90064, "s": 89820, "text": "In such a case you can define a meta-annotation which clubs multiple annotations together and the apply the meta annotation to the method. So for the above example you can fist define the collection of annotation using the AnnotationCollector." }, { "code": null, "e": 90153, "s": 90064, "text": "import groovy.transform.AnnotationCollector\n \n@Procedure \n@Master \n@AnnotationCollector" }, { "code": null, "e": 90231, "s": 90153, "text": "Once this is done, you can apply the following meta-annotator to the method −" }, { "code": null, "e": 90368, "s": 90231, "text": "import groovy.transform.AnnotationCollector\n \n@Procedure \n@Master \n@AnnotationCollector\n \n@MasterProcedure \nclass MyMasterProcedure {}" }, { "code": null, "e": 90646, "s": 90368, "text": "XML is a portable, open source language that allows programmers to develop applications that can be read by other applications, regardless of operating system and/or developmental language. This is one of the most common languages used for exchanging data between applications." }, { "code": null, "e": 90930, "s": 90646, "text": "The Extensible Markup Language XML is a markup language much like HTML or SGML. This is recommended by the World Wide Web Consortium and available as an open standard. XML is extremely useful for keeping track of small to medium amounts of data without requiring a SQLbased backbone." }, { "code": null, "e": 91042, "s": 90930, "text": "The Groovy language also provides a rich support of the XML language. The two most basic XML classes used are −" }, { "code": null, "e": 91576, "s": 91042, "text": "XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node." }, { "code": null, "e": 92110, "s": 91576, "text": "XML Markup Builder − Groovy supports a tree-based markup generator, BuilderSupport, that can be subclassed to make a variety of tree-structured object representations. Commonly, these builders are used to represent XML markup, HTML markup. Groovy’s markup generator catches calls to pseudomethods and converts them into elements or nodes of a tree structure. Parameters to these pseudomethods are treated as attributes of the nodes. Closures as part of the method call are considered as nested subcontent for the resulting tree node." }, { "code": null, "e": 92398, "s": 92110, "text": "XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing." }, { "code": null, "e": 92686, "s": 92398, "text": "XML Parser − The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing." }, { "code": null, "e": 92836, "s": 92686, "text": "For all our XML code examples, let's use the following simple XML file movies.xml for construction of the XML file and reading the file subsequently." }, { "code": null, "e": 93853, "s": 92836, "text": "<collection shelf = \"New Arrivals\"> \n\n <movie title = \"Enemy Behind\"> \n <type>War, Thriller</type> \n <format>DVD</format> \n <year>2003</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Talk about a US-Japan war</description> \n </movie> \n\t\n <movie title = \"Transformers\"> \n <type>Anime, Science Fiction</type>\n <format>DVD</format> \n <year>1989</year> \n <rating>R</rating> \n <stars>8</stars> \n <description>A schientific fiction</description> \n </movie> \n\t\n <movie title = \"Trigun\"> \n <type>Anime, Action</type> \n <format>DVD</format> \n <year>1986</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Vash the Stam pede!</description> \n </movie> \n\t\n <movie title = \"Ishtar\"> \n <type>Comedy</type> \n <format>VHS</format> \n <year>1987</year> \n <rating>PG</rating> \n <stars>2</stars> \n <description>Viewable boredom </description> \n </movie> \n\t\n</collection> " }, { "code": null, "e": 93877, "s": 93853, "text": "public MarkupBuilder()\n" }, { "code": null, "e": 94133, "s": 93877, "text": "The MarkupBuilder is used to construct the entire XML document. The XML document is created by first creating an object of the XML document class. Once the object is created, a pseudomethod can be called to create the various elements of the XML document." }, { "code": null, "e": 94243, "s": 94133, "text": "Let’s look at an example of how to create one block, that is, one movie element from the above XML document −" }, { "code": null, "e": 94666, "s": 94243, "text": "import groovy.xml.MarkupBuilder \n\nclass Example {\n static void main(String[] args) {\n def mB = new MarkupBuilder()\n\t\t\n // Compose the builder\n mB.collection(shelf : 'New Arrivals') {\n movie(title : 'Enemy Behind')\n type('War, Thriller')\n format('DVD')\n year('2003')\n rating('PG')\n stars(10)\n description('Talk about a US-Japan war') \n }\n } \n}" }, { "code": null, "e": 94728, "s": 94666, "text": "In the above example, the following things need to be noted −" }, { "code": null, "e": 94832, "s": 94728, "text": "mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection>" }, { "code": null, "e": 94936, "s": 94832, "text": "mB.collection() − This is a markup generator that creates the head XML tag of <collection></collection>" }, { "code": null, "e": 95176, "s": 94936, "text": "movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element." }, { "code": null, "e": 95416, "s": 95176, "text": "movie(title : 'Enemy Behind') − These pseudomethods create the child tags with this method creating the tag with the value. By specifying a value called title, this actually indicates that an attribute needs to be created for the element." }, { "code": null, "e": 95512, "s": 95416, "text": "A closure is provided to the pseudomethod to create the remaining elements of the XML document." }, { "code": null, "e": 95608, "s": 95512, "text": "A closure is provided to the pseudomethod to create the remaining elements of the XML document." }, { "code": null, "e": 95741, "s": 95608, "text": "The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream" }, { "code": null, "e": 95874, "s": 95741, "text": "The default constructor for the class MarkupBuilder is initialized so that the generated XML is issued to the standard output stream" }, { "code": null, "e": 95940, "s": 95874, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 96241, "s": 95940, "text": "<collection shelf = 'New Arrivals'> \n <movie title = 'Enemy Behind' /> \n <type>War, Thriller</type> \n <format>DVD</format> \n <year>2003</year> \n <rating>PG</rating> \n <stars>10</stars> \n <description>Talk about a US-Japan war</description> \n </movie> \n</collection>\n" }, { "code": null, "e": 96323, "s": 96241, "text": "In order to create the entire XML document, the following things need to be done." }, { "code": null, "e": 96402, "s": 96323, "text": "A map entry needs to be created to store the different values of the elements." }, { "code": null, "e": 96475, "s": 96402, "text": "For each element of the map, we are assigning the value to each element." }, { "code": null, "e": 97452, "s": 96475, "text": "import groovy.xml.MarkupBuilder \n\nclass Example {\n static void main(String[] args) {\n def mp = [1 : ['Enemy Behind', 'War, Thriller','DVD','2003', \n 'PG', '10','Talk about a US-Japan war'],\n 2 : ['Transformers','Anime, Science Fiction','DVD','1989', \n 'R', '8','A scientific fiction'],\n 3 : ['Trigun','Anime, Action','DVD','1986', \n 'PG', '10','Vash the Stam pede'],\n 4 : ['Ishtar','Comedy','VHS','1987', 'PG', \n '2','Viewable boredom ']] \n\t\t\t\n def mB = new MarkupBuilder() \n\t\t\n // Compose the builder\n def MOVIEDB = mB.collection('shelf': 'New Arrivals') {\n mp.each {\n sd -> \n mB.movie('title': sd.value[0]) { \n type(sd.value[1])\n format(sd.value[2])\n year(sd.value[3]) \n rating(sd.value[4])\n stars(sd.value[4]) \n description(sd.value[5]) \n }\n }\n }\n } \n} " }, { "code": null, "e": 97518, "s": 97452, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 98449, "s": 97518, "text": "<collection shelf = 'New Arrivals'> \n <movie title = 'Enemy Behind'> \n <type>War, Thriller</type> \n <format>DVD</format> \n <year>2003</year> \n <rating>PG</rating> \n <stars>PG</stars> \n <description>10</description> \n </movie> \n <movie title = 'Transformers'> \n <type>Anime, Science Fiction</type> \n <format>DVD</format> \n <year>1989</year>\n\t <rating>R</rating> \n <stars>R</stars> \n <description>8</description> \n </movie> \n <movie title = 'Trigun'> \n <type>Anime, Action</type> \n <format>DVD</format> \n <year>1986</year> \n <rating>PG</rating> \n <stars>PG</stars> \n <description>10</description> \n </movie> \n <movie title = 'Ishtar'> \n <type>Comedy</type> \n <format>VHS</format> \n <year>1987</year> \n <rating>PG</rating> \n <stars>PG</stars> \n <description>2</description> \n </movie> \n</collection> \n" }, { "code": null, "e": 98724, "s": 98449, "text": "The Groovy XmlParser class employs a simple model for parsing an XML document into a tree of Node instances. Each Node has the name of the XML element, the attributes of the element, and references to any child Nodes. This model is sufficient for most simple XML processing." }, { "code": null, "e": 98805, "s": 98724, "text": "public XmlParser() \n throws ParserConfigurationException, \n SAXException\n" }, { "code": null, "e": 98899, "s": 98805, "text": "The following codeshows an example of how the XML parser can be used to read an XML document." }, { "code": null, "e": 99181, "s": 98899, "text": "Let’s assume we have the same document called Movies.xml and we wanted to parse the XML document and display a proper output to the user. The following codeis a snippet of how we can traverse through the entire content of the XML document and display a proper response to the user." }, { "code": null, "e": 100016, "s": 99181, "text": "import groovy.xml.MarkupBuilder \nimport groovy.util.*\n\nclass Example {\n\n static void main(String[] args) { \n\t\n def parser = new XmlParser()\n def doc = parser.parse(\"D:\\\\Movies.xml\");\n\t\t\n doc.movie.each{\n bk->\n print(\"Movie Name:\")\n println \"${bk['@title']}\"\n\t\t\t\n print(\"Movie Type:\")\n println \"${bk.type[0].text()}\"\n\t\t\t\n print(\"Movie Format:\")\n println \"${bk.format[0].text()}\"\n\t\t\t\n print(\"Movie year:\")\n println \"${bk.year[0].text()}\"\n\t\t\t\n print(\"Movie rating:\")\n println \"${bk.rating[0].text()}\"\n\t\t\t\n print(\"Movie stars:\")\n println \"${bk.stars[0].text()}\"\n\t\t\t\n print(\"Movie description:\")\n println \"${bk.description[0].text()}\"\n println(\"*******************************\")\n }\n }\n} " }, { "code": null, "e": 100082, "s": 100016, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 100804, "s": 100082, "text": "Movie Name:Enemy Behind \nMovie Type:War, Thriller \nMovie Format:DVD \nMovie year:2003 \nMovie rating:PG \nMovie stars:10 \nMovie description:Talk about a US-Japan war \n******************************* \nMovie Name:Transformers \nMovie Type:Anime, Science Fiction \nMovie Format:DVD \nMovie year:1989 \nMovie rating:R \nMovie stars:8 \nMovie description:A schientific fiction \n******************************* \nMovie Name:Trigun \nMovie Type:Anime, Action\nMovie Format:DVD \nMovie year:1986 \nMovie rating:PG \nMovie stars:10 \nMovie description:Vash the Stam pede! \n******************************* \nMovie Name:Ishtar \nMovie Type:Comedy \nMovie Format:VHS \nMovie year:1987 \nMovie rating:PG \nMovie stars:2 \nMovie description:Viewable boredom\n" }, { "code": null, "e": 100855, "s": 100804, "text": "The important things to note about the above code." }, { "code": null, "e": 100954, "s": 100855, "text": "An object of the class XmlParser is being formed so that it can be used to parse the XML document." }, { "code": null, "e": 101053, "s": 100954, "text": "An object of the class XmlParser is being formed so that it can be used to parse the XML document." }, { "code": null, "e": 101103, "s": 101053, "text": "The parser is given the location of the XML file." }, { "code": null, "e": 101153, "s": 101103, "text": "The parser is given the location of the XML file." }, { "code": null, "e": 101272, "s": 101153, "text": "For each movie element, we are using a closure to browse through each child node and display the relevant information." }, { "code": null, "e": 101391, "s": 101272, "text": "For each movie element, we are using a closure to browse through each child node and display the relevant information." }, { "code": null, "e": 101509, "s": 101391, "text": "For the movie element itself, we are using the @ symbol to display the title attribute attached to the movie element." }, { "code": null, "e": 101773, "s": 101509, "text": "JMX is the defacto standard which is used for monitoring all applications which have anything to do with the Java virual environment. Given that Groovy sits directly on top of Java, Groovy can leverage the tremendous amount of work already done for JMX with Java." }, { "code": null, "e": 101939, "s": 101773, "text": "One can use the standard classes available in java.lang.management for carrying out the monitoring of the JVM. The following code example shows how this can be done." }, { "code": null, "e": 103397, "s": 101939, "text": "import java.lang.management.*\n\ndef os = ManagementFactory.operatingSystemMXBean \nprintln \"\"\"OPERATING SYSTEM: \n\\tOS architecture = $os.arch \n\\tOS name = $os.name \n\\tOS version = $os.version \n\\tOS processors = $os.availableProcessors \n\"\"\" \n \ndef rt = ManagementFactory.runtimeMXBean \nprintln \"\"\"RUNTIME: \n \\tRuntime name = $rt.name \n \\tRuntime spec name = $rt.specName \n \\tRuntime vendor = $rt.specVendor \n \\tRuntime spec version = $rt.specVersion \n \\tRuntime management spec version = $rt.managementSpecVersion \n \"\"\" \n\ndef mem = ManagementFactory.memoryMXBean \ndef heapUsage = mem.heapMemoryUsage \ndef nonHeapUsage = mem.nonHeapMemoryUsage \n\nprintln \"\"\"MEMORY: \n HEAP STORAGE: \n \\tMemory committed = $heapUsage.committed \n \\tMemory init = $heapUsage.init \n \\tMemory max = $heapUsage.max \n \\tMemory used = $heapUsage.used NON-HEAP STORAGE: \n \\tNon-heap memory committed = $nonHeapUsage.committed \n \\tNon-heap memory init = $nonHeapUsage.init \n \\tNon-heap memory max = $nonHeapUsage.max \n \\tNon-heap memory used = $nonHeapUsage.used \n \"\"\"\n \nprintln \"GARBAGE COLLECTION:\" \nManagementFactory.garbageCollectorMXBeans.each { gc ->\n println \"\\tname = $gc.name\"\n println \"\\t\\tcollection count = $gc.collectionCount\"\n println \"\\t\\tcollection time = $gc.collectionTime\"\n String[] mpoolNames = gc.memoryPoolNames\n\t\n mpoolNames.each { \n mpoolName -> println \"\\t\\tmpool name = $mpoolName\"\n } \n}" }, { "code": null, "e": 103534, "s": 103397, "text": "When the code is executed, the output will vary depending on the system on which the code is run. A sample of the output is given below." }, { "code": null, "e": 104638, "s": 103534, "text": "OPERATING SYSTEM: \n OS architecture = x86 \n OS name = Windows 7 \n OS version = 6.1 \n OS processors = 4\n \nRUNTIME: \n Runtime name = 5144@Babuli-PC \n Runtime spec name = Java Virtual Machine Specification \n Runtime vendor = Oracle Corporation \n Runtime spec version = 1.7 \n Runtime management spec version = 1.2\n \nMEMORY: \n HEAP STORAGE: \n Memory committed = 16252928 \n Memory init = 16777216 \n Memory max = 259522560 \n Memory used = 7355840\n \nNON-HEAP STORAGE: \n Non-heap memory committed = 37715968 \n Non-heap memory init = 35815424 \n Non-heap memory max = 123731968 \n Non-heap memory used = 18532232 \n \nGARBAGE COLLECTION: \n name = Copy \n collection count = 15 \n collection time = 47 \n mpool name = Eden Space \n mpool name = Survivor Space\n\t\t\n name = MarkSweepCompact \n collection count = 0 \n collection time = 0 \n\t\t\n mpool name = Eden Space \n mpool name = Survivor Space \n mpool name = Tenured Gen \n mpool name = Perm Gen \n mpool name = Perm Gen [shared-ro] \n mpool name = Perm Gen [shared-rw]" }, { "code": null, "e": 104729, "s": 104638, "text": "In order to monitor tomcat, the following parameter should be set when tomcat is started −" }, { "code": null, "e": 104915, "s": 104729, "text": "set JAVA_OPTS = -Dcom.sun.management.jmxremote \nDcom.sun.management.jmxremote.port = 9004\\\n \n-Dcom.sun.management.jmxremote.authenticate=false \nDcom.sun.management.jmxremote.ssl = false" }, { "code": null, "e": 105088, "s": 104915, "text": "The following code uses JMX to discover the available MBeans in the running Tomcat, determine which are the web modules and extract the processing time for each web module." }, { "code": null, "e": 106164, "s": 105088, "text": "import groovy.swing.SwingBuilder\n \nimport javax.management.ObjectName \nimport javax.management.remote.JMXConnectorFactory as JmxFactory \nimport javax.management.remote.JMXServiceURL as JmxUrl \nimport javax.swing.WindowConstants as WC \n \nimport org.jfree.chart.ChartFactory \nimport org.jfree.data.category.DefaultCategoryDataset as Dataset \nimport org.jfree.chart.plot.PlotOrientation as Orientation \n \ndef serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi' \ndef server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection \ndef serverInfo = new GroovyMBean(server, 'Catalina:type = Server').serverInfo \nprintln \"Connected to: $serverInfo\" \n \ndef query = new ObjectName('Catalina:*') \nString[] allNames = server.queryNames(query, null) \n\ndef modules = allNames.findAll { name -> \n name.contains('j2eeType=WebModule') \n}.collect{ new GroovyMBean(server, it) }\n \nprintln \"Found ${modules.size()} web modules. Processing ...\" \ndef dataset = new Dataset() \n \nmodules.each { m ->\n println m.name()\n dataset.addValue m.processingTime, 0, m.path \n}" }, { "code": null, "e": 106262, "s": 106164, "text": "This chapter covers how to we can use the Groovy language for parsing and producing JSON objects." }, { "code": null, "e": 106274, "s": 106262, "text": "JsonSlurper" }, { "code": null, "e": 106354, "s": 106274, "text": "JsonSlurper is a class that parses JSON text or reader content into Groovy data" }, { "code": null, "e": 106447, "s": 106354, "text": "Structures such as maps, lists and primitive types like Integer, Double, Boolean and String." }, { "code": null, "e": 106458, "s": 106447, "text": "JsonOutput" }, { "code": null, "e": 106535, "s": 106458, "text": "This method is responsible for serialising Groovy objects into JSON strings." }, { "code": null, "e": 106708, "s": 106535, "text": "JsonSlurper is a class that parses JSON text or reader content into Groovy data Structures such as maps, lists and primitive types like Integer, Double, Boolean and String." }, { "code": null, "e": 106741, "s": 106708, "text": "def slurper = new JsonSlurper()\n" }, { "code": null, "e": 106825, "s": 106741, "text": "JSON slurper parses text or reader content into a data structure of lists and maps." }, { "code": null, "e": 107380, "s": 106825, "text": "The JsonSlurper class comes with a couple of variants for parser implementations. Sometimes you may have different requirements when it comes to parsing certain strings. Let’s take an instance wherein one needs to read the JSON which is returned from the response from a web server. In such a case it’s beneficial to use the parser JsonParserLax variant. This parsee allows comments in the JSON text as well as no quote strings etc. To specify this sort of parser you need to use JsonParserType.LAX parser type when defining an object of the JsonSlurper." }, { "code": null, "e": 107601, "s": 107380, "text": "Let’s see an example of this given below. The example is for getting JSON data from a web server using the http module. For this type of traversal, the best option is to have the parser type set to JsonParserLax variant." }, { "code": null, "e": 107953, "s": 107601, "text": "http.request( GET, TEXT ) {\n headers.Accept = 'application/json'\n headers.'User-Agent' = USER_AGENT\n\t\n response.success = { \n res, rd -> \n def jsonText = rd.text \n\t\t\n //Setting the parser type to JsonParserLax\n def parser = new JsonSlurper().setType(JsonParserType.LAX)\n def jsonResp = parser.parseText(jsonText)\n }\n}" }, { "code": null, "e": 108027, "s": 107953, "text": "Similarly the following additional parser types are available in Groovy −" }, { "code": null, "e": 108260, "s": 108027, "text": "The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as \"chopping\") and operates on them individually." }, { "code": null, "e": 108493, "s": 108260, "text": "The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as \"chopping\") and operates on them individually." }, { "code": null, "e": 108901, "s": 108493, "text": "The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. JsonFastParser is also known as the index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It just keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible." }, { "code": null, "e": 109309, "s": 108901, "text": "The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. JsonFastParser is also known as the index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It just keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible." }, { "code": null, "e": 109551, "s": 109309, "text": "The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called \"character windowing\" to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics." }, { "code": null, "e": 109793, "s": 109551, "text": "The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called \"character windowing\" to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics." }, { "code": null, "e": 109869, "s": 109793, "text": "Let’s have a look at some examples of how we can use the JsonSlurper class." }, { "code": null, "e": 110137, "s": 109869, "text": "import groovy.json.JsonSlurper \n\nclass Example {\n static void main(String[] args) {\n def jsonSlurper = new JsonSlurper()\n def object = jsonSlurper.parseText('{ \"name\": \"John\", \"ID\" : \"1\"}') \n\t\t\n println(object.name);\n println(object.ID);\n } \n}" }, { "code": null, "e": 110168, "s": 110137, "text": "In the above example, we are −" }, { "code": null, "e": 110220, "s": 110168, "text": "First creating an instance of the JsonSlurper class" }, { "code": null, "e": 110272, "s": 110220, "text": "First creating an instance of the JsonSlurper class" }, { "code": null, "e": 110363, "s": 110272, "text": "We are then using the parseText function of the JsonSlurper class to parse some JSON text." }, { "code": null, "e": 110454, "s": 110363, "text": "We are then using the parseText function of the JsonSlurper class to parse some JSON text." }, { "code": null, "e": 110561, "s": 110454, "text": "When we get the object, you can see that we can actually access the values in the JSON string via the key." }, { "code": null, "e": 110668, "s": 110561, "text": "When we get the object, you can see that we can actually access the values in the JSON string via the key." }, { "code": null, "e": 110717, "s": 110668, "text": "The output of the above program is given below −" }, { "code": null, "e": 110726, "s": 110717, "text": "John \n1\n" }, { "code": null, "e": 110971, "s": 110726, "text": "Let’s take a look at another example of the JsonSlurper parsing method. In the following example, we are pasing a list of integers. You will notice from The following codethat we are able to use the List method of each and pass a closure to it." }, { "code": null, "e": 111205, "s": 110971, "text": "import groovy.json.JsonSlurper \nclass Example {\n static void main(String[] args) {\n def jsonSlurper = new JsonSlurper()\n Object lst = jsonSlurper.parseText('{ \"List\": [2, 3, 4, 5] }')\n lst.each { println it }\n } \n}" }, { "code": null, "e": 111254, "s": 111205, "text": "The output of the above program is given below −" }, { "code": null, "e": 111273, "s": 111254, "text": "List=[2, 3, 4, 5]\n" }, { "code": null, "e": 111458, "s": 111273, "text": "The JSON parser also supports the primitive data types of string, number, object, true, false and null. The JsonSlurper class converts these JSON types into corresponding Groovy types." }, { "code": null, "e": 111656, "s": 111458, "text": "The following example shows how to use the JsonSlurper to parse a JSON string. And here you can see that the JsonSlurper is able to parse the individual items into their respective primitive types." }, { "code": null, "e": 111977, "s": 111656, "text": "import groovy.json.JsonSlurper \nclass Example {\n\n static void main(String[] args) {\n def jsonSlurper = new JsonSlurper()\n def obj = jsonSlurper.parseText ''' {\"Integer\": 12, \"fraction\": 12.55, \"double\": 12e13}'''\n\t\t\n println(obj.Integer);\n println(obj.fraction);\n println(obj.double); \n } \n}" }, { "code": null, "e": 112026, "s": 111977, "text": "The output of the above program is given below −" }, { "code": null, "e": 112047, "s": 112026, "text": "12 \n12.55 \n1.2E+14 \n" }, { "code": null, "e": 112217, "s": 112047, "text": "Now let’s talk about how to print output in Json. This can be done by the JsonOutput method. This method is responsible for serialising Groovy objects into JSON strings." }, { "code": null, "e": 112264, "s": 112217, "text": "Static string JsonOutput.toJson(datatype obj)\n" }, { "code": null, "e": 112384, "s": 112264, "text": "Parameters − The parameters can be an object of a datatype – Number, Boolean, character,String, Date, Map, closure etc." }, { "code": null, "e": 112432, "s": 112384, "text": "Return type − The return type is a json string." }, { "code": null, "e": 112491, "s": 112432, "text": "Following is a simple example of how this can be achieved." }, { "code": null, "e": 112667, "s": 112491, "text": "import groovy.json.JsonOutput \nclass Example {\n static void main(String[] args) {\n def output = JsonOutput.toJson([name: 'John', ID: 1])\n println(output); \n }\n}" }, { "code": null, "e": 112716, "s": 112667, "text": "The output of the above program is given below −" }, { "code": null, "e": 112740, "s": 112716, "text": "{\"name\":\"John\",\"ID\":1}\n" }, { "code": null, "e": 112923, "s": 112740, "text": "The JsonOutput can also be used for plain old groovy objects. In the following example, you can see that we are actually passing objects of the type Student to the JsonOutput method." }, { "code": null, "e": 113201, "s": 112923, "text": "import groovy.json.JsonOutput \nclass Example {\n static void main(String[] args) {\n def output = JsonOutput.toJson([ new Student(name: 'John',ID:1),\n new Student(name: 'Mark',ID:2)])\n println(output); \n } \n}\n \nclass Student {\n String name\n int ID; \n}" }, { "code": null, "e": 113250, "s": 113201, "text": "The output of the above program is given below −" }, { "code": null, "e": 113299, "s": 113250, "text": "[{\"name\":\"John\",\"ID\":1},{\"name\":\"Mark\",\"ID\":2}]\n" }, { "code": null, "e": 113613, "s": 113299, "text": "Groovy allows one to omit parentheses around the arguments of a method call for top-level statements. This is known as the \"command chain\" feature. This extension works by allowing one to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls." }, { "code": null, "e": 113694, "s": 113613, "text": "If a call is executed as a b c d, this will actually be equivalent to a(b).c(d)." }, { "code": null, "e": 113935, "s": 113694, "text": "DSL or Domain specific language is meant to simplify the code written in Groovy in such a way that it becomes easily understandable for the common user. The following example shows what exactly is meant by having a domain specific language." }, { "code": null, "e": 113966, "s": 113935, "text": "def lst = [1,2,3,4] \nprint lst" }, { "code": null, "e": 114120, "s": 113966, "text": "The above code shows a list of numbers being printed to the console using the println statement. In a domain specific language the commands would be as −" }, { "code": null, "e": 114172, "s": 114120, "text": "Given the numbers 1,2,3,4\n \nDisplay all the numbers" }, { "code": null, "e": 114295, "s": 114172, "text": "So the above example shows the transformation of the programming language to meet the needs of a domain specific language." }, { "code": null, "e": 114367, "s": 114295, "text": "Let’s look at a simple example of how we can implement DSLs in Groovy −" }, { "code": null, "e": 115245, "s": 114367, "text": "class EmailDsl { \n String toText \n String fromText \n String body \n\t\n /** \n * This method accepts a closure which is essentially the DSL. Delegate the \n * closure methods to \n * the DSL class so the calls can be processed \n */ \n \n def static make(closure) { \n EmailDsl emailDsl = new EmailDsl() \n // any method called in closure will be delegated to the EmailDsl class \n closure.delegate = emailDsl\n closure() \n }\n \n /** \n * Store the parameter as a variable and use it later to output a memo \n */ \n\t\n def to(String toText) { \n this.toText = toText \n }\n \n def from(String fromText) { \n this.fromText = fromText \n }\n \n def body(String bodyText) { \n this.body = bodyText \n } \n}\n\nEmailDsl.make { \n to \"Nirav Assar\" \n from \"Barack Obama\" \n body \"How are things? We are doing well. Take care\" \n}" }, { "code": null, "e": 115311, "s": 115245, "text": "When we run the above program, we will get the following result −" }, { "code": null, "e": 115357, "s": 115311, "text": "How are things? We are doing well. Take care\n" }, { "code": null, "e": 115427, "s": 115357, "text": "The following needs to be noted about the above code implementation −" }, { "code": null, "e": 115528, "s": 115427, "text": "A static method is used that accepts a closure. This is mostly a hassle free way to implement a DSL." }, { "code": null, "e": 115629, "s": 115528, "text": "A static method is used that accepts a closure. This is mostly a hassle free way to implement a DSL." }, { "code": null, "e": 115878, "s": 115629, "text": "In the email example, the class EmailDsl has a make method. It creates an instance and delegates all calls in the closure to the instance. This is the mechanism where the \"to\", and \"from\" sections end up executing methods inside the EmailDsl class." }, { "code": null, "e": 116127, "s": 115878, "text": "In the email example, the class EmailDsl has a make method. It creates an instance and delegates all calls in the closure to the instance. This is the mechanism where the \"to\", and \"from\" sections end up executing methods inside the EmailDsl class." }, { "code": null, "e": 116218, "s": 116127, "text": "Once the to() method is called, we store the text in the instance for formatting later on." }, { "code": null, "e": 116309, "s": 116218, "text": "Once the to() method is called, we store the text in the instance for formatting later on." }, { "code": null, "e": 116409, "s": 116309, "text": "We can now call the EmailDSL method with an easy language that is easy to understand for end users." }, { "code": null, "e": 116509, "s": 116409, "text": "We can now call the EmailDSL method with an easy language that is easy to understand for end users." }, { "code": null, "e": 116701, "s": 116509, "text": "Groovy’s groovy-sql module provides a higher-level abstraction over the current Java’s JDBC technology. The Groovy sql API supports a wide variety of databases, some of which are shown below." }, { "code": null, "e": 116708, "s": 116701, "text": "HSQLDB" }, { "code": null, "e": 116715, "s": 116708, "text": "Oracle" }, { "code": null, "e": 116726, "s": 116715, "text": "SQL Server" }, { "code": null, "e": 116732, "s": 116726, "text": "MySQL" }, { "code": null, "e": 116740, "s": 116732, "text": "MongoDB" }, { "code": null, "e": 116962, "s": 116740, "text": "In our example, we are going to use MySQL DB as an example. In order to use MySQL with Groovy, the first thing to do is to download the MySQL jdbc jar file from the mysql site. The format of the MySQL will be shown below." }, { "code": null, "e": 116995, "s": 116962, "text": "mysql-connector-java-5.1.38-bin\n" }, { "code": null, "e": 117071, "s": 116995, "text": "Then ensure to add the above jar file to the classpath in your workstation." }, { "code": null, "e": 117140, "s": 117071, "text": "Before connecting to a MySQL database, make sure of the followings −" }, { "code": null, "e": 117176, "s": 117140, "text": "You have created a database TESTDB." }, { "code": null, "e": 117221, "s": 117176, "text": "You have created a table EMPLOYEE in TESTDB." }, { "code": null, "e": 117287, "s": 117221, "text": "This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME." }, { "code": null, "e": 117355, "s": 117287, "text": "User ID \"testuser\" and password \"test123\" are set to access TESTDB." }, { "code": null, "e": 117439, "s": 117355, "text": "Ensure you have downloaded the mysql jar file and added the file to your classpath." }, { "code": null, "e": 117504, "s": 117439, "text": "You have gone through MySQL tutorial to understand MySQL Basics" }, { "code": null, "e": 117577, "s": 117504, "text": "The following example shows how to connect with MySQL database \"TESTDB\"." }, { "code": null, "e": 118127, "s": 117577, "text": "import java.sql.*; \nimport groovy.sql.Sql \n\nclass Example {\n static void main(String[] args) {\n // Creating a connection to the database\n def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', \n 'testuser', 'test123', 'com.mysql.jdbc.Driver')\n\t\t\t\n // Executing the query SELECT VERSION which gets the version of the database\n // Also using the eachROW method to fetch the result from the database\n \n sql.eachRow('SELECT VERSION()'){ row ->\n println row[0]\n }\n\t\t\n sql.close() \n } \n} " }, { "code": null, "e": 118193, "s": 118127, "text": "While running this script, it is producing the following result −" }, { "code": null, "e": 118284, "s": 118193, "text": "5.7.10-log \nThe Sql.newInstance method is used to establish a connection to the database.\n" }, { "code": null, "e": 118540, "s": 118284, "text": "The next step after connecting to the database is to create the tables in our database. The following example shows how to create a table in the database using Groovy. The execute method of the Sql class is used to execute statements against the database." }, { "code": null, "e": 119063, "s": 118540, "text": "import java.sql.*; \nimport groovy.sql.Sql \n\nclass Example { \n static void main(String[] args) {\n // Creating a connection to the database\n def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', \n 'test123', 'com.mysql.jdbc.Driver')\n\t\t\t\n def sqlstr = \"\"\"CREATE TABLE EMPLOYEE ( \n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT )\"\"\" \n\t\t\t\t\t\t\t\n sql.execute(sqlstr);\n sql.close() \n } \n}" }, { "code": null, "e": 119138, "s": 119063, "text": "It is required when you want to create your records into a database table." }, { "code": null, "e": 119384, "s": 119138, "text": "The following example will insert a record in the employee table. The code is placed in a try catch block so that if the record is executed successfully, the transaction is committed to the database. If the transaction fails, a rollback is done." }, { "code": null, "e": 120080, "s": 119384, "text": "import java.sql.*; \nimport groovy.sql.Sql \n\nclass Example {\n static void main(String[] args) { \n // Creating a connection to the database\n def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', \n 'test123', 'com.mysql.jdbc.Driver')\n\t\t\t\n sql.connection.autoCommit = false\n\t\t\n def sqlstr = \"\"\"INSERT INTO EMPLOYEE(FIRST_NAME,\n LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)\"\"\" \n try {\n sql.execute(sqlstr);\n sql.commit()\n println(\"Successfully committed\") \n }catch(Exception ex) {\n sql.rollback()\n println(\"Transaction rollback\") \n }\n\t\t\n sql.close()\n } \n}" }, { "code": null, "e": 120445, "s": 120080, "text": "Suppose if you wanted to just select certain rows based on a criteria. The following codeshows how you can add a parameter placeholder to search for values. The above example can also be written to take in parameters as shown in the following code. The $ symbol is used to define a parameter which can then be replaced by values when the sql statement is executed." }, { "code": null, "e": 121297, "s": 120445, "text": "import java.sql.*; \nimport groovy.sql.Sql\n \nclass Example {\n static void main(String[] args) {\n // Creating a connection to the database\n def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', \n 'test123', 'com.mysql.jdbc.Driver')\n\t\t\t\n sql.connection.autoCommit = false \n \n def firstname = \"Mac\"\n def lastname =\"Mohan\"\n def age = 20\n def sex = \"M\"\n def income = 2000 \n\t\t\n def sqlstr = \"INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, \n INCOME) VALUES \" + \"(${firstname}, ${lastname}, ${age}, ${sex}, ${income} )\"\n\t\t\t\n try {\n sql.execute(sqlstr);\n sql.commit()\n println(\"Successfully committed\") \n } catch(Exception ex) {\n sql.rollback()\n println(\"Transaction rollback\")\n }\n\t\t\n sql.close()\n }\n}" }, { "code": null, "e": 121481, "s": 121297, "text": "READ Operation on any database means to fetch some useful information from the database. Once our database connection is established, you are ready to make a query into this database." }, { "code": null, "e": 121559, "s": 121481, "text": "The read operation is performed by using the eachRow method of the sql class." }, { "code": null, "e": 121603, "s": 121559, "text": "eachRow(GString gstring, Closure closure) \n" }, { "code": null, "e": 121691, "s": 121603, "text": "Performs the given SQL query calling the given Closure with each row of the result set." }, { "code": null, "e": 121702, "s": 121691, "text": "Parameters" }, { "code": null, "e": 121758, "s": 121702, "text": "Gstring − The sql statement which needs to be executed." }, { "code": null, "e": 121814, "s": 121758, "text": "Gstring − The sql statement which needs to be executed." }, { "code": null, "e": 121988, "s": 121814, "text": "Closure − The closure statement to process the rows retrived from the read operation. Performs the given SQL query calling the given Closure with each row of the result set." }, { "code": null, "e": 122162, "s": 121988, "text": "Closure − The closure statement to process the rows retrived from the read operation. Performs the given SQL query calling the given Closure with each row of the result set." }, { "code": null, "e": 122249, "s": 122162, "text": "The following code example shows how to fetch all the records from the employee table." }, { "code": null, "e": 122699, "s": 122249, "text": "import java.sql.*; \nimport groovy.sql.Sql\n \nclass Example {\n static void main(String[] args) {\n // Creating a connection to the database\n def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', \n 'test123', 'com.mysql.jdbc.Driver') \n\t\t\t\n sql.eachRow('select * from employee') {\n tp -> \n println([tp.FIRST_NAME,tp.LAST_NAME,tp.age,tp.sex,tp.INCOME])\n } \n\t\t\n sql.close()\n } \n}" }, { "code": null, "e": 122744, "s": 122699, "text": "The output from the above program would be −" }, { "code": null, "e": 122773, "s": 122744, "text": "[Mac, Mohan, 20, M, 2000.0]\n" }, { "code": null, "e": 123007, "s": 122773, "text": "UPDATE Operation on any database means to update one or more records, which are already available in the database. The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one year." }, { "code": null, "e": 123638, "s": 123007, "text": "import java.sql.*; \nimport groovy.sql.Sql \n\nclass Example {\n static void main(String[] args){\n // Creating a connection to the database\n def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', \n 'test@123', 'com.mysql.jdbc.Driver')\n\t\t\t\n sql.connection.autoCommit = false\n def sqlstr = \"UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = 'M'\" \n\t \n try {\n sql.execute(sqlstr);\n sql.commit()\n println(\"Successfully committed\")\n }catch(Exception ex) {\n sql.rollback() \n println(\"Transaction rollback\")\n }\n\t\t\n sql.close()\n } \n}" }, { "code": null, "e": 123818, "s": 123638, "text": "DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20." }, { "code": null, "e": 124435, "s": 123818, "text": "import java.sql.*; \nimport groovy.sql.Sql \n\nclass Example {\n static void main(String[] args) {\n // Creating a connection to the database\n def sql = Sql.newInstance('jdbc:mysql://localhost:3306/TESTDB', 'testuser', \n 'test@123', 'com.mysql.jdbc.Driver')\n\t\t\t\n sql.connection.autoCommit = false\n def sqlstr = \"DELETE FROM EMPLOYEE WHERE AGE > 20\"\n \n try {\n sql.execute(sqlstr);\n sql.commit()\n println(\"Successfully committed\")\n }catch(Exception ex) {\n sql.rollback()\n println(\"Transaction rollback\")\n }\n \n sql.close()\n } \n}" }, { "code": null, "e": 124545, "s": 124435, "text": "Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −" }, { "code": null, "e": 124615, "s": 124545, "text": "Atomicity − Either a transaction completes or nothing happens at all." }, { "code": null, "e": 124685, "s": 124615, "text": "Atomicity − Either a transaction completes or nothing happens at all." }, { "code": null, "e": 124790, "s": 124685, "text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state." }, { "code": null, "e": 124895, "s": 124790, "text": "Consistency − A transaction must start in a consistent state and leave the system in a consistent state." }, { "code": null, "e": 124994, "s": 124895, "text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction." }, { "code": null, "e": 125093, "s": 124994, "text": "Isolation − Intermediate results of a transaction are not visible outside the current transaction." }, { "code": null, "e": 125197, "s": 125093, "text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure." }, { "code": null, "e": 125301, "s": 125197, "text": "Durability − Once a transaction was committed, the effects are persistent, even after a system failure." }, { "code": null, "e": 125443, "s": 125301, "text": "Here is a simple example of how to implement transactions. We have already seen this example from our previous topic of the DELETE operation." }, { "code": null, "e": 125674, "s": 125443, "text": "def sqlstr = \"DELETE FROM EMPLOYEE WHERE AGE > 20\" \n \ntry {\n sql.execute(sqlstr); \n sql.commit()\n println(\"Successfully committed\") \n}catch(Exception ex) {\n sql.rollback()\n println(\"Transaction rollback\") \n} \nsql.close()" }, { "code": null, "e": 125800, "s": 125674, "text": "The commit operation is what tells the database to proceed ahead with the operation and finalize all changes to the database." }, { "code": null, "e": 125868, "s": 125800, "text": "In our above example, this is achieved by the following statement −" }, { "code": null, "e": 125882, "s": 125868, "text": "sql.commit()\n" }, { "code": null, "e": 126087, "s": 125882, "text": "If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use rollback method. In our above example, this is achieved by the following statement −" }, { "code": null, "e": 126103, "s": 126087, "text": "sql.rollback()\n" }, { "code": null, "e": 126160, "s": 126103, "text": "To disconnect Database connection, use the close method." }, { "code": null, "e": 126173, "s": 126160, "text": "sql.close()\n" }, { "code": null, "e": 126791, "s": 126173, "text": "During the process of software development, sometimes developers spend a lot of time in creating Data structures, domain classes, XML, GUI Layouts, Output streams etc.And sometimes the code used to create these specific requirements results in the repitition of the same snippet of code in many places. This is where Groovy builders come into play. Groovy has builders which can be used to create standard objects and structures. These builders saves time as developer dont need to write their own code to create these builders. In the couse of this chapter we will look at the different builders available in groovy." }, { "code": null, "e": 127039, "s": 126791, "text": "In groovy one can also create graphical user interfaces using the swing builders available in groovy. The main class for developing swing components is the SwingBuilder class. This class has many methods for creating graphical components such as −" }, { "code": null, "e": 127088, "s": 127039, "text": "JFrame − This is for creating the frame element." }, { "code": null, "e": 127137, "s": 127088, "text": "JFrame − This is for creating the frame element." }, { "code": null, "e": 127201, "s": 127137, "text": "JTextField − This is used for creating the textfield component." }, { "code": null, "e": 127265, "s": 127201, "text": "JTextField − This is used for creating the textfield component." }, { "code": null, "e": 127424, "s": 127265, "text": "Let’s look at a simple example of how to create a Swing application using the SwingBuilder class. In the following example, you can see the following points −" }, { "code": null, "e": 127504, "s": 127424, "text": "You need to import the groovy.swing.SwingBuilder and the javax.swing.* classes." }, { "code": null, "e": 127584, "s": 127504, "text": "You need to import the groovy.swing.SwingBuilder and the javax.swing.* classes." }, { "code": null, "e": 127676, "s": 127584, "text": "All of the componets displayed in the Swing application are part of the SwingBuilder class." }, { "code": null, "e": 127768, "s": 127676, "text": "All of the componets displayed in the Swing application are part of the SwingBuilder class." }, { "code": null, "e": 127895, "s": 127768, "text": "For the frame itself, you can specify the initial location and size of the frame. You can also specify the title of the frame." }, { "code": null, "e": 128022, "s": 127895, "text": "For the frame itself, you can specify the initial location and size of the frame. You can also specify the title of the frame." }, { "code": null, "e": 128106, "s": 128022, "text": "You need to set the Visibility property to true in order for the frame to be shown." }, { "code": null, "e": 128190, "s": 128106, "text": "You need to set the Visibility property to true in order for the frame to be shown." }, { "code": null, "e": 128614, "s": 128190, "text": "import groovy.swing.SwingBuilder \nimport javax.swing.* \n\n// Create a builder \ndef myapp = new SwingBuilder()\n\n// Compose the builder \ndef myframe = myapp.frame(title : 'Tutorials Point', location : [200, 200], \n size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE { \n label(text : 'Hello world')\n } \n\t\n// The following statement is used for displaying the form \nframe.setVisible(true)" }, { "code": null, "e": 128746, "s": 128614, "text": "The output of the above program is given below. The following output shows a JFrame along with a JLabel with a text of Hello World." }, { "code": null, "e": 129002, "s": 128746, "text": "Let’s look at our next example for creating an input screen with textboxes. In the following example, we want to create a form which has text boxes for Student name, subject and School Name. In the following example, you can see the following key points −" }, { "code": null, "e": 129102, "s": 129002, "text": "We are defining a layout for our controls on the screen. In this case we are using the Grid Layout." }, { "code": null, "e": 129153, "s": 129102, "text": "We are using an alignment property for our labels." }, { "code": null, "e": 129227, "s": 129153, "text": "We are using the textField method for displaying textboxes on the screen." }, { "code": null, "e": 130061, "s": 129227, "text": "import groovy.swing.SwingBuilder \nimport javax.swing.* \nimport java.awt.*\n \n// Create a builder \ndef myapp = new SwingBuilder() \n\n// Compose the builder \ndef myframe = myapp.frame(title : 'Tutorials Point', location : [200, 200], \n size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) { \n panel(layout: new GridLayout(3, 2, 5, 5)) { \n label(text : 'Student Name:', horizontalAlignment : JLabel.RIGHT) \n textField(text : '', columns : 10) \n\t\t\t\n label(text : 'Subject Name:', horizontalAlignment : JLabel.RIGHT) \n textField(text : '', columns : 10)\n\t\t\t\n label(text : 'School Name:', horizontalAlignment : JLabel.RIGHT) \n textField(text : '', columns : 10) \n } \n } \n\t\n// The following statement is used for displaying the form \nmyframe.setVisible(true)" }, { "code": null, "e": 130110, "s": 130061, "text": "The output of the above program is given below −" }, { "code": null, "e": 130363, "s": 130110, "text": "Now let’s look at event handlers. Event handlers are used for button to perform some sort of processing when a button is pressed. Each button pseudomethod call includes the actionPerformed parameter. This represents a code block presented as a closure." }, { "code": null, "e": 130582, "s": 130363, "text": "Let’s look at our next example for creating a screen with 2 buttons. When either button is pressed a corresponding message is sent to the console screen. In the following example, you can see the following key points −" }, { "code": null, "e": 130733, "s": 130582, "text": "For each button defined, we are using the actionPerformed method and defining a closure to send some output to the console when the button is clicked." }, { "code": null, "e": 130884, "s": 130733, "text": "For each button defined, we are using the actionPerformed method and defining a closure to send some output to the console when the button is clicked." }, { "code": null, "e": 131702, "s": 130884, "text": "import groovy.swing.SwingBuilder \nimport javax.swing.* \nimport java.awt.* \n\ndef myapp = new SwingBuilder()\n \ndef buttonPanel = {\n myapp.panel(constraints : BorderLayout.SOUTH) {\n\t\n button(text : 'Option A', actionPerformed : {\n println 'Option A chosen'\n })\n\t\t\n button(text : 'Option B', actionPerformed : {\n println 'Option B chosen'\n })\n }\n}\n \ndef mainPanel = {\n myapp.panel(layout : new BorderLayout()) {\n label(text : 'Which Option do you want', horizontalAlignment : \n JLabel.CENTER,\n constraints : BorderLayout.CENTER)\n buttonPanel()\n }\n}\n \ndef myframe = myapp.frame(title : 'Tutorials Point', location : [100, 100],\n size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE){\n mainPanel()\n }\n\t\nmyframe.setVisible(true)" }, { "code": null, "e": 131839, "s": 131702, "text": "The output of the above program is given below. When you click on either button, the required message is sent to the console log screen." }, { "code": null, "e": 132008, "s": 131839, "text": "Another variation of the above example is to define methods which can can act as handlers. In the following example we are defining 2 handlers of DisplayA and DisplayB." }, { "code": null, "e": 132834, "s": 132008, "text": "import groovy.swing.SwingBuilder \nimport javax.swing.* \nimport java.awt.* \n\ndef myapp = new SwingBuilder()\n \ndef DisplayA = {\n println(\"Option A\") \n} \n\ndef DisplayB = {\n println(\"Option B\")\n}\n\ndef buttonPanel = {\n myapp.panel(constraints : BorderLayout.SOUTH) {\n button(text : 'Option A', actionPerformed : DisplayA) \n button(text : 'Option B', actionPerformed : DisplayB)\n }\n} \n\ndef mainPanel = {\n myapp.panel(layout : new BorderLayout()) {\n label(text : 'Which Option do you want', horizontalAlignment : JLabel.CENTER,\n constraints : BorderLayout.CENTER)\n buttonPanel()\n }\n} \n\ndef myframe = myapp.frame(title : 'Tutorials Point', location : [100, 100],\n size : [400, 300], defaultCloseOperation : WindowConstants.EXIT_ON_CLOSE) {\n mainPanel()\n } \n\t\nmyframe.setVisible(true) " }, { "code": null, "e": 132912, "s": 132834, "text": "The output of the above program would remain the same as the earlier example." }, { "code": null, "e": 133011, "s": 132912, "text": "The DOM builder can be used for parsing HTML, XHTML and XML and converting it into a W3C DOM tree." }, { "code": null, "e": 133072, "s": 133011, "text": "The following example shows how the DOM builder can be used." }, { "code": null, "e": 133586, "s": 133072, "text": "String records = '''\n <library>\n\t\n <Student>\n <StudentName division = 'A'>Joe</StudentName>\n <StudentID>1</StudentID>\n </Student>\n\t \n <Student>\n <StudentName division = 'B'>John</StudentName>\n <StudentID>2</StudentID>\n </Student>\n\t \n <Student>\n <StudentName division = 'C'>Mark</StudentName>\n <StudentID>3</StudentID>\n </Student>\n\t\t\n </library>'''\n \ndef rd = new StringReader(records) \ndef doc = groovy.xml.DOMBuilder.parse(rd)" }, { "code": null, "e": 133642, "s": 133586, "text": "The JsonBuilder is used for creating json type objects." }, { "code": null, "e": 133704, "s": 133642, "text": "The following example shows how the Json builder can be used." }, { "code": null, "e": 133967, "s": 133704, "text": "def builder = new groovy.json.JsonBuilder() \n\ndef root = builder.students {\n student {\n studentname 'Joe'\n studentid '1'\n\t\t\n Marks(\n Subject1: 10,\n Subject2: 20,\n Subject3:30,\n )\n } \n} \nprintln(builder.toString());" }, { "code": null, "e": 134127, "s": 133967, "text": "The output of the above program is given below. The output clearlt shows that the Jsonbuilder was able to build the json object out of a structed set of nodes." }, { "code": null, "e": 134244, "s": 134127, "text": "{\"students\":{\"student\":{\"studentname\":\"Joe\",\"studentid\":\"1\",\"Marks\":{\"Subject1\":10,\n\"S ubject2\":20,\"Subject3\":30}}}}" }, { "code": null, "e": 134375, "s": 134244, "text": "The jsonbuilder can also take in a list and convert it to a json object. The following example shows how this can be accomplished." }, { "code": null, "e": 134479, "s": 134375, "text": "def builder = new groovy.json.JsonBuilder() \ndef lst = builder([1, 2, 3]) \nprintln(builder.toString());" }, { "code": null, "e": 134527, "s": 134479, "text": "The output of the above program is given below." }, { "code": null, "e": 134536, "s": 134527, "text": "[1,2,3]\n" }, { "code": null, "e": 134672, "s": 134536, "text": "The jsonBuilder can also be used for classes. The following example shows how objects of a class can become inputs to the json builder." }, { "code": null, "e": 134942, "s": 134672, "text": "def builder = new groovy.json.JsonBuilder() \n\nclass Student {\n String name \n} \n\ndef studentlist = [new Student (name: \"Joe\"), new Student (name: \"Mark\"), \n new Student (name: \"John\")] \n\t\nbuilder studentlist, { Student student ->name student.name} \nprintln(builder)" }, { "code": null, "e": 134990, "s": 134942, "text": "The output of the above program is given below." }, { "code": null, "e": 135041, "s": 134990, "text": "[{\"name\":\"Joe\"},{\"name\":\"Mark\"},{\"name\":\"John\"}] \n" }, { "code": null, "e": 135189, "s": 135041, "text": "NodeBuilder is used for creating nested trees of Node objects for handling arbitrary data. An example of the usage of a Nodebuilder is shown below." }, { "code": null, "e": 135467, "s": 135189, "text": "def nodeBuilder = new NodeBuilder() \n\ndef studentlist = nodeBuilder.userlist {\n user(id: '1', studentname: 'John', Subject: 'Chemistry')\n user(id: '2', studentname: 'Joe', Subject: 'Maths')\n user(id: '3', studentname: 'Mark', Subject: 'Physics') \n} \n\nprintln(studentlist)" }, { "code": null, "e": 135624, "s": 135467, "text": "FileTreeBuilder is a builder for generating a file directory structure from a specification. Following is an example of how the FileTreeBuilder can be used." }, { "code": null, "e": 135849, "s": 135624, "text": "tmpDir = File.createTempDir() \ndef fileTreeBuilder = new FileTreeBuilder(tmpDir) \n\nfileTreeBuilder.dir('main') {\n dir('submain') {\n dir('Tutorial') {\n file('Sample.txt', 'println \"Hello World\"')\n }\n } \n}" }, { "code": null, "e": 136025, "s": 135849, "text": "From the execution of the above code a file called sample.txt will be created in the folder main/submain/Tutorial. And the sample.txt file will have the text of “Hello World”." }, { "code": null, "e": 136215, "s": 136025, "text": "The Groovy shell known as groovysh can be easily used to evaluate groovy expressions, define classes and run simple programs. The command line shell gets installed when Groovy is installed." }, { "code": null, "e": 136276, "s": 136215, "text": "Following are the command line options available in Groovy −" }, { "code": null, "e": 136456, "s": 136276, "text": "The following snapshot shows a simple example of an expression being executed in the Groovy shell. In the following example we are just printing “Hello World” in the groovy shell." }, { "code": null, "e": 136812, "s": 136456, "text": "It is very easy to define a class in the command prompt, create a new object and invoke a method on the class. The following example shows how this can be implemented. In the following example, we are creating a simple Student class with a simple method. In the command prompt itself, we are creating an object of the class and calling the Display method." }, { "code": null, "e": 137142, "s": 136812, "text": "It is very easy to define a method in the command prompt and invoke the method. Note that the method is defined using the def type. Also note that we have included a parameter called name which then gets substituted with the actual value when the Display method is called. The following example shows how this can be implemented." }, { "code": null, "e": 137290, "s": 137142, "text": "The shell has a number of different commands, which provide rich access to the shell’s environment. Following is the list of them and what they do." }, { "code": null, "e": 137296, "s": 137290, "text": ":help" }, { "code": null, "e": 137328, "s": 137296, "text": "(:h ) Display this help message" }, { "code": null, "e": 137330, "s": 137328, "text": "?" }, { "code": null, "e": 137352, "s": 137330, "text": "(:? ) Alias to: :help" }, { "code": null, "e": 137358, "s": 137352, "text": ":exit" }, { "code": null, "e": 137379, "s": 137358, "text": "(:x ) Exit the shell" }, { "code": null, "e": 137385, "s": 137379, "text": ":quit" }, { "code": null, "e": 137407, "s": 137385, "text": "(:q ) Alias to: :exit" }, { "code": null, "e": 137414, "s": 137407, "text": "import" }, { "code": null, "e": 137454, "s": 137414, "text": "(:i ) Import a class into the namespace" }, { "code": null, "e": 137463, "s": 137454, "text": ":display" }, { "code": null, "e": 137496, "s": 137463, "text": "(:d ) Display the current buffer" }, { "code": null, "e": 137503, "s": 137496, "text": ":clear" }, { "code": null, "e": 137555, "s": 137503, "text": "(:c ) Clear the buffer and reset the prompt counter" }, { "code": null, "e": 137561, "s": 137555, "text": ":show" }, { "code": null, "e": 137602, "s": 137561, "text": "(:S ) Show variables, classes or imports" }, { "code": null, "e": 137611, "s": 137602, "text": ":inspect" }, { "code": null, "e": 137683, "s": 137611, "text": "(:n ) Inspect a variable or the last result with the GUI object browser" }, { "code": null, "e": 137690, "s": 137683, "text": ":purge" }, { "code": null, "e": 137745, "s": 137690, "text": "(:p ) Purge variables, classes, imports or preferences" }, { "code": null, "e": 137751, "s": 137745, "text": ":edit" }, { "code": null, "e": 137781, "s": 137751, "text": "(:e ) Edit the current buffer" }, { "code": null, "e": 137787, "s": 137781, "text": ":load" }, { "code": null, "e": 137828, "s": 137787, "text": "(:l ) Load a file or URL into the buffer" }, { "code": null, "e": 137830, "s": 137828, "text": "." }, { "code": null, "e": 137852, "s": 137830, "text": "(:. ) Alias to: :load" }, { "code": null, "e": 137858, "s": 137852, "text": ".save" }, { "code": null, "e": 137898, "s": 137858, "text": "(:s ) Save the current buffer to a file" }, { "code": null, "e": 137906, "s": 137898, "text": ".record" }, { "code": null, "e": 137949, "s": 137906, "text": "(:r ) Record the current session to a file" }, { "code": null, "e": 137956, "s": 137949, "text": ":alias" }, { "code": null, "e": 137978, "s": 137956, "text": "(:a ) Create an alias" }, { "code": null, "e": 137983, "s": 137978, "text": ":set" }, { "code": null, "e": 138015, "s": 137983, "text": "(:= ) Set (or list) preferences" }, { "code": null, "e": 138025, "s": 138015, "text": ":register" }, { "code": null, "e": 138070, "s": 138025, "text": "(:rc) Registers a new command with the shell" }, { "code": null, "e": 138075, "s": 138070, "text": ":doc" }, { "code": null, "e": 138140, "s": 138075, "text": "(:D ) Opens a browser window displaying the doc for the argument" }, { "code": null, "e": 138149, "s": 138140, "text": ":history" }, { "code": null, "e": 138200, "s": 138149, "text": "(:H ) Display, manage and recall edit-line history" }, { "code": null, "e": 138615, "s": 138200, "text": "The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods." }, { "code": null, "e": 138989, "s": 138615, "text": "JUnit is an open-source testing framework that is the accepted industry standard for the automated unit testing of Java code. Fortunately, the JUnit framework can be easily used for testing Groovy classes. All that is required is to extend the GroovyTestCase class that is part of the standard Groovy environment. The Groovy test case class is based on the Junit test case." }, { "code": null, "e": 139069, "s": 138989, "text": "Let assume we have the following class defined in a an application class file −" }, { "code": null, "e": 139345, "s": 139069, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.name = \"Joe\";\n mst.ID = 1;\n println(mst.Display())\n } \n} \n \npublic class Student {\n String name;\n int ID;\n\t\n String Display() {\n return name +ID;\n } \n}" }, { "code": null, "e": 139393, "s": 139345, "text": "The output of the above program is given below." }, { "code": null, "e": 139399, "s": 139393, "text": "Joe1\n" }, { "code": null, "e": 139585, "s": 139399, "text": "And now suppose we wanted to write a test case for the Student class. A typical test case would look like the one below. The following points need to be noted about the following code −" }, { "code": null, "e": 139638, "s": 139585, "text": "The test case class extends the GroovyTestCase class" }, { "code": null, "e": 139732, "s": 139638, "text": "We are using the assert statement to ensure that the Display method returns the right string." }, { "code": null, "e": 139934, "s": 139732, "text": "class StudentTest extends GroovyTestCase {\n void testDisplay() {\n def stud = new Student(name : 'Joe', ID : '1')\n def expected = 'Joe1'\n assertToString(stud.Display(), expected)\n }\n}" }, { "code": null, "e": 140288, "s": 139934, "text": "Normally as the number of unit tests increases, it would become difficult to keep on executing all the test cases one by one. Hence Groovy provides a facility to create a test suite that can encapsulate all test cases into one logicial unit. The following codesnippet shows how this can be achieved. The following things should be noted about the code −" }, { "code": null, "e": 140356, "s": 140288, "text": "The GroovyTestSuite is used to encapsulate all test cases into one." }, { "code": null, "e": 140424, "s": 140356, "text": "The GroovyTestSuite is used to encapsulate all test cases into one." }, { "code": null, "e": 140599, "s": 140424, "text": "In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing." }, { "code": null, "e": 140774, "s": 140599, "text": "In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing." }, { "code": null, "e": 141123, "s": 140774, "text": "import groovy.util.GroovyTestSuite \nimport junit.framework.Test \nimport junit.textui.TestRunner \n\nclass AllTests { \n static Test suite() { \n def allTests = new GroovyTestSuite() \n allTests.addTestSuite(StudentTest.class) \n allTests.addTestSuite(EmployeeTest.class) \n return allTests \n } \n} \n\nTestRunner.run(AllTests.suite())" }, { "code": null, "e": 141372, "s": 141123, "text": "Groovy’s template engine operates like a mail merge (the automatic addition of names and addresses from a database to letters and envelopes in order to facilitate sending mail, especially advertising, to many addresses) but it is much more general." }, { "code": null, "e": 141590, "s": 141372, "text": "If you take the simple example below, we are first defining a name variable to hold the string “Groovy”. In the println statement, we are using $ symbol to define a parameter or template where a value can be inserted." }, { "code": null, "e": 141652, "s": 141590, "text": "def name = \"Groovy\" \nprintln \"This Tutorial is about ${name}\"" }, { "code": null, "e": 141836, "s": 141652, "text": "If the above code is executed in groovy, the following output will be shown. The output clearly shows that the $name was replaced by the value which was assigned by the def statement." }, { "code": null, "e": 142165, "s": 141836, "text": "Following is an example of the SimpleTemplateEngine that allows you to use JSP-like scriptlets and EL expressions in your template in order to generate parametrized text. The templating engine allows you to bind a list of parameters and their values so that they can be replaced in the string which has the defined placeholders." }, { "code": null, "e": 142459, "s": 142165, "text": "def text ='This Tutorial focuses on $TutorialName. In this tutorial you will learn \n\nabout $Topic' \n\ndef binding = [\"TutorialName\":\"Groovy\", \"Topic\":\"Templates\"] \ndef engine = new groovy.text.SimpleTemplateEngine() \ndef template = engine.createTemplate(text).make(binding) \n\nprintln template" }, { "code": null, "e": 142536, "s": 142459, "text": "If the above code is executed in groovy, the following output will be shown." }, { "code": null, "e": 142880, "s": 142536, "text": "Let’s now use the templating feature for an XML file. As a first step let’s add the following code to a file called Student.template. In the following file you will notice that we have not added the actual values for the elements, but placeholders. So $name,$is and $subject are all put as placeholders which will need to replaced at runtime." }, { "code": null, "e": 142980, "s": 142880, "text": "<Student> \n <name>${name}</name> \n <ID>${id}</ID> \n <subject>${subject}</subject> \n</Student>" }, { "code": null, "e": 143173, "s": 142980, "text": "Now let’s add our Groovy script code to add the functionality which can be used to replace the above template with actual values. The following things should be noted about the following code." }, { "code": null, "e": 143365, "s": 143173, "text": "The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values." }, { "code": null, "e": 143557, "s": 143365, "text": "The mapping of the place-holders to actual values is done through a binding and a SimpleTemplateEngine. The binding is a Map with the place-holders as keys and the replacements as the values." }, { "code": null, "e": 143855, "s": 143557, "text": "import groovy.text.* \nimport java.io.* \n\ndef file = new File(\"D:/Student.template\") \ndef binding = ['name' : 'Joe', 'id' : 1, 'subject' : 'Physics']\n\t\t\t\t \ndef engine = new SimpleTemplateEngine() \ndef template = engine.createTemplate(file) \ndef writable = template.make(binding) \n\nprintln writable" }, { "code": null, "e": 144035, "s": 143855, "text": "If the above code is executed in groovy, the following output will be shown. From the output it can be seen that the values are successfully replaced in the relevant placeholders." }, { "code": null, "e": 144124, "s": 144035, "text": "<Student> \n <name>Joe</name> \n <ID>1</ID> \n <subject>Physics</subject> \n</Student>" }, { "code": null, "e": 144430, "s": 144124, "text": "The StreamingTemplateEngine engine is another templating engine available in Groovy. This is kind of equivalent to the SimpleTemplateEngine, but creates the template using writeable closures making it more scalable for large templates. Specifically this template engine can handle strings larger than 64k." }, { "code": null, "e": 144496, "s": 144430, "text": "Following is an example of how StreamingTemplateEngine are used −" }, { "code": null, "e": 144801, "s": 144496, "text": "def text = '''This Tutorial is <% out.print TutorialName %> The Topic name \n\nis ${TopicName}''' \ndef template = new groovy.text.StreamingTemplateEngine().createTemplate(text)\n \ndef binding = [TutorialName : \"Groovy\", TopicName : \"Templates\",]\nString response = template.make(binding) \nprintln(response)" }, { "code": null, "e": 144878, "s": 144801, "text": "If the above code is executed in groovy, the following output will be shown." }, { "code": null, "e": 144931, "s": 144878, "text": "This Tutorial is Groovy The Topic name is Templates\n" }, { "code": null, "e": 145180, "s": 144931, "text": "The XmlTemplateEngine is used in templating scenarios where both the template source and the expected output are intended to be XML. Templates use the normal ${expression} and $variable notations to insert an arbitrary expression into the template." }, { "code": null, "e": 145238, "s": 145180, "text": "Following is an example of how XMLTemplateEngine is used." }, { "code": null, "e": 145671, "s": 145238, "text": "def binding = [StudentName: 'Joe', id: 1, subject: 'Physics'] \ndef engine = new groovy.text.XmlTemplateEngine() \n\ndef text = '''\\\n <document xmlns:gsp='http://groovy.codehaus.org/2005/gsp'>\n <Student>\n <name>${StudentName}</name>\n <ID>${id}</ID>\n <subject>${subject}</subject>\n </Student>\n </document> \n''' \n\ndef template = engine.createTemplate(text).make(binding) \nprintln template.toString()" }, { "code": null, "e": 145747, "s": 145671, "text": "If the above code is executed in groovy, the following output will be shown" }, { "code": null, "e": 145792, "s": 145747, "text": " Joe\n \n \n 1\n \n \n Physics \n" }, { "code": null, "e": 145913, "s": 145792, "text": "Meta object programming or MOP can be used to invoke methods dynamically and also create classes and methods on the fly." }, { "code": null, "e": 146114, "s": 145913, "text": "So what does this mean? Let’s consider a class called Student, which is kind of an empty class with no member variables or methods. Suppose if you had to invoke the following statements on this class." }, { "code": null, "e": 146190, "s": 146114, "text": "Def myStudent = new Student() \nmyStudent.Name = ”Joe”; \nmyStudent.Display()" }, { "code": null, "e": 146340, "s": 146190, "text": "Now in meta object programming, even though the class does not have the member variable Name or the method Display(), the above code will still work." }, { "code": null, "e": 146544, "s": 146340, "text": "How can this work? Well, for this to work out, one has to implement the GroovyInterceptable interface to hook into the execution process of Groovy. Following are the methods available for this interface." }, { "code": null, "e": 146854, "s": 146544, "text": "Public interface GroovyInterceptable { \n Public object invokeMethod(String methodName, Object args) \n Public object getproperty(String propertyName) \n Public object setProperty(String propertyName, Object newValue) \n Public MetaClass getMetaClass() \n Public void setMetaClass(MetaClass metaClass) \n}" }, { "code": null, "e": 147020, "s": 146854, "text": "So in the above interface description, suppose if you had to implement the invokeMethod(), it would be called for every method which either exists or does not exist." }, { "code": null, "e": 147185, "s": 147020, "text": "So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code." }, { "code": null, "e": 147253, "s": 147185, "text": "The class Student has no member variable called Name or ID defined." }, { "code": null, "e": 147321, "s": 147253, "text": "The class Student has no member variable called Name or ID defined." }, { "code": null, "e": 147385, "s": 147321, "text": "The class Student implements the GroovyInterceptable interface." }, { "code": null, "e": 147449, "s": 147385, "text": "The class Student implements the GroovyInterceptable interface." }, { "code": null, "e": 147581, "s": 147449, "text": "There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly." }, { "code": null, "e": 147713, "s": 147581, "text": "There is a parameter called dynamicProps which will be used to hold the value of the member variables which are created on the fly." }, { "code": null, "e": 147844, "s": 147713, "text": "The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime." }, { "code": null, "e": 147975, "s": 147844, "text": "The methods getproperty and setproperty have been implemented to get and set the values of the property’s of the class at runtime." }, { "code": null, "e": 148395, "s": 147975, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.Name = \"Joe\";\n mst.ID = 1;\n\t\t\n println(mst.Name);\n println(mst.ID);\n }\n}\n\nclass Student implements GroovyInterceptable { \n protected dynamicProps=[:]\n\t\n void setProperty(String pName,val) {\n dynamicProps[pName] = val\n }\n \n def getProperty(String pName) {\n dynamicProps[pName]\n } \n} " }, { "code": null, "e": 148439, "s": 148395, "text": "The output of the following code would be −" }, { "code": null, "e": 148447, "s": 148439, "text": "Joe \n1\n" }, { "code": null, "e": 148613, "s": 148447, "text": "So let’s look an example of how we can implement Meta Object Programming for missing Properties. The following keys things should be noted about the following code −" }, { "code": null, "e": 148738, "s": 148613, "text": "The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not." }, { "code": null, "e": 148863, "s": 148738, "text": "The class Student now implememts the invokeMethod method which gets called irrespective of whether the method exists or not." }, { "code": null, "e": 149417, "s": 148863, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.Name = \"Joe\";\n mst.ID = 1;\n\t\t\n println(mst.Name);\n println(mst.ID);\n mst.AddMarks();\n } \n}\n \nclass Student implements GroovyInterceptable {\n protected dynamicProps = [:] \n \n void setProperty(String pName, val) {\n dynamicProps[pName] = val\n } \n \n def getProperty(String pName) {\n dynamicProps[pName]\n }\n \n def invokeMethod(String name, Object args) {\n return \"called invokeMethod $name $args\"\n }\n}" }, { "code": null, "e": 149574, "s": 149417, "text": "The output of the following codewould be shown below. Note that there is no error of missing Method Exception even though the method Display does not exist." }, { "code": null, "e": 149583, "s": 149574, "text": "Joe \n1 \n" }, { "code": null, "e": 149877, "s": 149583, "text": "This functionality is related to the MetaClass implementation. In the default implementation you can access fields without invoking their getters and setters. The following example shows how by using the metaClass function we are able to change the value of the private variables in the class." }, { "code": null, "e": 150196, "s": 149877, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n println mst.getName()\n mst.metaClass.setAttribute(mst, 'name', 'Mark')\n println mst.getName()\n } \n} \n\nclass Student {\n private String name = \"Joe\";\n\t\n public String getName() {\n return this.name;\n } \n}" }, { "code": null, "e": 150240, "s": 150196, "text": "The output of the following code would be −" }, { "code": null, "e": 150251, "s": 150240, "text": "Joe \nMark\n" }, { "code": null, "e": 150537, "s": 150251, "text": "Groovy supports the concept of methodMissing. This method differs from invokeMethod in that it is only invoked in case of a failed method dispatch, when no method can be found for the given name and/or the given arguments. The following example shows how the methodMissing can be used." }, { "code": null, "e": 151083, "s": 150537, "text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.Name = \"Joe\";\n mst.ID = 1;\n\t\t\n println(mst.Name);\n println(mst.ID);\n mst.AddMarks();\n } \n} \n\nclass Student implements GroovyInterceptable {\n protected dynamicProps = [:] \n \n void setProperty(String pName, val) {\n dynamicProps[pName] = val\n }\n \n def getProperty(String pName) {\n dynamicProps[pName]\n }\n \n def methodMissing(String name, def args) { \n println \"Missing method\"\n } \n}" } ]
2D vector in C++ with user defined size
A vector of a vector is called 2D vector. Begin Declare a variable v to the 2D vector type. Initialize values to the vector v. Print “the 2D vector is:”. for (int i = 0; i < v.size(); i++) for (int j = 0; j < v[i].size(); j++) print the value of 2D vector v[i][j]. End. Live Demo #include <iostream> #include <vector> //header file for 2D vector in C++ using namespace std; int main() { vector<vector<int> > v{ { 4,5, 3, 10 }, // initializing 2D vector with values. { 2, 7, 11 }, { 3, 2, 1, 12 } }; cout<<"the 2D vector is:"<<endl; for (int i = 0; i < v.size(); i++) { // printing the 2D vector. for (int j = 0; j < v[i].size(); j++) cout << v[i][j] << " "; cout << endl; } return 0; } the 2D vector is: 4 5 3 10 2 7 11 3 2 1 12
[ { "code": null, "e": 1229, "s": 1187, "text": "A vector of a vector is called 2D vector." }, { "code": null, "e": 1484, "s": 1229, "text": "Begin\n Declare a variable v to the 2D vector type.\n Initialize values to the vector v.\n Print “the 2D vector is:”.\n for (int i = 0; i < v.size(); i++)\n for (int j = 0; j < v[i].size(); j++)\n print the value of 2D vector v[i][j].\nEnd." }, { "code": null, "e": 1495, "s": 1484, "text": " Live Demo" }, { "code": null, "e": 1940, "s": 1495, "text": "#include <iostream>\n#include <vector> //header file for 2D vector in C++\nusing namespace std;\nint main() {\n vector<vector<int> > v{ { 4,5, 3, 10 }, // initializing 2D vector with values.\n { 2, 7, 11 },\n { 3, 2, 1, 12 } };\n cout<<\"the 2D vector is:\"<<endl;\n for (int i = 0; i < v.size(); i++) { // printing the 2D vector.\n for (int j = 0; j < v[i].size(); j++)\n cout << v[i][j] << \" \";\n cout << endl;\n }\n return 0;\n}" }, { "code": null, "e": 1985, "s": 1940, "text": "the 2D vector is: \n4 5 3 10\n2 7 11 \n3 2 1 12" } ]
Tri-Surface Plot in Python using Matplotlib
11 Nov, 2021 A Tri-Surface Plot is a type of surface plot, created by triangulation of compact surfaces of finite number of triangles which cover the whole surface in a manner that each and every point on the surface is in triangle. The intersection of any two triangles results in void or a common edge or vertex. This type of plot is created where the evenly sampled grids are restrictive and inconvenient to plot. Generally Tri-Surface plots are created by calling ax.plot_trisurf() function of matplotlib library. Some of the attributes of the function are listed below: Example 1: Let’s create a basic Tri-Surface plot using the ax.plot_trisurf() function. Python3 # Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetz = np.linspace(0, 50000, 100)x = np.sin(z)y = np.cos(z) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating plotax.plot_trisurf(x, y, z, linewidth = 0.2, antialiased = True); # show plotplt.show() Output : Example 2 : For better understanding Let’s take another example. Python3 # Import librariesfrom mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np # Creating radii and anglesr = np.linspace(0.125, 1.0, 100) a = np.linspace(0, 2 * np.pi, 100, endpoint = False) # Repeating all angles for every radius a = np.repeat(a[..., np.newaxis], 100, axis = 1) # Creating datasetx = np.append(0, (r * np.cos(a))) y = np.append(0, (r * np.sin(a))) z = (np.sin(x ** 4) + np.cos(y ** 4)) # Creating figurefig = plt.figure(figsize =(16, 9)) ax = plt.axes(projection ='3d') # Creating color mapmy_cmap = plt.get_cmap('hot') # Creating plottrisurf = ax.plot_trisurf(x, y, z, cmap = my_cmap, linewidth = 0.2, antialiased = True, edgecolor = 'grey') fig.colorbar(trisurf, ax = ax, shrink = 0.5, aspect = 5)ax.set_title('Tri-Surface plot') # Adding labelsax.set_xlabel('X-axis', fontweight ='bold')ax.set_ylabel('Y-axis', fontweight ='bold')ax.set_zlabel('Z-axis', fontweight ='bold') # show plotplt.show() Output: singghakshay anikakapoor Matplotlib Artist-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Nov, 2021" }, { "code": null, "e": 614, "s": 52, "text": "A Tri-Surface Plot is a type of surface plot, created by triangulation of compact surfaces of finite number of triangles which cover the whole surface in a manner that each and every point on the surface is in triangle. The intersection of any two triangles results in void or a common edge or vertex. This type of plot is created where the evenly sampled grids are restrictive and inconvenient to plot. Generally Tri-Surface plots are created by calling ax.plot_trisurf() function of matplotlib library. Some of the attributes of the function are listed below:" }, { "code": null, "e": 702, "s": 614, "text": "Example 1: Let’s create a basic Tri-Surface plot using the ax.plot_trisurf() function. " }, { "code": null, "e": 710, "s": 702, "text": "Python3" }, { "code": "# Import librariesfrom mpl_toolkits import mplot3dimport numpy as npimport matplotlib.pyplot as plt # Creating datasetz = np.linspace(0, 50000, 100)x = np.sin(z)y = np.cos(z) # Creating figurefig = plt.figure(figsize =(14, 9))ax = plt.axes(projection ='3d') # Creating plotax.plot_trisurf(x, y, z, linewidth = 0.2, antialiased = True); # show plotplt.show()", "e": 1099, "s": 710, "text": null }, { "code": null, "e": 1109, "s": 1099, "text": "Output : " }, { "code": null, "e": 1175, "s": 1109, "text": "Example 2 : For better understanding Let’s take another example. " }, { "code": null, "e": 1183, "s": 1175, "text": "Python3" }, { "code": "# Import librariesfrom mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np # Creating radii and anglesr = np.linspace(0.125, 1.0, 100) a = np.linspace(0, 2 * np.pi, 100, endpoint = False) # Repeating all angles for every radius a = np.repeat(a[..., np.newaxis], 100, axis = 1) # Creating datasetx = np.append(0, (r * np.cos(a))) y = np.append(0, (r * np.sin(a))) z = (np.sin(x ** 4) + np.cos(y ** 4)) # Creating figurefig = plt.figure(figsize =(16, 9)) ax = plt.axes(projection ='3d') # Creating color mapmy_cmap = plt.get_cmap('hot') # Creating plottrisurf = ax.plot_trisurf(x, y, z, cmap = my_cmap, linewidth = 0.2, antialiased = True, edgecolor = 'grey') fig.colorbar(trisurf, ax = ax, shrink = 0.5, aspect = 5)ax.set_title('Tri-Surface plot') # Adding labelsax.set_xlabel('X-axis', fontweight ='bold')ax.set_ylabel('Y-axis', fontweight ='bold')ax.set_zlabel('Z-axis', fontweight ='bold') # show plotplt.show()", "e": 2276, "s": 1183, "text": null }, { "code": null, "e": 2285, "s": 2276, "text": "Output: " }, { "code": null, "e": 2300, "s": 2287, "text": "singghakshay" }, { "code": null, "e": 2312, "s": 2300, "text": "anikakapoor" }, { "code": null, "e": 2336, "s": 2312, "text": "Matplotlib Artist-class" }, { "code": null, "e": 2354, "s": 2336, "text": "Python-matplotlib" }, { "code": null, "e": 2361, "s": 2354, "text": "Python" } ]
Python – All possible space joins in String
22 Apr, 2020 Sometimes, while working with Python Strings, we can have a problem in which we need to construct strings with single space at every possible word ending. This kind of application can occur in domains in which we need to perform testing. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + join()This is brute force way in which this task can be performed. In this, we perform the task of forming all possible joins using join() and task of iterating through all strings using loop. # Python3 code to demonstrate working of # All possible space joins in String# Using loop + join() # initializing stringtest_str = 'Geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # All possible space joins in String# Using loop + join()res = []temp = test_str.split(' ') strt_idx = 0lst_idx = len(temp)for idx in range(len(temp)-1): frst_wrd = "".join(temp[strt_idx : idx + 1]) scnd_wrd = "".join(temp[idx + 1 : lst_idx]) res.append(frst_wrd + " " + scnd_wrd) # printing result print("All possible spaces List : " + str(res)) The original string is : Geeksforgeeks is best for geeksAll possible spaces List : [‘Geeksforgeeks isbestforgeeks’, ‘Geeksforgeeksis bestforgeeks’, ‘Geeksforgeeksisbest forgeeks’, ‘Geeksforgeeksisbestfor geeks’] Method #2 : Using enumerate() + join() + combinations()The combination of above methods can be used to perform this task. In this, we perform the task of extracting combinations using combinations(). This prints all combinations of all occurrences of spaces rather than just one as in above method. # Python3 code to demonstrate working of # All possible space joins in String# Using enumerate() + join() + combinations()import itertools # initializing stringtest_str = 'Geeksforgeeks is best for geeks' # printing original stringprint("The original string is : " + str(test_str)) # All possible space joins in String# Using enumerate() + join() + combinations()res = []temp = test_str.split(' ')N = range(len(temp) - 1)for idx in N: for sub in itertools.combinations(N, idx + 1): temp1 = [val + " " if i in sub else val for i, val in enumerate(temp)] temp2 = "".join(temp1) res.append(temp2) # printing result print("All possible spaces List : " + str(res)) The original string is : Geeksforgeeks is best for geeksAll possible spaces List : [‘Geeksforgeeks isbestforgeeks’, ‘Geeksforgeeksis bestforgeeks’, ‘Geeksforgeeksisbest forgeeks’, ‘Geeksforgeeksisbestfor geeks’, ‘Geeksforgeeks is bestforgeeks’, ‘Geeksforgeeks isbest forgeeks’, ‘Geeksforgeeks isbestfor geeks’, ‘Geeksforgeeksis best forgeeks’, ‘Geeksforgeeksis bestfor geeks’, ‘Geeksforgeeksisbest for geeks’, ‘Geeksforgeeks is best forgeeks’, ‘Geeksforgeeks is bestfor geeks’, ‘Geeksforgeeks isbest for geeks’, ‘Geeksforgeeksis best for geeks’, ‘Geeksforgeeks is best for geeks’] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 329, "s": 28, "text": "Sometimes, while working with Python Strings, we can have a problem in which we need to construct strings with single space at every possible word ending. This kind of application can occur in domains in which we need to perform testing. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 547, "s": 329, "text": "Method #1 : Using loop + join()This is brute force way in which this task can be performed. In this, we perform the task of forming all possible joins using join() and task of iterating through all strings using loop." }, { "code": "# Python3 code to demonstrate working of # All possible space joins in String# Using loop + join() # initializing stringtest_str = 'Geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # All possible space joins in String# Using loop + join()res = []temp = test_str.split(' ') strt_idx = 0lst_idx = len(temp)for idx in range(len(temp)-1): frst_wrd = \"\".join(temp[strt_idx : idx + 1]) scnd_wrd = \"\".join(temp[idx + 1 : lst_idx]) res.append(frst_wrd + \" \" + scnd_wrd) # printing result print(\"All possible spaces List : \" + str(res)) ", "e": 1176, "s": 547, "text": null }, { "code": null, "e": 1388, "s": 1176, "text": "The original string is : Geeksforgeeks is best for geeksAll possible spaces List : [‘Geeksforgeeks isbestforgeeks’, ‘Geeksforgeeksis bestforgeeks’, ‘Geeksforgeeksisbest forgeeks’, ‘Geeksforgeeksisbestfor geeks’]" }, { "code": null, "e": 1689, "s": 1390, "text": "Method #2 : Using enumerate() + join() + combinations()The combination of above methods can be used to perform this task. In this, we perform the task of extracting combinations using combinations(). This prints all combinations of all occurrences of spaces rather than just one as in above method." }, { "code": "# Python3 code to demonstrate working of # All possible space joins in String# Using enumerate() + join() + combinations()import itertools # initializing stringtest_str = 'Geeksforgeeks is best for geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # All possible space joins in String# Using enumerate() + join() + combinations()res = []temp = test_str.split(' ')N = range(len(temp) - 1)for idx in N: for sub in itertools.combinations(N, idx + 1): temp1 = [val + \" \" if i in sub else val for i, val in enumerate(temp)] temp2 = \"\".join(temp1) res.append(temp2) # printing result print(\"All possible spaces List : \" + str(res)) ", "e": 2382, "s": 1689, "text": null }, { "code": null, "e": 2963, "s": 2382, "text": "The original string is : Geeksforgeeks is best for geeksAll possible spaces List : [‘Geeksforgeeks isbestforgeeks’, ‘Geeksforgeeksis bestforgeeks’, ‘Geeksforgeeksisbest forgeeks’, ‘Geeksforgeeksisbestfor geeks’, ‘Geeksforgeeks is bestforgeeks’, ‘Geeksforgeeks isbest forgeeks’, ‘Geeksforgeeks isbestfor geeks’, ‘Geeksforgeeksis best forgeeks’, ‘Geeksforgeeksis bestfor geeks’, ‘Geeksforgeeksisbest for geeks’, ‘Geeksforgeeks is best forgeeks’, ‘Geeksforgeeks is bestfor geeks’, ‘Geeksforgeeks isbest for geeks’, ‘Geeksforgeeksis best for geeks’, ‘Geeksforgeeks is best for geeks’]" }, { "code": null, "e": 2986, "s": 2963, "text": "Python string-programs" }, { "code": null, "e": 2993, "s": 2986, "text": "Python" }, { "code": null, "e": 3009, "s": 2993, "text": "Python Programs" }, { "code": null, "e": 3107, "s": 3009, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3139, "s": 3107, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3166, "s": 3139, "text": "Python Classes and Objects" }, { "code": null, "e": 3197, "s": 3166, "text": "Python | os.path.join() method" }, { "code": null, "e": 3220, "s": 3197, "text": "Introduction To PYTHON" }, { "code": null, "e": 3241, "s": 3220, "text": "Python OOPs Concepts" }, { "code": null, "e": 3263, "s": 3241, "text": "Defaultdict in Python" }, { "code": null, "e": 3302, "s": 3263, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3340, "s": 3302, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3389, "s": 3340, "text": "Python | Convert string dictionary to dictionary" } ]
Julia fractal in Python
03 Oct, 2018 Introduction to julia setIn the context of complex dynamics, a topic of mathematics, the Julia set and the Fatou set are two complementary sets (Julia ‘laces’ and Fatou ‘dusts’) defined from a function. Informally, the Fatou set of the function consists of values with the property that all nearby values behave similarly under repeated iteration of the function, and the Julia set consists of values such that an arbitrarily small perturbation can cause drastic changes in the sequence of iterated function values. Thus the behavior of the function on the Fatou set is ‘regular’, while on the Julia set its behavior is ‘chaotic’.The Julia set of a function f is commonly denoted J(f), and the Fatou set is denoted F(f). These sets are named after the French mathematicians Gaston Julia and Pierre Fatou whose work began the study of complex dynamics during the early 20th century. [Source Wiki] The equation to generate Julia fractal is: where c is a complex parameter. The Julia set for this system is the subset of the complex plane given by: So let’s now try to create one of the fractal in the above image. To do so we need the Pillow module of python which makes it easy to dealt with images and stuff. To install pillow through pip type the following command in the command prompt. pip install Pillow Now using this library to create the fractal image. # Python code for Julia Fractalfrom PIL import Image # driver functionif __name__ == "__main__": # setting the width, height and zoom # of the image to be created w, h, zoom = 1920,1080,1 # creating the new image in RGB mode bitmap = Image.new("RGB", (w, h), "white") # Allocating the storage for the image and # loading the pixel data. pix = bitmap.load() # setting up the variables according to # the equation to create the fractal cX, cY = -0.7, 0.27015 moveX, moveY = 0.0, 0.0 maxIter = 255 for x in range(w): for y in range(h): zx = 1.5*(x - w/2)/(0.5*zoom*w) + moveX zy = 1.0*(y - h/2)/(0.5*zoom*h) + moveY i = maxIter while zx*zx + zy*zy < 4 and i > 1: tmp = zx*zx - zy*zy + cX zy,zx = 2.0*zx*zy + cY, tmp i -= 1 # convert byte to RGB (3 bytes), kinda # magic to get nice colors pix[x,y] = (i << 21) + (i << 10) + i*8 # to display the created fractal bitmap.show() Output: Also refer to this video by numberphile for more information.Filled Julia Set - YouTubeNumberphile2242K subscribersFilled Julia SetWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=oCkQ7WK7vuY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> After understanding the code try to draw the other fractals by changing the value of the variables and post your github link to the code down in the comment section and i’ll be happy to help you if any error comes up. This article is contributed by Subhajit Saha. 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. Fractal Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Oct, 2018" }, { "code": null, "e": 950, "s": 54, "text": "Introduction to julia setIn the context of complex dynamics, a topic of mathematics, the Julia set and the Fatou set are two complementary sets (Julia ‘laces’ and Fatou ‘dusts’) defined from a function. Informally, the Fatou set of the function consists of values with the property that all nearby values behave similarly under repeated iteration of the function, and the Julia set consists of values such that an arbitrarily small perturbation can cause drastic changes in the sequence of iterated function values. Thus the behavior of the function on the Fatou set is ‘regular’, while on the Julia set its behavior is ‘chaotic’.The Julia set of a function f is commonly denoted J(f), and the Fatou set is denoted F(f). These sets are named after the French mathematicians Gaston Julia and Pierre Fatou whose work began the study of complex dynamics during the early 20th century. [Source Wiki]" }, { "code": null, "e": 993, "s": 950, "text": "The equation to generate Julia fractal is:" }, { "code": null, "e": 1100, "s": 993, "text": "where c is a complex parameter. The Julia set for this system is the subset of the complex plane given by:" }, { "code": null, "e": 1166, "s": 1100, "text": "So let’s now try to create one of the fractal in the above image." }, { "code": null, "e": 1263, "s": 1166, "text": "To do so we need the Pillow module of python which makes it easy to dealt with images and stuff." }, { "code": null, "e": 1343, "s": 1263, "text": "To install pillow through pip type the following command in the command prompt." }, { "code": null, "e": 1362, "s": 1343, "text": "pip install Pillow" }, { "code": null, "e": 1414, "s": 1362, "text": "Now using this library to create the fractal image." }, { "code": "# Python code for Julia Fractalfrom PIL import Image # driver functionif __name__ == \"__main__\": # setting the width, height and zoom # of the image to be created w, h, zoom = 1920,1080,1 # creating the new image in RGB mode bitmap = Image.new(\"RGB\", (w, h), \"white\") # Allocating the storage for the image and # loading the pixel data. pix = bitmap.load() # setting up the variables according to # the equation to create the fractal cX, cY = -0.7, 0.27015 moveX, moveY = 0.0, 0.0 maxIter = 255 for x in range(w): for y in range(h): zx = 1.5*(x - w/2)/(0.5*zoom*w) + moveX zy = 1.0*(y - h/2)/(0.5*zoom*h) + moveY i = maxIter while zx*zx + zy*zy < 4 and i > 1: tmp = zx*zx - zy*zy + cX zy,zx = 2.0*zx*zy + cY, tmp i -= 1 # convert byte to RGB (3 bytes), kinda # magic to get nice colors pix[x,y] = (i << 21) + (i << 10) + i*8 # to display the created fractal bitmap.show()", "e": 2490, "s": 1414, "text": null }, { "code": null, "e": 2498, "s": 2490, "text": "Output:" }, { "code": null, "e": 3376, "s": 2498, "text": "Also refer to this video by numberphile for more information.Filled Julia Set - YouTubeNumberphile2242K subscribersFilled Julia SetWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=oCkQ7WK7vuY\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 3594, "s": 3376, "text": "After understanding the code try to draw the other fractals by changing the value of the variables and post your github link to the code down in the comment section and i’ll be happy to help you if any error comes up." }, { "code": null, "e": 3895, "s": 3594, "text": "This article is contributed by Subhajit Saha. 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": 4020, "s": 3895, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4028, "s": 4020, "text": "Fractal" }, { "code": null, "e": 4035, "s": 4028, "text": "Python" } ]
tuple() Function in Python
23 Oct, 2020 The tuple() function is a built-in function in Python that can be used to create a tuple. A tuple is an immutable sequence type. Syntax: tuple(iterable) Parameters: This function accepts a single parameter iterable (optional). It is an iterable(list, range etc..) or an iterator object. If an iterable is passed, the corresponding tuple is created. If the iterable is not passed, empty tuple is created . Returns: It does not returns any-thing but creates a tuple. Error and Exception: It returns a TypeError, if an iterable is not passed. Below programs illustrate tuple() function in Python:Program 1: Program demonstrating the use of tuple() function # Python3 program demonstrating# the use of tuple() function # when parameter is not passedtuple1 = tuple()print(tuple1) # when an iterable(e.g., list) is passedlist1= [ 1, 2, 3, 4 ] tuple2 = tuple(list1)print(tuple2) # when an iterable(e.g., dictionary) is passeddict = { 1 : 'one', 2 : 'two' } tuple3 = tuple(dict)print(tuple3) # when an iterable(e.g., string) is passedstring = "geeksforgeeks" tuple4 = tuple(string)print(tuple4) Output: () (1, 2, 3, 4) (1, 2) ('g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's') Program 2: Program demonstrating the TypeError # Python3 program demonstrating # the TypeError in tuple() function # Error when a non-iterable is passedtuple1 = tuple(1) print(tuple1) Output: Traceback (most recent call last): File "/home/eaf759787ade3942e8b9b436d6c60ab3.py", line 5, in tuple1=tuple(1) TypeError: 'int' object is not iterable Akanksha_Rai Python-Functions python-tuple Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Oct, 2020" }, { "code": null, "e": 142, "s": 52, "text": "The tuple() function is a built-in function in Python that can be used to create a tuple." }, { "code": null, "e": 181, "s": 142, "text": "A tuple is an immutable sequence type." }, { "code": null, "e": 189, "s": 181, "text": "Syntax:" }, { "code": null, "e": 208, "s": 189, "text": "tuple(iterable) \n" }, { "code": null, "e": 460, "s": 208, "text": "Parameters: This function accepts a single parameter iterable (optional). It is an iterable(list, range etc..) or an iterator object. If an iterable is passed, the corresponding tuple is created. If the iterable is not passed, empty tuple is created ." }, { "code": null, "e": 520, "s": 460, "text": "Returns: It does not returns any-thing but creates a tuple." }, { "code": null, "e": 595, "s": 520, "text": "Error and Exception: It returns a TypeError, if an iterable is not passed." }, { "code": null, "e": 709, "s": 595, "text": "Below programs illustrate tuple() function in Python:Program 1: Program demonstrating the use of tuple() function" }, { "code": "# Python3 program demonstrating# the use of tuple() function # when parameter is not passedtuple1 = tuple()print(tuple1) # when an iterable(e.g., list) is passedlist1= [ 1, 2, 3, 4 ] tuple2 = tuple(list1)print(tuple2) # when an iterable(e.g., dictionary) is passeddict = { 1 : 'one', 2 : 'two' } tuple3 = tuple(dict)print(tuple3) # when an iterable(e.g., string) is passedstring = \"geeksforgeeks\" tuple4 = tuple(string)print(tuple4)", "e": 1146, "s": 709, "text": null }, { "code": null, "e": 1154, "s": 1146, "text": "Output:" }, { "code": null, "e": 1244, "s": 1154, "text": "()\n(1, 2, 3, 4)\n(1, 2)\n('g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's')\n" }, { "code": null, "e": 1291, "s": 1244, "text": "Program 2: Program demonstrating the TypeError" }, { "code": "# Python3 program demonstrating # the TypeError in tuple() function # Error when a non-iterable is passedtuple1 = tuple(1) print(tuple1)", "e": 1429, "s": 1291, "text": null }, { "code": null, "e": 1437, "s": 1429, "text": "Output:" }, { "code": null, "e": 1597, "s": 1437, "text": "Traceback (most recent call last):\n File \"/home/eaf759787ade3942e8b9b436d6c60ab3.py\", line 5, in \n tuple1=tuple(1) \nTypeError: 'int' object is not iterable" }, { "code": null, "e": 1610, "s": 1597, "text": "Akanksha_Rai" }, { "code": null, "e": 1627, "s": 1610, "text": "Python-Functions" }, { "code": null, "e": 1640, "s": 1627, "text": "python-tuple" }, { "code": null, "e": 1647, "s": 1640, "text": "Python" } ]
The painter’s partition problem
03 Jun, 2022 We have to paint n boards of length {A1, A2...An}. There are k painters available and each takes 1 unit time to paint 1 unit of board. The problem is to find the minimum time to get this job done under the constraints that any painter will only paint continuous sections of boards, say board {2, 3, 4} or only board {1} or nothing but not board {2, 4, 5}. Examples: Input : k = 2, A = {10, 10, 10, 10} Output : 20. Here we can divide the boards into 2 equal sized partitions, so each painter gets 20 units of board and the total time taken is 20. Input : k = 2, A = {10, 20, 30, 40} Output : 60. Here we can divide first 3 boards for one painter and the last board for second painter. From the above examples, it is obvious that the strategy of dividing the boards into k equal partitions won’t work for all the cases. We can observe that the problem can be broken down into: Given an array A of non-negative integers and a positive integer k, we have to divide A into k of fewer partitions such that the maximum sum of the elements in a partition, overall partitions is minimized. So for the second example above, possible divisions are: * One partition: so time is 100. * Two partitions: (10) & (20, 30, 40), so time is 90. Similarly we can put the first divider after 20 (=> time 70) or 30 (=> time 60); so this means the minimum time: (100, 90, 70, 60) is 60. A brute force solution is to consider all possible set of contiguous partitions and calculate the maximum sum partition in each case and return the minimum of all these cases. 1) Optimal Substructure: We can implement the naive solution using recursion with the following optimal substructure property: Assuming that we already have k-1 partitions in place (using k-2 dividers), we now have to put the k-1 th divider to get k partitions. How can we do this? We can put the k-1 th divider between the i th and i+1 th element where i = 1 to n. Please note that putting it before the first element is the same as putting it after the last element.The total cost of this arrangement can be calculated as the maximum of the following: a) The cost of the last partition: sum(Ai..An), where the k-1 th divider is before element i. b) The maximum cost of any partition already formed to the left of the k-1 th divider.Here a) can be found out using a simple helper function to calculate sum of elements between two indices in the array. How to find out b) ? We can observe that b) actually is to place the k-2 separators as fairly as possible, so it is a subproblem of the given problem. Thus we can write the optimal substructure property as the following recurrence relation: Following is the implementation of the above recursive equation: C++ Java Python3 C# PHP Javascript // CPP program for The painter's partition problem#include <climits>#include <iostream>using namespace std; // function to calculate sum between two indices// in arrayint sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // for n boards and k partitionsint partition(int arr[], int n, int k){ // base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; int best = INT_MAX; // find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for (int i = 1; i <= n; i++) best = min(best, max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} int main(){ int arr[] = { 10, 20, 60, 50, 30, 40 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << partition(arr, n, k) << endl; return 0;} // Java Program for The painter's partition problemimport java.util.*;import java.io.*; class GFG{// function to calculate sum between two indices// in arraystatic int sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // for n boards and k partitionsstatic int partition(int arr[], int n, int k){ // base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; int best = Integer.MAX_VALUE; // find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for (int i = 1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} // Driver codepublic static void main(String args[]){ int arr[] = { 10, 20, 60, 50, 30, 40 }; // Calculate size of array. int n = arr.length; int k = 3; System.out.println(partition(arr, n, k));}} // This code is contributed by Sahil_Bansall # Python program for The painter's# partition problem function to# calculate sum between two indices# in arraydef sum(arr, frm, to): total = 0; for i in range(frm, to + 1): total += arr[i] return total # for n boards and k partitionsdef partition(arr, n, k): # base cases if k == 1: # one partition return sum(arr, 0, n - 1) if n == 1: # one board return arr[0] best = 100000000 # find minimum of all possible # maximum k-1 partitions to # the left of arr[i], with i # elements, put k-1 th divider # between arr[i-1] & arr[i] to # get k-th partition for i in range(1, n + 1): best = min(best, max(partition(arr, i, k - 1), sum(arr, i, n - 1))) return best # Driver Codearr = [10, 20, 60, 50, 30, 40 ]n = len(arr)k = 3print(partition(arr, n, k)) # This code is contributed# by sahilshelangia // C# Program for The painter's partition problemusing System; class GFG { // function to calculate sum// between two indices in arraystatic int sum(int []arr, int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // for n boards and k partitionsstatic int partition(int []arr, int n, int k){ // base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; int best = int.MaxValue; // find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for (int i = 1; i <= n; i++) best = Math.Min(best, Math.Max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} // Driver codepublic static void Main(){ int []arr = {10, 20, 60, 50, 30, 40}; // Calculate size of array. int n = arr.Length; int k = 3; // Function calling Console.WriteLine(partition(arr, n, k));}} // This code is contributed by vt_m <?php// PHP program for The// painter's partition problem // function to calculate sum// between two indices in arrayfunction sum($arr, $from, $to){ $total = 0; for ($i = $from; $i <= $to; $i++) $total += $arr[$i]; return $total;} // for n boards// and k partitionsfunction partition($arr, $n, $k){ // base cases if ($k == 1) // one partition return sum($arr, 0, $n - 1); if ($n == 1) // one board return $arr[0]; $best = PHP_INT_MAX; // find minimum of all possible // maximum k-1 partitions to the // left of arr[i], with i elements, // put k-1 th divider between // arr[i-1] & arr[i] to get k-th // partition for ($i = 1; $i <= $n; $i++) $best = min($best, max(partition($arr, $i, $k - 1), sum($arr, $i, $n - 1))); return $best;}// Driver Code$arr = array(10, 20, 60, 50, 30, 40);$n = sizeof($arr);$k = 3;echo partition($arr, $n, $k), "\n"; // This code is contributed by ajit?> <script> // JavaScript Program for The painter's// partition problem // Function to calculate sum between// two indices in arrayfunction sum(arr, from, to){ let total = 0; for(let i = from; i <= to; i++) total += arr[i]; return total;} // For n boards and k partitionsfunction partition(arr, n, k){ // Base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; let best = Number.MAX_VALUE; // Find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for(let i = 1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} // Driver Codelet arr = [ 10, 20, 60, 50, 30, 40 ]; // Calculate size of array.let n = arr.length;let k = 3; document.write(partition(arr, n, k)); // This code is contributed by susmitakundugoaldanga </script> Output : 90 The time complexity of the above solution is exponential. 2) Overlapping subproblems: Following is the partial recursion tree for T(4, 3) in above equation. T(4, 3) / / \ .. T(1, 2) T(2, 2) T(3, 2) /.. /.. T(1, 1) T(1, 1) We can observe that many subproblems like T(1, 1) in the above problem are being solved again and again. Because of these two properties of this problem, we can solve it using dynamic programming, either by top down memoized method or bottom up tabular method. Following is the bottom up tabular implementation: C++ Java Python3 C# PHP Javascript // A DP based CPP program for painter's partition problem#include <climits>#include <iostream>using namespace std; // function to calculate sum between two indices// in arrayint sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // bottom up tabular dpint findMax(int arr[], int n, int k){ // initialize table int dp[k + 1][n + 1] = { 0 }; // base cases // k=1 for (int i = 1; i <= n; i++) dp[1][i] = sum(arr, 0, i - 1); // n=1 for (int i = 1; i <= k; i++) dp[i][1] = arr[0]; // 2 to k partitions for (int i = 2; i <= k; i++) { // 2 to n boards for (int j = 2; j <= n; j++) { // track minimum int best = INT_MAX; // i-1 th separator before position arr[p=1..j] for (int p = 1; p <= j; p++) best = min(best, max(dp[i - 1][p], sum(arr, p, j - 1))); dp[i][j] = best; } } // required return dp[k][n];} // driver functionint main(){ int arr[] = { 10, 20, 60, 50, 30, 40 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << findMax(arr, n, k) << endl; return 0;} // A DP based Java program for// painter's partition problemimport java.util.*;import java.io.*; class GFG{// function to calculate sum between two indices// in arraystatic int sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // bottom up tabular dpstatic int findMax(int arr[], int n, int k){ // initialize table int dp[][] = new int[k+1][n+1]; // base cases // k=1 for (int i = 1; i <= n; i++) dp[1][i] = sum(arr, 0, i - 1); // n=1 for (int i = 1; i <= k; i++) dp[i][1] = arr[0]; // 2 to k partitions for (int i = 2; i <= k; i++) { // 2 to n boards for (int j = 2; j <= n; j++) { // track minimum int best = Integer.MAX_VALUE; // i-1 th separator before position arr[p=1..j] for (int p = 1; p <= j; p++) best = Math.min(best, Math.max(dp[i - 1][p], sum(arr, p, j - 1))); dp[i][j] = best; } } // required return dp[k][n];} // Driver codepublic static void main(String args[]){ int arr[] = { 10, 20, 60, 50, 30, 40 }; // Calculate size of array. int n = arr.length; int k = 3; System.out.println(findMax(arr, n, k));}} // This code is contributed by Sahil_Bansall # A DP based Python3 program for# painter's partition problem # function to calculate sum between# two indices in listdef sum(arr, start, to): total = 0 for i in range(start, to + 1): total += arr[i] return total # bottom up tabular dpdef findMax(arr, n, k): # initialize table dp = [[0 for i in range(n + 1)] for j in range(k + 1)] # base cases # k=1 for i in range(1, n + 1): dp[1][i] = sum(arr, 0, i - 1) # n=1 for i in range(1, k + 1): dp[i][1] = arr[0] # 2 to k partitions for i in range(2, k + 1): # 2 to n boards for j in range(2, n + 1): # track minimum best = 100000000 # i-1 th separator before position arr[p=1..j] for p in range(1, j + 1): best = min(best, max(dp[i - 1][p], sum(arr, p, j - 1))) dp[i][j] = best # required return dp[k][n] # Driver Codearr = [10, 20, 60, 50, 30, 40]n = len(arr)k = 3print(findMax(arr, n, k)) # This code is contributed by ashutosh450 // A DP based C# program for// painter's partition problemusing System; class GFG { // function to calculate sum between// two indices in arraystatic int sum(int []arr, int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // bottom up tabular dpstatic int findMax(int []arr, int n, int k){ // initialize table int [,]dp = new int[k+1,n+1]; // base cases // k=1 for (int i = 1; i <= n; i++) dp[1,i] = sum(arr, 0, i - 1); // n=1 for (int i = 1; i <= k; i++) dp[i,1] = arr[0]; // 2 to k partitions for (int i = 2; i <= k; i++) { // 2 to n boards for (int j = 2; j <= n; j++) { // track minimum int best = int.MaxValue; // i-1 th separator before position arr[p=1..j] for (int p = 1; p <= j; p++) best = Math.Min(best, Math.Max(dp[i - 1,p], sum(arr, p, j - 1))); dp[i,j] = best; } } // required return dp[k,n];} // Driver codepublic static void Main(){ int []arr = {10, 20, 60, 50, 30, 40}; // Calculate size of array. int n = arr.Length; int k = 3; Console.WriteLine(findMax(arr, n, k));}} // This code is contributed by vt_m <?php// A DP based PHP program for// painter's partition problem // function to calculate sum// between two indices in arrayfunction sum($arr, $from, $to){ $total = 0; for ($i = $from; $i <= $to; $i++) $total += $arr[$i]; return $total;} // bottom up tabular dpfunction findMax($arr, $n, $k){ // initialize table $dp[$k + 1][$n + 1] = array( 0 ); // base cases // k=1 for ($i = 1; $i <= $n; $i++) $dp[1][$i] = sum($arr, 0, $i - 1); // n=1 for ($i = 1; $i <= $k; $i++) $dp[$i][1] = $arr[0]; // 2 to k partitions for ($i = 2; $i <= $k; $i++) { // 2 to n boards for ($j = 2; $j <= $n; $j++) { // track minimum $best = PHP_INT_MAX; // i-1 th separator before // position arr[p=1..j] for ($p = 1; $p <= $j; $p++) $best = min($best, max($dp[$i - 1][$p], sum($arr, $p, $j - 1))); $dp[$i][$j] = $best; } } // required return $dp[$k][$n];} // Driver Code$arr = array (10, 20, 60, 50, 30, 40 );$n = sizeof($arr);$k = 3;echo findMax($arr, $n, $k) ,"\n"; // This code is contributed by m_kit?> <script> // A DP based Javascript program for // painter's partition problem // function to calculate sum between // two indices in array function sum(arr, from, to) { let total = 0; for (let i = from; i <= to; i++) total += arr[i]; return total; } // bottom up tabular dp function findMax(arr, n, k) { // initialize table let dp = new Array(k+1); for(let i = 0; i < k + 1; i++) { dp[i] = new Array(n + 1); } // base cases // k=1 for (let i = 1; i <= n; i++) dp[1][i] = sum(arr, 0, i - 1); // n=1 for (let i = 1; i <= k; i++) dp[i][1] = arr[0]; // 2 to k partitions for (let i = 2; i <= k; i++) { // 2 to n boards for (let j = 2; j <= n; j++) { // track minimum let best = Number.MAX_VALUE; // i-1 th separator before position arr[p=1..j] for (let p = 1; p <= j; p++) best = Math.min(best, Math.max(dp[i - 1][p], sum(arr, p, j - 1))); dp[i][j] = best; } } // required return dp[k][n]; } // Driver code let arr = [10, 20, 60, 50, 30, 40]; // Calculate size of array. let n = arr.length; let k = 3; document.write(findMax(arr, n, k)); // This code is contributed by mukesh07.</script> Output: 90 Optimizations: 1) The time complexity of the above program is . It can be easily brought down to by precomputing the cumulative sums in an array thus avoiding repeated calls to the sum function: C++ Java Python3 C# Javascript int sum[n+1] = {0}; // sum from 1 to i elements of arr for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (int i = 1; i <= n; i++) dp[1][i] = sum[i]; // and using it to calculate the result as:best = min(best, max(dp[i-1][p], sum[j] - sum[p])); int sum[] = new int[n+1]; // sum from 1 to i elements of arr for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (int i = 1; i <= n; i++) dp[1][i] = sum[i]; // and using it to calculate the result as:best = Math.min(best, Math.max(dp[i-1][p], sum[j] - sum[p])); // This code is contributed by divyesh072019. sum = [0] * (n + 1) # sum from 1 to i elements of arrfor i in range(1, n + 1): sum[i] = sum[i-1] + arr[i-1] for i in range(1, n + 1): dp[1][i] = sum[i] # and using it to calculate the result as:best = min(best, max(dp[i-1][p], sum[j] - sum[p])); # This code is contributed by kraanzu. int[] sum = new int[n+1]; // sum from 1 to i elements of arr for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (int i = 1; i <= n; i++) dp[1,i] = sum[i]; // and using it to calculate the result as:best = Math.Min(best, Math.Max(dp[i-1][p], sum[j] - sum[p])); // This code is contributed by divyeshrabadiya07. <script>let sum = new Array(n+1); // sum from 1 to i elements of arrfor (let i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (let i = 1; i <= n; i++) dp[1][i] = sum[i]; // and using it to calculate the result as:best = Math.min(best, Math.max(dp[i-1][p], sum[j] - sum[p])); // This code is contributed by Saurabh Jaiswal.</script> 2) Though here we consider to divide A into k or fewer partitions, we can observe that the optimal case always occurs when we divide A into exactly k partitions. So we can use: C++ Java Python3 C# Javascript for (int i = k-1; i <= n; i++) best = min(best, max( partition(arr, i, k-1), sum(arr, i, n-1))); for (int i = k-1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k-1), sum(arr, i, n-1))); // This code is contributed by pratham76. for i range(k-1,n+1): best=min(best, max(partition(arr, i, k-1),sum(arr, i, n-1))) # This code is contributed by Aman Kumar. for(int i = k - 1; i <= n; i++) best = Math.Min(best, Math.Max(partition(arr, i, k - 1), sum(arr, i, n - 1))); // This code is contributed by rutvik_56 for(var i = k - 1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k - 1), sum(arr, i, n - 1))); // This code is contributed by Ankita saini and modify the other implementations accordingly. Exercise: Can you come up with a solution using binary search? Please refer Allocate minimum number of pages for details.References: https://articles.leetcode.com/the-painters-partition-problem/ vt_m jit_t sahilshelangia harshal_97 ashutosh450 __tejas_ divyeshrabadiya07 divyesh072019 pratham76 rutvik_56 mukesh07 susmitakundugoaldanga ankita_saini varshagumber28 _saurabh_jaiswal kraanzu amankr0211 Binary Search Codenation Google Divide and Conquer Dynamic Programming Searching Google Codenation Searching Dynamic Programming Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge Sort QuickSort Binary Search Maximum and minimum of an array using minimum number of comparisons Count Inversions in an array | Set 1 (Using Merge Sort) Largest Sum Contiguous Subarray Program for Fibonacci numbers Find if there is a path between two vertices in an undirected graph Longest Increasing Subsequence | DP-3 Longest Palindromic Substring | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jun, 2022" }, { "code": null, "e": 408, "s": 52, "text": "We have to paint n boards of length {A1, A2...An}. There are k painters available and each takes 1 unit time to paint 1 unit of board. The problem is to find the minimum time to get this job done under the constraints that any painter will only paint continuous sections of boards, say board {2, 3, 4} or only board {1} or nothing but not board {2, 4, 5}." }, { "code": null, "e": 419, "s": 408, "text": "Examples: " }, { "code": null, "e": 744, "s": 419, "text": "Input : k = 2, A = {10, 10, 10, 10} \nOutput : 20.\nHere we can divide the boards into 2\nequal sized partitions, so each painter \ngets 20 units of board and the total\ntime taken is 20. \n\nInput : k = 2, A = {10, 20, 30, 40} \nOutput : 60.\nHere we can divide first 3 boards for\none painter and the last board for \nsecond painter." }, { "code": null, "e": 1199, "s": 744, "text": "From the above examples, it is obvious that the strategy of dividing the boards into k equal partitions won’t work for all the cases. We can observe that the problem can be broken down into: Given an array A of non-negative integers and a positive integer k, we have to divide A into k of fewer partitions such that the maximum sum of the elements in a partition, overall partitions is minimized. So for the second example above, possible divisions are: " }, { "code": null, "e": 1233, "s": 1199, "text": "* One partition: so time is 100. " }, { "code": null, "e": 1602, "s": 1233, "text": "* Two partitions: (10) & (20, 30, 40), so time is 90. Similarly we can put the first divider after 20 (=> time 70) or 30 (=> time 60); so this means the minimum time: (100, 90, 70, 60) is 60. A brute force solution is to consider all possible set of contiguous partitions and calculate the maximum sum partition in each case and return the minimum of all these cases. " }, { "code": null, "e": 2697, "s": 1602, "text": "1) Optimal Substructure: We can implement the naive solution using recursion with the following optimal substructure property: Assuming that we already have k-1 partitions in place (using k-2 dividers), we now have to put the k-1 th divider to get k partitions. How can we do this? We can put the k-1 th divider between the i th and i+1 th element where i = 1 to n. Please note that putting it before the first element is the same as putting it after the last element.The total cost of this arrangement can be calculated as the maximum of the following: a) The cost of the last partition: sum(Ai..An), where the k-1 th divider is before element i. b) The maximum cost of any partition already formed to the left of the k-1 th divider.Here a) can be found out using a simple helper function to calculate sum of elements between two indices in the array. How to find out b) ? We can observe that b) actually is to place the k-2 separators as fairly as possible, so it is a subproblem of the given problem. Thus we can write the optimal substructure property as the following recurrence relation: " }, { "code": null, "e": 2763, "s": 2697, "text": "Following is the implementation of the above recursive equation: " }, { "code": null, "e": 2767, "s": 2763, "text": "C++" }, { "code": null, "e": 2772, "s": 2767, "text": "Java" }, { "code": null, "e": 2780, "s": 2772, "text": "Python3" }, { "code": null, "e": 2783, "s": 2780, "text": "C#" }, { "code": null, "e": 2787, "s": 2783, "text": "PHP" }, { "code": null, "e": 2798, "s": 2787, "text": "Javascript" }, { "code": "// CPP program for The painter's partition problem#include <climits>#include <iostream>using namespace std; // function to calculate sum between two indices// in arrayint sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // for n boards and k partitionsint partition(int arr[], int n, int k){ // base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; int best = INT_MAX; // find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for (int i = 1; i <= n; i++) best = min(best, max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} int main(){ int arr[] = { 10, 20, 60, 50, 30, 40 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << partition(arr, n, k) << endl; return 0;}", "e": 3848, "s": 2798, "text": null }, { "code": "// Java Program for The painter's partition problemimport java.util.*;import java.io.*; class GFG{// function to calculate sum between two indices// in arraystatic int sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // for n boards and k partitionsstatic int partition(int arr[], int n, int k){ // base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; int best = Integer.MAX_VALUE; // find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for (int i = 1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} // Driver codepublic static void main(String args[]){ int arr[] = { 10, 20, 60, 50, 30, 40 }; // Calculate size of array. int n = arr.length; int k = 3; System.out.println(partition(arr, n, k));}} // This code is contributed by Sahil_Bansall", "e": 5017, "s": 3848, "text": null }, { "code": "# Python program for The painter's# partition problem function to# calculate sum between two indices# in arraydef sum(arr, frm, to): total = 0; for i in range(frm, to + 1): total += arr[i] return total # for n boards and k partitionsdef partition(arr, n, k): # base cases if k == 1: # one partition return sum(arr, 0, n - 1) if n == 1: # one board return arr[0] best = 100000000 # find minimum of all possible # maximum k-1 partitions to # the left of arr[i], with i # elements, put k-1 th divider # between arr[i-1] & arr[i] to # get k-th partition for i in range(1, n + 1): best = min(best, max(partition(arr, i, k - 1), sum(arr, i, n - 1))) return best # Driver Codearr = [10, 20, 60, 50, 30, 40 ]n = len(arr)k = 3print(partition(arr, n, k)) # This code is contributed# by sahilshelangia", "e": 5939, "s": 5017, "text": null }, { "code": "// C# Program for The painter's partition problemusing System; class GFG { // function to calculate sum// between two indices in arraystatic int sum(int []arr, int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // for n boards and k partitionsstatic int partition(int []arr, int n, int k){ // base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; int best = int.MaxValue; // find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for (int i = 1; i <= n; i++) best = Math.Min(best, Math.Max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} // Driver codepublic static void Main(){ int []arr = {10, 20, 60, 50, 30, 40}; // Calculate size of array. int n = arr.Length; int k = 3; // Function calling Console.WriteLine(partition(arr, n, k));}} // This code is contributed by vt_m", "e": 7097, "s": 5939, "text": null }, { "code": "<?php// PHP program for The// painter's partition problem // function to calculate sum// between two indices in arrayfunction sum($arr, $from, $to){ $total = 0; for ($i = $from; $i <= $to; $i++) $total += $arr[$i]; return $total;} // for n boards// and k partitionsfunction partition($arr, $n, $k){ // base cases if ($k == 1) // one partition return sum($arr, 0, $n - 1); if ($n == 1) // one board return $arr[0]; $best = PHP_INT_MAX; // find minimum of all possible // maximum k-1 partitions to the // left of arr[i], with i elements, // put k-1 th divider between // arr[i-1] & arr[i] to get k-th // partition for ($i = 1; $i <= $n; $i++) $best = min($best, max(partition($arr, $i, $k - 1), sum($arr, $i, $n - 1))); return $best;}// Driver Code$arr = array(10, 20, 60, 50, 30, 40);$n = sizeof($arr);$k = 3;echo partition($arr, $n, $k), \"\\n\"; // This code is contributed by ajit?>", "e": 8107, "s": 7097, "text": null }, { "code": "<script> // JavaScript Program for The painter's// partition problem // Function to calculate sum between// two indices in arrayfunction sum(arr, from, to){ let total = 0; for(let i = from; i <= to; i++) total += arr[i]; return total;} // For n boards and k partitionsfunction partition(arr, n, k){ // Base cases if (k == 1) // one partition return sum(arr, 0, n - 1); if (n == 1) // one board return arr[0]; let best = Number.MAX_VALUE; // Find minimum of all possible maximum // k-1 partitions to the left of arr[i], // with i elements, put k-1 th divider // between arr[i-1] & arr[i] to get k-th // partition for(let i = 1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k - 1), sum(arr, i, n - 1))); return best;} // Driver Codelet arr = [ 10, 20, 60, 50, 30, 40 ]; // Calculate size of array.let n = arr.length;let k = 3; document.write(partition(arr, n, k)); // This code is contributed by susmitakundugoaldanga </script>", "e": 9193, "s": 8107, "text": null }, { "code": null, "e": 9203, "s": 9193, "text": "Output : " }, { "code": null, "e": 9206, "s": 9203, "text": "90" }, { "code": null, "e": 9265, "s": 9206, "text": "The time complexity of the above solution is exponential. " }, { "code": null, "e": 9365, "s": 9265, "text": "2) Overlapping subproblems: Following is the partial recursion tree for T(4, 3) in above equation. " }, { "code": null, "e": 9487, "s": 9365, "text": " T(4, 3)\n / / \\ .. \nT(1, 2) T(2, 2) T(3, 2) \n /.. /.. \n T(1, 1) T(1, 1)" }, { "code": null, "e": 9800, "s": 9487, "text": "We can observe that many subproblems like T(1, 1) in the above problem are being solved again and again. Because of these two properties of this problem, we can solve it using dynamic programming, either by top down memoized method or bottom up tabular method. Following is the bottom up tabular implementation: " }, { "code": null, "e": 9804, "s": 9800, "text": "C++" }, { "code": null, "e": 9809, "s": 9804, "text": "Java" }, { "code": null, "e": 9817, "s": 9809, "text": "Python3" }, { "code": null, "e": 9820, "s": 9817, "text": "C#" }, { "code": null, "e": 9824, "s": 9820, "text": "PHP" }, { "code": null, "e": 9835, "s": 9824, "text": "Javascript" }, { "code": "// A DP based CPP program for painter's partition problem#include <climits>#include <iostream>using namespace std; // function to calculate sum between two indices// in arrayint sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // bottom up tabular dpint findMax(int arr[], int n, int k){ // initialize table int dp[k + 1][n + 1] = { 0 }; // base cases // k=1 for (int i = 1; i <= n; i++) dp[1][i] = sum(arr, 0, i - 1); // n=1 for (int i = 1; i <= k; i++) dp[i][1] = arr[0]; // 2 to k partitions for (int i = 2; i <= k; i++) { // 2 to n boards for (int j = 2; j <= n; j++) { // track minimum int best = INT_MAX; // i-1 th separator before position arr[p=1..j] for (int p = 1; p <= j; p++) best = min(best, max(dp[i - 1][p], sum(arr, p, j - 1))); dp[i][j] = best; } } // required return dp[k][n];} // driver functionint main(){ int arr[] = { 10, 20, 60, 50, 30, 40 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << findMax(arr, n, k) << endl; return 0;}", "e": 11069, "s": 9835, "text": null }, { "code": "// A DP based Java program for// painter's partition problemimport java.util.*;import java.io.*; class GFG{// function to calculate sum between two indices// in arraystatic int sum(int arr[], int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // bottom up tabular dpstatic int findMax(int arr[], int n, int k){ // initialize table int dp[][] = new int[k+1][n+1]; // base cases // k=1 for (int i = 1; i <= n; i++) dp[1][i] = sum(arr, 0, i - 1); // n=1 for (int i = 1; i <= k; i++) dp[i][1] = arr[0]; // 2 to k partitions for (int i = 2; i <= k; i++) { // 2 to n boards for (int j = 2; j <= n; j++) { // track minimum int best = Integer.MAX_VALUE; // i-1 th separator before position arr[p=1..j] for (int p = 1; p <= j; p++) best = Math.min(best, Math.max(dp[i - 1][p], sum(arr, p, j - 1))); dp[i][j] = best; } } // required return dp[k][n];} // Driver codepublic static void main(String args[]){ int arr[] = { 10, 20, 60, 50, 30, 40 }; // Calculate size of array. int n = arr.length; int k = 3; System.out.println(findMax(arr, n, k));}} // This code is contributed by Sahil_Bansall", "e": 12413, "s": 11069, "text": null }, { "code": "# A DP based Python3 program for# painter's partition problem # function to calculate sum between# two indices in listdef sum(arr, start, to): total = 0 for i in range(start, to + 1): total += arr[i] return total # bottom up tabular dpdef findMax(arr, n, k): # initialize table dp = [[0 for i in range(n + 1)] for j in range(k + 1)] # base cases # k=1 for i in range(1, n + 1): dp[1][i] = sum(arr, 0, i - 1) # n=1 for i in range(1, k + 1): dp[i][1] = arr[0] # 2 to k partitions for i in range(2, k + 1): # 2 to n boards for j in range(2, n + 1): # track minimum best = 100000000 # i-1 th separator before position arr[p=1..j] for p in range(1, j + 1): best = min(best, max(dp[i - 1][p], sum(arr, p, j - 1))) dp[i][j] = best # required return dp[k][n] # Driver Codearr = [10, 20, 60, 50, 30, 40]n = len(arr)k = 3print(findMax(arr, n, k)) # This code is contributed by ashutosh450", "e": 13516, "s": 12413, "text": null }, { "code": "// A DP based C# program for// painter's partition problemusing System; class GFG { // function to calculate sum between// two indices in arraystatic int sum(int []arr, int from, int to){ int total = 0; for (int i = from; i <= to; i++) total += arr[i]; return total;} // bottom up tabular dpstatic int findMax(int []arr, int n, int k){ // initialize table int [,]dp = new int[k+1,n+1]; // base cases // k=1 for (int i = 1; i <= n; i++) dp[1,i] = sum(arr, 0, i - 1); // n=1 for (int i = 1; i <= k; i++) dp[i,1] = arr[0]; // 2 to k partitions for (int i = 2; i <= k; i++) { // 2 to n boards for (int j = 2; j <= n; j++) { // track minimum int best = int.MaxValue; // i-1 th separator before position arr[p=1..j] for (int p = 1; p <= j; p++) best = Math.Min(best, Math.Max(dp[i - 1,p], sum(arr, p, j - 1))); dp[i,j] = best; } } // required return dp[k,n];} // Driver codepublic static void Main(){ int []arr = {10, 20, 60, 50, 30, 40}; // Calculate size of array. int n = arr.Length; int k = 3; Console.WriteLine(findMax(arr, n, k));}} // This code is contributed by vt_m", "e": 14799, "s": 13516, "text": null }, { "code": "<?php// A DP based PHP program for// painter's partition problem // function to calculate sum// between two indices in arrayfunction sum($arr, $from, $to){ $total = 0; for ($i = $from; $i <= $to; $i++) $total += $arr[$i]; return $total;} // bottom up tabular dpfunction findMax($arr, $n, $k){ // initialize table $dp[$k + 1][$n + 1] = array( 0 ); // base cases // k=1 for ($i = 1; $i <= $n; $i++) $dp[1][$i] = sum($arr, 0, $i - 1); // n=1 for ($i = 1; $i <= $k; $i++) $dp[$i][1] = $arr[0]; // 2 to k partitions for ($i = 2; $i <= $k; $i++) { // 2 to n boards for ($j = 2; $j <= $n; $j++) { // track minimum $best = PHP_INT_MAX; // i-1 th separator before // position arr[p=1..j] for ($p = 1; $p <= $j; $p++) $best = min($best, max($dp[$i - 1][$p], sum($arr, $p, $j - 1))); $dp[$i][$j] = $best; } } // required return $dp[$k][$n];} // Driver Code$arr = array (10, 20, 60, 50, 30, 40 );$n = sizeof($arr);$k = 3;echo findMax($arr, $n, $k) ,\"\\n\"; // This code is contributed by m_kit?>", "e": 16037, "s": 14799, "text": null }, { "code": "<script> // A DP based Javascript program for // painter's partition problem // function to calculate sum between // two indices in array function sum(arr, from, to) { let total = 0; for (let i = from; i <= to; i++) total += arr[i]; return total; } // bottom up tabular dp function findMax(arr, n, k) { // initialize table let dp = new Array(k+1); for(let i = 0; i < k + 1; i++) { dp[i] = new Array(n + 1); } // base cases // k=1 for (let i = 1; i <= n; i++) dp[1][i] = sum(arr, 0, i - 1); // n=1 for (let i = 1; i <= k; i++) dp[i][1] = arr[0]; // 2 to k partitions for (let i = 2; i <= k; i++) { // 2 to n boards for (let j = 2; j <= n; j++) { // track minimum let best = Number.MAX_VALUE; // i-1 th separator before position arr[p=1..j] for (let p = 1; p <= j; p++) best = Math.min(best, Math.max(dp[i - 1][p], sum(arr, p, j - 1))); dp[i][j] = best; } } // required return dp[k][n]; } // Driver code let arr = [10, 20, 60, 50, 30, 40]; // Calculate size of array. let n = arr.length; let k = 3; document.write(findMax(arr, n, k)); // This code is contributed by mukesh07.</script>", "e": 17530, "s": 16037, "text": null }, { "code": null, "e": 17539, "s": 17530, "text": "Output: " }, { "code": null, "e": 17542, "s": 17539, "text": "90" }, { "code": null, "e": 17558, "s": 17542, "text": "Optimizations: " }, { "code": null, "e": 17740, "s": 17558, "text": "1) The time complexity of the above program is . It can be easily brought down to by precomputing the cumulative sums in an array thus avoiding repeated calls to the sum function: " }, { "code": null, "e": 17744, "s": 17740, "text": "C++" }, { "code": null, "e": 17749, "s": 17744, "text": "Java" }, { "code": null, "e": 17757, "s": 17749, "text": "Python3" }, { "code": null, "e": 17760, "s": 17757, "text": "C#" }, { "code": null, "e": 17771, "s": 17760, "text": "Javascript" }, { "code": "int sum[n+1] = {0}; // sum from 1 to i elements of arr for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (int i = 1; i <= n; i++) dp[1][i] = sum[i]; // and using it to calculate the result as:best = min(best, max(dp[i-1][p], sum[j] - sum[p]));", "e": 18034, "s": 17771, "text": null }, { "code": "int sum[] = new int[n+1]; // sum from 1 to i elements of arr for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (int i = 1; i <= n; i++) dp[1][i] = sum[i]; // and using it to calculate the result as:best = Math.min(best, Math.max(dp[i-1][p], sum[j] - sum[p])); // This code is contributed by divyesh072019.", "e": 18365, "s": 18034, "text": null }, { "code": "sum = [0] * (n + 1) # sum from 1 to i elements of arrfor i in range(1, n + 1): sum[i] = sum[i-1] + arr[i-1] for i in range(1, n + 1): dp[1][i] = sum[i] # and using it to calculate the result as:best = min(best, max(dp[i-1][p], sum[j] - sum[p])); # This code is contributed by kraanzu.", "e": 18656, "s": 18365, "text": null }, { "code": "int[] sum = new int[n+1]; // sum from 1 to i elements of arr for (int i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (int i = 1; i <= n; i++) dp[1,i] = sum[i]; // and using it to calculate the result as:best = Math.Min(best, Math.Max(dp[i-1][p], sum[j] - sum[p])); // This code is contributed by divyeshrabadiya07.", "e": 18987, "s": 18656, "text": null }, { "code": "<script>let sum = new Array(n+1); // sum from 1 to i elements of arrfor (let i = 1; i <= n; i++) sum[i] = sum[i-1] + arr[i-1]; for (let i = 1; i <= n; i++) dp[1][i] = sum[i]; // and using it to calculate the result as:best = Math.min(best, Math.max(dp[i-1][p], sum[j] - sum[p])); // This code is contributed by Saurabh Jaiswal.</script>", "e": 19330, "s": 18987, "text": null }, { "code": null, "e": 19508, "s": 19330, "text": "2) Though here we consider to divide A into k or fewer partitions, we can observe that the optimal case always occurs when we divide A into exactly k partitions. So we can use: " }, { "code": null, "e": 19512, "s": 19508, "text": "C++" }, { "code": null, "e": 19517, "s": 19512, "text": "Java" }, { "code": null, "e": 19525, "s": 19517, "text": "Python3" }, { "code": null, "e": 19528, "s": 19525, "text": "C#" }, { "code": null, "e": 19539, "s": 19528, "text": "Javascript" }, { "code": "for (int i = k-1; i <= n; i++) best = min(best, max( partition(arr, i, k-1), sum(arr, i, n-1)));", "e": 19666, "s": 19539, "text": null }, { "code": "for (int i = k-1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k-1), sum(arr, i, n-1))); // This code is contributed by pratham76.", "e": 19848, "s": 19666, "text": null }, { "code": "for i range(k-1,n+1): best=min(best, max(partition(arr, i, k-1),sum(arr, i, n-1))) # This code is contributed by Aman Kumar.", "e": 19980, "s": 19848, "text": null }, { "code": "for(int i = k - 1; i <= n; i++) best = Math.Min(best, Math.Max(partition(arr, i, k - 1), sum(arr, i, n - 1))); // This code is contributed by rutvik_56", "e": 20175, "s": 19980, "text": null }, { "code": "for(var i = k - 1; i <= n; i++) best = Math.min(best, Math.max(partition(arr, i, k - 1), sum(arr, i, n - 1))); // This code is contributed by Ankita saini", "e": 20420, "s": 20175, "text": null }, { "code": null, "e": 20665, "s": 20420, "text": "and modify the other implementations accordingly. Exercise: Can you come up with a solution using binary search? Please refer Allocate minimum number of pages for details.References: https://articles.leetcode.com/the-painters-partition-problem/" }, { "code": null, "e": 20670, "s": 20665, "text": "vt_m" }, { "code": null, "e": 20676, "s": 20670, "text": "jit_t" }, { "code": null, "e": 20691, "s": 20676, "text": "sahilshelangia" }, { "code": null, "e": 20702, "s": 20691, "text": "harshal_97" }, { "code": null, "e": 20714, "s": 20702, "text": "ashutosh450" }, { "code": null, "e": 20723, "s": 20714, "text": "__tejas_" }, { "code": null, "e": 20741, "s": 20723, "text": "divyeshrabadiya07" }, { "code": null, "e": 20755, "s": 20741, "text": "divyesh072019" }, { "code": null, "e": 20765, "s": 20755, "text": "pratham76" }, { "code": null, "e": 20775, "s": 20765, "text": "rutvik_56" }, { "code": null, "e": 20784, "s": 20775, "text": "mukesh07" }, { "code": null, "e": 20806, "s": 20784, "text": "susmitakundugoaldanga" }, { "code": null, "e": 20819, "s": 20806, "text": "ankita_saini" }, { "code": null, "e": 20834, "s": 20819, "text": "varshagumber28" }, { "code": null, "e": 20851, "s": 20834, "text": "_saurabh_jaiswal" }, { "code": null, "e": 20859, "s": 20851, "text": "kraanzu" }, { "code": null, "e": 20870, "s": 20859, "text": "amankr0211" }, { "code": null, "e": 20884, "s": 20870, "text": "Binary Search" }, { "code": null, "e": 20895, "s": 20884, "text": "Codenation" }, { "code": null, "e": 20902, "s": 20895, "text": "Google" }, { "code": null, "e": 20921, "s": 20902, "text": "Divide and Conquer" }, { "code": null, "e": 20941, "s": 20921, "text": "Dynamic Programming" }, { "code": null, "e": 20951, "s": 20941, "text": "Searching" }, { "code": null, "e": 20958, "s": 20951, "text": "Google" }, { "code": null, "e": 20969, "s": 20958, "text": "Codenation" }, { "code": null, "e": 20979, "s": 20969, "text": "Searching" }, { "code": null, "e": 20999, "s": 20979, "text": "Dynamic Programming" }, { "code": null, "e": 21018, "s": 20999, "text": "Divide and Conquer" }, { "code": null, "e": 21032, "s": 21018, "text": "Binary Search" }, { "code": null, "e": 21130, "s": 21032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21141, "s": 21130, "text": "Merge Sort" }, { "code": null, "e": 21151, "s": 21141, "text": "QuickSort" }, { "code": null, "e": 21165, "s": 21151, "text": "Binary Search" }, { "code": null, "e": 21233, "s": 21165, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 21289, "s": 21233, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 21321, "s": 21289, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 21351, "s": 21321, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 21419, "s": 21351, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 21457, "s": 21419, "text": "Longest Increasing Subsequence | DP-3" } ]
SWING - ImageIcon Class
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images. Following is the declaration for javax.swing.ImageIcon class − public class ImageIcon extends Object implements Icon, Serializable, Accessible Following are the fields for javax.swing.ImageIcon class − protected static Component component protected static MediaTracker tracker ImageIcon() Creates an uninitialized image icon. ImageIcon(byte[] imageData) Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG. ImageIcon(byte[] imageData, String description) Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG. ImageIcon(Image image) Creates an ImageIcon from an image object. ImageIcon(Image image, String description) Creates an ImageIcon from the image. ImageIcon(String filename) Creates an ImageIcon from the specified file. ImageIcon(String filename, String description) Creates an ImageIcon from the specified file. ImageIcon(URL location) Creates an ImageIcon from the specified URL. ImageIcon(URL location, String description) Creates an ImageIcon from the specified URL. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this ImageIcon. String getDescription() Gets the description of the image. int getIconHeight() Gets the height of the icon. int getIconWidth() Gets the width of the icon. Image getImage() Returns this icon's Image. int getImageLoadStatus() Returns the status of the image loading operation. ImageObserver getImageObserver() Returns the image observer for the image. protected void loadImage(Image image) Loads the image, returning only when the image is loaded. void paintIcon(Component c, Graphics g, int x, int y) Paints the icon. void setDescription(String description) Sets the description of the image. void setImage(Image image) Sets the image displayed by this icon. void setImageObserver(ImageObserver observer) Sets the image observer for the image. String toString() Returns a string representation of this image. This class inherits methods from the following classes − java.lang.Object Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui > SwingControlDemo.java package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingControlDemo { private JFrame mainFrame; private JLabel headerLabel; private JLabel statusLabel; private JPanel controlPanel; public SwingControlDemo(){ prepareGUI(); } public static void main(String[] args){ SwingControlDemo swingControlDemo = new SwingControlDemo(); swingControlDemo.showImageIconDemo(); } private void prepareGUI(){ mainFrame = new JFrame("Java Swing Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("",JLabel.CENTER); statusLabel.setSize(350,100); controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } // Returns an ImageIcon, or null if the path was invalid. private static ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = SwingControlDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } else { System.err.println("Couldn't find file: " + path); return null; } } private void showImageIconDemo(){ headerLabel.setText("Control in action: ImageIcon"); ImageIcon icon = createImageIcon("/resources/java_icon.png","Java"); JLabel commentlabel = new JLabel("", icon,JLabel.CENTER); controlPanel.add(commentlabel); mainFrame.setVisible(true); } } Compile the program using the command prompt. Go to D:/ > SWING and type the following command. D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java If no error occurs, it means the compilation is successful. Run the program using the following command. D:\SWING>java com.tutorialspoint.gui.SwingControlDemo Verify the following output.
[ { "code": null, "e": 1991, "s": 1897, "text": "The class ImageIcon is an implementation of the Icon interface that paints Icons from Images." }, { "code": null, "e": 2054, "s": 1991, "text": "Following is the declaration for javax.swing.ImageIcon class −" }, { "code": null, "e": 2144, "s": 2054, "text": "public class ImageIcon\n extends Object\n implements Icon, Serializable, Accessible\n" }, { "code": null, "e": 2203, "s": 2144, "text": "Following are the fields for javax.swing.ImageIcon class −" }, { "code": null, "e": 2240, "s": 2203, "text": "protected static Component component" }, { "code": null, "e": 2278, "s": 2240, "text": "protected static MediaTracker tracker" }, { "code": null, "e": 2290, "s": 2278, "text": "ImageIcon()" }, { "code": null, "e": 2327, "s": 2290, "text": "Creates an uninitialized image icon." }, { "code": null, "e": 2355, "s": 2327, "text": "ImageIcon(byte[] imageData)" }, { "code": null, "e": 2510, "s": 2355, "text": "Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG." }, { "code": null, "e": 2558, "s": 2510, "text": "ImageIcon(byte[] imageData, String description)" }, { "code": null, "e": 2713, "s": 2558, "text": "Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG." }, { "code": null, "e": 2736, "s": 2713, "text": "ImageIcon(Image image)" }, { "code": null, "e": 2779, "s": 2736, "text": "Creates an ImageIcon from an image object." }, { "code": null, "e": 2822, "s": 2779, "text": "ImageIcon(Image image, String description)" }, { "code": null, "e": 2859, "s": 2822, "text": "Creates an ImageIcon from the image." }, { "code": null, "e": 2886, "s": 2859, "text": "ImageIcon(String filename)" }, { "code": null, "e": 2932, "s": 2886, "text": "Creates an ImageIcon from the specified file." }, { "code": null, "e": 2979, "s": 2932, "text": "ImageIcon(String filename, String description)" }, { "code": null, "e": 3025, "s": 2979, "text": "Creates an ImageIcon from the specified file." }, { "code": null, "e": 3049, "s": 3025, "text": "ImageIcon(URL location)" }, { "code": null, "e": 3094, "s": 3049, "text": "Creates an ImageIcon from the specified URL." }, { "code": null, "e": 3138, "s": 3094, "text": "ImageIcon(URL location, String description)" }, { "code": null, "e": 3183, "s": 3138, "text": "Creates an ImageIcon from the specified URL." }, { "code": null, "e": 3224, "s": 3183, "text": "AccessibleContext getAccessibleContext()" }, { "code": null, "e": 3283, "s": 3224, "text": "Gets the AccessibleContext associated with this ImageIcon." }, { "code": null, "e": 3307, "s": 3283, "text": "String getDescription()" }, { "code": null, "e": 3342, "s": 3307, "text": "Gets the description of the image." }, { "code": null, "e": 3362, "s": 3342, "text": "int getIconHeight()" }, { "code": null, "e": 3391, "s": 3362, "text": "Gets the height of the icon." }, { "code": null, "e": 3410, "s": 3391, "text": "int getIconWidth()" }, { "code": null, "e": 3438, "s": 3410, "text": "Gets the width of the icon." }, { "code": null, "e": 3455, "s": 3438, "text": "Image getImage()" }, { "code": null, "e": 3482, "s": 3455, "text": "Returns this icon's Image." }, { "code": null, "e": 3507, "s": 3482, "text": "int getImageLoadStatus()" }, { "code": null, "e": 3558, "s": 3507, "text": "Returns the status of the image loading operation." }, { "code": null, "e": 3591, "s": 3558, "text": "ImageObserver getImageObserver()" }, { "code": null, "e": 3633, "s": 3591, "text": "Returns the image observer for the image." }, { "code": null, "e": 3671, "s": 3633, "text": "protected void loadImage(Image image)" }, { "code": null, "e": 3729, "s": 3671, "text": "Loads the image, returning only when the image is loaded." }, { "code": null, "e": 3783, "s": 3729, "text": "void paintIcon(Component c, Graphics g, int x, int y)" }, { "code": null, "e": 3800, "s": 3783, "text": "Paints the icon." }, { "code": null, "e": 3840, "s": 3800, "text": "void setDescription(String description)" }, { "code": null, "e": 3875, "s": 3840, "text": "Sets the description of the image." }, { "code": null, "e": 3902, "s": 3875, "text": "void setImage(Image image)" }, { "code": null, "e": 3941, "s": 3902, "text": "Sets the image displayed by this icon." }, { "code": null, "e": 3987, "s": 3941, "text": "void setImageObserver(ImageObserver observer)" }, { "code": null, "e": 4026, "s": 3987, "text": "Sets the image observer for the image." }, { "code": null, "e": 4044, "s": 4026, "text": "String toString()" }, { "code": null, "e": 4091, "s": 4044, "text": "Returns a string representation of this image." }, { "code": null, "e": 4148, "s": 4091, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 4165, "s": 4148, "text": "java.lang.Object" }, { "code": null, "e": 4281, "s": 4165, "text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >" }, { "code": null, "e": 4303, "s": 4281, "text": "SwingControlDemo.java" }, { "code": null, "e": 6254, "s": 4303, "text": "package com.tutorialspoint.gui;\n \nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n \npublic class SwingControlDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n\n public SwingControlDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingControlDemo swingControlDemo = new SwingControlDemo(); \n swingControlDemo.showImageIconDemo();\n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java Swing Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new JLabel(\"\", JLabel.CENTER); \n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n // Returns an ImageIcon, or null if the path was invalid. \n private static ImageIcon createImageIcon(String path,\n String description) {\n java.net.URL imgURL = SwingControlDemo.class.getResource(path);\n \n if (imgURL != null) {\n return new ImageIcon(imgURL, description);\n } else { \n System.err.println(\"Couldn't find file: \" + path);\n return null;\n }\n }\n private void showImageIconDemo(){\n headerLabel.setText(\"Control in action: ImageIcon\"); \n ImageIcon icon = createImageIcon(\"/resources/java_icon.png\",\"Java\");\n\n JLabel commentlabel = new JLabel(\"\", icon,JLabel.CENTER);\n controlPanel.add(commentlabel);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 6350, "s": 6254, "text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command." }, { "code": null, "e": 6411, "s": 6350, "text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingControlDemo.java\n" }, { "code": null, "e": 6516, "s": 6411, "text": "If no error occurs, it means the compilation is successful. Run the program using the following command." }, { "code": null, "e": 6571, "s": 6516, "text": "D:\\SWING>java com.tutorialspoint.gui.SwingControlDemo\n" } ]
HTTP status codes | Informational Responses
31 Oct, 2019 The HTTP status codes are used to indicate that any specific HTTP request has successfully completed or not. The HTTP status codes are categorized into five sections those are listed below: Informational responses (100–199) Successful responses (200–299) Redirects (300–399) Client errors (400–499) Server errors (500–599) There are four Informational Responses those are Continue, Switching Protocols, Processing, and Early Hints. All of them are described below: 100 Continue: The HTTP 100 Continue Informational Response status code is used to inform the client that till now everything is OKAY with the request. If the work is done then the client will ignore it if it’s not done yet then the client will proceed with the other requests. The server needs to send a final response when the request has been completed.When the request contains the Expect header field that includes 100-continue expectation, the 100 response indicates that the server waiting to receive the request payload body. The client does not need to send the request-header with the 100-continue expectation. If it does not wish to send a request body.Status:100 Continue 100 Continue 101 Switching Protocols: The HTTP 101 Switching Protocol Informational Response status code is used to indicate the protocols that are going to switch for the client request which includes the upgrade request header for the protocols. This status code can be used with the WebSockets.Status:101 Switching ProtocolsExample: Performing with the websockets.HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Status: 101 Switching Protocols Example: Performing with the websockets. HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade 102 Processing: The 102 Processing Informational Response status code is used to indicate that the server received the request and working on the request but in response, there is nothing till now. 103 Early Hints: The 103 Early Hints Informational Response status code is used with the link header to allow the User-Agent to reloading the resources when the server is preparing a response. So basically when the server is working on to prepare the response then, the 103 Early Hints forcefully reloading the resources so the server can have few times on preparing a response.Status:103 Early Hints 103 Early Hints Supported Browsers: The browsers compatible with the HTTP status codes Informational Responses are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP- response-status-codes Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How do you run JavaScript script through the Terminal? Node.js | fs.writeFileSync() Method ReactJS setState() Difference between var, let and const keywords in JavaScript How to set space between the flexbox ? How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React JavaScript | promise resolve() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2019" }, { "code": null, "e": 218, "s": 28, "text": "The HTTP status codes are used to indicate that any specific HTTP request has successfully completed or not. The HTTP status codes are categorized into five sections those are listed below:" }, { "code": null, "e": 252, "s": 218, "text": "Informational responses (100–199)" }, { "code": null, "e": 283, "s": 252, "text": "Successful responses (200–299)" }, { "code": null, "e": 303, "s": 283, "text": "Redirects (300–399)" }, { "code": null, "e": 327, "s": 303, "text": "Client errors (400–499)" }, { "code": null, "e": 351, "s": 327, "text": "Server errors (500–599)" }, { "code": null, "e": 493, "s": 351, "text": "There are four Informational Responses those are Continue, Switching Protocols, Processing, and Early Hints. All of them are described below:" }, { "code": null, "e": 1176, "s": 493, "text": "100 Continue: The HTTP 100 Continue Informational Response status code is used to inform the client that till now everything is OKAY with the request. If the work is done then the client will ignore it if it’s not done yet then the client will proceed with the other requests. The server needs to send a final response when the request has been completed.When the request contains the Expect header field that includes 100-continue expectation, the 100 response indicates that the server waiting to receive the request payload body. The client does not need to send the request-header with the 100-continue expectation. If it does not wish to send a request body.Status:100 Continue" }, { "code": null, "e": 1189, "s": 1176, "text": "100 Continue" }, { "code": null, "e": 1616, "s": 1189, "text": "101 Switching Protocols: The HTTP 101 Switching Protocol Informational Response status code is used to indicate the protocols that are going to switch for the client request which includes the upgrade request header for the protocols. This status code can be used with the WebSockets.Status:101 Switching ProtocolsExample: Performing with the websockets.HTTP/1.1 101 Switching Protocols\nUpgrade: websocket \nConnection: Upgrade" }, { "code": null, "e": 1624, "s": 1616, "text": "Status:" }, { "code": null, "e": 1648, "s": 1624, "text": "101 Switching Protocols" }, { "code": null, "e": 1689, "s": 1648, "text": "Example: Performing with the websockets." }, { "code": null, "e": 1762, "s": 1689, "text": "HTTP/1.1 101 Switching Protocols\nUpgrade: websocket \nConnection: Upgrade" }, { "code": null, "e": 1960, "s": 1762, "text": "102 Processing: The 102 Processing Informational Response status code is used to indicate that the server received the request and working on the request but in response, there is nothing till now." }, { "code": null, "e": 2361, "s": 1960, "text": "103 Early Hints: The 103 Early Hints Informational Response status code is used with the link header to allow the User-Agent to reloading the resources when the server is preparing a response. So basically when the server is working on to prepare the response then, the 103 Early Hints forcefully reloading the resources so the server can have few times on preparing a response.Status:103 Early Hints" }, { "code": null, "e": 2377, "s": 2361, "text": "103 Early Hints" }, { "code": null, "e": 2490, "s": 2377, "text": "Supported Browsers: The browsers compatible with the HTTP status codes Informational Responses are listed below:" }, { "code": null, "e": 2504, "s": 2490, "text": "Google Chrome" }, { "code": null, "e": 2522, "s": 2504, "text": "Internet Explorer" }, { "code": null, "e": 2530, "s": 2522, "text": "Firefox" }, { "code": null, "e": 2537, "s": 2530, "text": "Safari" }, { "code": null, "e": 2543, "s": 2537, "text": "Opera" }, { "code": null, "e": 2571, "s": 2543, "text": "HTTP- response-status-codes" }, { "code": null, "e": 2588, "s": 2571, "text": "Web Technologies" }, { "code": null, "e": 2686, "s": 2588, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2719, "s": 2686, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 2779, "s": 2719, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2834, "s": 2779, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 2870, "s": 2834, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 2889, "s": 2870, "text": "ReactJS setState()" }, { "code": null, "e": 2950, "s": 2889, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2989, "s": 2950, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3047, "s": 2989, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 3119, "s": 3047, "text": "Differences between Functional Components and Class Components in React" } ]
Auto-Hide or Auto-Extend Floating Action Button for NestedScrollView in Android
19 Feb, 2021 In the previous article Extended Floating Action Button in Android with Example it’s been discussed how to implement the Extended Floating Action Button (FAB) in Android and more of its functionalities. In this article it’s been discussed it’s one of the features auto-hide or auto-extend the Floating Action Button in Android. Have a look at the following image on what things are discussed in this article. In this article, the nested scroll view is used. Step 1: Create an empty activity project Create an empty activity Android studio. And select Java as a programming language. Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Step 2: Invoking Dependencies in App-level gradle file First, locate the app-level gradle file in app -> build.gradle. Invoke the following dependencies to the app level gradle file. Make sure the system is connected to the network so that it downloads the required dependencies. for Material design Extended Floating Action Button: implementation ‘com.google.android.material:material:1.3.0-alpha03’ for NestedScrollView: implementation ‘androidx.legacy:legacy-support-v4:1.0.0’ Refer to the following image if unable to locate the app-level gradle file and invoke the dependencies. Step 3: Create sample list_item.xml inside the layout folder Implement the sample list_item with only one TextView. Invoke the following code inside the list_item.xml file under the layout folder. XML <?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="32dp" android:text="Some Content" android:textColor="@android:color/black" android:textSize="18sp" tools:ignore="HardcodedText"></TextView> Step 4: Working with the activity_main.xml file The root layout should be Coordinator layout in activity_main.xml. Further, the NestedScrollViews and one Extended Floating Action button are implemented in the layout with gravity “bottom|end”. Inside the NestedScrollView layout sample layout is included for the demonstration purpose. Invoke the following code inside the activity_main.xml file to implement the required UI. XML <?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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" tools:context=".MainActivity" tools:ignore="HardcodedText"> <androidx.core.widget.NestedScrollView android:id="@+id/nestedScrollView" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--repeatedly invoke the list_item layout inside the NestedScrollView--> <!--this consumes lot memory resource from the device, this is done only for demonstration purposes--> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> </LinearLayout> </androidx.core.widget.NestedScrollView> <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton android:id="@+id/extFloatingActionButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_marginEnd="16dp" android:layout_marginBottom="16dp" android:backgroundTint="@color/colorPrimary" android:text="ACTIONS" android:textColor="@android:color/white" app:icon="@drawable/ic_add_black_24dp" app:iconTint="@android:color/white" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Output UI: Step 5: Now working with the MainActivity.java file There is a need to handle the NestedScrollView with OnScrollChangeListener. If the NestedScrollView is scrolled down then the ExtendedFloatingAction button should be shrink state, and when scrolled up the FAB should be in an extended state. Invoke the following code to implement the functionality. Comments are added for better understanding. Java import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import android.os.Bundle;import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the extended floating action Button final ExtendedFloatingActionButton extendedFloatingActionButton = findViewById(R.id.extFloatingActionButton); // register the nestedScrollView from the main layout NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView); // handle the nestedScrollView behaviour with OnScrollChangeListener // to extend or shrink the Extended Floating Action Button nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // the delay of the extension of the FAB is set for 12 items if (scrollY > oldScrollY + 12 && extendedFloatingActionButton.isExtended()) { extendedFloatingActionButton.shrink(); } // the delay of the extension of the FAB is set for 12 items if (scrollY < oldScrollY - 12 && !extendedFloatingActionButton.isExtended()) { extendedFloatingActionButton.extend(); } // if the nestedScrollView is at the first item of the list then the // extended floating action should be in extended state if (scrollY == 0) { extendedFloatingActionButton.extend(); } } }); }} Replace the Extended Floating Action Button with Normal Floating Action Button to hide the FAB when scrolled down, and it FAB should appear when scrolled up. Invoke the following code inside the activity_main.xml file. Here the Extended FAB is replaced with the normal FAB. XML <?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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" tools:context=".MainActivity" tools:ignore="HardcodedText"> <androidx.core.widget.NestedScrollView android:id="@+id/nestedScrollView" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--repeatedly invoke the list_item layout inside the NestedScrollView--> <!--this consumes lot memory resource from the device, this is done only for demonstration purposes--> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> <include layout="@layout/list_item" /> </LinearLayout> </androidx.core.widget.NestedScrollView> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/extFloatingActionButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_marginEnd="16dp" android:layout_marginBottom="16dp" android:backgroundTint="@color/colorPrimary" android:text="ACTIONS" android:textColor="@android:color/white" app:srcCompat="@drawable/ic_add_black_24dp" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Output UI: Now Invoke the following code inside the MainActivity.java file to show or hide the Floating Action Button. Java import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import android.os.Bundle;import com.google.android.material.floatingactionbutton.FloatingActionButton; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the floating action Button final FloatingActionButton extendedFloatingActionButton = findViewById(R.id.extFloatingActionButton); // register the nestedScrollView from the main layout NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView); // handle the nestedScrollView behaviour with OnScrollChangeListener // to hide or show the Floating Action Button nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // the delay of the extension of the FAB is set for 12 items if (scrollY > oldScrollY + 12 && extendedFloatingActionButton.isShown()) { extendedFloatingActionButton.hide(); } // the delay of the extension of the FAB is set for 12 items if (scrollY < oldScrollY - 12 && !extendedFloatingActionButton.isShown()) { extendedFloatingActionButton.show(); } // if the nestedScrollView is at the first item of the list then the // floating action should be in show state if (scrollY == 0) { extendedFloatingActionButton.show(); } } }); }} Android-Button Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Android RecyclerView in Kotlin Broadcast Receiver in Android With Example Navigation Drawer in Android Android Project folder Structure 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": "\n19 Feb, 2021" }, { "code": null, "e": 486, "s": 28, "text": "In the previous article Extended Floating Action Button in Android with Example it’s been discussed how to implement the Extended Floating Action Button (FAB) in Android and more of its functionalities. In this article it’s been discussed it’s one of the features auto-hide or auto-extend the Floating Action Button in Android. Have a look at the following image on what things are discussed in this article. In this article, the nested scroll view is used." }, { "code": null, "e": 527, "s": 486, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 611, "s": 527, "text": "Create an empty activity Android studio. And select Java as a programming language." }, { "code": null, "e": 747, "s": 611, "text": "Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project." }, { "code": null, "e": 802, "s": 747, "text": "Step 2: Invoking Dependencies in App-level gradle file" }, { "code": null, "e": 866, "s": 802, "text": "First, locate the app-level gradle file in app -> build.gradle." }, { "code": null, "e": 930, "s": 866, "text": "Invoke the following dependencies to the app level gradle file." }, { "code": null, "e": 1027, "s": 930, "text": "Make sure the system is connected to the network so that it downloads the required dependencies." }, { "code": null, "e": 1080, "s": 1027, "text": "for Material design Extended Floating Action Button:" }, { "code": null, "e": 1148, "s": 1080, "text": "implementation ‘com.google.android.material:material:1.3.0-alpha03’" }, { "code": null, "e": 1170, "s": 1148, "text": "for NestedScrollView:" }, { "code": null, "e": 1227, "s": 1170, "text": "implementation ‘androidx.legacy:legacy-support-v4:1.0.0’" }, { "code": null, "e": 1331, "s": 1227, "text": "Refer to the following image if unable to locate the app-level gradle file and invoke the dependencies." }, { "code": null, "e": 1392, "s": 1331, "text": "Step 3: Create sample list_item.xml inside the layout folder" }, { "code": null, "e": 1447, "s": 1392, "text": "Implement the sample list_item with only one TextView." }, { "code": null, "e": 1528, "s": 1447, "text": "Invoke the following code inside the list_item.xml file under the layout folder." }, { "code": null, "e": 1532, "s": 1528, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><TextView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/listView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:padding=\"32dp\" android:text=\"Some Content\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" tools:ignore=\"HardcodedText\"></TextView>", "e": 1974, "s": 1532, "text": null }, { "code": null, "e": 2022, "s": 1974, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2089, "s": 2022, "text": "The root layout should be Coordinator layout in activity_main.xml." }, { "code": null, "e": 2217, "s": 2089, "text": "Further, the NestedScrollViews and one Extended Floating Action button are implemented in the layout with gravity “bottom|end”." }, { "code": null, "e": 2309, "s": 2217, "text": "Inside the NestedScrollView layout sample layout is included for the demonstration purpose." }, { "code": null, "e": 2399, "s": 2309, "text": "Invoke the following code inside the activity_main.xml file to implement the required UI." }, { "code": null, "e": 2403, "s": 2399, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <androidx.core.widget.NestedScrollView android:id=\"@+id/nestedScrollView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--repeatedly invoke the list_item layout inside the NestedScrollView--> <!--this consumes lot memory resource from the device, this is done only for demonstration purposes--> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> </LinearLayout> </androidx.core.widget.NestedScrollView> <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton android:id=\"@+id/extFloatingActionButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"end|bottom\" android:layout_marginEnd=\"16dp\" android:layout_marginBottom=\"16dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"ACTIONS\" android:textColor=\"@android:color/white\" app:icon=\"@drawable/ic_add_black_24dp\" app:iconTint=\"@android:color/white\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>", "e": 4846, "s": 2403, "text": null }, { "code": null, "e": 4857, "s": 4846, "text": "Output UI:" }, { "code": null, "e": 4909, "s": 4857, "text": "Step 5: Now working with the MainActivity.java file" }, { "code": null, "e": 5150, "s": 4909, "text": "There is a need to handle the NestedScrollView with OnScrollChangeListener. If the NestedScrollView is scrolled down then the ExtendedFloatingAction button should be shrink state, and when scrolled up the FAB should be in an extended state." }, { "code": null, "e": 5253, "s": 5150, "text": "Invoke the following code to implement the functionality. Comments are added for better understanding." }, { "code": null, "e": 5258, "s": 5253, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import android.os.Bundle;import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the extended floating action Button final ExtendedFloatingActionButton extendedFloatingActionButton = findViewById(R.id.extFloatingActionButton); // register the nestedScrollView from the main layout NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView); // handle the nestedScrollView behaviour with OnScrollChangeListener // to extend or shrink the Extended Floating Action Button nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // the delay of the extension of the FAB is set for 12 items if (scrollY > oldScrollY + 12 && extendedFloatingActionButton.isExtended()) { extendedFloatingActionButton.shrink(); } // the delay of the extension of the FAB is set for 12 items if (scrollY < oldScrollY - 12 && !extendedFloatingActionButton.isExtended()) { extendedFloatingActionButton.extend(); } // if the nestedScrollView is at the first item of the list then the // extended floating action should be in extended state if (scrollY == 0) { extendedFloatingActionButton.extend(); } } }); }}", "e": 7162, "s": 5258, "text": null }, { "code": null, "e": 7320, "s": 7162, "text": "Replace the Extended Floating Action Button with Normal Floating Action Button to hide the FAB when scrolled down, and it FAB should appear when scrolled up." }, { "code": null, "e": 7436, "s": 7320, "text": "Invoke the following code inside the activity_main.xml file. Here the Extended FAB is replaced with the normal FAB." }, { "code": null, "e": 7440, "s": 7436, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <androidx.core.widget.NestedScrollView android:id=\"@+id/nestedScrollView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--repeatedly invoke the list_item layout inside the NestedScrollView--> <!--this consumes lot memory resource from the device, this is done only for demonstration purposes--> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> <include layout=\"@layout/list_item\" /> </LinearLayout> </androidx.core.widget.NestedScrollView> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id=\"@+id/extFloatingActionButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"end|bottom\" android:layout_marginEnd=\"16dp\" android:layout_marginBottom=\"16dp\" android:backgroundTint=\"@color/colorPrimary\" android:text=\"ACTIONS\" android:textColor=\"@android:color/white\" app:srcCompat=\"@drawable/ic_add_black_24dp\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>", "e": 9837, "s": 7440, "text": null }, { "code": null, "e": 9848, "s": 9837, "text": "Output UI:" }, { "code": null, "e": 9956, "s": 9848, "text": "Now Invoke the following code inside the MainActivity.java file to show or hide the Floating Action Button." }, { "code": null, "e": 9961, "s": 9956, "text": "Java" }, { "code": "import androidx.appcompat.app.AppCompatActivity;import androidx.core.widget.NestedScrollView;import android.os.Bundle;import com.google.android.material.floatingactionbutton.FloatingActionButton; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the floating action Button final FloatingActionButton extendedFloatingActionButton = findViewById(R.id.extFloatingActionButton); // register the nestedScrollView from the main layout NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView); // handle the nestedScrollView behaviour with OnScrollChangeListener // to hide or show the Floating Action Button nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { // the delay of the extension of the FAB is set for 12 items if (scrollY > oldScrollY + 12 && extendedFloatingActionButton.isShown()) { extendedFloatingActionButton.hide(); } // the delay of the extension of the FAB is set for 12 items if (scrollY < oldScrollY - 12 && !extendedFloatingActionButton.isShown()) { extendedFloatingActionButton.show(); } // if the nestedScrollView is at the first item of the list then the // floating action should be in show state if (scrollY == 0) { extendedFloatingActionButton.show(); } } }); }}", "e": 11804, "s": 9961, "text": null }, { "code": null, "e": 11819, "s": 11804, "text": "Android-Button" }, { "code": null, "e": 11843, "s": 11819, "text": "Technical Scripter 2020" }, { "code": null, "e": 11851, "s": 11843, "text": "Android" }, { "code": null, "e": 11856, "s": 11851, "text": "Java" }, { "code": null, "e": 11875, "s": 11856, "text": "Technical Scripter" }, { "code": null, "e": 11880, "s": 11875, "text": "Java" }, { "code": null, "e": 11888, "s": 11880, "text": "Android" }, { "code": null, "e": 11986, "s": 11888, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12018, "s": 11986, "text": "Android SDK and it's Components" }, { "code": null, "e": 12049, "s": 12018, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 12092, "s": 12049, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 12121, "s": 12092, "text": "Navigation Drawer in Android" }, { "code": null, "e": 12154, "s": 12121, "text": "Android Project folder Structure" }, { "code": null, "e": 12169, "s": 12154, "text": "Arrays in Java" }, { "code": null, "e": 12213, "s": 12169, "text": "Split() String method in Java with examples" }, { "code": null, "e": 12249, "s": 12213, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 12300, "s": 12249, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Find Sum of Series 1^2 – 2^2 + 3^2 – 4^2 ..... upto n terms
23 Jun, 2022 Given a number n, the task is to find the sum of the below series upto n terms: 12 – 22 + 32 – 42 + ..... Examples: Input: n = 2 Output: -3 Explanation: sum = 12 - 22 = 1 - 4 = -3 Input: n = 3 Output: 6 Explanation: sum = 12 - 22 + 32 = 1 - 4 + 9 = 6 This method involves simply running a loop of i from 1 to n and if i is odd then simply add its square to the result it i is even then simply subtract square of it to the result.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ... #include <bits/stdc++.h>using namespace std; // Function to find sum of seriesint sum_of_series(int n){ int result = 0; for (int i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - pow(i, 2); // If i is odd else result = result + pow(i, 2); } // return the result return result;} // Driver Codeint main(void){ // Get n int n = 3; // Find the sum cout << sum_of_series(n) << endl; // Get n n = 10; // Find the sum cout << sum_of_series(n) << endl;} // Java Program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ...import java.util.*;import java.lang.*; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; for (int i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - (int)Math.pow(i, 2); // If i is odd else result = result + (int)Math.pow(i, 2); } // return the result return result;} // Driver Codepublic static void main(String args[]){ // Get n int n = 3; // Find the sum System.out.println(sum_of_series(n)); // Get n n = 10; // Find the sum System.out.println(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku) # Python3 program to find sum of series# 1^2 - 2^2 + 3^3 - 4^4 + ... # Function to find sum of seriesdef sum_of_series(n): result = 0 for i in range(1, n + 1) : # If i is even if (i % 2 == 0): result = result - pow(i, 2) # If i is odd else: result = result + pow(i, 2) # return the result return result # Driver Codeif __name__ == "__main__": # Get n n = 3 # Find the sum print(sum_of_series(n)) # Get n n = 10 # Find the sum print(sum_of_series(n)) # This code is contributed# by ChitraNayal // C# Program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ...using System; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; for (int i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - (int)Math.Pow(i, 2); // If i is odd else result = result + (int)Math.Pow(i, 2); } // return the result return result;} // Driver Codepublic static void Main(){ // Get n int n = 3; // Find the sum Console.WriteLine(sum_of_series(n)); // Get n n = 10; // Find the sum Console.WriteLine(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ...// Function to find sum of seriesfunction sum_of_series($n){ $result = 0; for ($i = 1; $i <= $n; $i++) { // If i is even if ($i % 2 == 0) $result = $result - pow($i, 2); // If i is odd else $result = $result + pow($i, 2); } // return the result return $result;} // Driver Code // Get n$n = 3; // Find the sumecho sum_of_series($n),"\n"; // Get n$n = 10; // Find the sumecho sum_of_series($n),"\n"; // This Code is Contributed by anuj_67?> <script> // javascript Program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ... // Function to find sum of seriesfunction sum_of_series(n){ var result = 0; for (i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - parseInt(Math.pow(i, 2)); // If i is odd else result = result + parseInt(Math.pow(i, 2)); } // return the result return result;} // Driver Code // Get nvar n = 3; // Find the sumdocument.write(sum_of_series(n)+ "<br>"); // Get nn = 10; // Find the sumdocument.write(sum_of_series(n)); // This code is contributed by 29AjayKumar </script> 6 -55 Time Complexity: O(nlogn) Auxiliary Space: O(1) It is based on condition of n If n is even: If n is odd: Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... #include <bits/stdc++.h>using namespace std; // Function to find sum of seriesint sum_of_series(int n){ int result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result;} // Driver Codeint main(void){ // Get n int n = 3; // Find the sum cout << sum_of_series(n) << endl; // Get n n = 10; // Find the sum cout << sum_of_series(n) << endl;} // Java Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ...import java.util.*;import java.lang.*; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result;} // Driver Codepublic static void main(String args[]){ // Get n int n = 3; // Find the sum System.out.println(sum_of_series(n)); // Get n n = 10; // Find the sum System.out.println(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku) # Python3 Program to find sum of series# 1^2 - 2^2 +3^3 -4^4 + ... # Function to find sum of seriesdef sum_of_series(n) : result = 0 # If n is even if (n % 2 == 0) : result = -(n * (n + 1)) // 2 # If n is odd else : result = (n * (n + 1)) // 2 # return the result return result # Driver Codeif __name__ == "__main__" : # Get n n = 3 # Find the sum print(sum_of_series(n)) # Get n n = 10 # Find the sum print(sum_of_series(n)) # This code is contributed by Ryuga // C# Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... using System; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result;} // Driver Codepublic static void Main(){ // Get n int n = 3; // Find the sum Console.WriteLine(sum_of_series(n)); // Get n n = 10; // Find the sum Console.WriteLine(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... // Function to find sum of seriesfunction sum_of_series($n){ $result = 0; // If n is even if ($n % 2 == 0) { $result = -($n * ($n + 1)) / 2; } // If n is odd else { $result = ($n * ($n + 1)) / 2; } // return the result return $result;} // Driver Code // Get n$n = 3; // Find the sumecho sum_of_series($n);echo ("\n"); // Get n$n = 10; // Find the sumecho sum_of_series($n);echo ("\n"); // Get n$n = 10; // This code is contributed// by Shivi_Aggarwal?> <script>// Javascript Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... // Function to find sum of series function sum_of_series( n) { let result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result; } // Driver Code // Get n let n = 3; // Find the sum document.write(sum_of_series(n)+"<br/>"); // Get n n = 10; // Find the sum document.write(sum_of_series(n)); // This code is contributed by 29AjayKumar </script> 6 -55 Time Complexity: O(1), the code will run in a constant time.Auxiliary Space: O(1), no extra space is required, so it is a constant. vt_m Akanksha_Rai Shivi_Aggarwal ukasp ankthon 29AjayKumar samim2000 series series-sum Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2022" }, { "code": null, "e": 109, "s": 28, "text": "Given a number n, the task is to find the sum of the below series upto n terms: " }, { "code": null, "e": 135, "s": 109, "text": "12 – 22 + 32 – 42 + ....." }, { "code": null, "e": 147, "s": 135, "text": "Examples: " }, { "code": null, "e": 309, "s": 147, "text": "Input: n = 2\nOutput: -3\nExplanation: \n sum = 12 - 22\n = 1 - 4\n = -3\n\nInput: n = 3\nOutput: 6\nExplanation: \n sum = 12 - 22 + 32\n = 1 - 4 + 9\n = 6" }, { "code": null, "e": 541, "s": 311, "text": "This method involves simply running a loop of i from 1 to n and if i is odd then simply add its square to the result it i is even then simply subtract square of it to the result.Below is the implementation of the above approach: " }, { "code": null, "e": 545, "s": 541, "text": "C++" }, { "code": null, "e": 550, "s": 545, "text": "Java" }, { "code": null, "e": 558, "s": 550, "text": "Python3" }, { "code": null, "e": 561, "s": 558, "text": "C#" }, { "code": null, "e": 565, "s": 561, "text": "PHP" }, { "code": null, "e": 576, "s": 565, "text": "Javascript" }, { "code": "// C++ program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ... #include <bits/stdc++.h>using namespace std; // Function to find sum of seriesint sum_of_series(int n){ int result = 0; for (int i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - pow(i, 2); // If i is odd else result = result + pow(i, 2); } // return the result return result;} // Driver Codeint main(void){ // Get n int n = 3; // Find the sum cout << sum_of_series(n) << endl; // Get n n = 10; // Find the sum cout << sum_of_series(n) << endl;}", "e": 1207, "s": 576, "text": null }, { "code": "// Java Program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ...import java.util.*;import java.lang.*; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; for (int i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - (int)Math.pow(i, 2); // If i is odd else result = result + (int)Math.pow(i, 2); } // return the result return result;} // Driver Codepublic static void main(String args[]){ // Get n int n = 3; // Find the sum System.out.println(sum_of_series(n)); // Get n n = 10; // Find the sum System.out.println(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 2000, "s": 1207, "text": null }, { "code": "# Python3 program to find sum of series# 1^2 - 2^2 + 3^3 - 4^4 + ... # Function to find sum of seriesdef sum_of_series(n): result = 0 for i in range(1, n + 1) : # If i is even if (i % 2 == 0): result = result - pow(i, 2) # If i is odd else: result = result + pow(i, 2) # return the result return result # Driver Codeif __name__ == \"__main__\": # Get n n = 3 # Find the sum print(sum_of_series(n)) # Get n n = 10 # Find the sum print(sum_of_series(n)) # This code is contributed# by ChitraNayal", "e": 2587, "s": 2000, "text": null }, { "code": "// C# Program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ...using System; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; for (int i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - (int)Math.Pow(i, 2); // If i is odd else result = result + (int)Math.Pow(i, 2); } // return the result return result;} // Driver Codepublic static void Main(){ // Get n int n = 3; // Find the sum Console.WriteLine(sum_of_series(n)); // Get n n = 10; // Find the sum Console.WriteLine(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 3338, "s": 2587, "text": null }, { "code": "<?php// PHP program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ...// Function to find sum of seriesfunction sum_of_series($n){ $result = 0; for ($i = 1; $i <= $n; $i++) { // If i is even if ($i % 2 == 0) $result = $result - pow($i, 2); // If i is odd else $result = $result + pow($i, 2); } // return the result return $result;} // Driver Code // Get n$n = 3; // Find the sumecho sum_of_series($n),\"\\n\"; // Get n$n = 10; // Find the sumecho sum_of_series($n),\"\\n\"; // This Code is Contributed by anuj_67?>", "e": 3919, "s": 3338, "text": null }, { "code": "<script> // javascript Program to find sum of series// 1^2 - 2^2 + 3^3 - 4^4 + ... // Function to find sum of seriesfunction sum_of_series(n){ var result = 0; for (i = 1; i <= n; i++) { // If i is even if (i % 2 == 0) result = result - parseInt(Math.pow(i, 2)); // If i is odd else result = result + parseInt(Math.pow(i, 2)); } // return the result return result;} // Driver Code // Get nvar n = 3; // Find the sumdocument.write(sum_of_series(n)+ \"<br>\"); // Get nn = 10; // Find the sumdocument.write(sum_of_series(n)); // This code is contributed by 29AjayKumar </script>", "e": 4604, "s": 3919, "text": null }, { "code": null, "e": 4610, "s": 4604, "text": "6\n-55" }, { "code": null, "e": 4639, "s": 4612, "text": " Time Complexity: O(nlogn)" }, { "code": null, "e": 4661, "s": 4639, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4706, "s": 4661, "text": "It is based on condition of n If n is even: " }, { "code": null, "e": 4721, "s": 4706, "text": "If n is odd: " }, { "code": null, "e": 4774, "s": 4721, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 4778, "s": 4774, "text": "C++" }, { "code": null, "e": 4783, "s": 4778, "text": "Java" }, { "code": null, "e": 4791, "s": 4783, "text": "Python3" }, { "code": null, "e": 4794, "s": 4791, "text": "C#" }, { "code": null, "e": 4798, "s": 4794, "text": "PHP" }, { "code": null, "e": 4809, "s": 4798, "text": "Javascript" }, { "code": "// C++ Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... #include <bits/stdc++.h>using namespace std; // Function to find sum of seriesint sum_of_series(int n){ int result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result;} // Driver Codeint main(void){ // Get n int n = 3; // Find the sum cout << sum_of_series(n) << endl; // Get n n = 10; // Find the sum cout << sum_of_series(n) << endl;}", "e": 5388, "s": 4809, "text": null }, { "code": "// Java Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ...import java.util.*;import java.lang.*; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result;} // Driver Codepublic static void main(String args[]){ // Get n int n = 3; // Find the sum System.out.println(sum_of_series(n)); // Get n n = 10; // Find the sum System.out.println(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 6074, "s": 5388, "text": null }, { "code": "# Python3 Program to find sum of series# 1^2 - 2^2 +3^3 -4^4 + ... # Function to find sum of seriesdef sum_of_series(n) : result = 0 # If n is even if (n % 2 == 0) : result = -(n * (n + 1)) // 2 # If n is odd else : result = (n * (n + 1)) // 2 # return the result return result # Driver Codeif __name__ == \"__main__\" : # Get n n = 3 # Find the sum print(sum_of_series(n)) # Get n n = 10 # Find the sum print(sum_of_series(n)) # This code is contributed by Ryuga", "e": 6611, "s": 6074, "text": null }, { "code": "// C# Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... using System; class GFG{// Function to find sum of seriesstatic int sum_of_series(int n){ int result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result;} // Driver Codepublic static void Main(){ // Get n int n = 3; // Find the sum Console.WriteLine(sum_of_series(n)); // Get n n = 10; // Find the sum Console.WriteLine(sum_of_series(n));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 7256, "s": 6611, "text": null }, { "code": "<?php// PHP program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... // Function to find sum of seriesfunction sum_of_series($n){ $result = 0; // If n is even if ($n % 2 == 0) { $result = -($n * ($n + 1)) / 2; } // If n is odd else { $result = ($n * ($n + 1)) / 2; } // return the result return $result;} // Driver Code // Get n$n = 3; // Find the sumecho sum_of_series($n);echo (\"\\n\"); // Get n$n = 10; // Find the sumecho sum_of_series($n);echo (\"\\n\"); // Get n$n = 10; // This code is contributed// by Shivi_Aggarwal?>", "e": 7829, "s": 7256, "text": null }, { "code": "<script>// Javascript Program to find sum of series// 1^2 - 2^2 +3^3 -4^4 + ... // Function to find sum of series function sum_of_series( n) { let result = 0; // If n is even if (n % 2 == 0) { result = -(n * (n + 1)) / 2; } // If n is odd else { result = (n * (n + 1)) / 2; } // return the result return result; } // Driver Code // Get n let n = 3; // Find the sum document.write(sum_of_series(n)+\"<br/>\"); // Get n n = 10; // Find the sum document.write(sum_of_series(n)); // This code is contributed by 29AjayKumar </script>", "e": 8526, "s": 7829, "text": null }, { "code": null, "e": 8532, "s": 8526, "text": "6\n-55" }, { "code": null, "e": 8666, "s": 8534, "text": "Time Complexity: O(1), the code will run in a constant time.Auxiliary Space: O(1), no extra space is required, so it is a constant." }, { "code": null, "e": 8671, "s": 8666, "text": "vt_m" }, { "code": null, "e": 8684, "s": 8671, "text": "Akanksha_Rai" }, { "code": null, "e": 8699, "s": 8684, "text": "Shivi_Aggarwal" }, { "code": null, "e": 8705, "s": 8699, "text": "ukasp" }, { "code": null, "e": 8713, "s": 8705, "text": "ankthon" }, { "code": null, "e": 8725, "s": 8713, "text": "29AjayKumar" }, { "code": null, "e": 8735, "s": 8725, "text": "samim2000" }, { "code": null, "e": 8742, "s": 8735, "text": "series" }, { "code": null, "e": 8753, "s": 8742, "text": "series-sum" }, { "code": null, "e": 8766, "s": 8753, "text": "Mathematical" }, { "code": null, "e": 8785, "s": 8766, "text": "School Programming" }, { "code": null, "e": 8798, "s": 8785, "text": "Mathematical" }, { "code": null, "e": 8805, "s": 8798, "text": "series" } ]
Java Multithreading Tutorial
18 May, 2022 Threads are the backbone of multithreading. We are living in a real-world which in itself is caught on the web surrounded by lots of applications. Same this with the advancement in technologies we cannot compensate with the speed for which we need to run them simultaneously for which we need more applications to run in parallel. It is achieved by the concept of thread. Real-life Example Suppose you are using two tasks at a time on the computer be it using Microsoft Word and listening to music. These two tasks are called processes. So you start typing in Word and at the same time music up there, this is called multitasking. Now you committed a mistake in a Word and spell check shows exception, this means even a Word is a process that is broken down into sub-processes. Now if a machine is dual-core then one process or task is been handled by one core and music is been handled by another core. In the above example, we come across both multiprocessing and multithreading are somehow indirectly used to achieve multitasking. We have achieved In this way the mechanism of dividing the tasks is called multithreading in which every process or task is called by a thread where a thread is responsible for when to execute, when to stop and how long to be in a waiting state. Hence, a thread is the smallest unit of processing whereas multitasking is a process of executing multiple tasks at a time. Multitasking is being achieved in two ways: Multiprocessing: Process-based multitasking is a heavyweight process and occupies different address spaces in memory. Hence, while switching from one process to another will require some time be it very small causing a lag while switching as registers will be loaded in memory maps and the list will be updated.Multithreading: Thread-based multitasking is a lightweight process and occupies the same address space. Hence, while switching cost of communication will be very less. Multiprocessing: Process-based multitasking is a heavyweight process and occupies different address spaces in memory. Hence, while switching from one process to another will require some time be it very small causing a lag while switching as registers will be loaded in memory maps and the list will be updated. Multithreading: Thread-based multitasking is a lightweight process and occupies the same address space. Hence, while switching cost of communication will be very less. Below is the Lifecycle of a Thread been illustrated New: When a thread is just created.Runnable: When a start() method is called over thread processed by the thread scheduler.Case A: Can be a running threadCase B: Can not be a running threadRunning: When it hits case 1 means the scheduler has selected it to be run the thread from runnable state to run state.Blocked: When it hits case 2 meaning the scheduler has selected not to allow a thread to change state from runnable to run.Terminated: When the run() method exists or stop() method is called over a thread. New: When a thread is just created. Runnable: When a start() method is called over thread processed by the thread scheduler.Case A: Can be a running threadCase B: Can not be a running thread Case A: Can be a running thread Case B: Can not be a running thread Running: When it hits case 1 means the scheduler has selected it to be run the thread from runnable state to run state. Blocked: When it hits case 2 meaning the scheduler has selected not to allow a thread to change state from runnable to run. Terminated: When the run() method exists or stop() method is called over a thread. If we do incorporate threads in operating systems one can perceive that the process scheduling algorithms in operating systems are strongly deep-down working on the same concept incorporating thread in Gantt charts. A few of the most popular are listed below which wraps up all of them and are used practically in software development. First In First Out Last In First Out Round Robin Scheduling Now one Imagine the concept of Deadlock in operating systems with threads by now how the switching is getting computed over internally if one only has an overview of them. So bar far we have understood multithreading and thread conceptually, so we can conclude out advantages of multithreading before introducing to any other concept or getting to programs in multithreading. The user is not blocked as threads are independent even if there is an issue with one thread then only the corresponding process will be stopped rest all the operations will be computed successfully. Saves time as too many operations are carried over at the same time causing work to get finished as if threads are not used the only one process will be handled by the processor. Threads are independents though being sharing the same address space. So we have touched all main concepts of multithreading but the question striving in the head is left. why do we need it, where to use it and how? Now, will discuss all three scenarios why multithreading is needed and where it is implemented via the help of programs in which we will be further learning more about threads and their methods. We need multithreading in four scenarios as listed. Thread Class Mobile applicationsAsynchronous thread Asynchronous thread Web applications Game Development Note: By default we only have one main thread which is responsible for main thread exception as you have encountered even without having any prior knowledge of multithreading Using Thread Class Using Runnable Interface Java provides Thread class to achieve programming invoking threads thereby some major methods of thread class are shown below in the tabular format with which we deal frequently along the action performed by them. Pre-requisites: Basic syntax and methods to deal with threads Now let us come up with how to set the name of the thread. By default, threads are named thread-0, thread-1, and so on. But there is also a method been there that is often used refer to as setName() method. Also corresponding to it there is a method getName() which returns the name of the thread be it default or settled already by using setName() method. The syntax is as follows: Syntax: (a) Returning the name of the thread public String getName() ; (b) Changing the name of the thread public void setName(String name); Taking a step further, let us dive into the implementation part to acquire more concepts about multithreading. So, there are basically two ways of implementing multithreading: Illustration: Consider if one has to multiply all elements by 2 and there are 500 elements in an array. Examples Java Java Java // Case 1// Java Program to illustrate Creation and execution of// thread via start() and run() method in Single inheritance // Class 1// Helper thread Class extending main Thread Classclass MyThread1 extends Thread { // Method inside MyThread2 // run() method which is called as // soon as thread is started public void run() { // Print statement when the thread is called System.out.println("Thread1 is running"); }} // Class 2// Main thread Class extending main Thread Classclass MyThread2 extends Thread { // Method inside MyThread2 // run() method which is called // as soon as thread is started public void run() { // run() method which is called as soon as thread is // started // Print statement when the thread is called System.out.println("Thread2 is running"); }} // Class 3// Main Classclass GFG { // Main method public static void main(String[] args) { // Creating a thread object of our thread class MyThread1 obj1 = new MyThread1(); MyThread2 obj2 = new MyThread2(); // Getting the threads to the run state // This thread will transcend from runnable to run // as start() method will look for run() and execute // it obj1.start(); // This thread will also transcend from runnable to // run as start() method will look for run() and // execute it obj2.start(); }} // Case 2// Java Program to illustrate Difference between Runnable// & Non-runnable Threads And Single Inheritance // Class 1// Helper thread Class extending main Thread Classclass MyThread1 extends Thread { // Method inside MyThread2 // run() method which is called as soon as thread is // started public void run() { // Print statement when the thread is called System.out.println("Thread 1 is running"); }} // Class 2// Main thread Class extending main Thread Classclass MyThread2 extends Thread { // Method public void show() { // Print statement when thread is called System.out.println("Thread 2"); }} // Class 3// Main Classclass GFG { // Main method public static void main(String[] args) { // Creating a thread object of our thread class MyThread1 obj1 = new MyThread1(); MyThread2 obj2 = new MyThread2(); // Getting the threads to the run state // This thread will transcend from runnable to run // as start() method will look for run() and execute // it obj1.start(); // This thread will now look for run() method which is absent // Thread is simply created not runnable obj2.start(); }} // Java Program to illustrate difference between// start() method thread vs show() method // Class 1// Helper thread Class extending main Thread Classclass MyThread1 extends Thread { // Method inside MyThread2 // run() method which is called as soon as thread is // started public void run() { // Print statement when the thread is called System.out.println("Thread 1 is running"); }} // Class 2// Main thread Class extending main Thread Classclass MyThread2 extends Thread { // Method public void show() { // Print statement when thread is called System.out.println("Thread 2"); }} // Class 3// Main Classclass GFG { // Main method public static void main(String[] args) { // Creating a thread object of our thread class MyThread1 obj1 = new MyThread1(); MyThread2 obj2 = new MyThread2(); // Getting the threads to the run state // This thread will transcend from runnable to run // as start() method will look for run() and execute // it obj1.start(); // This thread is simply a function call as // no start() method is executed so here only // thread is created only followed by call obj2.show(); }} Case 1: Thread1 is running Thread2 is running Here we do have created our two thread classes for each thread. In the main method, we are simply creating objects of these thread classes where objects are now threads. So in main, we call thread using start() method over both the threads. Now start() method starts the thread and lookup for their run() method to run. Here both of our thread classes were having run() methods, so both threads are put to run state from runnable by the scheduler, and output on the console is justified. Case 2: Thread 1 is running Here we do have created our two thread classes for each thread. In the main method, we are simply creating objects of these thread classes where objects are now threads. So in main, we call thread using start() method over both the threads. Now start() method starts the thread and lookup their run() method to run. Here only class 1 is having the run() method to make the thread transcend from runnable to tun state to execute whereas thread 2 is only created but not put to run state by the scheduler as its corresponding run() method was missing. Hence, only thread 1 is called rest thread 2 is created only and is in the runnable state later blocked by scheduler because the corresponding run() method was missing. Case 3: Thread 2 Thread 1 is running Another way to achieve multithreading in java is via the Runnable interface. Here as we have seen in the above example in way 1 where Thread class is extended. Here Runnable interface being a functional interface has its own run() method. Here classes are implemented to the Runnable interface. Later on, in the main() method, Runnable reference is created for the classes that are implemented in order to make bondage between with Thread class to run our own corresponding run() methods. Further, while creating an object of Thread class we will pass these references in Thread class as its constructor allows an only runnable object, which is passed as a parameter while creating Thread class object in a main() method. Now lastly just likely what we did in Thread class, start() method is invoked over the runnable object who are now already linked with Thread class objects, so the execution begins for our run() methods in case of Runnable interface. It is shown in the program below as follows: Example: Java // Java Program to illustrate Runnable Interface in threads// as multiple inheritance is not allowed // Importing basic packagesimport java.io.*;import java.util.*; // Class 1// Helper class implementing Runnable interfaceclass MyThread1 implements Runnable { // run() method inside this class public void run() { // Iterating to get more execution of threads for (int i = 0; i < 5; i++) { // Print statement whenever run() method // of this class is called System.out.println("Thread1"); // Getting sleep method in try block to // check for any exceptions try { // Making the thread pause for a certain // time using sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (Exception e) { } } }} // Class 2// Helper class implementing Runnable interfaceclass MyThread2 implements Runnable { // run() method inside this class public void run() { for (int i = 0; i < 5; i++) { // Print statement whenever run() method // of this class is called System.out.println("Thread2"); // Getting sleep method in try block to // check for any exceptions try { // Making the thread pause for a certain // time // using sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (Exception e) { } } }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating reference of Runnable to // our classes above in main() method Runnable obj1 = new MyThread1(); Runnable obj2 = new MyThread2(); // Creating reference of thread class // by passing object of Runnable in constructor of // Thread class Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); // Starting the execution of our own run() method // in the classes above t1.start(); t2.start(); }} Thread2 Thread1 Thread2 Thread1 Thread2 Thread1 Thread2 Thread1 Thread2 Thread1 Points to remember: Whenever you wanted to create threads, there are only two ways: Extending the classImplementing the interface which is runnable Extending the class Implementing the interface which is runnable Make sure to create an object of threads in which you have to pass the object of runnable Now let us discuss there are various methods been there for threads. Here we will be discussing out major ones in order to have a practical understanding of threads and multithreading which are sequential as follows: start() Methodsuspend() Method stop() Method wait() Method notify() Method notifyAll() Methodsleep() MethodOutput Without sleep() MethodOutput with sleep() method in Serial Execution Processes (Blocking methods approach)Output with sleep() method in Parallel Execution Processes (Unblocking methods approach)join() Method start() Method suspend() Method stop() Method wait() Method notify() Method notifyAll() Method sleep() MethodOutput Without sleep() MethodOutput with sleep() method in Serial Execution Processes (Blocking methods approach)Output with sleep() method in Parallel Execution Processes (Unblocking methods approach) Output Without sleep() Method Output with sleep() method in Serial Execution Processes (Blocking methods approach) Output with sleep() method in Parallel Execution Processes (Unblocking methods approach) join() Method Note: For naive users in multithreading where threads are backbone go through Program 4 to get very basics of threads, how to start, make it hold, or terminate then only toggle to program 1 and rest as follows. Implementation: Java Java Java // Example 1// Java Program to illustrate Output Without sleep() Method // Class 1// Helper Class 1class Shot extends Thread { // Method 1 public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement whenever method // of this class is called System.out.println("Shot"); } }} // Class 2// Helper Class 2class Miss extends Thread { // Method 2 public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement whenever method // of this class is called System.out.println("Miss"); } } } // Class 3// Main classpublic class GFG { // Method 3 // Main method public static void main(String[] args) { // Creating objects in the main() method // of class 1 and class 2 Shot obj1 = new Shot(); Miss obj2 = new Miss(); // Calling methods of the class 1 and class 2 obj1.show(); obj2.show(); }} // Example 2// Java Program to illustrate Output Using sleep() Method// in Serial Execution // Class 1// Helper Class 1class Shot extends Thread { // Method 1 // public void show() { public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println("Shot"); // Making thread to sleep using sleep() method // Try-catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 2// Helper Class 2 Helloclass Miss extends Thread { // Method 2 // public void show() { public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println("Miss"); // Making thread to sleep using sleep() method // Try-catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 3// Main classpublic class GFG { // Method 3 // Main method public static void main(String[] args) { // Creating objects in the main() method Shot obj1 = new Shot(); Miss obj2 = new Miss(); // Starting the thread objects obj1.start(); obj2.start(); // Calling methods of class 1 and class 2 obj1.show(); obj2.show(); }} // Example 3// Java Program to illustrate Output Using sleep() Method// in Parallel Execution // Class 1// Helper Class 1class Shot extends Thread { // Method 1 // public void show() { public void run() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println("Shot"); // Making thread to sleep using sleep() method // Try catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 2// Helper Class 2 Helloclass Miss extends Thread { // Method 2 // public void show() { public void run() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println("Miss"); // Making thread to sleep using sleep() method // Try catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 3// Main classpublic class GFG { // Method 3 // Main method public static void main(String[] args) { // Creating objects in the main() method Shot obj1 = new Shot(); Miss obj2 = new Miss(); // Starting the thread objects // using start() method // start() method calls the run() method // automatically obj1.start(); obj2.start(); }} Output: Case 1: Shot Shot Shot Shot Shot Miss Miss Miss Miss Miss Case 2: Video output Shot Shot Shot Shot Shot Miss Miss Miss Miss Miss Case 3: Video output Shot Miss Shot Miss Shot Miss Shot Miss Shot Miss Note: There is no priority been set for threads for which as per the order of execution of threads outputs will vary so do remember this drawback of multithreading of different outputs leading to data inconsistency issues which we will be discussing in-depth in the later part under synchronization in threads. Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. The default priority is set to 5 as excepted. Minimum priority is set to 0. Maximum priority is set to 10. Here 3 constants are defined in it namely as follows: public static int NORM_PRIORITYpublic static int MIN_PRIORITYpublic static int MAX_PRIORITY public static int NORM_PRIORITY public static int MIN_PRIORITY public static int MAX_PRIORITY Let us discuss it with an example to get how internally the work is getting executed. Here we will be using the knowledge gathered above as follows: We will use currentThread() method to get the name of the current thread. User can also use setName() method if he/she wants to make names of thread as per choice for understanding purposes. getName() method will be used to get the name of the thread. Java Java Java Java // Java Program to illustrate Priority Threads// Case 1: No priority is assigned (Default priority) // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println("Running Thread : " + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println("Running Thread Priority : " + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Case 1: Default Priority no setting t1.start(); t2.start(); }} // Java Program to illustrate Priority Threads// Case 2: NORM_PRIORITY // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { // run() method to transit thread from // runnable to run state public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println("Running Thread : " + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println("Running Thread Priority : " + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Setting priority to thread via NORM_PRIORITY // which set priority to 5 as default thread t1.setPriority(Thread.NORM_PRIORITY); t2.setPriority(Thread.NORM_PRIORITY); // Setting default priority using // NORM_PRIORITY t1.start(); t2.start(); }} // Java Program to illustrate Priority Threads// Case 3: MIN_PRIORITY // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { // run() method to transit thread from // runnable to run state public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println("Running Thread : " + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println("Running Thread Priority : " + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Setting priority to thread via NORM_PRIORITY // which set priority to 1 as least priority thread t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); // Setting default priority using // NORM_PRIORITY t1.start(); t2.start(); }} // Java Program to illustrate Priority Threads// Case 4: MAX_PRIORITY // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { // run() method to transit thread from // runnable to run state public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println("Running Thread : " + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println("Running Thread Priority : " + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Setting priority to thread via MAX_PRIORITY // which set priority to 1 as most priority thread t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); // Setting default priority using // MAX_PRIORITY // Starting the threads using start() method // which automatically invokes run() method t1.start(); t2.start(); }} Output: Case 1: Default Priority Running Thread : Thread-0 Running Thread : Thread-1 Running Thread Priority : 5 Running Thread Priority : 5 Case 2: NORM_PRIORITY Running Thread : Thread-0 Running Thread : Thread-1 Running Thread Priority : 5 Running Thread Priority : 5 Case 3: MIN_PRIORITY Running Thread : Thread-0 Running Thread : Thread-1 Running Thread Priority : 1 Running Thread Priority : 1 Case 4: MAX_PRIORITY Running Thread : Thread-1 Running Thread : Thread-0 Running Thread Priority : 10 Running Thread Priority : 10 Output Explanation: If we look carefully we do see the outputs for cases 1 and 2 are equivalent. This signifies that when the user is not even aware of the priority threads still NORM_PRIORITY is showcasing the same result up to what default priority is. It is because the default priority of running thread as soon as the corresponding start() method is called is executed as per setting priorities for all the thread to 5 which is equivalent to the priority of NORM case. This is because both the outputs are equivalent to each other. While in case 3 priority is set to a minimum on a scale of 1 to 10 so do the same in case 4 where priority is assigned to 10 on the same scale. Hence, all the outputs in terms of priorities are justified. Now let us move ahead onto an important aspect of priority threading been incorporated in daily life is Daemon thread Daemon thread is basically a service provider thread that provides services to the user thread. The scope for this thread start() or be it terminate() is completely dependent on the user’s thread as it supports in the backend for user threads being getting run. As soon as the user thread is terminated daemon thread is also terminated at the same time as being the service provider thread. Hence, the characteristics of the Daemon thread are as follows: It is only the service provider thread not responsible for interpretation in user threads. So, it is a low-priority thread. It is a dependent thread as it has no existence on its own. JVM terminates the thread as soon as user threads are terminated and come back into play as the user’s thread starts. Yes, you guess the most popular example is garbage collector in java. Some other examples do include ‘finalizer’. Exceptions: IllegalArgumentException as return type while setting a Daemon thread is boolean so do apply carefully. Note: To get rid of the exception users thread should only start after setting it to daemon thread. The other way of starting prior setting it to daemon will not work as it will pop-out IllegalArgumentException As discussed above in the Thread class two most widely used method is as follows: Let us discuss the implementation of the Daemon thread before jumping onto the garbage collector. Java Java // Java Program to show Working of Daemon Thread// with users threads import java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class extending Thread classclass CheckingMyDaemonThread extends Thread { // Method // run() method which is invoked as soon as // thread start via start() public void run() { // Checking whether the thread is daemon thread or // not if (Thread.currentThread().isDaemon()) { // Print statement when Daemon thread is called System.out.println( "I am daemon thread and I am working"); } else { // Print statement whenever users thread is // called System.out.println( "I am user thread and I am working"); } }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating threads in the main body CheckingMyDaemonThread t1 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t2 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t3 = new CheckingMyDaemonThread(); // Setting thread named 't2' as our Daemon thread t2.setDaemon(true); // Starting all 3 threads using start() method t1.start(); t2.start(); t3.start(); // Now start() will automatically // invoke run() method }} // Java Program to show Working of Daemon Thread// with users threads where start() is invoked// prior before setting thread to Daemon import java.io.*;// Basically we are importing Thread class// from java.util packageimport java.util.*; // Class 1// Helper Class extending Thread classclass CheckingMyDaemonThread extends Thread { // Method // run() method which is invoked as soon as // thread start via start() public void run() { // Checking whether the thread is daemon thread or // not if (Thread.currentThread().isDaemon()) { // Print statement when Daemon thread is called System.out.println( "I am daemon thread and I am working"); } else { // Print statement whenever users thread is // called System.out.println( "I am user thread and I am working"); } }} // Class 2// Main Classclass GFG { // Method // Main driver method public static void main(String[] args) { // Creating threads objects of above class // in the main body CheckingMyDaemonThread t1 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t2 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t3 = new CheckingMyDaemonThread(); // Starting all 3 threads using start() method t1.start(); t2.start(); t3.start(); // Now start() will automatically invoke run() // method // Now at last setting already running thread 't2' // as our Daemon thread will throw an exception t2.setDaemon(true); }} Another way to achieve the same is through Thread Group in which as the name suggests multiple threads are treated as a single object and later on all the operations are carried on over this object itself aiding in providing a substitute for the Thread Pool. Note: While implementing ThreadGroup do note that ThreadGroup is a part of ‘java.lang.ThreadGroup’ class not a part of Thread class in java so do peek out constructors and methods of ThreadGroup class before moving ahead keeping a check over deprecated methods in his class so as not to face any ambiguity further. Here main() method in itself is a thread because of which you do see Exception in main() while running the program because of which system.main thread exception is thrown sometimes while execution of the program. It is the mechanism that bounds the access of multiple threads to share a common resource hence is suggested to be useful where only one thread at a time is granted the access to run over. It is implemented in the program by using ‘synchronized‘ keyword. Now let’s finally discuss some advantages and disadvantages of synchronization before implementing the same. For more depth in synchronization, one can also learn object level lock and class level lock and do notice the differences between two to get a fair understanding of the same before implementing the same. Why synchronization is required? Data inconsistency issues are the primary issue where multiple threads are accessing the common memory which sometimes results in faults in order to avoid that a thread is overlooked by another thread if it fails out.Data integrityTo work with a common shared resource which is very essential in the real world such as in banking systems. Data inconsistency issues are the primary issue where multiple threads are accessing the common memory which sometimes results in faults in order to avoid that a thread is overlooked by another thread if it fails out. Data integrity To work with a common shared resource which is very essential in the real world such as in banking systems. Note: Do not go for synchronized keyword unless it is most needed, remember this as there is no priority setup for threads, so if the main thread runs before or after other thread the output of the program would be different. The biggest advantage of synchronization is the increase in idiotic resistance as one can not choose arbitrarily an object to lock on as a result string literal can not be locked or be the content. Hence, these bad practices are not possible to perform on synchronized method block. As we have seen humongous advantages and get to know how important it is but there comes disadvantage with it. Disadvantage: Performance issues will arise as during the execution of one thread all the other threads are put to a blocking state and do note they are not in waiting state. This causes a performance drop if the time taken for one thread is too long. As perceived from the image in which we are getting that count variable being shared resource is updating randomly. It is because of multithreading for which this concept becomes a necessity. Case 1: If ‘main thread’ executes first then count will be incremented followed by a ‘thread T’ in synchronization Case 2: If ‘thread T‘ executes first then count will not increment followed by ‘main thread‘ in synchronization Implementation: Let us take a sample program to observe this 0 1 count conflict Example: Java // Java Program to illustrate Output Conflict between// Execution of Main thread vs Thread created // count = 1 if main thread executes first// count = 1 if created thread executes first // Importing basic required librariesimport java.io.*;import java.util.*; // Class 1// Helper Class extending Thread classclass MyThread extends Thread { // Declaring and initializing initial count to zero int count = 0; // Method 1 // To increment the count above by unity void increment() { count++; } // Method 2 // run method for thread invoked after // created thread has started public void run() { // Call method in this method increment(); // Print and display the count System.out.println("Count : " + count); }} // Class 2public class GFG { // Main driver method public static void main(String[] args) { // Creating the above our Thread class object // in the main() method MyThread t1 = new MyThread(); // start() method to start execution of created // thread that will look for run() method t1.start(); }} Output: Output Explanation: Here the count is incremented to 1 meaning ‘main thread‘ has executed prior to ‘created thread‘. We have run it many times and compiled and run once again wherein all cases here main thread is executing faster than created thread but do remember output may vary. Our created thread can execute prior to ‘main thread‘ leading to ‘Count : 0’ as an output on the console. Now another topic that arises in dealing with synchronization in threads is Thread safety in java synchronization is the new concept that arises out in synchronization so let us discuss it considering A real-life scenario followed by Pictorial representation as an illustration followed by Technically description and implementation Real-life Scenario Suppose a person is withdrawing some amount of money from the bank and at the same time the ATM card registered with the same account number is carrying on withdrawal operation by some other user. Now suppose if withdrawing some amount of money from net banking makes funds in account lesser than the amount which needed to be withdrawal or the other way. This makes the bank unsafe as more funds are debited from the account than was actually present in the account making the bank very unsafe and is not seen in daily life. So what banks do is that they only let one transaction at a time. Once it is over then another is permitted. Illustration: Interpreting the same technology as there are two different processes going on which object in case of parallel execution is over headed by threads. Now possessing such traits over threads such that they should look after for before execution or in simpler words making them synchronized. This mechanism is referred to as Thread Safe with the use of the keyword ‘synchronized‘ before the common shared method/function to be performed parallel. Technical Description: As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe, and we will get inconsistent results. When a thread is already working on an object and preventing another thread from working on the same object, this process is called Thread-Safety. Now there are several ways to achieve thread-safety in our program namely as follows: Using SynchronizationUsing Volatile KeywordUsing Atomic VariableUsing Final Keyword Using Synchronization Using Volatile Keyword Using Atomic Variable Using Final Keyword Conclusion: Hence, if we are accessing one thread at a time then we can say thread-safe program and if multiple threads are getting accessed then the program is said to be thread-unsafe that is one resource at a time can not be shared by multiple threads at a time. Implementation: Java Program to illustrate Incomplete Thread Iterations returning counter value to Zero irrespective of iteration bound Java Program to Illustrate Complete Thread Iterations illustrating join() Method Java Program to Illustrate thread-unsafe or non-synchronizing programs as of incomplete iterations Java Program to Illustrate Thread Safe And synchronized Programs as of Complete iterations using ‘synchronized‘ Keyword. Examples Java Java Java Java // Example 1// Java Program to illustrate Incomplete Thread Iterations// Returning Counter Value to Zero// irrespective of iteration bound // Importing input output classesimport java.io.*; // Class 1// Helper Classclass TickTock { // Member variable of this class int count; // Method of this Class // It increments counter value whenever called public void increment() { // Increment count by unity // i.e count = count + 1; count++; } //} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 10000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method in Ticktock class t1.start(); // Print and display the count System.out.println("Count : " + tt.count); }} // Example 2// Java Program to Illustrate Complete Thread Iterations// illustrating join() Method // Importing input output classesimport java.io.*; // Class 1// Helper Classclass TickTock { // Member variable of this class int count; // Method of this Class public void increment() { // Increment count by unity // whenever this function is called count++; }} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 1000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method t1.start(); // Now we are making main() thread to wait so // that thread t1 completes it job // using join() method t1.join(); // Print and display the count value System.out.println("Count : " + tt.count); }} // Example 3// Java Program to Illustrate Thread Unsafe Or// Non-synchronizing Programs as of Incomplete Iteations// Without using 'synchronized' program // Importing input output classesimport java.io.*; // Class 1// Helper Classclass TickTock { // Member variable of this class int count; // Method of this Class public void increment() { // Increment count by unity count++; }} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Now creating another thread and lets check // how they increment count value running parallelly // Thread 2 Thread t2 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method t1.start(); t2.start(); // Now we are making main() thread to wait so // that thread t1 completes it job t1.join(); t2.join(); // Print and display the count System.out.println("Count : " + tt.count); }} // Example 4// Java Program to Illustrate Thread Safe And// Synchronized Programs as of Complete Iteations// using 'synchronized' Keyword // Importing input output classesimport java.io.*; // Class 1// helper Classclass TickTock { // Member variable of this class int count; // Method of this Class public synchronized void increment() { // Increment count by unity count++; } //} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Thread 2 Thread t2 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method t1.start(); t2.start(); // Now we are making main() thread to wait so // that thread t1 completes it job t1.join(); t2.join(); // Print and display the count System.out.println("Count : " + tt.count); }} Output: Case 1 Count : 0 Case 2 Count : 10000 Case 3 Count : 151138 Case 4 Count : 200000 Output Explanation: In case 1 we can see that count is zero as initialized. Now we have two threads main thread and the thread t1. So there are two threads so now what happens sometimes instance is shared among both of the threads. In case 1 both are accessing the count variable where we are directly trying to access thread via thread t1.count which will throw out 0 always as we need to call it with the help of object to perform the execution. Now we have understood the working of synchronization is a thread that is nothing but referred to as a term Concurrency in java which in layman language is executing multiple tasks. Let us depict concurrency in threads with the help of a pictorial illustration. Consider the task of multiplying an array of elements by a multiplier of 2. Now if we start multiplying every element randomly wise it will take a serious amount of time as every time the element will be searched over and computer. By far we have studied multithreading above in which we have concluded to a single line that thread is the backbone of multithreading. So incorporating threads in the above situation as the machine is quad-core we here take 4 threads for every core where we divide the above computing sample set to (1/4)th resulting out in 4x faster computing. If in the above scenario it had taken 4 seconds then now it will take 1 second only. This mechanism of parallel running threads in order to achieve faster and lag-free computations is known as concurrency. Note: Go for multithreading always for concurrent execution and if not using this concept go for sequential execution despite having bigger chunks of code as safety to our code is the primary issue. anikaseth98 simranarora5sos saurabh1990aror rkbhola5 Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 May, 2022" }, { "code": null, "e": 427, "s": 54, "text": "Threads are the backbone of multithreading. We are living in a real-world which in itself is caught on the web surrounded by lots of applications. Same this with the advancement in technologies we cannot compensate with the speed for which we need to run them simultaneously for which we need more applications to run in parallel. It is achieved by the concept of thread. " }, { "code": null, "e": 446, "s": 427, "text": "Real-life Example " }, { "code": null, "e": 961, "s": 446, "text": "Suppose you are using two tasks at a time on the computer be it using Microsoft Word and listening to music. These two tasks are called processes. So you start typing in Word and at the same time music up there, this is called multitasking. Now you committed a mistake in a Word and spell check shows exception, this means even a Word is a process that is broken down into sub-processes. Now if a machine is dual-core then one process or task is been handled by one core and music is been handled by another core. " }, { "code": null, "e": 1461, "s": 961, "text": "In the above example, we come across both multiprocessing and multithreading are somehow indirectly used to achieve multitasking. We have achieved In this way the mechanism of dividing the tasks is called multithreading in which every process or task is called by a thread where a thread is responsible for when to execute, when to stop and how long to be in a waiting state. Hence, a thread is the smallest unit of processing whereas multitasking is a process of executing multiple tasks at a time." }, { "code": null, "e": 1505, "s": 1461, "text": "Multitasking is being achieved in two ways:" }, { "code": null, "e": 1984, "s": 1505, "text": "Multiprocessing: Process-based multitasking is a heavyweight process and occupies different address spaces in memory. Hence, while switching from one process to another will require some time be it very small causing a lag while switching as registers will be loaded in memory maps and the list will be updated.Multithreading: Thread-based multitasking is a lightweight process and occupies the same address space. Hence, while switching cost of communication will be very less." }, { "code": null, "e": 2296, "s": 1984, "text": "Multiprocessing: Process-based multitasking is a heavyweight process and occupies different address spaces in memory. Hence, while switching from one process to another will require some time be it very small causing a lag while switching as registers will be loaded in memory maps and the list will be updated." }, { "code": null, "e": 2464, "s": 2296, "text": "Multithreading: Thread-based multitasking is a lightweight process and occupies the same address space. Hence, while switching cost of communication will be very less." }, { "code": null, "e": 2516, "s": 2464, "text": "Below is the Lifecycle of a Thread been illustrated" }, { "code": null, "e": 3030, "s": 2516, "text": "New: When a thread is just created.Runnable: When a start() method is called over thread processed by the thread scheduler.Case A: Can be a running threadCase B: Can not be a running threadRunning: When it hits case 1 means the scheduler has selected it to be run the thread from runnable state to run state.Blocked: When it hits case 2 meaning the scheduler has selected not to allow a thread to change state from runnable to run.Terminated: When the run() method exists or stop() method is called over a thread." }, { "code": null, "e": 3066, "s": 3030, "text": "New: When a thread is just created." }, { "code": null, "e": 3221, "s": 3066, "text": "Runnable: When a start() method is called over thread processed by the thread scheduler.Case A: Can be a running threadCase B: Can not be a running thread" }, { "code": null, "e": 3253, "s": 3221, "text": "Case A: Can be a running thread" }, { "code": null, "e": 3289, "s": 3253, "text": "Case B: Can not be a running thread" }, { "code": null, "e": 3409, "s": 3289, "text": "Running: When it hits case 1 means the scheduler has selected it to be run the thread from runnable state to run state." }, { "code": null, "e": 3533, "s": 3409, "text": "Blocked: When it hits case 2 meaning the scheduler has selected not to allow a thread to change state from runnable to run." }, { "code": null, "e": 3616, "s": 3533, "text": "Terminated: When the run() method exists or stop() method is called over a thread." }, { "code": null, "e": 3952, "s": 3616, "text": "If we do incorporate threads in operating systems one can perceive that the process scheduling algorithms in operating systems are strongly deep-down working on the same concept incorporating thread in Gantt charts. A few of the most popular are listed below which wraps up all of them and are used practically in software development." }, { "code": null, "e": 3971, "s": 3952, "text": "First In First Out" }, { "code": null, "e": 3989, "s": 3971, "text": "Last In First Out" }, { "code": null, "e": 4012, "s": 3989, "text": "Round Robin Scheduling" }, { "code": null, "e": 4185, "s": 4012, "text": "Now one Imagine the concept of Deadlock in operating systems with threads by now how the switching is getting computed over internally if one only has an overview of them. " }, { "code": null, "e": 4389, "s": 4185, "text": "So bar far we have understood multithreading and thread conceptually, so we can conclude out advantages of multithreading before introducing to any other concept or getting to programs in multithreading." }, { "code": null, "e": 4589, "s": 4389, "text": "The user is not blocked as threads are independent even if there is an issue with one thread then only the corresponding process will be stopped rest all the operations will be computed successfully." }, { "code": null, "e": 4768, "s": 4589, "text": "Saves time as too many operations are carried over at the same time causing work to get finished as if threads are not used the only one process will be handled by the processor." }, { "code": null, "e": 4838, "s": 4768, "text": "Threads are independents though being sharing the same address space." }, { "code": null, "e": 5231, "s": 4838, "text": "So we have touched all main concepts of multithreading but the question striving in the head is left. why do we need it, where to use it and how? Now, will discuss all three scenarios why multithreading is needed and where it is implemented via the help of programs in which we will be further learning more about threads and their methods. We need multithreading in four scenarios as listed." }, { "code": null, "e": 5244, "s": 5231, "text": "Thread Class" }, { "code": null, "e": 5283, "s": 5244, "text": "Mobile applicationsAsynchronous thread" }, { "code": null, "e": 5303, "s": 5283, "text": "Asynchronous thread" }, { "code": null, "e": 5320, "s": 5303, "text": "Web applications" }, { "code": null, "e": 5337, "s": 5320, "text": "Game Development" }, { "code": null, "e": 5512, "s": 5337, "text": "Note: By default we only have one main thread which is responsible for main thread exception as you have encountered even without having any prior knowledge of multithreading" }, { "code": null, "e": 5531, "s": 5512, "text": "Using Thread Class" }, { "code": null, "e": 5556, "s": 5531, "text": "Using Runnable Interface" }, { "code": null, "e": 5770, "s": 5556, "text": "Java provides Thread class to achieve programming invoking threads thereby some major methods of thread class are shown below in the tabular format with which we deal frequently along the action performed by them." }, { "code": null, "e": 5832, "s": 5770, "text": "Pre-requisites: Basic syntax and methods to deal with threads" }, { "code": null, "e": 6215, "s": 5832, "text": "Now let us come up with how to set the name of the thread. By default, threads are named thread-0, thread-1, and so on. But there is also a method been there that is often used refer to as setName() method. Also corresponding to it there is a method getName() which returns the name of the thread be it default or settled already by using setName() method. The syntax is as follows:" }, { "code": null, "e": 6224, "s": 6215, "text": "Syntax: " }, { "code": null, "e": 6261, "s": 6224, "text": "(a) Returning the name of the thread" }, { "code": null, "e": 6287, "s": 6261, "text": "public String getName() ;" }, { "code": null, "e": 6323, "s": 6287, "text": "(b) Changing the name of the thread" }, { "code": null, "e": 6358, "s": 6323, "text": " public void setName(String name);" }, { "code": null, "e": 6534, "s": 6358, "text": "Taking a step further, let us dive into the implementation part to acquire more concepts about multithreading. So, there are basically two ways of implementing multithreading:" }, { "code": null, "e": 6638, "s": 6534, "text": "Illustration: Consider if one has to multiply all elements by 2 and there are 500 elements in an array." }, { "code": null, "e": 6649, "s": 6638, "text": "Examples " }, { "code": null, "e": 6654, "s": 6649, "text": "Java" }, { "code": null, "e": 6659, "s": 6654, "text": "Java" }, { "code": null, "e": 6664, "s": 6659, "text": "Java" }, { "code": "// Case 1// Java Program to illustrate Creation and execution of// thread via start() and run() method in Single inheritance // Class 1// Helper thread Class extending main Thread Classclass MyThread1 extends Thread { // Method inside MyThread2 // run() method which is called as // soon as thread is started public void run() { // Print statement when the thread is called System.out.println(\"Thread1 is running\"); }} // Class 2// Main thread Class extending main Thread Classclass MyThread2 extends Thread { // Method inside MyThread2 // run() method which is called // as soon as thread is started public void run() { // run() method which is called as soon as thread is // started // Print statement when the thread is called System.out.println(\"Thread2 is running\"); }} // Class 3// Main Classclass GFG { // Main method public static void main(String[] args) { // Creating a thread object of our thread class MyThread1 obj1 = new MyThread1(); MyThread2 obj2 = new MyThread2(); // Getting the threads to the run state // This thread will transcend from runnable to run // as start() method will look for run() and execute // it obj1.start(); // This thread will also transcend from runnable to // run as start() method will look for run() and // execute it obj2.start(); }}", "e": 8126, "s": 6664, "text": null }, { "code": "// Case 2// Java Program to illustrate Difference between Runnable// & Non-runnable Threads And Single Inheritance // Class 1// Helper thread Class extending main Thread Classclass MyThread1 extends Thread { // Method inside MyThread2 // run() method which is called as soon as thread is // started public void run() { // Print statement when the thread is called System.out.println(\"Thread 1 is running\"); }} // Class 2// Main thread Class extending main Thread Classclass MyThread2 extends Thread { // Method public void show() { // Print statement when thread is called System.out.println(\"Thread 2\"); }} // Class 3// Main Classclass GFG { // Main method public static void main(String[] args) { // Creating a thread object of our thread class MyThread1 obj1 = new MyThread1(); MyThread2 obj2 = new MyThread2(); // Getting the threads to the run state // This thread will transcend from runnable to run // as start() method will look for run() and execute // it obj1.start(); // This thread will now look for run() method which is absent // Thread is simply created not runnable obj2.start(); }}", "e": 9372, "s": 8126, "text": null }, { "code": "// Java Program to illustrate difference between// start() method thread vs show() method // Class 1// Helper thread Class extending main Thread Classclass MyThread1 extends Thread { // Method inside MyThread2 // run() method which is called as soon as thread is // started public void run() { // Print statement when the thread is called System.out.println(\"Thread 1 is running\"); }} // Class 2// Main thread Class extending main Thread Classclass MyThread2 extends Thread { // Method public void show() { // Print statement when thread is called System.out.println(\"Thread 2\"); }} // Class 3// Main Classclass GFG { // Main method public static void main(String[] args) { // Creating a thread object of our thread class MyThread1 obj1 = new MyThread1(); MyThread2 obj2 = new MyThread2(); // Getting the threads to the run state // This thread will transcend from runnable to run // as start() method will look for run() and execute // it obj1.start(); // This thread is simply a function call as // no start() method is executed so here only // thread is created only followed by call obj2.show(); }}", "e": 10629, "s": 9372, "text": null }, { "code": null, "e": 10638, "s": 10629, "text": "Case 1: " }, { "code": null, "e": 10676, "s": 10638, "text": "Thread1 is running\nThread2 is running" }, { "code": null, "e": 11165, "s": 10676, "text": "Here we do have created our two thread classes for each thread. In the main method, we are simply creating objects of these thread classes where objects are now threads. So in main, we call thread using start() method over both the threads. Now start() method starts the thread and lookup for their run() method to run. Here both of our thread classes were having run() methods, so both threads are put to run state from runnable by the scheduler, and output on the console is justified." }, { "code": null, "e": 11173, "s": 11165, "text": "Case 2:" }, { "code": null, "e": 11193, "s": 11173, "text": "Thread 1 is running" }, { "code": null, "e": 11912, "s": 11193, "text": "Here we do have created our two thread classes for each thread. In the main method, we are simply creating objects of these thread classes where objects are now threads. So in main, we call thread using start() method over both the threads. Now start() method starts the thread and lookup their run() method to run. Here only class 1 is having the run() method to make the thread transcend from runnable to tun state to execute whereas thread 2 is only created but not put to run state by the scheduler as its corresponding run() method was missing. Hence, only thread 1 is called rest thread 2 is created only and is in the runnable state later blocked by scheduler because the corresponding run() method was missing." }, { "code": null, "e": 11920, "s": 11912, "text": "Case 3:" }, { "code": null, "e": 11949, "s": 11920, "text": "Thread 2\nThread 1 is running" }, { "code": null, "e": 12950, "s": 11949, "text": "Another way to achieve multithreading in java is via the Runnable interface. Here as we have seen in the above example in way 1 where Thread class is extended. Here Runnable interface being a functional interface has its own run() method. Here classes are implemented to the Runnable interface. Later on, in the main() method, Runnable reference is created for the classes that are implemented in order to make bondage between with Thread class to run our own corresponding run() methods. Further, while creating an object of Thread class we will pass these references in Thread class as its constructor allows an only runnable object, which is passed as a parameter while creating Thread class object in a main() method. Now lastly just likely what we did in Thread class, start() method is invoked over the runnable object who are now already linked with Thread class objects, so the execution begins for our run() methods in case of Runnable interface. It is shown in the program below as follows:" }, { "code": null, "e": 12959, "s": 12950, "text": "Example:" }, { "code": null, "e": 12964, "s": 12959, "text": "Java" }, { "code": "// Java Program to illustrate Runnable Interface in threads// as multiple inheritance is not allowed // Importing basic packagesimport java.io.*;import java.util.*; // Class 1// Helper class implementing Runnable interfaceclass MyThread1 implements Runnable { // run() method inside this class public void run() { // Iterating to get more execution of threads for (int i = 0; i < 5; i++) { // Print statement whenever run() method // of this class is called System.out.println(\"Thread1\"); // Getting sleep method in try block to // check for any exceptions try { // Making the thread pause for a certain // time using sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (Exception e) { } } }} // Class 2// Helper class implementing Runnable interfaceclass MyThread2 implements Runnable { // run() method inside this class public void run() { for (int i = 0; i < 5; i++) { // Print statement whenever run() method // of this class is called System.out.println(\"Thread2\"); // Getting sleep method in try block to // check for any exceptions try { // Making the thread pause for a certain // time // using sleep() method Thread.sleep(1000); } // Catch block to handle the exceptions catch (Exception e) { } } }} // Class 3// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating reference of Runnable to // our classes above in main() method Runnable obj1 = new MyThread1(); Runnable obj2 = new MyThread2(); // Creating reference of thread class // by passing object of Runnable in constructor of // Thread class Thread t1 = new Thread(obj1); Thread t2 = new Thread(obj2); // Starting the execution of our own run() method // in the classes above t1.start(); t2.start(); }}", "e": 15216, "s": 12964, "text": null }, { "code": null, "e": 15296, "s": 15216, "text": "Thread2\nThread1\nThread2\nThread1\nThread2\nThread1\nThread2\nThread1\nThread2\nThread1" }, { "code": null, "e": 15380, "s": 15296, "text": "Points to remember: Whenever you wanted to create threads, there are only two ways:" }, { "code": null, "e": 15444, "s": 15380, "text": "Extending the classImplementing the interface which is runnable" }, { "code": null, "e": 15464, "s": 15444, "text": "Extending the class" }, { "code": null, "e": 15509, "s": 15464, "text": "Implementing the interface which is runnable" }, { "code": null, "e": 15601, "s": 15509, "text": "Make sure to create an object of threads in which you have to pass the object of runnable " }, { "code": null, "e": 15819, "s": 15601, "text": "Now let us discuss there are various methods been there for threads. Here we will be discussing out major ones in order to have a practical understanding of threads and multithreading which are sequential as follows: " }, { "code": null, "e": 16141, "s": 15819, "text": "start() Methodsuspend() Method stop() Method wait() Method notify() Method notifyAll() Methodsleep() MethodOutput Without sleep() MethodOutput with sleep() method in Serial Execution Processes (Blocking methods approach)Output with sleep() method in Parallel Execution Processes (Unblocking methods approach)join() Method" }, { "code": null, "e": 16156, "s": 16141, "text": "start() Method" }, { "code": null, "e": 16174, "s": 16156, "text": "suspend() Method " }, { "code": null, "e": 16189, "s": 16174, "text": "stop() Method " }, { "code": null, "e": 16204, "s": 16189, "text": "wait() Method " }, { "code": null, "e": 16221, "s": 16204, "text": "notify() Method " }, { "code": null, "e": 16240, "s": 16221, "text": "notifyAll() Method" }, { "code": null, "e": 16456, "s": 16240, "text": "sleep() MethodOutput Without sleep() MethodOutput with sleep() method in Serial Execution Processes (Blocking methods approach)Output with sleep() method in Parallel Execution Processes (Unblocking methods approach)" }, { "code": null, "e": 16486, "s": 16456, "text": "Output Without sleep() Method" }, { "code": null, "e": 16571, "s": 16486, "text": "Output with sleep() method in Serial Execution Processes (Blocking methods approach)" }, { "code": null, "e": 16660, "s": 16571, "text": "Output with sleep() method in Parallel Execution Processes (Unblocking methods approach)" }, { "code": null, "e": 16674, "s": 16660, "text": "join() Method" }, { "code": null, "e": 16886, "s": 16674, "text": "Note: For naive users in multithreading where threads are backbone go through Program 4 to get very basics of threads, how to start, make it hold, or terminate then only toggle to program 1 and rest as follows. " }, { "code": null, "e": 16903, "s": 16886, "text": "Implementation: " }, { "code": null, "e": 16908, "s": 16903, "text": "Java" }, { "code": null, "e": 16913, "s": 16908, "text": "Java" }, { "code": null, "e": 16918, "s": 16913, "text": "Java" }, { "code": "// Example 1// Java Program to illustrate Output Without sleep() Method // Class 1// Helper Class 1class Shot extends Thread { // Method 1 public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement whenever method // of this class is called System.out.println(\"Shot\"); } }} // Class 2// Helper Class 2class Miss extends Thread { // Method 2 public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement whenever method // of this class is called System.out.println(\"Miss\"); } } } // Class 3// Main classpublic class GFG { // Method 3 // Main method public static void main(String[] args) { // Creating objects in the main() method // of class 1 and class 2 Shot obj1 = new Shot(); Miss obj2 = new Miss(); // Calling methods of the class 1 and class 2 obj1.show(); obj2.show(); }}", "e": 18002, "s": 16918, "text": null }, { "code": "// Example 2// Java Program to illustrate Output Using sleep() Method// in Serial Execution // Class 1// Helper Class 1class Shot extends Thread { // Method 1 // public void show() { public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println(\"Shot\"); // Making thread to sleep using sleep() method // Try-catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 2// Helper Class 2 Helloclass Miss extends Thread { // Method 2 // public void show() { public void show() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println(\"Miss\"); // Making thread to sleep using sleep() method // Try-catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 3// Main classpublic class GFG { // Method 3 // Main method public static void main(String[] args) { // Creating objects in the main() method Shot obj1 = new Shot(); Miss obj2 = new Miss(); // Starting the thread objects obj1.start(); obj2.start(); // Calling methods of class 1 and class 2 obj1.show(); obj2.show(); }}", "e": 19539, "s": 18002, "text": null }, { "code": "// Example 3// Java Program to illustrate Output Using sleep() Method// in Parallel Execution // Class 1// Helper Class 1class Shot extends Thread { // Method 1 // public void show() { public void run() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println(\"Shot\"); // Making thread to sleep using sleep() method // Try catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 2// Helper Class 2 Helloclass Miss extends Thread { // Method 2 // public void show() { public void run() { // Iterating to print more number of times for (int i = 0; i < 5; i++) { // Print statement System.out.println(\"Miss\"); // Making thread to sleep using sleep() method // Try catch block for exceptions try { Thread.sleep(1000); } catch (Exception e) { } } }} // Class 3// Main classpublic class GFG { // Method 3 // Main method public static void main(String[] args) { // Creating objects in the main() method Shot obj1 = new Shot(); Miss obj2 = new Miss(); // Starting the thread objects // using start() method // start() method calls the run() method // automatically obj1.start(); obj2.start(); }}", "e": 21090, "s": 19539, "text": null }, { "code": null, "e": 21098, "s": 21090, "text": "Output:" }, { "code": null, "e": 21106, "s": 21098, "text": "Case 1:" }, { "code": null, "e": 21156, "s": 21106, "text": "Shot\nShot\nShot\nShot\nShot\nMiss\nMiss\nMiss\nMiss\nMiss" }, { "code": null, "e": 21177, "s": 21156, "text": "Case 2: Video output" }, { "code": null, "e": 21227, "s": 21177, "text": "Shot\nShot\nShot\nShot\nShot\nMiss\nMiss\nMiss\nMiss\nMiss" }, { "code": null, "e": 21249, "s": 21227, "text": "Case 3: Video output " }, { "code": null, "e": 21299, "s": 21249, "text": "Shot\nMiss\nShot\nMiss\nShot\nMiss\nShot\nMiss\nShot\nMiss" }, { "code": null, "e": 21611, "s": 21299, "text": "Note: There is no priority been set for threads for which as per the order of execution of threads outputs will vary so do remember this drawback of multithreading of different outputs leading to data inconsistency issues which we will be discussing in-depth in the later part under synchronization in threads. " }, { "code": null, "e": 21816, "s": 21611, "text": "Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. " }, { "code": null, "e": 21862, "s": 21816, "text": "The default priority is set to 5 as excepted." }, { "code": null, "e": 21892, "s": 21862, "text": "Minimum priority is set to 0." }, { "code": null, "e": 21923, "s": 21892, "text": "Maximum priority is set to 10." }, { "code": null, "e": 21977, "s": 21923, "text": "Here 3 constants are defined in it namely as follows:" }, { "code": null, "e": 22069, "s": 21977, "text": "public static int NORM_PRIORITYpublic static int MIN_PRIORITYpublic static int MAX_PRIORITY" }, { "code": null, "e": 22101, "s": 22069, "text": "public static int NORM_PRIORITY" }, { "code": null, "e": 22132, "s": 22101, "text": "public static int MIN_PRIORITY" }, { "code": null, "e": 22163, "s": 22132, "text": "public static int MAX_PRIORITY" }, { "code": null, "e": 22312, "s": 22163, "text": "Let us discuss it with an example to get how internally the work is getting executed. Here we will be using the knowledge gathered above as follows:" }, { "code": null, "e": 22503, "s": 22312, "text": "We will use currentThread() method to get the name of the current thread. User can also use setName() method if he/she wants to make names of thread as per choice for understanding purposes." }, { "code": null, "e": 22564, "s": 22503, "text": "getName() method will be used to get the name of the thread." }, { "code": null, "e": 22569, "s": 22564, "text": "Java" }, { "code": null, "e": 22574, "s": 22569, "text": "Java" }, { "code": null, "e": 22579, "s": 22574, "text": "Java" }, { "code": null, "e": 22584, "s": 22579, "text": "Java" }, { "code": "// Java Program to illustrate Priority Threads// Case 1: No priority is assigned (Default priority) // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println(\"Running Thread : \" + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println(\"Running Thread Priority : \" + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Case 1: Default Priority no setting t1.start(); t2.start(); }}", "e": 23715, "s": 22584, "text": null }, { "code": "// Java Program to illustrate Priority Threads// Case 2: NORM_PRIORITY // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { // run() method to transit thread from // runnable to run state public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println(\"Running Thread : \" + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println(\"Running Thread Priority : \" + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Setting priority to thread via NORM_PRIORITY // which set priority to 5 as default thread t1.setPriority(Thread.NORM_PRIORITY); t2.setPriority(Thread.NORM_PRIORITY); // Setting default priority using // NORM_PRIORITY t1.start(); t2.start(); }}", "e": 25104, "s": 23715, "text": null }, { "code": "// Java Program to illustrate Priority Threads// Case 3: MIN_PRIORITY // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { // run() method to transit thread from // runnable to run state public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println(\"Running Thread : \" + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println(\"Running Thread Priority : \" + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Setting priority to thread via NORM_PRIORITY // which set priority to 1 as least priority thread t1.setPriority(Thread.MIN_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); // Setting default priority using // NORM_PRIORITY t1.start(); t2.start(); }}", "e": 26497, "s": 25104, "text": null }, { "code": "// Java Program to illustrate Priority Threads// Case 4: MAX_PRIORITY // Importing input output thread classimport java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class (Our thread class)class MyThread extends Thread { // run() method to transit thread from // runnable to run state public void run() { // Printing the current running thread via getName() // method using currentThread() method System.out.println(\"Running Thread : \" + currentThread().getName()); // Print and display the priority of current thread // via currentThread() using getPriority() method System.out.println(\"Running Thread Priority : \" + currentThread().getPriority()); }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating objects of MyThread(above class) // in the main() method MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); // Setting priority to thread via MAX_PRIORITY // which set priority to 1 as most priority thread t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MAX_PRIORITY); // Setting default priority using // MAX_PRIORITY // Starting the threads using start() method // which automatically invokes run() method t1.start(); t2.start(); }}", "e": 27991, "s": 26497, "text": null }, { "code": null, "e": 27999, "s": 27991, "text": "Output:" }, { "code": null, "e": 28024, "s": 27999, "text": "Case 1: Default Priority" }, { "code": null, "e": 28132, "s": 28024, "text": "Running Thread : Thread-0\nRunning Thread : Thread-1\nRunning Thread Priority : 5\nRunning Thread Priority : 5" }, { "code": null, "e": 28154, "s": 28132, "text": "Case 2: NORM_PRIORITY" }, { "code": null, "e": 28262, "s": 28154, "text": "Running Thread : Thread-0\nRunning Thread : Thread-1\nRunning Thread Priority : 5\nRunning Thread Priority : 5" }, { "code": null, "e": 28283, "s": 28262, "text": "Case 3: MIN_PRIORITY" }, { "code": null, "e": 28391, "s": 28283, "text": "Running Thread : Thread-0\nRunning Thread : Thread-1\nRunning Thread Priority : 1\nRunning Thread Priority : 1" }, { "code": null, "e": 28412, "s": 28391, "text": "Case 4: MAX_PRIORITY" }, { "code": null, "e": 28522, "s": 28412, "text": "Running Thread : Thread-1\nRunning Thread : Thread-0\nRunning Thread Priority : 10\nRunning Thread Priority : 10" }, { "code": null, "e": 28543, "s": 28522, "text": "Output Explanation: " }, { "code": null, "e": 29205, "s": 28543, "text": "If we look carefully we do see the outputs for cases 1 and 2 are equivalent. This signifies that when the user is not even aware of the priority threads still NORM_PRIORITY is showcasing the same result up to what default priority is. It is because the default priority of running thread as soon as the corresponding start() method is called is executed as per setting priorities for all the thread to 5 which is equivalent to the priority of NORM case. This is because both the outputs are equivalent to each other. While in case 3 priority is set to a minimum on a scale of 1 to 10 so do the same in case 4 where priority is assigned to 10 on the same scale. " }, { "code": null, "e": 29384, "s": 29205, "text": "Hence, all the outputs in terms of priorities are justified. Now let us move ahead onto an important aspect of priority threading been incorporated in daily life is Daemon thread" }, { "code": null, "e": 29775, "s": 29384, "text": "Daemon thread is basically a service provider thread that provides services to the user thread. The scope for this thread start() or be it terminate() is completely dependent on the user’s thread as it supports in the backend for user threads being getting run. As soon as the user thread is terminated daemon thread is also terminated at the same time as being the service provider thread." }, { "code": null, "e": 29839, "s": 29775, "text": "Hence, the characteristics of the Daemon thread are as follows:" }, { "code": null, "e": 29930, "s": 29839, "text": "It is only the service provider thread not responsible for interpretation in user threads." }, { "code": null, "e": 29963, "s": 29930, "text": "So, it is a low-priority thread." }, { "code": null, "e": 30023, "s": 29963, "text": "It is a dependent thread as it has no existence on its own." }, { "code": null, "e": 30141, "s": 30023, "text": "JVM terminates the thread as soon as user threads are terminated and come back into play as the user’s thread starts." }, { "code": null, "e": 30255, "s": 30141, "text": "Yes, you guess the most popular example is garbage collector in java. Some other examples do include ‘finalizer’." }, { "code": null, "e": 30371, "s": 30255, "text": "Exceptions: IllegalArgumentException as return type while setting a Daemon thread is boolean so do apply carefully." }, { "code": null, "e": 30583, "s": 30371, "text": "Note: To get rid of the exception users thread should only start after setting it to daemon thread. The other way of starting prior setting it to daemon will not work as it will pop-out IllegalArgumentException " }, { "code": null, "e": 30665, "s": 30583, "text": "As discussed above in the Thread class two most widely used method is as follows:" }, { "code": null, "e": 30763, "s": 30665, "text": "Let us discuss the implementation of the Daemon thread before jumping onto the garbage collector." }, { "code": null, "e": 30768, "s": 30763, "text": "Java" }, { "code": null, "e": 30773, "s": 30768, "text": "Java" }, { "code": "// Java Program to show Working of Daemon Thread// with users threads import java.io.*;// Importing Thread class from java.util packageimport java.util.*; // Class 1// Helper Class extending Thread classclass CheckingMyDaemonThread extends Thread { // Method // run() method which is invoked as soon as // thread start via start() public void run() { // Checking whether the thread is daemon thread or // not if (Thread.currentThread().isDaemon()) { // Print statement when Daemon thread is called System.out.println( \"I am daemon thread and I am working\"); } else { // Print statement whenever users thread is // called System.out.println( \"I am user thread and I am working\"); } }} // Class 2// Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating threads in the main body CheckingMyDaemonThread t1 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t2 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t3 = new CheckingMyDaemonThread(); // Setting thread named 't2' as our Daemon thread t2.setDaemon(true); // Starting all 3 threads using start() method t1.start(); t2.start(); t3.start(); // Now start() will automatically // invoke run() method }}", "e": 32263, "s": 30773, "text": null }, { "code": "// Java Program to show Working of Daemon Thread// with users threads where start() is invoked// prior before setting thread to Daemon import java.io.*;// Basically we are importing Thread class// from java.util packageimport java.util.*; // Class 1// Helper Class extending Thread classclass CheckingMyDaemonThread extends Thread { // Method // run() method which is invoked as soon as // thread start via start() public void run() { // Checking whether the thread is daemon thread or // not if (Thread.currentThread().isDaemon()) { // Print statement when Daemon thread is called System.out.println( \"I am daemon thread and I am working\"); } else { // Print statement whenever users thread is // called System.out.println( \"I am user thread and I am working\"); } }} // Class 2// Main Classclass GFG { // Method // Main driver method public static void main(String[] args) { // Creating threads objects of above class // in the main body CheckingMyDaemonThread t1 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t2 = new CheckingMyDaemonThread(); CheckingMyDaemonThread t3 = new CheckingMyDaemonThread(); // Starting all 3 threads using start() method t1.start(); t2.start(); t3.start(); // Now start() will automatically invoke run() // method // Now at last setting already running thread 't2' // as our Daemon thread will throw an exception t2.setDaemon(true); }}", "e": 33939, "s": 32263, "text": null }, { "code": null, "e": 34203, "s": 33942, "text": "Another way to achieve the same is through Thread Group in which as the name suggests multiple threads are treated as a single object and later on all the operations are carried on over this object itself aiding in providing a substitute for the Thread Pool. " }, { "code": null, "e": 34212, "s": 34205, "text": "Note: " }, { "code": null, "e": 34522, "s": 34212, "text": "While implementing ThreadGroup do note that ThreadGroup is a part of ‘java.lang.ThreadGroup’ class not a part of Thread class in java so do peek out constructors and methods of ThreadGroup class before moving ahead keeping a check over deprecated methods in his class so as not to face any ambiguity further. " }, { "code": null, "e": 34737, "s": 34524, "text": "Here main() method in itself is a thread because of which you do see Exception in main() while running the program because of which system.main thread exception is thrown sometimes while execution of the program." }, { "code": null, "e": 34930, "s": 34741, "text": "It is the mechanism that bounds the access of multiple threads to share a common resource hence is suggested to be useful where only one thread at a time is granted the access to run over." }, { "code": null, "e": 34998, "s": 34932, "text": "It is implemented in the program by using ‘synchronized‘ keyword." }, { "code": null, "e": 35314, "s": 35000, "text": "Now let’s finally discuss some advantages and disadvantages of synchronization before implementing the same. For more depth in synchronization, one can also learn object level lock and class level lock and do notice the differences between two to get a fair understanding of the same before implementing the same." }, { "code": null, "e": 35349, "s": 35316, "text": "Why synchronization is required?" }, { "code": null, "e": 35690, "s": 35351, "text": "Data inconsistency issues are the primary issue where multiple threads are accessing the common memory which sometimes results in faults in order to avoid that a thread is overlooked by another thread if it fails out.Data integrityTo work with a common shared resource which is very essential in the real world such as in banking systems." }, { "code": null, "e": 35908, "s": 35690, "text": "Data inconsistency issues are the primary issue where multiple threads are accessing the common memory which sometimes results in faults in order to avoid that a thread is overlooked by another thread if it fails out." }, { "code": null, "e": 35923, "s": 35908, "text": "Data integrity" }, { "code": null, "e": 36031, "s": 35923, "text": "To work with a common shared resource which is very essential in the real world such as in banking systems." }, { "code": null, "e": 36257, "s": 36031, "text": "Note: Do not go for synchronized keyword unless it is most needed, remember this as there is no priority setup for threads, so if the main thread runs before or after other thread the output of the program would be different." }, { "code": null, "e": 36542, "s": 36259, "text": "The biggest advantage of synchronization is the increase in idiotic resistance as one can not choose arbitrarily an object to lock on as a result string literal can not be locked or be the content. Hence, these bad practices are not possible to perform on synchronized method block." }, { "code": null, "e": 36655, "s": 36544, "text": "As we have seen humongous advantages and get to know how important it is but there comes disadvantage with it." }, { "code": null, "e": 36909, "s": 36657, "text": "Disadvantage: Performance issues will arise as during the execution of one thread all the other threads are put to a blocking state and do note they are not in waiting state. This causes a performance drop if the time taken for one thread is too long." }, { "code": null, "e": 37105, "s": 36913, "text": "As perceived from the image in which we are getting that count variable being shared resource is updating randomly. It is because of multithreading for which this concept becomes a necessity." }, { "code": null, "e": 37222, "s": 37107, "text": "Case 1: If ‘main thread’ executes first then count will be incremented followed by a ‘thread T’ in synchronization" }, { "code": null, "e": 37334, "s": 37222, "text": "Case 2: If ‘thread T‘ executes first then count will not increment followed by ‘main thread‘ in synchronization" }, { "code": null, "e": 37416, "s": 37336, "text": "Implementation: Let us take a sample program to observe this 0 1 count conflict" }, { "code": null, "e": 37427, "s": 37418, "text": "Example:" }, { "code": null, "e": 37434, "s": 37429, "text": "Java" }, { "code": "// Java Program to illustrate Output Conflict between// Execution of Main thread vs Thread created // count = 1 if main thread executes first// count = 1 if created thread executes first // Importing basic required librariesimport java.io.*;import java.util.*; // Class 1// Helper Class extending Thread classclass MyThread extends Thread { // Declaring and initializing initial count to zero int count = 0; // Method 1 // To increment the count above by unity void increment() { count++; } // Method 2 // run method for thread invoked after // created thread has started public void run() { // Call method in this method increment(); // Print and display the count System.out.println(\"Count : \" + count); }} // Class 2public class GFG { // Main driver method public static void main(String[] args) { // Creating the above our Thread class object // in the main() method MyThread t1 = new MyThread(); // start() method to start execution of created // thread that will look for run() method t1.start(); }}", "e": 38562, "s": 37434, "text": null }, { "code": null, "e": 38570, "s": 38562, "text": "Output:" }, { "code": null, "e": 38592, "s": 38572, "text": "Output Explanation:" }, { "code": null, "e": 38963, "s": 38592, "text": "Here the count is incremented to 1 meaning ‘main thread‘ has executed prior to ‘created thread‘. We have run it many times and compiled and run once again wherein all cases here main thread is executing faster than created thread but do remember output may vary. Our created thread can execute prior to ‘main thread‘ leading to ‘Count : 0’ as an output on the console. " }, { "code": null, "e": 39164, "s": 38963, "text": "Now another topic that arises in dealing with synchronization in threads is Thread safety in java synchronization is the new concept that arises out in synchronization so let us discuss it considering" }, { "code": null, "e": 39197, "s": 39164, "text": "A real-life scenario followed by" }, { "code": null, "e": 39253, "s": 39197, "text": "Pictorial representation as an illustration followed by" }, { "code": null, "e": 39296, "s": 39253, "text": "Technically description and implementation" }, { "code": null, "e": 39316, "s": 39296, "text": "Real-life Scenario " }, { "code": null, "e": 39951, "s": 39316, "text": "Suppose a person is withdrawing some amount of money from the bank and at the same time the ATM card registered with the same account number is carrying on withdrawal operation by some other user. Now suppose if withdrawing some amount of money from net banking makes funds in account lesser than the amount which needed to be withdrawal or the other way. This makes the bank unsafe as more funds are debited from the account than was actually present in the account making the bank very unsafe and is not seen in daily life. So what banks do is that they only let one transaction at a time. Once it is over then another is permitted." }, { "code": null, "e": 39965, "s": 39951, "text": "Illustration:" }, { "code": null, "e": 40410, "s": 39965, "text": "Interpreting the same technology as there are two different processes going on which object in case of parallel execution is over headed by threads. Now possessing such traits over threads such that they should look after for before execution or in simpler words making them synchronized. This mechanism is referred to as Thread Safe with the use of the keyword ‘synchronized‘ before the common shared method/function to be performed parallel. " }, { "code": null, "e": 40434, "s": 40410, "text": "Technical Description: " }, { "code": null, "e": 40940, "s": 40434, "text": "As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe, and we will get inconsistent results. When a thread is already working on an object and preventing another thread from working on the same object, this process is called Thread-Safety. Now there are several ways to achieve thread-safety in our program namely as follows:" }, { "code": null, "e": 41024, "s": 40940, "text": "Using SynchronizationUsing Volatile KeywordUsing Atomic VariableUsing Final Keyword" }, { "code": null, "e": 41046, "s": 41024, "text": "Using Synchronization" }, { "code": null, "e": 41069, "s": 41046, "text": "Using Volatile Keyword" }, { "code": null, "e": 41091, "s": 41069, "text": "Using Atomic Variable" }, { "code": null, "e": 41111, "s": 41091, "text": "Using Final Keyword" }, { "code": null, "e": 41377, "s": 41111, "text": "Conclusion: Hence, if we are accessing one thread at a time then we can say thread-safe program and if multiple threads are getting accessed then the program is said to be thread-unsafe that is one resource at a time can not be shared by multiple threads at a time." }, { "code": null, "e": 41393, "s": 41377, "text": "Implementation:" }, { "code": null, "e": 41513, "s": 41393, "text": "Java Program to illustrate Incomplete Thread Iterations returning counter value to Zero irrespective of iteration bound" }, { "code": null, "e": 41594, "s": 41513, "text": "Java Program to Illustrate Complete Thread Iterations illustrating join() Method" }, { "code": null, "e": 41693, "s": 41594, "text": "Java Program to Illustrate thread-unsafe or non-synchronizing programs as of incomplete iterations" }, { "code": null, "e": 41814, "s": 41693, "text": "Java Program to Illustrate Thread Safe And synchronized Programs as of Complete iterations using ‘synchronized‘ Keyword." }, { "code": null, "e": 41823, "s": 41814, "text": "Examples" }, { "code": null, "e": 41828, "s": 41823, "text": "Java" }, { "code": null, "e": 41833, "s": 41828, "text": "Java" }, { "code": null, "e": 41838, "s": 41833, "text": "Java" }, { "code": null, "e": 41843, "s": 41838, "text": "Java" }, { "code": "// Example 1// Java Program to illustrate Incomplete Thread Iterations// Returning Counter Value to Zero// irrespective of iteration bound // Importing input output classesimport java.io.*; // Class 1// Helper Classclass TickTock { // Member variable of this class int count; // Method of this Class // It increments counter value whenever called public void increment() { // Increment count by unity // i.e count = count + 1; count++; } //} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 10000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method in Ticktock class t1.start(); // Print and display the count System.out.println(\"Count : \" + tt.count); }}", "e": 43320, "s": 41843, "text": null }, { "code": "// Example 2// Java Program to Illustrate Complete Thread Iterations// illustrating join() Method // Importing input output classesimport java.io.*; // Class 1// Helper Classclass TickTock { // Member variable of this class int count; // Method of this Class public void increment() { // Increment count by unity // whenever this function is called count++; }} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 1000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method t1.start(); // Now we are making main() thread to wait so // that thread t1 completes it job // using join() method t1.join(); // Print and display the count value System.out.println(\"Count : \" + tt.count); }}", "e": 44842, "s": 43320, "text": null }, { "code": "// Example 3// Java Program to Illustrate Thread Unsafe Or// Non-synchronizing Programs as of Incomplete Iteations// Without using 'synchronized' program // Importing input output classesimport java.io.*; // Class 1// Helper Classclass TickTock { // Member variable of this class int count; // Method of this Class public void increment() { // Increment count by unity count++; }} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Now creating another thread and lets check // how they increment count value running parallelly // Thread 2 Thread t2 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method t1.start(); t2.start(); // Now we are making main() thread to wait so // that thread t1 completes it job t1.join(); t2.join(); // Print and display the count System.out.println(\"Count : \" + tt.count); }}", "e": 46918, "s": 44842, "text": null }, { "code": "// Example 4// Java Program to Illustrate Thread Safe And// Synchronized Programs as of Complete Iteations// using 'synchronized' Keyword // Importing input output classesimport java.io.*; // Class 1// helper Classclass TickTock { // Member variable of this class int count; // Method of this Class public synchronized void increment() { // Increment count by unity count++; } //} // Class 2// Synchronization demo class// Main Classclass GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating an object of class TickTock in main() TickTock tt = new TickTock(); // Now, creating an thread object // using Runnable interface Thread t1 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Thread 2 Thread t2 = new Thread(new Runnable() { // Method // To begin the execution of thread public void run() { // Expression for (int i = 0; i < 100000; i++) { // Calling object of above class // in main() method tt.increment(); } } }); // Making above thread created to start // via start() method which automatically // calls run() method t1.start(); t2.start(); // Now we are making main() thread to wait so // that thread t1 completes it job t1.join(); t2.join(); // Print and display the count System.out.println(\"Count : \" + tt.count); }}", "e": 48884, "s": 46918, "text": null }, { "code": null, "e": 48894, "s": 48884, "text": "Output: " }, { "code": null, "e": 48902, "s": 48894, "text": "Case 1 " }, { "code": null, "e": 48913, "s": 48902, "text": "Count : 0 " }, { "code": null, "e": 48921, "s": 48913, "text": "Case 2 " }, { "code": null, "e": 48936, "s": 48921, "text": "Count : 10000 " }, { "code": null, "e": 48944, "s": 48936, "text": "Case 3 " }, { "code": null, "e": 48960, "s": 48944, "text": "Count : 151138 " }, { "code": null, "e": 48968, "s": 48960, "text": "Case 4 " }, { "code": null, "e": 48983, "s": 48968, "text": "Count : 200000" }, { "code": null, "e": 49005, "s": 48983, "text": " Output Explanation: " }, { "code": null, "e": 49219, "s": 49005, "text": "In case 1 we can see that count is zero as initialized. Now we have two threads main thread and the thread t1. So there are two threads so now what happens sometimes instance is shared among both of the threads. " }, { "code": null, "e": 49436, "s": 49219, "text": "In case 1 both are accessing the count variable where we are directly trying to access thread via thread t1.count which will throw out 0 always as we need to call it with the help of object to perform the execution. " }, { "code": null, "e": 49698, "s": 49436, "text": "Now we have understood the working of synchronization is a thread that is nothing but referred to as a term Concurrency in java which in layman language is executing multiple tasks. Let us depict concurrency in threads with the help of a pictorial illustration." }, { "code": null, "e": 50483, "s": 49700, "text": "Consider the task of multiplying an array of elements by a multiplier of 2. Now if we start multiplying every element randomly wise it will take a serious amount of time as every time the element will be searched over and computer. By far we have studied multithreading above in which we have concluded to a single line that thread is the backbone of multithreading. So incorporating threads in the above situation as the machine is quad-core we here take 4 threads for every core where we divide the above computing sample set to (1/4)th resulting out in 4x faster computing. If in the above scenario it had taken 4 seconds then now it will take 1 second only. This mechanism of parallel running threads in order to achieve faster and lag-free computations is known as concurrency." }, { "code": null, "e": 50684, "s": 50485, "text": "Note: Go for multithreading always for concurrent execution and if not using this concept go for sequential execution despite having bigger chunks of code as safety to our code is the primary issue." }, { "code": null, "e": 50698, "s": 50686, "text": "anikaseth98" }, { "code": null, "e": 50714, "s": 50698, "text": "simranarora5sos" }, { "code": null, "e": 50730, "s": 50714, "text": "saurabh1990aror" }, { "code": null, "e": 50739, "s": 50730, "text": "rkbhola5" }, { "code": null, "e": 50759, "s": 50739, "text": "Java-Multithreading" }, { "code": null, "e": 50764, "s": 50759, "text": "Java" }, { "code": null, "e": 50769, "s": 50764, "text": "Java" } ]
Node.js fs.statSync() Method - GeeksforGeeks
12 Oct, 2021 The fs.statSync() method is used to synchronously return information about the given file path. The fs.Stat object returned has several fields and methods to get more details about the file.Syntax: fs.statSync( path, options ) Parameters: This method accept two parameters as mentioned above and described below: path: It holds the path of the file that has to be checked. It can be a String, Buffer or URL. options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. Returns: It returns a Stats object which contains the details of the file path.Below examples illustrate the fs.statSync() method in Node.js:Example 1: This example uses fs.statSync() method to get the details of the path. javascript // Node.js program to demonstrate the// fs.statSync() method // Import the filesystem moduleconst fs = require('fs'); // Getting information for a filestatsObj = fs.statSync("test_file.txt"); console.log(statsObj); console.log("Path is file:", statsObj.isFile());console.log("Path is directory:", statsObj.isDirectory()); // Getting information for a directorystatsObj = fs.statSync("test_directory"); console.log(statsObj);console.log("Path is file:", statsObj.isFile());console.log("Path is directory:", statsObj.isDirectory()); Output: Stats { dev: 3229478529, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 1970324837039946, size: 0, blocks: 0, atimeMs: 1582306776282, mtimeMs: 1582482953967, ctimeMs: 1582482953968.2532, birthtimeMs: 1582306776282.142, atime: 2020-02-21T17:39:36.282Z, mtime: 2020-02-23T18:35:53.967Z, ctime: 2020-02-23T18:35:53.968Z, birthtime: 2020-02-21T17:39:36.282Z } Path is file: true Path is directory: false Stats { dev: 3229478529, mode: 16822, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 562949953486669, size: 0, blocks: 0, atimeMs: 1582482965037.8445, mtimeMs: 1581074249467.7114, ctimeMs: 1582482964979.8303, birthtimeMs: 1582306776288.1958, atime: 2020-02-23T18:36:05.038Z, mtime: 2020-02-07T11:17:29.468Z, ctime: 2020-02-23T18:36:04.980Z, birthtime: 2020-02-21T17:39:36.288Z } Path is file: false Path is directory: true Example 2: This example uses fs.statSync() method to get the details of files with the bigint option. javascript // Node.js program to demonstrate the// fs.stat() method // Import the filesystem moduleconst fs = require('fs'); statsObj = fs.statSync("test_file.txt");console.log(statsObj); // Using the bigint option to return// the values in big integer formatstatsObj = fs.statSync("test_file.txt", {bigint: true});console.log(statsObj); Output: Stats { dev: 3229478529, mode: 33206, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 1970324837039946, size: 0, blocks: 0, atimeMs: 1582306776282, mtimeMs: 1582482953967, ctimeMs: 1582482953968.2532, birthtimeMs: 1582306776282.142, atime: 2020-02-21T17:39:36.282Z, mtime: 2020-02-23T18:35:53.967Z, ctime: 2020-02-23T18:35:53.968Z, birthtime: 2020-02-21T17:39:36.282Z } BigIntStats { dev: 3229478529n, mode: 33206n, nlink: 1n, uid: 0n, gid: 0n, rdev: 0n, blksize: 4096n, ino: 1970324837039946n, size: 0n, blocks: 0n, atimeMs: 1582306776282n, mtimeMs: 1582482953967n, ctimeMs: 1582482953968n, birthtimeMs: 1582306776282n, atimeNs: 1582306776282000000n, mtimeNs: 1582482953967000000n, ctimeNs: 1582482953968253100n, birthtimeNs: 1582306776282142200n, atime: 2020-02-21T17:39:36.282Z, mtime: 2020-02-23T18:35:53.967Z, ctime: 2020-02-23T18:35:53.968Z, birthtime: 2020-02-21T17:39:36.282Z } Reference: https://nodejs.org/api/fs.html#fs_fs_statsync_path_options mmurasovs Node.js-fs-module Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function Mongoose Populate() Method Express.js res.render() Function Express.js res.json() Function How to use an ES6 import in Node.js? Express.js express.Router() Function How to set input type date in dd-mm-yyyy format using HTML ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24123, "s": 24095, "text": "\n12 Oct, 2021" }, { "code": null, "e": 24323, "s": 24123, "text": "The fs.statSync() method is used to synchronously return information about the given file path. The fs.Stat object returned has several fields and methods to get more details about the file.Syntax: " }, { "code": null, "e": 24352, "s": 24323, "text": "fs.statSync( path, options )" }, { "code": null, "e": 24440, "s": 24352, "text": "Parameters: This method accept two parameters as mentioned above and described below: " }, { "code": null, "e": 24535, "s": 24440, "text": "path: It holds the path of the file that has to be checked. It can be a String, Buffer or URL." }, { "code": null, "e": 24807, "s": 24535, "text": "options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 24947, "s": 24807, "text": "bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 25171, "s": 24947, "text": "Returns: It returns a Stats object which contains the details of the file path.Below examples illustrate the fs.statSync() method in Node.js:Example 1: This example uses fs.statSync() method to get the details of the path. " }, { "code": null, "e": 25182, "s": 25171, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.statSync() method // Import the filesystem moduleconst fs = require('fs'); // Getting information for a filestatsObj = fs.statSync(\"test_file.txt\"); console.log(statsObj); console.log(\"Path is file:\", statsObj.isFile());console.log(\"Path is directory:\", statsObj.isDirectory()); // Getting information for a directorystatsObj = fs.statSync(\"test_directory\"); console.log(statsObj);console.log(\"Path is file:\", statsObj.isFile());console.log(\"Path is directory:\", statsObj.isDirectory());", "e": 25718, "s": 25182, "text": null }, { "code": null, "e": 25728, "s": 25718, "text": "Output: " }, { "code": null, "e": 26652, "s": 25728, "text": "Stats {\n dev: 3229478529,\n mode: 33206,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 1970324837039946,\n size: 0,\n blocks: 0,\n atimeMs: 1582306776282,\n mtimeMs: 1582482953967,\n ctimeMs: 1582482953968.2532,\n birthtimeMs: 1582306776282.142,\n atime: 2020-02-21T17:39:36.282Z,\n mtime: 2020-02-23T18:35:53.967Z,\n ctime: 2020-02-23T18:35:53.968Z,\n birthtime: 2020-02-21T17:39:36.282Z\n}\nPath is file: true\nPath is directory: false\nStats {\n dev: 3229478529,\n mode: 16822,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 562949953486669,\n size: 0,\n blocks: 0,\n atimeMs: 1582482965037.8445,\n mtimeMs: 1581074249467.7114,\n ctimeMs: 1582482964979.8303,\n birthtimeMs: 1582306776288.1958,\n atime: 2020-02-23T18:36:05.038Z,\n mtime: 2020-02-07T11:17:29.468Z,\n ctime: 2020-02-23T18:36:04.980Z,\n birthtime: 2020-02-21T17:39:36.288Z\n}\nPath is file: false\nPath is directory: true" }, { "code": null, "e": 26755, "s": 26652, "text": "Example 2: This example uses fs.statSync() method to get the details of files with the bigint option. " }, { "code": null, "e": 26766, "s": 26755, "text": "javascript" }, { "code": "// Node.js program to demonstrate the// fs.stat() method // Import the filesystem moduleconst fs = require('fs'); statsObj = fs.statSync(\"test_file.txt\");console.log(statsObj); // Using the bigint option to return// the values in big integer formatstatsObj = fs.statSync(\"test_file.txt\", {bigint: true});console.log(statsObj);", "e": 27096, "s": 26766, "text": null }, { "code": null, "e": 27106, "s": 27096, "text": "Output: " }, { "code": null, "e": 28079, "s": 27106, "text": "Stats {\n dev: 3229478529,\n mode: 33206,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 1970324837039946,\n size: 0,\n blocks: 0,\n atimeMs: 1582306776282,\n mtimeMs: 1582482953967,\n ctimeMs: 1582482953968.2532,\n birthtimeMs: 1582306776282.142,\n atime: 2020-02-21T17:39:36.282Z,\n mtime: 2020-02-23T18:35:53.967Z,\n ctime: 2020-02-23T18:35:53.968Z,\n birthtime: 2020-02-21T17:39:36.282Z\n}\nBigIntStats {\n dev: 3229478529n,\n mode: 33206n,\n nlink: 1n,\n uid: 0n,\n gid: 0n,\n rdev: 0n,\n blksize: 4096n,\n ino: 1970324837039946n,\n size: 0n,\n blocks: 0n,\n atimeMs: 1582306776282n,\n mtimeMs: 1582482953967n,\n ctimeMs: 1582482953968n,\n birthtimeMs: 1582306776282n,\n atimeNs: 1582306776282000000n,\n mtimeNs: 1582482953967000000n,\n ctimeNs: 1582482953968253100n,\n birthtimeNs: 1582306776282142200n,\n atime: 2020-02-21T17:39:36.282Z,\n mtime: 2020-02-23T18:35:53.967Z,\n ctime: 2020-02-23T18:35:53.968Z,\n birthtime: 2020-02-21T17:39:36.282Z\n}" }, { "code": null, "e": 28150, "s": 28079, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_statsync_path_options " }, { "code": null, "e": 28160, "s": 28150, "text": "mmurasovs" }, { "code": null, "e": 28178, "s": 28160, "text": "Node.js-fs-module" }, { "code": null, "e": 28185, "s": 28178, "text": "Picked" }, { "code": null, "e": 28193, "s": 28185, "text": "Node.js" }, { "code": null, "e": 28210, "s": 28193, "text": "Web Technologies" }, { "code": null, "e": 28308, "s": 28210, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28317, "s": 28308, "text": "Comments" }, { "code": null, "e": 28330, "s": 28317, "text": "Old Comments" }, { "code": null, "e": 28367, "s": 28330, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28394, "s": 28367, "text": "Mongoose Populate() Method" }, { "code": null, "e": 28427, "s": 28394, "text": "Express.js res.render() Function" }, { "code": null, "e": 28458, "s": 28427, "text": "Express.js res.json() Function" }, { "code": null, "e": 28495, "s": 28458, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28532, "s": 28495, "text": "Express.js express.Router() Function" }, { "code": null, "e": 28593, "s": 28532, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28665, "s": 28593, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28723, "s": 28665, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Athena Health Interview Experience | Set 2 - GeeksforGeeks
18 Dec, 2014 Round 1:10 Aptitude questions with difficulty level hard. Round 2:3 programs given. 1st one mandatory. 1) Replace wild cards with all possible combinations of zeros and ones. String given: 0?1? Result: 0010 0011 0110 0111 2) Triplet problem.Array = {2,3,7,6,8,9} and k=6.{2,3,6} (2×3 = 6){3,2,6} (3×2 = 6) 3) Another one dynamic programming problem. I couldn’t remember. Round 3(F2F): if n=3 prepare matrix like 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3 and modify my code to print 1 1 1 1 1 1 2 2 2 1 1 2 3 2 1 1 2 2 2 1 1 1 1 1 1 Questions about previous projects done and my roles on it and my leadership capabilities. Few technical questions from Threads and multi-processing and. Discussed about triplet problem done in round 2 and how to tweak my algorithm to avoid getting redundant entries. Search in row wise, column wise sorted matrix {10, 20, 30, 40} {15, 25, 35, 45} {27, 29, 37, 48} {32, 33, 39, 50} Round 4(F2F):Level order traversal of a tree and discussed about time and space complexity of both techniques(Using Queue and recursive technique) https://www.geeksforgeeks.org/level-order-tree-traversal/ Array of 0’s and 1’s. Move 0’s to left and 1’s to right side. https://www.geeksforgeeks.org/segregate-0s-and-1s-in-an-array-by-traversing-array-once/ Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. {16, 17, 4, 3, 5, 2} = {17, 5, 5, 5, 2, -1}https://www.geeksforgeeks.org/replace-every-element-with-the-greatest-on-right-side/ Find loop in Linked list. https://www.geeksforgeeks.org/write-a-c-function-to-detect-loop-in-a-linked-list/ Detect and remove loop in a Linked list. https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/ Difference between Tree and Trie data structure along with implementation of Trie and real time examples. Questions on data structure for implementing dictionary and its pros and cons. Questions on implementation of Linux directory structure. Discussed about logic I used in 2nd round for wild card permutation question and discussed time complexity of it. Round 5(F2F):Given 3 points in below triangle, find wheather these 3 points are forming equalaterial triangle? (5,12,14) = true (6,18,22) = true (2,11,15) = false 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 and so on.. Questions about previous projects and current one. Why Athena and shifting from old company in short period? Aptitude problems from first round and how i understood and approached towards solution Deep discussion about 8 queens problem and its solution(I used backtracking approach) Round 6(F2F): Turing machine problems.(http://en.wikipedia.org/wiki/Turing_machine_examples) 1. There is a sequence of bytes coming. after every instance I need to check wheather that number can be devisible by 3 or not. Need turing machine diagram and approach. 2. Similar turing machine question for prime number. Tree level order and spiral order traversal and its complexity analysis. Questions on array split to two halves of equal sum. Round 7(HR): Behavioral questions and team skills. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Athena-Health Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Amazon Interview Experience for SDE-1 (On-Campus) Microsoft Interview Experience for Internship (Via Engage) Amazon Interview Experience Amazon Interview Experience for SDE-1 Difference between ANN, CNN and RNN Amazon Interview Experience (Off-Campus) 2022 Amazon Interview Experience for SDE-1(Off-Campus) Amazon Interview Experience for SDE-1 Amazon Interview Experience for SDE1 (8 Months Experienced) 2022 Zoho Interview | Set 1 (On-Campus)
[ { "code": null, "e": 25208, "s": 25180, "text": "\n18 Dec, 2014" }, { "code": null, "e": 25266, "s": 25208, "text": "Round 1:10 Aptitude questions with difficulty level hard." }, { "code": null, "e": 25311, "s": 25266, "text": "Round 2:3 programs given. 1st one mandatory." }, { "code": null, "e": 25383, "s": 25311, "text": "1) Replace wild cards with all possible combinations of zeros and ones." }, { "code": null, "e": 25539, "s": 25383, "text": " String given: 0?1?\n Result:\n 0010\n 0011\n 0110\n 0111 " }, { "code": null, "e": 25623, "s": 25539, "text": "2) Triplet problem.Array = {2,3,7,6,8,9} and k=6.{2,3,6} (2×3 = 6){3,2,6} (3×2 = 6)" }, { "code": null, "e": 25688, "s": 25623, "text": "3) Another one dynamic programming problem. I couldn’t remember." }, { "code": null, "e": 25702, "s": 25688, "text": "Round 3(F2F):" }, { "code": null, "e": 26115, "s": 25702, "text": " if n=3 prepare matrix like\n 3 3 3 3 3\n 3 2 2 2 3\n 3 2 1 2 3\n 3 2 2 2 3\n 3 3 3 3 3\n\n and modify my code to print\n 1 1 1 1 1\n 1 2 2 2 1\n 1 2 3 2 1\n 1 2 2 2 1\n 1 1 1 1 1 " }, { "code": null, "e": 26205, "s": 26115, "text": "Questions about previous projects done and my roles on it and my leadership capabilities." }, { "code": null, "e": 26268, "s": 26205, "text": "Few technical questions from Threads and multi-processing and." }, { "code": null, "e": 26382, "s": 26268, "text": "Discussed about triplet problem done in round 2 and how to tweak my algorithm to avoid getting redundant entries." }, { "code": null, "e": 26428, "s": 26382, "text": "Search in row wise, column wise sorted matrix" }, { "code": null, "e": 26525, "s": 26428, "text": " {10, 20, 30, 40}\n {15, 25, 35, 45}\n {27, 29, 37, 48}\n {32, 33, 39, 50} " }, { "code": null, "e": 26672, "s": 26525, "text": "Round 4(F2F):Level order traversal of a tree and discussed about time and space complexity of both techniques(Using Queue and recursive technique)" }, { "code": null, "e": 26730, "s": 26672, "text": "https://www.geeksforgeeks.org/level-order-tree-traversal/" }, { "code": null, "e": 26792, "s": 26730, "text": "Array of 0’s and 1’s. Move 0’s to left and 1’s to right side." }, { "code": null, "e": 26880, "s": 26792, "text": "https://www.geeksforgeeks.org/segregate-0s-and-1s-in-an-array-by-traversing-array-once/" }, { "code": null, "e": 27140, "s": 26880, "text": "Given an array of integers, replace every element with the next greatest element (greatest element on the right side) in the array. {16, 17, 4, 3, 5, 2} = {17, 5, 5, 5, 2, -1}https://www.geeksforgeeks.org/replace-every-element-with-the-greatest-on-right-side/" }, { "code": null, "e": 27248, "s": 27140, "text": "Find loop in Linked list. https://www.geeksforgeeks.org/write-a-c-function-to-detect-loop-in-a-linked-list/" }, { "code": null, "e": 27360, "s": 27248, "text": "Detect and remove loop in a Linked list. https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/" }, { "code": null, "e": 27466, "s": 27360, "text": "Difference between Tree and Trie data structure along with implementation of Trie and real time examples." }, { "code": null, "e": 27545, "s": 27466, "text": "Questions on data structure for implementing dictionary and its pros and cons." }, { "code": null, "e": 27603, "s": 27545, "text": "Questions on implementation of Linux directory structure." }, { "code": null, "e": 27717, "s": 27603, "text": "Discussed about logic I used in 2nd round for wild card permutation question and discussed time complexity of it." }, { "code": null, "e": 27828, "s": 27717, "text": "Round 5(F2F):Given 3 points in below triangle, find wheather these 3 points are forming equalaterial triangle?" }, { "code": null, "e": 27929, "s": 27828, "text": " (5,12,14) = true\n (6,18,22) = true\n (2,11,15) = false " }, { "code": null, "e": 28304, "s": 27929, "text": " 1\n \n 2 3\n\n 4 5 6\n\n 7 8 9 10\n\n 11 12 13 14 15\n\n 16 17 18 19 20 21\n and so on.. " }, { "code": null, "e": 28355, "s": 28304, "text": "Questions about previous projects and current one." }, { "code": null, "e": 28413, "s": 28355, "text": "Why Athena and shifting from old company in short period?" }, { "code": null, "e": 28501, "s": 28413, "text": "Aptitude problems from first round and how i understood and approached towards solution" }, { "code": null, "e": 28587, "s": 28501, "text": "Deep discussion about 8 queens problem and its solution(I used backtracking approach)" }, { "code": null, "e": 28601, "s": 28587, "text": "Round 6(F2F):" }, { "code": null, "e": 28680, "s": 28601, "text": "Turing machine problems.(http://en.wikipedia.org/wiki/Turing_machine_examples)" }, { "code": null, "e": 28850, "s": 28680, "text": "1. There is a sequence of bytes coming. after every instance I need to check wheather that number can be devisible by 3 or not. Need turing machine diagram and approach." }, { "code": null, "e": 28903, "s": 28850, "text": "2. Similar turing machine question for prime number." }, { "code": null, "e": 28976, "s": 28903, "text": "Tree level order and spiral order traversal and its complexity analysis." }, { "code": null, "e": 29029, "s": 28976, "text": "Questions on array split to two halves of equal sum." }, { "code": null, "e": 29042, "s": 29029, "text": "Round 7(HR):" }, { "code": null, "e": 29080, "s": 29042, "text": "Behavioral questions and team skills." }, { "code": null, "e": 29301, "s": 29080, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 29315, "s": 29301, "text": "Athena-Health" }, { "code": null, "e": 29337, "s": 29315, "text": "Interview Experiences" }, { "code": null, "e": 29435, "s": 29337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29485, "s": 29435, "text": "Amazon Interview Experience for SDE-1 (On-Campus)" }, { "code": null, "e": 29544, "s": 29485, "text": "Microsoft Interview Experience for Internship (Via Engage)" }, { "code": null, "e": 29572, "s": 29544, "text": "Amazon Interview Experience" }, { "code": null, "e": 29610, "s": 29572, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 29646, "s": 29610, "text": "Difference between ANN, CNN and RNN" }, { "code": null, "e": 29692, "s": 29646, "text": "Amazon Interview Experience (Off-Campus) 2022" }, { "code": null, "e": 29742, "s": 29692, "text": "Amazon Interview Experience for SDE-1(Off-Campus)" }, { "code": null, "e": 29780, "s": 29742, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 29845, "s": 29780, "text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022" } ]
Setting up databases with PostgreSQL, PSequel, and Python | by Hamza Bendemra, Ph.D. | Towards Data Science
As the demand for Data Scientists continues to increase, and is being dubbed the the “sexiest job job of the 21st century” by various outlets (including Harvard Business Review), questions have been asked of what skills should aspiring data scientists master on their way to their first data analyst job. There is now a plethora of online courses to gain the skills needed for a data scientist to be good at their job (excellent reviews of online resources here and here). However, as I reviewed the various courses myself , I noticed that a lot of focus is put on exciting and flashy topics like Machine Learning and Deep Learning without covering the basics of what is needed to gather and store datasets needed for such analysis. Before we go into PostgreSQL, I suspect many of you have the same question: why should I care about SQL? Although database management may seem like a boring topic for aspiring data scientists — implementing a dog breed classifier is very rewarding I know! — it is a necessary skill once you join the industry and the data supports this: SQL remains the most common and in-demand skill listed in LinkedIn job postings for data science jobs. Pandas can perform the most common SQL operations well but is not suitable for large databases — its main limit comes to the amount of data one can fit in memory. Hence, if a data scientist is working with large databases, SQL is used to transform the data into something manageable for pandas before loading it in memory. Furthermore, SQL is much more than just a method to have flat files dropped into a table. The power of SQL comes in the way that it allows users to have a set of tables that “relate” to one another, this is often represented in an “Entity Relationship Diagram” or ERD. Many data scientists use both simultaneously — they use SQL queries to join, slice and load data into memory; then they do the bulk of the data analysis in Python using pandas library functions. This is particularly important when dealing with the large datasets found in Big Data applications. Such applications would have tens of TBs in databases with several billion rows. Data Scientist often start with SQL queries that would extract 1% of data needed to a csv file, before moving to Python Pandas for data analysis. There is a way to learn SQL without leaving the much loved Python environment in which so much Machine Learning and Deep Learning techniques are taught and used: PostgreSQL. PostgreSQL allows you to leverage the amazing Pandas library for data wrangling when dealing with large datasets that are not stored in flat files but rather in databases. PostgreSQL can be installed in Windows, Mac, and Linux environments (see install details here). If you have a Mac, I’d highly recommend installing the Postgres.App SQL environment. For Windows, check out BigSQL. PostgreSQL uses a client/server model. This involves two running processes: Server process: manages database files, accepts connections to the database from client applications, and performs database actions on behalf of the clients. User Client App: often involves SQL command entries, a friendly graphical interface, and some database maintenance tool. In real-case scenarios, the client and the server will often be on different hosts and they would communicate over a TCP/IP network connection. I’ll be focusing on Postgres.App for Mac OS in the rest of the tutorial. After installing PostgresApp, you can setup your first database by following the instructions below: Click “Initialize” to create a new server An optional step is to configure a$PATH to be able to use the command line tools delivered with Postgres.app by executing the following command in Terminal and then close & reopen the window:sudo mkdir -p /etc/paths.d &&echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp You now have a PostgreSQL server running on your Mac with default settings:Host: localhost, Port: 5432, Connection URL: posgresql://localhost The PostgreSQL GUI client we’ll use in this tutorial is PSequel. It has a minimalist and easy to use interface that I really enjoy to easily perform PostgreSQL tasks. Once Postgres.App and PSequel installed, you are now ready to set up your first database! First, start by opening Postgres.App and you’ll see a little elephant icon appear in the top menu. You’ll also notice a button that allows you to “Open psql”. This will open a ommand line that will allow you to enter commands. This is mostly used to create databases, which we will create using the following command:create database sample_db; Then, we connect to the database we just created using PSequel. We’ll open PSequel and enter the name’s database, in our case: sample_db . Click on “Connect” to connect to the database. Let’s create a table (consisting of rows and columns) in PSequel. We define the table’s name, and the name and type of each column. The available datatypes in PostgreSQL for the columns (i.e. variables), can be found on the PostgreSQL Datatypes Documentation. In this tutorial, we’ll create a simple table with world countries. The first column will provide each country an ‘id’ integer, and the second column will provide the country’s name using variable length character string (with 255 characters max). Once ready, click “Run Query”. The table will then be created in the database. Don’t forget to click the “Refresh” icon (bottom right) to see the table listed. We are now ready to populate our columns with data. There are many different ways to populate a table in a database. To enter data manually, the INSERT will come in handy. For instance, to enter the country Morocco with id number 1, and Australia with id number 2, the SQL command is: INSERT INTO country_list (id, name) VALUES (1, 'Morocco');INSERT INTO country_list (id, name) VALUES (2, 'Australia'); After running the query and refreshing the tables, we get the following table: In practice, populating the tables in the database manually is not feasible. It is likely that the data of interest is stored in CSV files. To import a CSV file into the country_list_csv table, you use COPY statement as follows: COPY country_list_csv(id,name)FROM 'C:\{path}\{file_name}.csv' DELIMITER ',' CSV HEADER; As you can see in the commands above, the table with column names is specified after the COPY command. The columns must be ordered in the same fashion as in the CSV file. The CSV file path is specified after the FROM keyword. The CSVDELIMITER must also be specified. If the CSV file contains a header line with column names, it is indicated with the HEADER keyword so that PostgreSQL ignores the first line when importing the data from the CSV file. The key to SQL is understanding statements. A few statements include: CREATE TABLE is a statement that creates a new table in a database.DROP TABLE is a statement that removes a table in a database.SELECT allows you to read data and display it. CREATE TABLE is a statement that creates a new table in a database. DROP TABLE is a statement that removes a table in a database. SELECT allows you to read data and display it. SELECT is where you tell the query what columns you want back.FROM is where you tell the query what table you are querying from. Notice the columns need to exist in this table. For example, let’s say we have a table of orders with several columns but we are only interested in a subset of three: SELECT id, account_id, occurred_atFROM orders Also, the LIMIT statement is useful when you want to see just the first few rows of a table. This can be much faster for loading than if we load the entire dataset. The ORDER BY statement allows us to order our table by any row. We can use these two commands together to a table of ‘orders’ in a database as: SELECT id, account_id, total_amt_usdFROM ordersORDER BY total_amt_usd DESCLIMIT 5; Now that you know how to setup a database, create a table and populate in PostgreSQL, you can explore the other common SQL commands as explained in the following tutorials: SQL Basics for Data Science Khan Academy: Intro to SQL SQL in a Nutshell Cheat Sheet SQL Commands Once your PostgreSQL database and tables are setup, you can then move to Python to perform any Data Analysis or Wrangling required. PostgreSQL can be integrated with Python using psycopg2 module. It is a popular PostgreSQL database adapter for Python. It is shipped along with default libraries in Python version 2.5.x onwards Connecting to an existing PostgreSQL database can be achieved with: import psycopg2conn = psycopg2.connect(database="sample_db", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432") Going back to our country_list table example, inserting records into the table in sample_db can be accomplished in Python with the following commands: cur = conn.cursor()cur.execute("INSERT INTO country_list (id, name) \ VALUES (1, 'Morocco')");cur.execute("INSERT INTO country_list (id, name) \ VALUES (2, 'Australia')");conn.commit()conn.close() Other commands for creating, populating and querying tables can be found on various tutorials on Tutorial Points and PostgreSQL Tutorial. You now have a working PostgreSQL database server ready for you to populate and play with. It’s powerful, flexible, free and is used by numerous applications.
[ { "code": null, "e": 477, "s": 172, "text": "As the demand for Data Scientists continues to increase, and is being dubbed the the “sexiest job job of the 21st century” by various outlets (including Harvard Business Review), questions have been asked of what skills should aspiring data scientists master on their way to their first data analyst job." }, { "code": null, "e": 905, "s": 477, "text": "There is now a plethora of online courses to gain the skills needed for a data scientist to be good at their job (excellent reviews of online resources here and here). However, as I reviewed the various courses myself , I noticed that a lot of focus is put on exciting and flashy topics like Machine Learning and Deep Learning without covering the basics of what is needed to gather and store datasets needed for such analysis." }, { "code": null, "e": 1010, "s": 905, "text": "Before we go into PostgreSQL, I suspect many of you have the same question: why should I care about SQL?" }, { "code": null, "e": 1345, "s": 1010, "text": "Although database management may seem like a boring topic for aspiring data scientists — implementing a dog breed classifier is very rewarding I know! — it is a necessary skill once you join the industry and the data supports this: SQL remains the most common and in-demand skill listed in LinkedIn job postings for data science jobs." }, { "code": null, "e": 1668, "s": 1345, "text": "Pandas can perform the most common SQL operations well but is not suitable for large databases — its main limit comes to the amount of data one can fit in memory. Hence, if a data scientist is working with large databases, SQL is used to transform the data into something manageable for pandas before loading it in memory." }, { "code": null, "e": 1937, "s": 1668, "text": "Furthermore, SQL is much more than just a method to have flat files dropped into a table. The power of SQL comes in the way that it allows users to have a set of tables that “relate” to one another, this is often represented in an “Entity Relationship Diagram” or ERD." }, { "code": null, "e": 2132, "s": 1937, "text": "Many data scientists use both simultaneously — they use SQL queries to join, slice and load data into memory; then they do the bulk of the data analysis in Python using pandas library functions." }, { "code": null, "e": 2313, "s": 2132, "text": "This is particularly important when dealing with the large datasets found in Big Data applications. Such applications would have tens of TBs in databases with several billion rows." }, { "code": null, "e": 2459, "s": 2313, "text": "Data Scientist often start with SQL queries that would extract 1% of data needed to a csv file, before moving to Python Pandas for data analysis." }, { "code": null, "e": 2633, "s": 2459, "text": "There is a way to learn SQL without leaving the much loved Python environment in which so much Machine Learning and Deep Learning techniques are taught and used: PostgreSQL." }, { "code": null, "e": 2805, "s": 2633, "text": "PostgreSQL allows you to leverage the amazing Pandas library for data wrangling when dealing with large datasets that are not stored in flat files but rather in databases." }, { "code": null, "e": 3017, "s": 2805, "text": "PostgreSQL can be installed in Windows, Mac, and Linux environments (see install details here). If you have a Mac, I’d highly recommend installing the Postgres.App SQL environment. For Windows, check out BigSQL." }, { "code": null, "e": 3093, "s": 3017, "text": "PostgreSQL uses a client/server model. This involves two running processes:" }, { "code": null, "e": 3251, "s": 3093, "text": "Server process: manages database files, accepts connections to the database from client applications, and performs database actions on behalf of the clients." }, { "code": null, "e": 3372, "s": 3251, "text": "User Client App: often involves SQL command entries, a friendly graphical interface, and some database maintenance tool." }, { "code": null, "e": 3516, "s": 3372, "text": "In real-case scenarios, the client and the server will often be on different hosts and they would communicate over a TCP/IP network connection." }, { "code": null, "e": 3690, "s": 3516, "text": "I’ll be focusing on Postgres.App for Mac OS in the rest of the tutorial. After installing PostgresApp, you can setup your first database by following the instructions below:" }, { "code": null, "e": 3732, "s": 3690, "text": "Click “Initialize” to create a new server" }, { "code": null, "e": 4049, "s": 3732, "text": "An optional step is to configure a$PATH to be able to use the command line tools delivered with Postgres.app by executing the following command in Terminal and then close & reopen the window:sudo mkdir -p /etc/paths.d &&echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp" }, { "code": null, "e": 4191, "s": 4049, "text": "You now have a PostgreSQL server running on your Mac with default settings:Host: localhost, Port: 5432, Connection URL: posgresql://localhost" }, { "code": null, "e": 4358, "s": 4191, "text": "The PostgreSQL GUI client we’ll use in this tutorial is PSequel. It has a minimalist and easy to use interface that I really enjoy to easily perform PostgreSQL tasks." }, { "code": null, "e": 4547, "s": 4358, "text": "Once Postgres.App and PSequel installed, you are now ready to set up your first database! First, start by opening Postgres.App and you’ll see a little elephant icon appear in the top menu." }, { "code": null, "e": 4792, "s": 4547, "text": "You’ll also notice a button that allows you to “Open psql”. This will open a ommand line that will allow you to enter commands. This is mostly used to create databases, which we will create using the following command:create database sample_db;" }, { "code": null, "e": 4978, "s": 4792, "text": "Then, we connect to the database we just created using PSequel. We’ll open PSequel and enter the name’s database, in our case: sample_db . Click on “Connect” to connect to the database." }, { "code": null, "e": 5110, "s": 4978, "text": "Let’s create a table (consisting of rows and columns) in PSequel. We define the table’s name, and the name and type of each column." }, { "code": null, "e": 5238, "s": 5110, "text": "The available datatypes in PostgreSQL for the columns (i.e. variables), can be found on the PostgreSQL Datatypes Documentation." }, { "code": null, "e": 5486, "s": 5238, "text": "In this tutorial, we’ll create a simple table with world countries. The first column will provide each country an ‘id’ integer, and the second column will provide the country’s name using variable length character string (with 255 characters max)." }, { "code": null, "e": 5646, "s": 5486, "text": "Once ready, click “Run Query”. The table will then be created in the database. Don’t forget to click the “Refresh” icon (bottom right) to see the table listed." }, { "code": null, "e": 5931, "s": 5646, "text": "We are now ready to populate our columns with data. There are many different ways to populate a table in a database. To enter data manually, the INSERT will come in handy. For instance, to enter the country Morocco with id number 1, and Australia with id number 2, the SQL command is:" }, { "code": null, "e": 6050, "s": 5931, "text": "INSERT INTO country_list (id, name) VALUES (1, 'Morocco');INSERT INTO country_list (id, name) VALUES (2, 'Australia');" }, { "code": null, "e": 6129, "s": 6050, "text": "After running the query and refreshing the tables, we get the following table:" }, { "code": null, "e": 6358, "s": 6129, "text": "In practice, populating the tables in the database manually is not feasible. It is likely that the data of interest is stored in CSV files. To import a CSV file into the country_list_csv table, you use COPY statement as follows:" }, { "code": null, "e": 6447, "s": 6358, "text": "COPY country_list_csv(id,name)FROM 'C:\\{path}\\{file_name}.csv' DELIMITER ',' CSV HEADER;" }, { "code": null, "e": 6714, "s": 6447, "text": "As you can see in the commands above, the table with column names is specified after the COPY command. The columns must be ordered in the same fashion as in the CSV file. The CSV file path is specified after the FROM keyword. The CSVDELIMITER must also be specified." }, { "code": null, "e": 6897, "s": 6714, "text": "If the CSV file contains a header line with column names, it is indicated with the HEADER keyword so that PostgreSQL ignores the first line when importing the data from the CSV file." }, { "code": null, "e": 6967, "s": 6897, "text": "The key to SQL is understanding statements. A few statements include:" }, { "code": null, "e": 7142, "s": 6967, "text": "CREATE TABLE is a statement that creates a new table in a database.DROP TABLE is a statement that removes a table in a database.SELECT allows you to read data and display it." }, { "code": null, "e": 7210, "s": 7142, "text": "CREATE TABLE is a statement that creates a new table in a database." }, { "code": null, "e": 7272, "s": 7210, "text": "DROP TABLE is a statement that removes a table in a database." }, { "code": null, "e": 7319, "s": 7272, "text": "SELECT allows you to read data and display it." }, { "code": null, "e": 7615, "s": 7319, "text": "SELECT is where you tell the query what columns you want back.FROM is where you tell the query what table you are querying from. Notice the columns need to exist in this table. For example, let’s say we have a table of orders with several columns but we are only interested in a subset of three:" }, { "code": null, "e": 7661, "s": 7615, "text": "SELECT id, account_id, occurred_atFROM orders" }, { "code": null, "e": 7970, "s": 7661, "text": "Also, the LIMIT statement is useful when you want to see just the first few rows of a table. This can be much faster for loading than if we load the entire dataset. The ORDER BY statement allows us to order our table by any row. We can use these two commands together to a table of ‘orders’ in a database as:" }, { "code": null, "e": 8053, "s": 7970, "text": "SELECT id, account_id, total_amt_usdFROM ordersORDER BY total_amt_usd DESCLIMIT 5;" }, { "code": null, "e": 8226, "s": 8053, "text": "Now that you know how to setup a database, create a table and populate in PostgreSQL, you can explore the other common SQL commands as explained in the following tutorials:" }, { "code": null, "e": 8254, "s": 8226, "text": "SQL Basics for Data Science" }, { "code": null, "e": 8281, "s": 8254, "text": "Khan Academy: Intro to SQL" }, { "code": null, "e": 8299, "s": 8281, "text": "SQL in a Nutshell" }, { "code": null, "e": 8324, "s": 8299, "text": "Cheat Sheet SQL Commands" }, { "code": null, "e": 8456, "s": 8324, "text": "Once your PostgreSQL database and tables are setup, you can then move to Python to perform any Data Analysis or Wrangling required." }, { "code": null, "e": 8651, "s": 8456, "text": "PostgreSQL can be integrated with Python using psycopg2 module. It is a popular PostgreSQL database adapter for Python. It is shipped along with default libraries in Python version 2.5.x onwards" }, { "code": null, "e": 8719, "s": 8651, "text": "Connecting to an existing PostgreSQL database can be achieved with:" }, { "code": null, "e": 8856, "s": 8719, "text": "import psycopg2conn = psycopg2.connect(database=\"sample_db\", user = \"postgres\", password = \"pass123\", host = \"127.0.0.1\", port = \"5432\")" }, { "code": null, "e": 9007, "s": 8856, "text": "Going back to our country_list table example, inserting records into the table in sample_db can be accomplished in Python with the following commands:" }, { "code": null, "e": 9214, "s": 9007, "text": "cur = conn.cursor()cur.execute(\"INSERT INTO country_list (id, name) \\ VALUES (1, 'Morocco')\");cur.execute(\"INSERT INTO country_list (id, name) \\ VALUES (2, 'Australia')\");conn.commit()conn.close()" }, { "code": null, "e": 9352, "s": 9214, "text": "Other commands for creating, populating and querying tables can be found on various tutorials on Tutorial Points and PostgreSQL Tutorial." } ]
How to get the thread ID from a thread in C#?
A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time-consuming operations, then it is often helpful to set different execution paths or threads, with each thread performing a particular job. Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application. In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created. The threads created using the Thread class are called the child threads of the main thread. You can access a thread using the CurrentThread property of the Thread class. class Program{ public static void Main(){ Thread thr; thr = Thread.CurrentThread; thr.Name = "Main thread"; Console.WriteLine("Name of current running " + "thread: {0}", Thread.CurrentThread.Name); Console.WriteLine("Id of current running " + "thread: {0}", Thread.CurrentThread.ManagedThreadId); Console.ReadLine(); } } Name of current running thread: Main thread Id of current running thread: 1
[ { "code": null, "e": 1352, "s": 1062, "text": "A thread is defined as the execution path of a program. Each thread defines a unique\nflow of control. If your application involves complicated and time-consuming\noperations, then it is often helpful to set different execution paths or threads, with\neach thread performing a particular job." }, { "code": null, "e": 1581, "s": 1352, "text": "Threads are lightweight processes. One common example of use of thread is\nimplementation of concurrent programming by modern operating systems. Use of\nthreads saves wastage of CPU cycle and increase efficiency of an application." }, { "code": null, "e": 1812, "s": 1581, "text": "In C#, the System.Threading.Thread class is used for working with threads. It allows creating and accessing individual threads in a multithreaded application. The first thread to be executed in a process is called the main thread." }, { "code": null, "e": 2060, "s": 1812, "text": "When a C# program starts execution, the main thread is automatically created. The\nthreads created using the Thread class are called the child threads of the main thread.\nYou can access a thread using the CurrentThread property of the Thread class." }, { "code": null, "e": 2423, "s": 2060, "text": "class Program{\n public static void Main(){\n Thread thr;\n thr = Thread.CurrentThread;\n thr.Name = \"Main thread\";\n Console.WriteLine(\"Name of current running \" + \"thread: {0}\", Thread.CurrentThread.Name);\n Console.WriteLine(\"Id of current running \" + \"thread: {0}\", Thread.CurrentThread.ManagedThreadId);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2499, "s": 2423, "text": "Name of current running thread: Main thread\nId of current running thread: 1" } ]
getters and setters in JavaScript classes?
Classes allow using getters and setters. It is smart to use getters and setters for the properties, especially if you want to do something special with the value before returning them, or before you set them. To add getters and setters in the class, use the get and set keywords. In the following example, getters and setters were added to the class 'Company' and the property value is obtained by using a 'get' keyword. Live Demo <html> <body> <p id="method"></p> <script> class Company { constructor(brand) { this.Compname = brand; } get name() { return this.Compname; } set name(x) { this.Compname = x; } } myName = new Company("Tutorialspoint"); document.getElementById("method").innerHTML = myName.Compname; </script> </body> </html> Tutorialspoint
[ { "code": null, "e": 1342, "s": 1062, "text": "Classes allow using getters and setters. It is smart to use getters and setters for the properties, especially if you want to do something special with the value before returning them, or before you set them. To add getters and setters in the class, use the get and set keywords." }, { "code": null, "e": 1485, "s": 1342, "text": " In the following example, getters and setters were added to the class 'Company' and the property value is obtained by using a 'get' keyword. " }, { "code": null, "e": 1495, "s": 1485, "text": "Live Demo" }, { "code": null, "e": 1878, "s": 1495, "text": "<html>\n<body>\n<p id=\"method\"></p>\n<script>\n class Company {\n constructor(brand) {\n this.Compname = brand;\n }\n get name() {\n return this.Compname;\n }\n set name(x) {\n this.Compname = x;\n }\n }\n myName = new Company(\"Tutorialspoint\");\n document.getElementById(\"method\").innerHTML = myName.Compname;\n</script>\n</body>\n</html>" }, { "code": null, "e": 1893, "s": 1878, "text": "Tutorialspoint" } ]
Python - Filter Pandas DataFrame by Time
To filter DataFrame by time, use the loc and set the condition in it to fetch records. At first, import the required library − import pandas as pd Create a Dictionary of list with date records − d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-05-19', '2021-08-22'] } Creating a dataframe from the above dictionary of lists − dataFrame = pd.DataFrame(d) Now, let’s say we need to fetch cars purchased after a specific date. For this, we use loc − resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"] Following is the complete code − import pandas as pd # dictionary of lists d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-05-19', '2021-08-22'] } # creating dataframe from the above dictionary of lists dataFrame = pd.DataFrame(d) print"DataFrame...\n",dataFrame # fetch cars purchased after 15th July 2021 resDF = dataFrame.loc[dataFrame["Date_of_Purchase"] > "2021-07-15"] # print filtered data frame print"\nCars purchased after 15th July 2021: \n",resDF This will produce the following output − DataFrame... Car Date_of_Purchase 0 BMW 2021-07-10 1 Lexus 2021-08-12 2 Audi 2021-06-17 3 Mercedes 2021-03-16 4 Jaguar 2021-05-19 5 Bentley 2021-08-22 Cars purchased after 15th July 2021: Car Date_of_Purchase 1 Lexus 2021-08-12 5 Bentley 2021-08-22
[ { "code": null, "e": 1189, "s": 1062, "text": "To filter DataFrame by time, use the loc and set the condition in it to fetch records. At first, import the required library −" }, { "code": null, "e": 1209, "s": 1189, "text": "import pandas as pd" }, { "code": null, "e": 1257, "s": 1209, "text": "Create a Dictionary of list with date records −" }, { "code": null, "e": 1437, "s": 1257, "text": "d = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-05-19', '2021-08-22']\n }" }, { "code": null, "e": 1495, "s": 1437, "text": "Creating a dataframe from the above dictionary of lists −" }, { "code": null, "e": 1524, "s": 1495, "text": "dataFrame = pd.DataFrame(d)\n" }, { "code": null, "e": 1617, "s": 1524, "text": "Now, let’s say we need to fetch cars purchased after a specific date. For this, we use loc −" }, { "code": null, "e": 1685, "s": 1617, "text": "resDF = dataFrame.loc[dataFrame[\"Date_of_Purchase\"] > \"2021-07-15\"]" }, { "code": null, "e": 1718, "s": 1685, "text": "Following is the complete code −" }, { "code": null, "e": 2255, "s": 1718, "text": "import pandas as pd\n\n# dictionary of lists\nd = {'Car': ['BMW', 'Lexus', 'Audi', 'Mercedes', 'Jaguar', 'Bentley'],'Date_of_Purchase': ['2021-07-10', '2021-08-12', '2021-06-17', '2021-03-16', '2021-05-19', '2021-08-22']\n }\n\n# creating dataframe from the above dictionary of lists\ndataFrame = pd.DataFrame(d)\nprint\"DataFrame...\\n\",dataFrame\n\n# fetch cars purchased after 15th July 2021\nresDF = dataFrame.loc[dataFrame[\"Date_of_Purchase\"] > \"2021-07-15\"]\n\n# print filtered data frame\nprint\"\\nCars purchased after 15th July 2021: \\n\",resDF" }, { "code": null, "e": 2296, "s": 2255, "text": "This will produce the following output −" }, { "code": null, "e": 2654, "s": 2296, "text": "DataFrame...\n Car Date_of_Purchase\n0 BMW 2021-07-10\n1 Lexus 2021-08-12\n2 Audi 2021-06-17\n3 Mercedes 2021-03-16\n4 Jaguar 2021-05-19\n5 Bentley 2021-08-22\n\nCars purchased after 15th July 2021:\n Car Date_of_Purchase\n1 Lexus 2021-08-12\n5 Bentley 2021-08-22" } ]
How to find the size of an int[] in C/C++?
In this section, we will see how we can get the size of an integer array in C or C++? The size of int[] is basically counting the number of elements inside that array. To get this we can use the sizeof() operator. If the array name is passed inside the sizeof(), then it will return total size of memory blocks that are occupied by the array. Now if we divide it by the size of each element, then we can get number of elements. Let us see the following example to get the better idea about it. #include <iostream> using namespace std; int main() { int data[] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 91, 82, 73, 64}; cout << "Memory occupied by data[]: " << sizeof(data) << endl; cout << "Size of data[] array: " << sizeof(data)/sizeof(data[0]) << endl; } Memory occupied by data[]: 52 Size of data[] array: 13
[ { "code": null, "e": 1490, "s": 1062, "text": "In this section, we will see how we can get the size of an integer array in C or C++? The size of int[] is basically counting the number of elements inside that array. To get this we can use the sizeof() operator. If the array name is passed inside the sizeof(), then it will return total size of memory blocks that are occupied by the array. Now if we divide it by the size of each element, then we can get number of elements." }, { "code": null, "e": 1556, "s": 1490, "text": "Let us see the following example to get the better idea about it." }, { "code": null, "e": 1825, "s": 1556, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int data[] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 91, 82, 73, 64};\n cout << \"Memory occupied by data[]: \" << sizeof(data) << endl;\n cout << \"Size of data[] array: \" << sizeof(data)/sizeof(data[0]) << endl;\n}" }, { "code": null, "e": 1880, "s": 1825, "text": "Memory occupied by data[]: 52\nSize of data[] array: 13" } ]
Cryptography with Python - Reverse Cipher
The previous chapter gave you an overview of installation of Python on your local computer. In this chapter you will learn in detail about reverse cipher and its coding. The algorithm of reverse cipher holds the following features − Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text. Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text. The process of encryption and decryption is same. The process of encryption and decryption is same. To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text. To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text. The major drawback of reverse cipher is that it is very weak. A hacker can easily break the cipher text to get the original message. Hence, reverse cipher is not considered as good option to maintain secure communication channel,. Consider an example where the statement This is program to explain reverse cipher is to be implemented with reverse cipher algorithm. The following python code uses the algorithm to obtain the output. message = 'This is program to explain reverse cipher.' translated = '' #cipher text is stored in this variable i = len(message) - 1 while i >= 0: translated = translated + message[i] i = i - 1 print(“The cipher text is : “, translated) You can see the reversed text, that is the output as shown in the following image − Plain text is stored in the variable message and the translated variable is used to store the cipher text created. Plain text is stored in the variable message and the translated variable is used to store the cipher text created. The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line. The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2462, "s": 2292, "text": "The previous chapter gave you an overview of installation of Python on your local computer. In this chapter you will learn in detail about reverse cipher and its coding." }, { "code": null, "e": 2525, "s": 2462, "text": "The algorithm of reverse cipher holds the following features −" }, { "code": null, "e": 2620, "s": 2525, "text": "Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text." }, { "code": null, "e": 2715, "s": 2620, "text": "Reverse Cipher uses a pattern of reversing the string of plain text to convert as cipher text." }, { "code": null, "e": 2765, "s": 2715, "text": "The process of encryption and decryption is same." }, { "code": null, "e": 2815, "s": 2765, "text": "The process of encryption and decryption is same." }, { "code": null, "e": 2911, "s": 2815, "text": "To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text." }, { "code": null, "e": 3007, "s": 2911, "text": "To decrypt cipher text, the user simply needs to reverse the cipher text to get the plain text." }, { "code": null, "e": 3238, "s": 3007, "text": "The major drawback of reverse cipher is that it is very weak. A hacker can easily break the cipher text to get the original message. Hence, reverse cipher is not considered as good option to maintain secure communication channel,." }, { "code": null, "e": 3439, "s": 3238, "text": "Consider an example where the statement This is program to explain reverse cipher is to be implemented with reverse cipher algorithm. The following python code uses the algorithm to obtain the output." }, { "code": null, "e": 3682, "s": 3439, "text": "message = 'This is program to explain reverse cipher.'\ntranslated = '' #cipher text is stored in this variable\ni = len(message) - 1\n\nwhile i >= 0:\n translated = translated + message[i]\n i = i - 1\nprint(“The cipher text is : “, translated)" }, { "code": null, "e": 3766, "s": 3682, "text": "You can see the reversed text, that is the output as shown in the following image −" }, { "code": null, "e": 3881, "s": 3766, "text": "Plain text is stored in the variable message and the translated variable is used to store the cipher text created." }, { "code": null, "e": 3996, "s": 3881, "text": "Plain text is stored in the variable message and the translated variable is used to store the cipher text created." }, { "code": null, "e": 4177, "s": 3996, "text": "The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line." }, { "code": null, "e": 4358, "s": 4177, "text": "The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line." }, { "code": null, "e": 4391, "s": 4358, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4407, "s": 4391, "text": " Total Seminars" }, { "code": null, "e": 4440, "s": 4407, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4463, "s": 4440, "text": " Stone River ELearning" }, { "code": null, "e": 4470, "s": 4463, "text": " Print" }, { "code": null, "e": 4481, "s": 4470, "text": " Add Notes" } ]
Extract a number from a string using JavaScript
21 Jul, 2021 The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/). Example 1: This example uses match() function to extract number from string. <!DOCTYPE html><html><head> <title> Extract number from string </title></head> <body > <div align="center" style="background-color: green;"> <h1>GeeksforGeeks</h1> <p>String is "jhkj7682834"</p> <p id="GFG"> Click the button to extract number </p> <input type="button" value="click " onclick="myGeeks()"> </div> <script> function myGeeks() { var str = "jhkj7682834"; var matches = str.match(/(\d+)/); if (matches) { document.getElementById('GFG').innerHTML = matches[0]; } } </script></body></html> Output: Before Clicking the button: After Clicking the button: Example 2: This example uses match() function to extract number from string. <!DOCTYPE html><html><head> <title> Extract number from string </title></head> <body> <div align="center" style="background-color: green;"> <h1>GeeksforGeeks</h1> <p>String is "foo35bar5jhkj88"</p> <h3> The string contains 3 numbers. So the numbers are stored in an array and print together </h3> <p id="GFG"> Click the button to extract number </p><br> <h3 id="Geeks"></h3> <input type="button" value="Click Here!" onclick="myGeeks()"> </div> <script> function myGeeks() { var str = "foo35bar5jhkj88"; matches = str.match(/\d+/g); var i=0 document.getElementById('GFG').innerHTML = matches[0] + matches[1] + matches[2]; document.getElementById("Geeks").innerHTML = "Where 35 is the first, 5 is the second" + " and 88 is the third number" } </script></body></html> Output: Before Clicking the button: After Clicking the button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. javascript-string Picked 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 Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners 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": 53, "s": 25, "text": "\n21 Jul, 2021" }, { "code": null, "e": 315, "s": 53, "text": "The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\\d+)/)." }, { "code": null, "e": 392, "s": 315, "text": "Example 1: This example uses match() function to extract number from string." }, { "code": "<!DOCTYPE html><html><head> <title> Extract number from string </title></head> <body > <div align=\"center\" style=\"background-color: green;\"> <h1>GeeksforGeeks</h1> <p>String is \"jhkj7682834\"</p> <p id=\"GFG\"> Click the button to extract number </p> <input type=\"button\" value=\"click \" onclick=\"myGeeks()\"> </div> <script> function myGeeks() { var str = \"jhkj7682834\"; var matches = str.match(/(\\d+)/); if (matches) { document.getElementById('GFG').innerHTML = matches[0]; } } </script></body></html> ", "e": 1152, "s": 392, "text": null }, { "code": null, "e": 1160, "s": 1152, "text": "Output:" }, { "code": null, "e": 1188, "s": 1160, "text": "Before Clicking the button:" }, { "code": null, "e": 1215, "s": 1188, "text": "After Clicking the button:" }, { "code": null, "e": 1292, "s": 1215, "text": "Example 2: This example uses match() function to extract number from string." }, { "code": "<!DOCTYPE html><html><head> <title> Extract number from string </title></head> <body> <div align=\"center\" style=\"background-color: green;\"> <h1>GeeksforGeeks</h1> <p>String is \"foo35bar5jhkj88\"</p> <h3> The string contains 3 numbers. So the numbers are stored in an array and print together </h3> <p id=\"GFG\"> Click the button to extract number </p><br> <h3 id=\"Geeks\"></h3> <input type=\"button\" value=\"Click Here!\" onclick=\"myGeeks()\"> </div> <script> function myGeeks() { var str = \"foo35bar5jhkj88\"; matches = str.match(/\\d+/g); var i=0 document.getElementById('GFG').innerHTML = matches[0] + matches[1] + matches[2]; document.getElementById(\"Geeks\").innerHTML = \"Where 35 is the first, 5 is the second\" + \" and 88 is the third number\" } </script></body></html> ", "e": 2392, "s": 1292, "text": null }, { "code": null, "e": 2400, "s": 2392, "text": "Output:" }, { "code": null, "e": 2428, "s": 2400, "text": "Before Clicking the button:" }, { "code": null, "e": 2455, "s": 2428, "text": "After Clicking the button:" }, { "code": null, "e": 2674, "s": 2455, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 2692, "s": 2674, "text": "javascript-string" }, { "code": null, "e": 2699, "s": 2692, "text": "Picked" }, { "code": null, "e": 2710, "s": 2699, "text": "JavaScript" }, { "code": null, "e": 2727, "s": 2710, "text": "Web Technologies" }, { "code": null, "e": 2754, "s": 2727, "text": "Web technologies Questions" }, { "code": null, "e": 2852, "s": 2754, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2913, "s": 2852, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2985, "s": 2913, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3025, "s": 2985, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3066, "s": 3025, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3108, "s": 3066, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3141, "s": 3108, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3203, "s": 3141, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3264, "s": 3203, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3314, "s": 3264, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Batch Script - CLS
This batch command clears the screen. cls @echo off Cls The command prompt screen will be cleared.
[ { "code": null, "e": 2341, "s": 2303, "text": "This batch command clears the screen." }, { "code": null, "e": 2346, "s": 2341, "text": "cls\n" }, { "code": null, "e": 2361, "s": 2346, "text": "@echo off \nCls" } ]
Find index of first occurrence when an unsorted array is sorted
23 May, 2022 Given an unsorted array and a number x, find an index of first occurrence of x when we sort the array. If x is not present, print -1. Examples: Input : arr[] = {10, 30, 20, 50, 20} x = 20 Output : 1 Sorted array is {10, 20, 20, 30, 50} Input : arr[] = {10, 30, 20, 50, 20} x = 60 Output : -1 60 is not present in array. A simple solution is to first sort the array, then do binary search to find first occurrence. C++ Java Python3 C# PHP Javascript // C++ program to find index of first// occurrence of x when array is sorted.#include <bits/stdc++.h>using namespace std; int findFirst(int arr[], int n, int x){ sort(arr, arr + n); // lower_bound returns iterator pointing to // first element that does not compare less // to x. int* ptr = lower_bound(arr, arr + n, x); // If x is not present return -1. return (*ptr != x) ? -1 : (ptr - arr);} int main(){ int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findFirst(arr, n, x); return 0;} // Java program to find index of first// occurrence of x when array is sorted.import java.util.*; class GFG { static int findFirst(int arr[], int n, int x) { Arrays.sort(arr); // lower_bound returns iterator pointing to // first element that does not compare less // to x. int ptr = lowerBound(arr, 0, n, x); // If x is not present return -1. return (arr[ptr] != x) ? -1 : (ptr); } static int lowerBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (element > a[middle]) low = middle + 1; else high = middle; } return low; } // Driver Code public static void main(String[] args) { int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = arr.length; System.out.println(findFirst(arr, n, x)); }} // This code is contributed by 29AjayKumar # Python3 program to find index of first# occurrence of x when array is sorted.import math def findFirst(arr, n, x): arr.sort() # lower_bound returns iterator pointing to # first element that does not compare less # to x. ptr = lowerBound(arr, 0, n, x) # If x is not present return -1. return 1 if (ptr != x) else (ptr - arr) def lowerBound(a, low, high, element): while(low < high): middle = low + (high - low) // 2 if(element > a[middle]): low = middle + 1 else: high = middle return low # Driver Codeif __name__ == '__main__': x = 20 arr = [10, 30, 20, 50, 20] n = len(arr) print(findFirst(arr, n, x)) # This code is contributed by Rajput-Ji // C# program to find index of first// occurrence of x when array is sorted.using System; class GFG { static int findFirst(int[] arr, int n, int x) { Array.Sort(arr); // lower_bound returns iterator pointing to // first element that does not compare less // to x. int ptr = lowerBound(arr, 0, n, x); // If x is not present return -1. return (arr[ptr] != x) ? -1 : (ptr); } static int lowerBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (element > a[middle]) low = middle + 1; else high = middle; } return low; } // Driver Code static public void Main() { int x = 20; int[] arr = { 10, 30, 20, 50, 20 }; int n = arr.Length; Console.Write(findFirst(arr, n, x)); }} // This code is contributed by ajit. <?php//PHP program to find index of first// occurrence of x when array is sorted. function findFirst( $arr, $n, $x){ sort($arr); // lower_bound returns iterator pointing to// first element that does not compare less// to x.$ptr = floor($arr); // If x is not present return -1.return ($ptr != $x)? 1 : ($ptr - $arr);}//Code driven $x = 20; $arr = array(10, 30, 20, 50, 20); $n = sizeof($arr)/sizeof($arr[0]); echo findFirst($arr, $n, $x); #This code is contributed by Tushil.?> <script> // Javascript program to find index of first// occurrence of x when array is sorted.function findFirst(arr, n, x){ arr.sort(); // lower_bound returns iterator pointing // to first element that does not compare // less to x. let ptr = lowerBound(arr, 0, n, x); // If x is not present return -1. return (arr[ptr] != x) ? -1 : (ptr);} function lowerBound(a, low, high, element){ while (low < high) { let middle = low + parseInt( (high - low) / 2, 10); if (element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver codelet x = 20;let arr = [ 10, 30, 20, 50, 20 ];let n = arr.length; document.write(findFirst(arr, n, x)); // This code is contributed by mukesh07 </script> Output: 1 Time Complexity : O(n Log n) Auxiliary Space: O(1) An efficient solution is to simply count smaller elements than x. C++ Java Python3 C# PHP Javascript // C++ program to find index of first// occurrence of x when array is sorted.#include <bits/stdc++.h>using namespace std; int findFirst(int arr[], int n, int x){ int count = 0; bool isX = false; for (int i = 0; i < n; i++) { if (arr[i] == x) isX = true; else if (arr[i] < x) count++; } return (isX == false) ? -1 : count;} int main(){ int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findFirst(arr, n, x); return 0;} // Java program to find index of first// occurrence of x when array is sorted. public class GFG { static int findFirst(int arr[], int n, int x) { int count = 0; boolean isX = false; for (int i = 0; i < n; i++) { if (arr[i] == x) { isX = true; } else if (arr[i] < x) { count++; } } return (isX == false) ? -1 : count; } // Driver main public static void main(String[] args) { int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = arr.length; System.out.println(findFirst(arr, n, x)); }}/*This code is contributed by PrinciRaj1992*/ # Python 3 program to find index# of first occurrence of x when# array is sorted. def findFirst(arr, n, x): count = 0 isX = False for i in range(n): if (arr[i] == x): isX = True elif (arr[i] < x): count += 1 return -1 if(isX == False) else count # Driver Codeif __name__ == "__main__": x = 20 arr = [10, 30, 20, 50, 20] n = len(arr) print(findFirst(arr, n, x)) # This code is contributed# by ChitraNayal // C# program to find index of first// occurrence of x when array is sorted.using System; public class GFG { static int findFirst(int[] arr, int n, int x) { int count = 0; bool isX = false; for (int i = 0; i < n; i++) { if (arr[i] == x) { isX = true; } else if (arr[i] < x) { count++; } } return (isX == false) ? -1 : count; } // Driver main public static void Main() { int x = 20; int[] arr = { 10, 30, 20, 50, 20 }; int n = arr.Length; Console.WriteLine(findFirst(arr, n, x)); }}/*This code is contributed by PrinciRaj1992*/ <?php// PHP program to find index of first// occurrence of x when array is sorted. function findFirst($arr, $n, $x){ $count = 0; $isX = false; for ($i = 0; $i < $n; $i++) { if ($arr[$i] == $x) $isX = true; else if ($arr[$i] < $x) $count++; } return ($isX == false)? -1 : $count;} // Driver Code$x = 20;$arr = array(10, 30, 20, 50, 20);$n = sizeof($arr);echo findFirst($arr, $n, $x); // This code is contributed// by Akanksha Rai?> <script> // JavaScript program to find index of first// occurrence of x when array is sorted.function findFirst(arr, n, x){ var count = 0; var isX = false; for(var i = 0; i < n; i++) { if (arr[i] == x) { isX = true; } else if (arr[i] < x) { count++; } } return (isX == false) ? -1 : count;} // Driver Codevar x = 20, arr = [ 10, 30, 20, 50, 20 ];var n = arr.length; document.write(findFirst(arr, n, x)); // This code is contributed by Khushboogoyal499 </script> Output: 1 Time Complexity: O(N) Auxiliary Space: O(1) ukasp Akanksha_Rai princiraj1992 jit_t 29AjayKumar Rajput-Ji aashish999 mukesh07 khushboogoyal499 jayanth_mkv Binary Search Arrays Searching Arrays Searching Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 May, 2022" }, { "code": null, "e": 186, "s": 52, "text": "Given an unsorted array and a number x, find an index of first occurrence of x when we sort the array. If x is not present, print -1." }, { "code": null, "e": 197, "s": 186, "text": "Examples: " }, { "code": null, "e": 397, "s": 197, "text": "Input : arr[] = {10, 30, 20, 50, 20}\n x = 20\nOutput : 1\nSorted array is {10, 20, 20, 30, 50}\n\nInput : arr[] = {10, 30, 20, 50, 20}\n x = 60\nOutput : -1\n60 is not present in array. " }, { "code": null, "e": 491, "s": 397, "text": "A simple solution is to first sort the array, then do binary search to find first occurrence." }, { "code": null, "e": 495, "s": 491, "text": "C++" }, { "code": null, "e": 500, "s": 495, "text": "Java" }, { "code": null, "e": 508, "s": 500, "text": "Python3" }, { "code": null, "e": 511, "s": 508, "text": "C#" }, { "code": null, "e": 515, "s": 511, "text": "PHP" }, { "code": null, "e": 526, "s": 515, "text": "Javascript" }, { "code": "// C++ program to find index of first// occurrence of x when array is sorted.#include <bits/stdc++.h>using namespace std; int findFirst(int arr[], int n, int x){ sort(arr, arr + n); // lower_bound returns iterator pointing to // first element that does not compare less // to x. int* ptr = lower_bound(arr, arr + n, x); // If x is not present return -1. return (*ptr != x) ? -1 : (ptr - arr);} int main(){ int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findFirst(arr, n, x); return 0;}", "e": 1090, "s": 526, "text": null }, { "code": "// Java program to find index of first// occurrence of x when array is sorted.import java.util.*; class GFG { static int findFirst(int arr[], int n, int x) { Arrays.sort(arr); // lower_bound returns iterator pointing to // first element that does not compare less // to x. int ptr = lowerBound(arr, 0, n, x); // If x is not present return -1. return (arr[ptr] != x) ? -1 : (ptr); } static int lowerBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (element > a[middle]) low = middle + 1; else high = middle; } return low; } // Driver Code public static void main(String[] args) { int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = arr.length; System.out.println(findFirst(arr, n, x)); }} // This code is contributed by 29AjayKumar", "e": 2095, "s": 1090, "text": null }, { "code": "# Python3 program to find index of first# occurrence of x when array is sorted.import math def findFirst(arr, n, x): arr.sort() # lower_bound returns iterator pointing to # first element that does not compare less # to x. ptr = lowerBound(arr, 0, n, x) # If x is not present return -1. return 1 if (ptr != x) else (ptr - arr) def lowerBound(a, low, high, element): while(low < high): middle = low + (high - low) // 2 if(element > a[middle]): low = middle + 1 else: high = middle return low # Driver Codeif __name__ == '__main__': x = 20 arr = [10, 30, 20, 50, 20] n = len(arr) print(findFirst(arr, n, x)) # This code is contributed by Rajput-Ji", "e": 2827, "s": 2095, "text": null }, { "code": "// C# program to find index of first// occurrence of x when array is sorted.using System; class GFG { static int findFirst(int[] arr, int n, int x) { Array.Sort(arr); // lower_bound returns iterator pointing to // first element that does not compare less // to x. int ptr = lowerBound(arr, 0, n, x); // If x is not present return -1. return (arr[ptr] != x) ? -1 : (ptr); } static int lowerBound(int[] a, int low, int high, int element) { while (low < high) { int middle = low + (high - low) / 2; if (element > a[middle]) low = middle + 1; else high = middle; } return low; } // Driver Code static public void Main() { int x = 20; int[] arr = { 10, 30, 20, 50, 20 }; int n = arr.Length; Console.Write(findFirst(arr, n, x)); }} // This code is contributed by ajit.", "e": 3810, "s": 2827, "text": null }, { "code": "<?php//PHP program to find index of first// occurrence of x when array is sorted. function findFirst( $arr, $n, $x){ sort($arr); // lower_bound returns iterator pointing to// first element that does not compare less// to x.$ptr = floor($arr); // If x is not present return -1.return ($ptr != $x)? 1 : ($ptr - $arr);}//Code driven $x = 20; $arr = array(10, 30, 20, 50, 20); $n = sizeof($arr)/sizeof($arr[0]); echo findFirst($arr, $n, $x); #This code is contributed by Tushil.?>", "e": 4310, "s": 3810, "text": null }, { "code": "<script> // Javascript program to find index of first// occurrence of x when array is sorted.function findFirst(arr, n, x){ arr.sort(); // lower_bound returns iterator pointing // to first element that does not compare // less to x. let ptr = lowerBound(arr, 0, n, x); // If x is not present return -1. return (arr[ptr] != x) ? -1 : (ptr);} function lowerBound(a, low, high, element){ while (low < high) { let middle = low + parseInt( (high - low) / 2, 10); if (element > a[middle]) low = middle + 1; else high = middle; } return low;} // Driver codelet x = 20;let arr = [ 10, 30, 20, 50, 20 ];let n = arr.length; document.write(findFirst(arr, n, x)); // This code is contributed by mukesh07 </script>", "e": 5129, "s": 4310, "text": null }, { "code": null, "e": 5138, "s": 5129, "text": "Output: " }, { "code": null, "e": 5140, "s": 5138, "text": "1" }, { "code": null, "e": 5169, "s": 5140, "text": "Time Complexity : O(n Log n)" }, { "code": null, "e": 5191, "s": 5169, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5258, "s": 5191, "text": "An efficient solution is to simply count smaller elements than x. " }, { "code": null, "e": 5262, "s": 5258, "text": "C++" }, { "code": null, "e": 5267, "s": 5262, "text": "Java" }, { "code": null, "e": 5275, "s": 5267, "text": "Python3" }, { "code": null, "e": 5278, "s": 5275, "text": "C#" }, { "code": null, "e": 5282, "s": 5278, "text": "PHP" }, { "code": null, "e": 5293, "s": 5282, "text": "Javascript" }, { "code": "// C++ program to find index of first// occurrence of x when array is sorted.#include <bits/stdc++.h>using namespace std; int findFirst(int arr[], int n, int x){ int count = 0; bool isX = false; for (int i = 0; i < n; i++) { if (arr[i] == x) isX = true; else if (arr[i] < x) count++; } return (isX == false) ? -1 : count;} int main(){ int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findFirst(arr, n, x); return 0;}", "e": 5814, "s": 5293, "text": null }, { "code": "// Java program to find index of first// occurrence of x when array is sorted. public class GFG { static int findFirst(int arr[], int n, int x) { int count = 0; boolean isX = false; for (int i = 0; i < n; i++) { if (arr[i] == x) { isX = true; } else if (arr[i] < x) { count++; } } return (isX == false) ? -1 : count; } // Driver main public static void main(String[] args) { int x = 20, arr[] = { 10, 30, 20, 50, 20 }; int n = arr.length; System.out.println(findFirst(arr, n, x)); }}/*This code is contributed by PrinciRaj1992*/", "e": 6496, "s": 5814, "text": null }, { "code": "# Python 3 program to find index# of first occurrence of x when# array is sorted. def findFirst(arr, n, x): count = 0 isX = False for i in range(n): if (arr[i] == x): isX = True elif (arr[i] < x): count += 1 return -1 if(isX == False) else count # Driver Codeif __name__ == \"__main__\": x = 20 arr = [10, 30, 20, 50, 20] n = len(arr) print(findFirst(arr, n, x)) # This code is contributed# by ChitraNayal", "e": 6964, "s": 6496, "text": null }, { "code": "// C# program to find index of first// occurrence of x when array is sorted.using System; public class GFG { static int findFirst(int[] arr, int n, int x) { int count = 0; bool isX = false; for (int i = 0; i < n; i++) { if (arr[i] == x) { isX = true; } else if (arr[i] < x) { count++; } } return (isX == false) ? -1 : count; } // Driver main public static void Main() { int x = 20; int[] arr = { 10, 30, 20, 50, 20 }; int n = arr.Length; Console.WriteLine(findFirst(arr, n, x)); }}/*This code is contributed by PrinciRaj1992*/", "e": 7651, "s": 6964, "text": null }, { "code": "<?php// PHP program to find index of first// occurrence of x when array is sorted. function findFirst($arr, $n, $x){ $count = 0; $isX = false; for ($i = 0; $i < $n; $i++) { if ($arr[$i] == $x) $isX = true; else if ($arr[$i] < $x) $count++; } return ($isX == false)? -1 : $count;} // Driver Code$x = 20;$arr = array(10, 30, 20, 50, 20);$n = sizeof($arr);echo findFirst($arr, $n, $x); // This code is contributed// by Akanksha Rai?>", "e": 8136, "s": 7651, "text": null }, { "code": "<script> // JavaScript program to find index of first// occurrence of x when array is sorted.function findFirst(arr, n, x){ var count = 0; var isX = false; for(var i = 0; i < n; i++) { if (arr[i] == x) { isX = true; } else if (arr[i] < x) { count++; } } return (isX == false) ? -1 : count;} // Driver Codevar x = 20, arr = [ 10, 30, 20, 50, 20 ];var n = arr.length; document.write(findFirst(arr, n, x)); // This code is contributed by Khushboogoyal499 </script>", "e": 8685, "s": 8136, "text": null }, { "code": null, "e": 8694, "s": 8685, "text": "Output: " }, { "code": null, "e": 8696, "s": 8694, "text": "1" }, { "code": null, "e": 8741, "s": 8696, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 8747, "s": 8741, "text": "ukasp" }, { "code": null, "e": 8760, "s": 8747, "text": "Akanksha_Rai" }, { "code": null, "e": 8774, "s": 8760, "text": "princiraj1992" }, { "code": null, "e": 8780, "s": 8774, "text": "jit_t" }, { "code": null, "e": 8792, "s": 8780, "text": "29AjayKumar" }, { "code": null, "e": 8802, "s": 8792, "text": "Rajput-Ji" }, { "code": null, "e": 8813, "s": 8802, "text": "aashish999" }, { "code": null, "e": 8822, "s": 8813, "text": "mukesh07" }, { "code": null, "e": 8839, "s": 8822, "text": "khushboogoyal499" }, { "code": null, "e": 8851, "s": 8839, "text": "jayanth_mkv" }, { "code": null, "e": 8865, "s": 8851, "text": "Binary Search" }, { "code": null, "e": 8872, "s": 8865, "text": "Arrays" }, { "code": null, "e": 8882, "s": 8872, "text": "Searching" }, { "code": null, "e": 8889, "s": 8882, "text": "Arrays" }, { "code": null, "e": 8899, "s": 8889, "text": "Searching" }, { "code": null, "e": 8913, "s": 8899, "text": "Binary Search" } ]
Introduction and Installation of Heroku CLI on Windows machine
11 May, 2022 Heroku: It is a cloud based application deployment and management service.Heroku works on the container based design system and these smart containers are known as dynos.It runs application inside various dynos and each dyno is separated from each other. Step 1: Download Windows installerDownload the appropriate installer for your Windows installation from here according to the system configuration Download the appropriate installer for your Windows installation from here according to the system configuration Step 2: Running the installer to the systemNow, click on the installer file and it will ask for choosing components from the following options as given below. Heroku cli Adding heroku to system path Adding local data Make sure that you check all of them. Now click the “Next” button. Heroku cli Adding heroku to system path Adding local data Make sure that you check all of them. Now click the “Next” button. Step 3: Setting the destination folderDefault path will be the path of the C drive of system. The default path for installation can be changed using the “Browse” button. Step 4: Installation:After clicking “Install”, it will start to install Heroku CLI into the destination folder as shown in the below screenshot:After a couple of seconds Heroku CLI will be installed to the system completely.Heroku CLI has been successfully installed on your system. To verify,Run the following command in the Command Prompt or Terminal.herokuFor checking the version of Heroku, Run the following command in the terminal:heroku -vSo, the Heroku CLI has been installed properly of your system. After a couple of seconds Heroku CLI will be installed to the system completely. Heroku CLI has been successfully installed on your system. To verify,Run the following command in the Command Prompt or Terminal. heroku For checking the version of Heroku, Run the following command in the terminal: heroku -v So, the Heroku CLI has been installed properly of your system. Step 5 : Signing up for the Heroku services:Create an account for Heroku services hereAfter successfully creating an account for Heroku services we will log in through Heroku CLI. After successfully creating an account for Heroku services we will log in through Heroku CLI. Login via terminal into Heroku CLIFor login through Heroku CLI Run the following command in terminal: heroku login Now, The terminal will ask to press “any key” for redirecting the process to the browser or “Q” to quit the login process. After pressing any key it will redirect you to the browser as shown in the below screenshot On Successfully logging into the account, the following message will be displayed on the browser screen: Another method for logging is through the command prompt:For doing it run the following command in the terminal heroku login -i On Successful Login, you can now use the Heroku CLI into your system. The Heroku CLI is successfully installed and initialized into your system. Heroku Cloud how-to-install GBlog Installation Guide Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial How to Learn Data Science in 10 weeks? How to Install PIP on Windows ? Installation of Node.js on Linux How to install Jupyter Notebook on Windows? How to Install OpenCV for Python on Windows? How to Install FFmpeg on Windows?
[ { "code": null, "e": 28, "s": 0, "text": "\n11 May, 2022" }, { "code": null, "e": 283, "s": 28, "text": "Heroku: It is a cloud based application deployment and management service.Heroku works on the container based design system and these smart containers are known as dynos.It runs application inside various dynos and each dyno is separated from each other." }, { "code": null, "e": 430, "s": 283, "text": "Step 1: Download Windows installerDownload the appropriate installer for your Windows installation from here according to the system configuration" }, { "code": null, "e": 543, "s": 430, "text": "Download the appropriate installer for your Windows installation from here according to the system configuration" }, { "code": null, "e": 829, "s": 543, "text": "Step 2: Running the installer to the systemNow, click on the installer file and it will ask for choosing components from the following options as given below.\nHeroku cli\nAdding heroku to system path\nAdding local data \n\nMake sure that you check all of them. Now click the “Next” button." }, { "code": null, "e": 891, "s": 829, "text": "\nHeroku cli\nAdding heroku to system path\nAdding local data \n\n" }, { "code": null, "e": 958, "s": 891, "text": "Make sure that you check all of them. Now click the “Next” button." }, { "code": null, "e": 1128, "s": 958, "text": "Step 3: Setting the destination folderDefault path will be the path of the C drive of system. The default path for installation can be changed using the “Browse” button." }, { "code": null, "e": 1637, "s": 1128, "text": "Step 4: Installation:After clicking “Install”, it will start to install Heroku CLI into the destination folder as shown in the below screenshot:After a couple of seconds Heroku CLI will be installed to the system completely.Heroku CLI has been successfully installed on your system. To verify,Run the following command in the Command Prompt or Terminal.herokuFor checking the version of Heroku, Run the following command in the terminal:heroku -vSo, the Heroku CLI has been installed properly of your system." }, { "code": null, "e": 1718, "s": 1637, "text": "After a couple of seconds Heroku CLI will be installed to the system completely." }, { "code": null, "e": 1848, "s": 1718, "text": "Heroku CLI has been successfully installed on your system. To verify,Run the following command in the Command Prompt or Terminal." }, { "code": null, "e": 1855, "s": 1848, "text": "heroku" }, { "code": null, "e": 1934, "s": 1855, "text": "For checking the version of Heroku, Run the following command in the terminal:" }, { "code": null, "e": 1944, "s": 1934, "text": "heroku -v" }, { "code": null, "e": 2007, "s": 1944, "text": "So, the Heroku CLI has been installed properly of your system." }, { "code": null, "e": 2187, "s": 2007, "text": "Step 5 : Signing up for the Heroku services:Create an account for Heroku services hereAfter successfully creating an account for Heroku services we will log in through Heroku CLI." }, { "code": null, "e": 2281, "s": 2187, "text": "After successfully creating an account for Heroku services we will log in through Heroku CLI." }, { "code": null, "e": 2383, "s": 2281, "text": "Login via terminal into Heroku CLIFor login through Heroku CLI Run the following command in terminal:" }, { "code": null, "e": 2396, "s": 2383, "text": "heroku login" }, { "code": null, "e": 2519, "s": 2396, "text": "Now, The terminal will ask to press “any key” for redirecting the process to the browser or “Q” to quit the login process." }, { "code": null, "e": 2611, "s": 2519, "text": "After pressing any key it will redirect you to the browser as shown in the below screenshot" }, { "code": null, "e": 2716, "s": 2611, "text": "On Successfully logging into the account, the following message will be displayed on the browser screen:" }, { "code": null, "e": 2828, "s": 2716, "text": "Another method for logging is through the command prompt:For doing it run the following command in the terminal" }, { "code": null, "e": 2844, "s": 2828, "text": "heroku login -i" }, { "code": null, "e": 2914, "s": 2844, "text": "On Successful Login, you can now use the Heroku CLI into your system." }, { "code": null, "e": 2989, "s": 2914, "text": "The Heroku CLI is successfully installed and initialized into your system." }, { "code": null, "e": 3002, "s": 2989, "text": "Heroku Cloud" }, { "code": null, "e": 3017, "s": 3002, "text": "how-to-install" }, { "code": null, "e": 3023, "s": 3017, "text": "GBlog" }, { "code": null, "e": 3042, "s": 3023, "text": "Installation Guide" }, { "code": null, "e": 3059, "s": 3042, "text": "Web Technologies" }, { "code": null, "e": 3157, "s": 3059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3182, "s": 3157, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 3237, "s": 3182, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 3274, "s": 3237, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 3312, "s": 3274, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 3351, "s": 3312, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 3383, "s": 3351, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3416, "s": 3383, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3460, "s": 3416, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 3505, "s": 3460, "text": "How to Install OpenCV for Python on Windows?" } ]
What is the implicit implementation of the interface and when to use implicit implementation of the interface in C#?
C# interface members can be implemented explicitly or implicitly. Implicit implementations don't include the name of the interface being implemented before the member name, so the compiler infers this. The members will be exposed as public and will be accessible when the object is cast as the concrete type. The call of the method is also not different. Just create an object of the class and invoke it. Implicit interface cannot be used if there is same method name declared in multiple interfaces interface ICar { void displayCar(); } interface IBike { void displayBike(); } class ShowRoom : ICar, IBike { public void displayCar() { throw new NotImplementedException(); } public void displayBike() { throw new NotImplementedException(); } } class Program { static void Main() { ICar car = new ShowRoom(); IBike bike = new ShowRoom(); Console.ReadKey(); } }
[ { "code": null, "e": 1128, "s": 1062, "text": "C# interface members can be implemented explicitly or implicitly." }, { "code": null, "e": 1371, "s": 1128, "text": "Implicit implementations don't include the name of the interface being implemented before the member name, so the compiler infers this. The members will be exposed as public and will be accessible when the object is cast as the concrete type." }, { "code": null, "e": 1467, "s": 1371, "text": "The call of the method is also not different. Just create an object of the class and invoke it." }, { "code": null, "e": 1562, "s": 1467, "text": "Implicit interface cannot be used if there is same method name declared in multiple interfaces" }, { "code": null, "e": 1976, "s": 1562, "text": "interface ICar {\n void displayCar();\n}\ninterface IBike {\n void displayBike();\n}\nclass ShowRoom : ICar, IBike {\n public void displayCar() {\n throw new NotImplementedException();\n }\n public void displayBike() {\n throw new NotImplementedException();\n }\n}\nclass Program {\n static void Main() {\n ICar car = new ShowRoom();\n IBike bike = new ShowRoom();\n Console.ReadKey();\n }\n}" } ]
Modes of Python Program | Python Program Example Tutorials
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we will see the different ways to develop a python program/application are We can develop a python program in 2 different styles. Interactive Mode and Batch Mode. Interactive mode is a command line shell. If we write a python program in the command line shell. Typically the interactive mode is used to test the features of the python, or to run a smaller script that may not be reusable. Open the command prompt, and go to the location which your python has been installed and hit the python command. On the above example, I have executed some arithmetic operations on the python command shell. Batch mode is mainly used to develop business applications. In batch mode, we can write a group of python statements in any one of the following editors or IDEs Editors : Notepad Notepad++ editPlus nano gedit IDLE Etc.. IDEs : pycharm Eric Eclipse Netbeans Etc.. We can write our python programs any one of the above Editors/IDEs. Example for Batch Mode: demo.py i=100 j=200 print i+j print i-j print i*j After writing the above code on any favourite editor, save it with the extension of either .py or .pyw. Then run the above python program by passing the below command on your terminal. chandrashekhar@goka:~/Documents$ python demo.py 300 -100 20000 Happy Learning 🙂 Python – How to remove duplicate elements from List Python – Print different vowels present in a String IDEs Support in PHP Tutorials What is Python Programming Language How to merge two lists in Python How to read a text file in Python ? How install Python on Windows 10 How to get Words Count in Python from a File How to Create or Delete Directories in Python ? How to Convert Python List Of Objects to CSV File Python Operators Example Features of Python Language Python Number Systems Example Python raw_input read input from keyboard Python Conditional Statements Python – How to remove duplicate elements from List Python – Print different vowels present in a String IDEs Support in PHP Tutorials What is Python Programming Language How to merge two lists in Python How to read a text file in Python ? How install Python on Windows 10 How to get Words Count in Python from a File How to Create or Delete Directories in Python ? How to Convert Python List Of Objects to CSV File Python Operators Example Features of Python Language Python Number Systems Example Python raw_input read input from keyboard Python Conditional Statements Δ Python – Introduction Python – Features Python – Install on Windows Python – Modes of Program Python – Number System Python – Identifiers Python – Operators Python – Ternary Operator Python – Command Line Arguments Python – Keywords Python – Data Types Python – Upgrade Python PIP Python – Virtual Environment Pyhton – Type Casting Python – String to Int Python – Conditional Statements Python – if statement Python – *args and **kwargs Python – Date Formatting Python – Read input from keyboard Python – raw_input Python – List In Depth Python – List Comprehension Python – Set in Depth Python – Dictionary in Depth Python – Tuple in Depth Python – Stack Datastructure Python – Classes and Objects Python – Constructors Python – Object Introspection Python – Inheritance Python – Decorators Python – Serialization with Pickle Python – Exceptions Handling Python – User defined Exceptions Python – Multiprocessing Python – Default function parameters Python – Lambdas Functions Python – NumPy Library Python – MySQL Connector Python – MySQL Create Database Python – MySQL Read Data Python – MySQL Insert Data Python – MySQL Update Records Python – MySQL Delete Records Python – String Case Conversion Howto – Find biggest of 2 numbers Howto – Remove duplicates from List Howto – Convert any Number to Binary Howto – Merge two Lists Howto – Merge two dicts Howto – Get Characters Count in a File Howto – Get Words Count in a File Howto – Remove Spaces from String Howto – Read Env variables Howto – Read a text File Howto – Read a JSON File Howto – Read Config.ini files Howto – Iterate Dictionary Howto – Convert List Of Objects to CSV Howto – Merge two dict in Python Howto – create Zip File Howto – Get OS info Howto – Get size of Directory Howto – Check whether a file exists Howto – Remove key from dictionary Howto – Sort Objects Howto – Create or Delete Directories Howto – Read CSV File Howto – Create Python Iterable class Howto – Access for loop index Howto – Clear all elements from List Howto – Remove empty lists from a List Howto – Remove special characters from String Howto – Sort dictionary by key Howto – Filter a list
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 491, "s": 398, "text": "In this tutorial, we will see the different ways to develop a python program/application are" }, { "code": null, "e": 546, "s": 491, "text": "We can develop a python program in 2 different styles." }, { "code": null, "e": 567, "s": 546, "text": "Interactive Mode and" }, { "code": null, "e": 579, "s": 567, "text": "Batch Mode." }, { "code": null, "e": 677, "s": 579, "text": "Interactive mode is a command line shell. If we write a python program in the command line shell." }, { "code": null, "e": 805, "s": 677, "text": "Typically the interactive mode is used to test the features of the python, or to run a smaller script that may not be reusable." }, { "code": null, "e": 918, "s": 805, "text": "Open the command prompt, and go to the location which your python has been installed and hit the python command." }, { "code": null, "e": 1012, "s": 918, "text": "On the above example, I have executed some arithmetic operations on the python command shell." }, { "code": null, "e": 1173, "s": 1012, "text": "Batch mode is mainly used to develop business applications. In batch mode, we can write a group of python statements in any one of the following editors or IDEs" }, { "code": null, "e": 1183, "s": 1173, "text": "Editors :" }, { "code": null, "e": 1191, "s": 1183, "text": "Notepad" }, { "code": null, "e": 1201, "s": 1191, "text": "Notepad++" }, { "code": null, "e": 1210, "s": 1201, "text": "editPlus" }, { "code": null, "e": 1215, "s": 1210, "text": "nano" }, { "code": null, "e": 1221, "s": 1215, "text": "gedit" }, { "code": null, "e": 1226, "s": 1221, "text": "IDLE" }, { "code": null, "e": 1232, "s": 1226, "text": "Etc.." }, { "code": null, "e": 1239, "s": 1232, "text": "IDEs :" }, { "code": null, "e": 1247, "s": 1239, "text": "pycharm" }, { "code": null, "e": 1252, "s": 1247, "text": "Eric" }, { "code": null, "e": 1260, "s": 1252, "text": "Eclipse" }, { "code": null, "e": 1277, "s": 1260, "text": "Netbeans Etc.." }, { "code": null, "e": 1345, "s": 1277, "text": "We can write our python programs any one of the above Editors/IDEs." }, { "code": null, "e": 1369, "s": 1345, "text": "Example for Batch Mode:" }, { "code": null, "e": 1377, "s": 1369, "text": "demo.py" }, { "code": null, "e": 1420, "s": 1377, "text": "i=100\nj=200\nprint i+j\nprint i-j\nprint i*j\n" }, { "code": null, "e": 1524, "s": 1420, "text": "After writing the above code on any favourite editor, save it with the extension of either .py or .pyw." }, { "code": null, "e": 1605, "s": 1524, "text": "Then run the above python program by passing the below command on your terminal." }, { "code": null, "e": 1670, "s": 1607, "text": "chandrashekhar@goka:~/Documents$ python demo.py\n300\n-100\n20000" }, { "code": null, "e": 1687, "s": 1670, "text": "Happy Learning 🙂" }, { "code": null, "e": 2259, "s": 1687, "text": "\nPython – How to remove duplicate elements from List\nPython – Print different vowels present in a String\nIDEs Support in PHP Tutorials\nWhat is Python Programming Language\nHow to merge two lists in Python\nHow to read a text file in Python ?\nHow install Python on Windows 10\nHow to get Words Count in Python from a File\nHow to Create or Delete Directories in Python ?\nHow to Convert Python List Of Objects to CSV File\nPython Operators Example\nFeatures of Python Language\nPython Number Systems Example\nPython raw_input read input from keyboard\nPython Conditional Statements\n" }, { "code": null, "e": 2311, "s": 2259, "text": "Python – How to remove duplicate elements from List" }, { "code": null, "e": 2363, "s": 2311, "text": "Python – Print different vowels present in a String" }, { "code": null, "e": 2393, "s": 2363, "text": "IDEs Support in PHP Tutorials" }, { "code": null, "e": 2429, "s": 2393, "text": "What is Python Programming Language" }, { "code": null, "e": 2462, "s": 2429, "text": "How to merge two lists in Python" }, { "code": null, "e": 2498, "s": 2462, "text": "How to read a text file in Python ?" }, { "code": null, "e": 2531, "s": 2498, "text": "How install Python on Windows 10" }, { "code": null, "e": 2576, "s": 2531, "text": "How to get Words Count in Python from a File" }, { "code": null, "e": 2624, "s": 2576, "text": "How to Create or Delete Directories in Python ?" }, { "code": null, "e": 2674, "s": 2624, "text": "How to Convert Python List Of Objects to CSV File" }, { "code": null, "e": 2699, "s": 2674, "text": "Python Operators Example" }, { "code": null, "e": 2727, "s": 2699, "text": "Features of Python Language" }, { "code": null, "e": 2757, "s": 2727, "text": "Python Number Systems Example" }, { "code": null, "e": 2799, "s": 2757, "text": "Python raw_input read input from keyboard" }, { "code": null, "e": 2829, "s": 2799, "text": "Python Conditional Statements" }, { "code": null, "e": 2835, "s": 2833, "text": "Δ" }, { "code": null, "e": 2858, "s": 2835, "text": " Python – Introduction" }, { "code": null, "e": 2877, "s": 2858, "text": " Python – Features" }, { "code": null, "e": 2906, "s": 2877, "text": " Python – Install on Windows" }, { "code": null, "e": 2933, "s": 2906, "text": " Python – Modes of Program" }, { "code": null, "e": 2957, "s": 2933, "text": " Python – Number System" }, { "code": null, "e": 2979, "s": 2957, "text": " Python – Identifiers" }, { "code": null, "e": 2999, "s": 2979, "text": " Python – Operators" }, { "code": null, "e": 3026, "s": 2999, "text": " Python – Ternary Operator" }, { "code": null, "e": 3059, "s": 3026, "text": " Python – Command Line Arguments" }, { "code": null, "e": 3078, "s": 3059, "text": " Python – Keywords" }, { "code": null, "e": 3099, "s": 3078, "text": " Python – Data Types" }, { "code": null, "e": 3128, "s": 3099, "text": " Python – Upgrade Python PIP" }, { "code": null, "e": 3158, "s": 3128, "text": " Python – Virtual Environment" }, { "code": null, "e": 3181, "s": 3158, "text": " Pyhton – Type Casting" }, { "code": null, "e": 3205, "s": 3181, "text": " Python – String to Int" }, { "code": null, "e": 3238, "s": 3205, "text": " Python – Conditional Statements" }, { "code": null, "e": 3261, "s": 3238, "text": " Python – if statement" }, { "code": null, "e": 3290, "s": 3261, "text": " Python – *args and **kwargs" }, { "code": null, "e": 3316, "s": 3290, "text": " Python – Date Formatting" }, { "code": null, "e": 3351, "s": 3316, "text": " Python – Read input from keyboard" }, { "code": null, "e": 3371, "s": 3351, "text": " Python – raw_input" }, { "code": null, "e": 3395, "s": 3371, "text": " Python – List In Depth" }, { "code": null, "e": 3424, "s": 3395, "text": " Python – List Comprehension" }, { "code": null, "e": 3447, "s": 3424, "text": " Python – Set in Depth" }, { "code": null, "e": 3477, "s": 3447, "text": " Python – Dictionary in Depth" }, { "code": null, "e": 3502, "s": 3477, "text": " Python – Tuple in Depth" }, { "code": null, "e": 3532, "s": 3502, "text": " Python – Stack Datastructure" }, { "code": null, "e": 3562, "s": 3532, "text": " Python – Classes and Objects" }, { "code": null, "e": 3585, "s": 3562, "text": " Python – Constructors" }, { "code": null, "e": 3616, "s": 3585, "text": " Python – Object Introspection" }, { "code": null, "e": 3638, "s": 3616, "text": " Python – Inheritance" }, { "code": null, "e": 3659, "s": 3638, "text": " Python – Decorators" }, { "code": null, "e": 3695, "s": 3659, "text": " Python – Serialization with Pickle" }, { "code": null, "e": 3725, "s": 3695, "text": " Python – Exceptions Handling" }, { "code": null, "e": 3759, "s": 3725, "text": " Python – User defined Exceptions" }, { "code": null, "e": 3785, "s": 3759, "text": " Python – Multiprocessing" }, { "code": null, "e": 3823, "s": 3785, "text": " Python – Default function parameters" }, { "code": null, "e": 3851, "s": 3823, "text": " Python – Lambdas Functions" }, { "code": null, "e": 3875, "s": 3851, "text": " Python – NumPy Library" }, { "code": null, "e": 3901, "s": 3875, "text": " Python – MySQL Connector" }, { "code": null, "e": 3933, "s": 3901, "text": " Python – MySQL Create Database" }, { "code": null, "e": 3959, "s": 3933, "text": " Python – MySQL Read Data" }, { "code": null, "e": 3987, "s": 3959, "text": " Python – MySQL Insert Data" }, { "code": null, "e": 4018, "s": 3987, "text": " Python – MySQL Update Records" }, { "code": null, "e": 4049, "s": 4018, "text": " Python – MySQL Delete Records" }, { "code": null, "e": 4082, "s": 4049, "text": " Python – String Case Conversion" }, { "code": null, "e": 4117, "s": 4082, "text": " Howto – Find biggest of 2 numbers" }, { "code": null, "e": 4154, "s": 4117, "text": " Howto – Remove duplicates from List" }, { "code": null, "e": 4192, "s": 4154, "text": " Howto – Convert any Number to Binary" }, { "code": null, "e": 4218, "s": 4192, "text": " Howto – Merge two Lists" }, { "code": null, "e": 4243, "s": 4218, "text": " Howto – Merge two dicts" }, { "code": null, "e": 4283, "s": 4243, "text": " Howto – Get Characters Count in a File" }, { "code": null, "e": 4318, "s": 4283, "text": " Howto – Get Words Count in a File" }, { "code": null, "e": 4353, "s": 4318, "text": " Howto – Remove Spaces from String" }, { "code": null, "e": 4382, "s": 4353, "text": " Howto – Read Env variables" }, { "code": null, "e": 4408, "s": 4382, "text": " Howto – Read a text File" }, { "code": null, "e": 4434, "s": 4408, "text": " Howto – Read a JSON File" }, { "code": null, "e": 4466, "s": 4434, "text": " Howto – Read Config.ini files" }, { "code": null, "e": 4494, "s": 4466, "text": " Howto – Iterate Dictionary" }, { "code": null, "e": 4534, "s": 4494, "text": " Howto – Convert List Of Objects to CSV" }, { "code": null, "e": 4568, "s": 4534, "text": " Howto – Merge two dict in Python" }, { "code": null, "e": 4593, "s": 4568, "text": " Howto – create Zip File" }, { "code": null, "e": 4614, "s": 4593, "text": " Howto – Get OS info" }, { "code": null, "e": 4645, "s": 4614, "text": " Howto – Get size of Directory" }, { "code": null, "e": 4682, "s": 4645, "text": " Howto – Check whether a file exists" }, { "code": null, "e": 4719, "s": 4682, "text": " Howto – Remove key from dictionary" }, { "code": null, "e": 4741, "s": 4719, "text": " Howto – Sort Objects" }, { "code": null, "e": 4779, "s": 4741, "text": " Howto – Create or Delete Directories" }, { "code": null, "e": 4802, "s": 4779, "text": " Howto – Read CSV File" }, { "code": null, "e": 4840, "s": 4802, "text": " Howto – Create Python Iterable class" }, { "code": null, "e": 4871, "s": 4840, "text": " Howto – Access for loop index" }, { "code": null, "e": 4909, "s": 4871, "text": " Howto – Clear all elements from List" }, { "code": null, "e": 4949, "s": 4909, "text": " Howto – Remove empty lists from a List" }, { "code": null, "e": 4996, "s": 4949, "text": " Howto – Remove special characters from String" }, { "code": null, "e": 5028, "s": 4996, "text": " Howto – Sort dictionary by key" } ]
Gotta Simulate ’Em All — Pokemon. Simulating Pokemon Battles From... | by Tyler Marrs | Towards Data Science
Many of us grew up playing Pokemon at various iterations of the series. When I was ten years old, the first generation (red and blue) of Pokemon came out in the United States. I spent countless hours playing that game with my friends. In 2018, I came across a PyData talk, “Vincent Warmerdam: Winning with Simple, even Linear, Models | PyData London 2018”, that mentioned how easy it is to obtain Pokemon data. The talk did not focus on Pokemon battle simulation, although it inspired me to create a Pokemon battle simulator and write this article. In this article, I will discuss: Limitations of this implementation The data collection process Algorithms used throughout the simulator How I ranked Pokemon NOTE: If you would like to review all of the source code, please find it at github.com/tylerwmarrs/pokemon-battle-simulation. While I tried to capture most of the battle mechanics in the game, some mechanics were left out. Ailments, such as paralysis, poison, and others, were left out to simplify a battle. There is no way that a Pokemon may restore health. Battles consist of damaging abilities that a Pokemon learns by leveling. Attacking mechanics could be improved by ranking effectiveness instead of choosing at random. These limitations may impact some Pokemon ranks. I highly encourage anyone interested to implement the missing details by contributing to the repository. The data collection process was painless. A website provided me with the majority of the information I needed on the Pokemon themselves. The website pokeapi.co, provides an open API with results in the JSON format. The documentation of the website is quite thorough. Obtaining Pokemon attributes and moves involved: Identifying Pokemon from the red/blue versionsFor each Pokemon, download the attributesIdentify moves from the red/blue versionsFor each move, download the attributes Identifying Pokemon from the red/blue versions For each Pokemon, download the attributes Identify moves from the red/blue versions For each move, download the attributes Once all of the moves and Pokemon downloaded, I mapped the moves to each Pokemon using a pandas join. I prefer to work with CSV files over JSON, so I spent some time flattening the structure of the attributes required for simulating battle. The JSON structure consisted of optional attributes, nested many layers deep. Flattening the attributes made it much easier to query. Pokemon Attributes name — The name of the Pokemon hp — The health points attack — General attack statistic speed — Speed is a statistic used to compute damage special attack — Special attack statistic defense — Statistic to determine damage taken against regular attacks special defense — Statistic to determine damage taken against special attacks types — The type(s) of the Pokemon; Fire, Water, Rock, etc. Move Attributes name — The name of the move pp — Number of times the move may be applied type — The type of move; Fire, Normal, Water, etc. crit_rate — A flag to adjust the critical chance of the move power — Power is a statistic used to compute damage min_hits — The minimum number of times the move may apply in a given turn. max_hits — The maximum number of times the move may apply in a given turn. In addition to the moves and Pokemon, I needed to obtain data to help quantify the damage. Pokemon is a turn-based game in which a player chooses an action to apply. This simulation is only concerned with attack moves to compute damage. Each Pokemon is a specific type, and so is each attack. The goal is to either defeat the opposing Pokemon or capture it. This simulation only captures victory and defeat. When an attack is applied, it may cause more damage given: The attacking Pokemon type The type of attack The defending Pokemon type The table shows how attack damage applies to a given Pokemon type. I retrieved it from this website using and cleaned it. The table captures exceptions to the default type modifier value of one. The critical chance algorithm, based on a random number generator, depends on the attack. Some attacks are more likely to crit than others. I obtained the formula from this website and removed some flaws within the implementation of the game. A couple of notable flaws include: The original game formula intended for a 100% critical chance; however, the implementation resulted in a maximum of 99.6%. My implementation allows for a 100% critical chance. Some boosting abilities decrease the critical chance when it should have increased it. However, boosting moves are entirely ignored in this simulation. The algorithm takes the Pokemon’s base speed and the attacks critical chance rate to determine if a critical hit is occurring. The speed of the Pokemon is a big factor in deciding a critical chance. The damage algorithm determines how much damage to apply given the Pokemon attributes and critical strike boolean from the critical hit algorithm. These algorithms are derived from the formulas on this website. Randomly chooses a move with power points remaining based on the attacking Pokemon’s move list. When all moves are exhausted, null is returned. This is needed in the case that two Pokemon will tie; otherwise, an endless loop will occur in the apply_move algorithm. This algorithm manages: Critical chance randomization Same type attack bonus (a fire Pokemon applying a fire move) Attacking Pokemon’s power points (PP) Defending Pokemon’s health points (HP) Number of times the move should be applied Note that this function has a hardcoded level value of 10, which may impact the damage calculation. The battle algorithm keeps track of the simulation state: Randomly chooses the Pokemon that may attack first Which Pokemon’s turn it is Checking for a winner Checking for a tie Here is an example of a battle that illustrates Pikachu against Gastly. pikachu = Pokemon('pikachu')gastly = Pokemon('gastly')battle(pikachu, gastly)Output------gastly damaged pikachu with night-shade for 2.0 hpgastly pp for night-shade is 14/15pikachu hp is 33.0/35pikachu damaged gastly with thunder-shock for 10.0 hppikachu pp for thunder-shock is 29/30gastly hp is 20.0/30gastly damaged pikachu with dream-eater for 22.0 hpgastly pp for dream-eater is 14/15pikachu hp is 11.0/35pikachu damaged gastly with thunder-shock for 11.0 hppikachu pp for thunder-shock is 28/30gastly hp is 9.0/30gastly damaged pikachu with lick for 6.0 hpgastly pp for lick is 29/30pikachu hp is 5.0/35pikachu damaged gastly with thunder-shock for 10.0 hppikachu pp for thunder-shock is 27/30gastly hp is -1.0/30{'pokemon': 'pikachu', 'pokemonb': 'gastly', 'moves': 6, 'winner': 'pikachu', 'first_attack': 'gastly'} With the battle algorithm complete, I created some logic to simulate battles 1,000 times between all Pokemon that contain at least one damaging move. Pokemon of the same species are excluded from battling. For example, Pikachu vs. Pikachu is not simulated. At the beginning of every battle, each Pokemon is randomly assigned up to four of their damaging abilities. The results are tallied between each pair of Pokemon tracking who lost, who won, and the number of ties. A single Pokemon battles 146,000 times. With the statistics aggregated, I ranked the Pokemon in two ways: Bayesian ranking — priors were set as 50/50 chancePercent ranking Bayesian ranking — priors were set as 50/50 chance Percent ranking The top 20 Pokemon, shown below by Bayesian rank, seems logical in that Mewtwo is ranked number one. Mewtwo is considered the best Pokemon in the first generation with attributes that make it so. It was also one of the rarest Pokemon to capture. The bottom 20 Pokemon also seems logical since Magikarp is last. Magikarp has the worst attributes in the game with low defense and attack. For a full list of rankings, please visit this link. While my implementation of Pokemon battling is limited, the results seem logical. Hopefully, I have inspired another Pokemon fan to take some of these concepts so they may apply them in their simulation. Simulating and modeling is a great skill to have. Applying it to something you are familiar with makes the modeling process more manageable. Please take the time to critique this work if you find it interesting.
[ { "code": null, "e": 720, "s": 171, "text": "Many of us grew up playing Pokemon at various iterations of the series. When I was ten years old, the first generation (red and blue) of Pokemon came out in the United States. I spent countless hours playing that game with my friends. In 2018, I came across a PyData talk, “Vincent Warmerdam: Winning with Simple, even Linear, Models | PyData London 2018”, that mentioned how easy it is to obtain Pokemon data. The talk did not focus on Pokemon battle simulation, although it inspired me to create a Pokemon battle simulator and write this article." }, { "code": null, "e": 753, "s": 720, "text": "In this article, I will discuss:" }, { "code": null, "e": 788, "s": 753, "text": "Limitations of this implementation" }, { "code": null, "e": 816, "s": 788, "text": "The data collection process" }, { "code": null, "e": 857, "s": 816, "text": "Algorithms used throughout the simulator" }, { "code": null, "e": 878, "s": 857, "text": "How I ranked Pokemon" }, { "code": null, "e": 1004, "s": 878, "text": "NOTE: If you would like to review all of the source code, please find it at github.com/tylerwmarrs/pokemon-battle-simulation." }, { "code": null, "e": 1101, "s": 1004, "text": "While I tried to capture most of the battle mechanics in the game, some mechanics were left out." }, { "code": null, "e": 1186, "s": 1101, "text": "Ailments, such as paralysis, poison, and others, were left out to simplify a battle." }, { "code": null, "e": 1237, "s": 1186, "text": "There is no way that a Pokemon may restore health." }, { "code": null, "e": 1310, "s": 1237, "text": "Battles consist of damaging abilities that a Pokemon learns by leveling." }, { "code": null, "e": 1404, "s": 1310, "text": "Attacking mechanics could be improved by ranking effectiveness instead of choosing at random." }, { "code": null, "e": 1558, "s": 1404, "text": "These limitations may impact some Pokemon ranks. I highly encourage anyone interested to implement the missing details by contributing to the repository." }, { "code": null, "e": 1874, "s": 1558, "text": "The data collection process was painless. A website provided me with the majority of the information I needed on the Pokemon themselves. The website pokeapi.co, provides an open API with results in the JSON format. The documentation of the website is quite thorough. Obtaining Pokemon attributes and moves involved:" }, { "code": null, "e": 2041, "s": 1874, "text": "Identifying Pokemon from the red/blue versionsFor each Pokemon, download the attributesIdentify moves from the red/blue versionsFor each move, download the attributes" }, { "code": null, "e": 2088, "s": 2041, "text": "Identifying Pokemon from the red/blue versions" }, { "code": null, "e": 2130, "s": 2088, "text": "For each Pokemon, download the attributes" }, { "code": null, "e": 2172, "s": 2130, "text": "Identify moves from the red/blue versions" }, { "code": null, "e": 2211, "s": 2172, "text": "For each move, download the attributes" }, { "code": null, "e": 2313, "s": 2211, "text": "Once all of the moves and Pokemon downloaded, I mapped the moves to each Pokemon using a pandas join." }, { "code": null, "e": 2586, "s": 2313, "text": "I prefer to work with CSV files over JSON, so I spent some time flattening the structure of the attributes required for simulating battle. The JSON structure consisted of optional attributes, nested many layers deep. Flattening the attributes made it much easier to query." }, { "code": null, "e": 2605, "s": 2586, "text": "Pokemon Attributes" }, { "code": null, "e": 2636, "s": 2605, "text": "name — The name of the Pokemon" }, { "code": null, "e": 2659, "s": 2636, "text": "hp — The health points" }, { "code": null, "e": 2693, "s": 2659, "text": "attack — General attack statistic" }, { "code": null, "e": 2745, "s": 2693, "text": "speed — Speed is a statistic used to compute damage" }, { "code": null, "e": 2787, "s": 2745, "text": "special attack — Special attack statistic" }, { "code": null, "e": 2857, "s": 2787, "text": "defense — Statistic to determine damage taken against regular attacks" }, { "code": null, "e": 2935, "s": 2857, "text": "special defense — Statistic to determine damage taken against special attacks" }, { "code": null, "e": 2995, "s": 2935, "text": "types — The type(s) of the Pokemon; Fire, Water, Rock, etc." }, { "code": null, "e": 3011, "s": 2995, "text": "Move Attributes" }, { "code": null, "e": 3039, "s": 3011, "text": "name — The name of the move" }, { "code": null, "e": 3084, "s": 3039, "text": "pp — Number of times the move may be applied" }, { "code": null, "e": 3135, "s": 3084, "text": "type — The type of move; Fire, Normal, Water, etc." }, { "code": null, "e": 3196, "s": 3135, "text": "crit_rate — A flag to adjust the critical chance of the move" }, { "code": null, "e": 3248, "s": 3196, "text": "power — Power is a statistic used to compute damage" }, { "code": null, "e": 3323, "s": 3248, "text": "min_hits — The minimum number of times the move may apply in a given turn." }, { "code": null, "e": 3398, "s": 3323, "text": "max_hits — The maximum number of times the move may apply in a given turn." }, { "code": null, "e": 3865, "s": 3398, "text": "In addition to the moves and Pokemon, I needed to obtain data to help quantify the damage. Pokemon is a turn-based game in which a player chooses an action to apply. This simulation is only concerned with attack moves to compute damage. Each Pokemon is a specific type, and so is each attack. The goal is to either defeat the opposing Pokemon or capture it. This simulation only captures victory and defeat. When an attack is applied, it may cause more damage given:" }, { "code": null, "e": 3892, "s": 3865, "text": "The attacking Pokemon type" }, { "code": null, "e": 3911, "s": 3892, "text": "The type of attack" }, { "code": null, "e": 3938, "s": 3911, "text": "The defending Pokemon type" }, { "code": null, "e": 4133, "s": 3938, "text": "The table shows how attack damage applies to a given Pokemon type. I retrieved it from this website using and cleaned it. The table captures exceptions to the default type modifier value of one." }, { "code": null, "e": 4376, "s": 4133, "text": "The critical chance algorithm, based on a random number generator, depends on the attack. Some attacks are more likely to crit than others. I obtained the formula from this website and removed some flaws within the implementation of the game." }, { "code": null, "e": 4411, "s": 4376, "text": "A couple of notable flaws include:" }, { "code": null, "e": 4587, "s": 4411, "text": "The original game formula intended for a 100% critical chance; however, the implementation resulted in a maximum of 99.6%. My implementation allows for a 100% critical chance." }, { "code": null, "e": 4739, "s": 4587, "text": "Some boosting abilities decrease the critical chance when it should have increased it. However, boosting moves are entirely ignored in this simulation." }, { "code": null, "e": 4938, "s": 4739, "text": "The algorithm takes the Pokemon’s base speed and the attacks critical chance rate to determine if a critical hit is occurring. The speed of the Pokemon is a big factor in deciding a critical chance." }, { "code": null, "e": 5149, "s": 4938, "text": "The damage algorithm determines how much damage to apply given the Pokemon attributes and critical strike boolean from the critical hit algorithm. These algorithms are derived from the formulas on this website." }, { "code": null, "e": 5414, "s": 5149, "text": "Randomly chooses a move with power points remaining based on the attacking Pokemon’s move list. When all moves are exhausted, null is returned. This is needed in the case that two Pokemon will tie; otherwise, an endless loop will occur in the apply_move algorithm." }, { "code": null, "e": 5438, "s": 5414, "text": "This algorithm manages:" }, { "code": null, "e": 5468, "s": 5438, "text": "Critical chance randomization" }, { "code": null, "e": 5529, "s": 5468, "text": "Same type attack bonus (a fire Pokemon applying a fire move)" }, { "code": null, "e": 5567, "s": 5529, "text": "Attacking Pokemon’s power points (PP)" }, { "code": null, "e": 5606, "s": 5567, "text": "Defending Pokemon’s health points (HP)" }, { "code": null, "e": 5649, "s": 5606, "text": "Number of times the move should be applied" }, { "code": null, "e": 5749, "s": 5649, "text": "Note that this function has a hardcoded level value of 10, which may impact the damage calculation." }, { "code": null, "e": 5807, "s": 5749, "text": "The battle algorithm keeps track of the simulation state:" }, { "code": null, "e": 5858, "s": 5807, "text": "Randomly chooses the Pokemon that may attack first" }, { "code": null, "e": 5885, "s": 5858, "text": "Which Pokemon’s turn it is" }, { "code": null, "e": 5907, "s": 5885, "text": "Checking for a winner" }, { "code": null, "e": 5926, "s": 5907, "text": "Checking for a tie" }, { "code": null, "e": 5998, "s": 5926, "text": "Here is an example of a battle that illustrates Pikachu against Gastly." }, { "code": null, "e": 6821, "s": 5998, "text": "pikachu = Pokemon('pikachu')gastly = Pokemon('gastly')battle(pikachu, gastly)Output------gastly damaged pikachu with night-shade for 2.0 hpgastly pp for night-shade is 14/15pikachu hp is 33.0/35pikachu damaged gastly with thunder-shock for 10.0 hppikachu pp for thunder-shock is 29/30gastly hp is 20.0/30gastly damaged pikachu with dream-eater for 22.0 hpgastly pp for dream-eater is 14/15pikachu hp is 11.0/35pikachu damaged gastly with thunder-shock for 11.0 hppikachu pp for thunder-shock is 28/30gastly hp is 9.0/30gastly damaged pikachu with lick for 6.0 hpgastly pp for lick is 29/30pikachu hp is 5.0/35pikachu damaged gastly with thunder-shock for 10.0 hppikachu pp for thunder-shock is 27/30gastly hp is -1.0/30{'pokemon': 'pikachu', 'pokemonb': 'gastly', 'moves': 6, 'winner': 'pikachu', 'first_attack': 'gastly'}" }, { "code": null, "e": 7331, "s": 6821, "text": "With the battle algorithm complete, I created some logic to simulate battles 1,000 times between all Pokemon that contain at least one damaging move. Pokemon of the same species are excluded from battling. For example, Pikachu vs. Pikachu is not simulated. At the beginning of every battle, each Pokemon is randomly assigned up to four of their damaging abilities. The results are tallied between each pair of Pokemon tracking who lost, who won, and the number of ties. A single Pokemon battles 146,000 times." }, { "code": null, "e": 7397, "s": 7331, "text": "With the statistics aggregated, I ranked the Pokemon in two ways:" }, { "code": null, "e": 7463, "s": 7397, "text": "Bayesian ranking — priors were set as 50/50 chancePercent ranking" }, { "code": null, "e": 7514, "s": 7463, "text": "Bayesian ranking — priors were set as 50/50 chance" }, { "code": null, "e": 7530, "s": 7514, "text": "Percent ranking" }, { "code": null, "e": 7776, "s": 7530, "text": "The top 20 Pokemon, shown below by Bayesian rank, seems logical in that Mewtwo is ranked number one. Mewtwo is considered the best Pokemon in the first generation with attributes that make it so. It was also one of the rarest Pokemon to capture." }, { "code": null, "e": 7916, "s": 7776, "text": "The bottom 20 Pokemon also seems logical since Magikarp is last. Magikarp has the worst attributes in the game with low defense and attack." }, { "code": null, "e": 7969, "s": 7916, "text": "For a full list of rankings, please visit this link." }, { "code": null, "e": 8314, "s": 7969, "text": "While my implementation of Pokemon battling is limited, the results seem logical. Hopefully, I have inspired another Pokemon fan to take some of these concepts so they may apply them in their simulation. Simulating and modeling is a great skill to have. Applying it to something you are familiar with makes the modeling process more manageable." } ]
C library function - strcspn()
The C library function size_t strcspn(const char *str1, const char *str2) calculates the length of the initial segment of str1, which consists entirely of characters not in str2. Following is the declaration for strcspn() function. size_t strcspn(const char *str1, const char *str2) str1 − This is the main C string to be scanned. str1 − This is the main C string to be scanned. str2 − This is the string containing a list of characters to match in str1. str2 − This is the string containing a list of characters to match in str1. This function returns the number of characters in the initial segment of string str1 which are not in the string str2. The following example shows the usage of strcspn() function. #include <stdio.h> #include <string.h> int main () { int len; const char str1[] = "ABCDEF4960910"; const char str2[] = "013"; len = strcspn(str1, str2); printf("First matched character is at %d\n", len + 1); return(0); } Let us compile and run the above program that will produce the following result − First matched character is at 10 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2187, "s": 2007, "text": "The C library function size_t strcspn(const char *str1, const char *str2) calculates the length of the initial segment of str1, which consists entirely of characters not in str2." }, { "code": null, "e": 2240, "s": 2187, "text": "Following is the declaration for strcspn() function." }, { "code": null, "e": 2291, "s": 2240, "text": "size_t strcspn(const char *str1, const char *str2)" }, { "code": null, "e": 2339, "s": 2291, "text": "str1 − This is the main C string to be scanned." }, { "code": null, "e": 2387, "s": 2339, "text": "str1 − This is the main C string to be scanned." }, { "code": null, "e": 2463, "s": 2387, "text": "str2 − This is the string containing a list of characters to match in str1." }, { "code": null, "e": 2539, "s": 2463, "text": "str2 − This is the string containing a list of characters to match in str1." }, { "code": null, "e": 2658, "s": 2539, "text": "This function returns the number of characters in the initial segment of string str1 which are not in the string str2." }, { "code": null, "e": 2719, "s": 2658, "text": "The following example shows the usage of strcspn() function." }, { "code": null, "e": 2965, "s": 2719, "text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n int len;\n const char str1[] = \"ABCDEF4960910\";\n const char str2[] = \"013\";\n\n len = strcspn(str1, str2);\n\n printf(\"First matched character is at %d\\n\", len + 1);\n \n return(0);\n}" }, { "code": null, "e": 3047, "s": 2965, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 3081, "s": 3047, "text": "First matched character is at 10\n" }, { "code": null, "e": 3114, "s": 3081, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3129, "s": 3114, "text": " Nishant Malik" }, { "code": null, "e": 3164, "s": 3129, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3179, "s": 3164, "text": " Nishant Malik" }, { "code": null, "e": 3214, "s": 3179, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3228, "s": 3214, "text": " Asif Hussain" }, { "code": null, "e": 3261, "s": 3228, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3279, "s": 3261, "text": " Richa Maheshwari" }, { "code": null, "e": 3314, "s": 3279, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3333, "s": 3314, "text": " Vandana Annavaram" }, { "code": null, "e": 3366, "s": 3333, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3378, "s": 3366, "text": " Amit Diwan" }, { "code": null, "e": 3385, "s": 3378, "text": " Print" }, { "code": null, "e": 3396, "s": 3385, "text": " Add Notes" } ]
Requests - Authentication
This chapter will discuss the types of authentication available in the Requests module. We are going to discuss the following − Working of Authentication in HTTP Requests Basic Authentication Digest Authentication OAuth2 Authentication HTTP authentication is on the server-side asking for some authentication information like username, password when the client requests a URL. This is additional security for the request and the response being exchanged between the client and the server. From the client-side these additional authentication information i.e. username and password can be sent in the headers, which later on the server side will be validated. The response will be delivered from the server-side only when the authentication is valid. Requests library has most commonly used authentication in requests.auth, which are Basic Authentication (HTTPBasicAuth) and Digest Authentication (HTTPDigestAuth). This is the simplest form of providing authentication to the server. To work with basic authentication, we are going to use HTTPBasicAuth class available with requests library. Here is a working example of how to use it. import requests from requests.auth import HTTPBasicAuth response_data = requests.get('httpbin.org/basic-auth/admin/admin123', auth = HTTPDigestAuth('admin', 'admin123')) print(response_data.text) We are calling the url, https://httpbin.org/basic-auth/admin/admin123 with user as admin and password as admin123. So, this URL will not work without authentication, i.e. user and password. Once you give the authentication using the auth param, then only the server will give back the response. E:\prequests>python makeRequest.py { "authenticated": true, "user": "admin" } This is another form of authentication available with requests. We are going to make use of HTTPDigestAuth class from requests. import requests from requests.auth import HTTPDigestAuth response_data = requests.get('https://httpbin.org/digest-auth/auth/admin/admin123', auth = HTTPDigestAuth('admin', 'admin123')) print(response_data.text) E:\prequests>python makeRequest.py { "authenticated": true, "user": "admin" } To use OAuth2 Authentication, we need “requests_oauth2” library. To install “requests_oauth2” do the following − pip install requests_oauth2 The display in your terminal while installing will be something as shown below − E:\prequests>pip install requests_oauth2 Collecting requests_oauth2 Downloading https://files.pythonhosted.org/packages/52/dc/01c3c75e6e7341a2c7a9 71d111d7105df230ddb74b5d4e10a3dabb61750c/requests-oauth2-0.3.0.tar.gz Requirement already satisfied: requests in c:\users\xyz\appdata\local\programs \python\python37\lib\site-packages (from requests_oauth2) (2.22.0) Requirement already satisfied: six in c:\users\xyz\appdata\local\programs\pyth on\python37\lib\site-packages (from requests_oauth2) (1.12.0) Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\use rs\xyz\appdata\local\programs\python\python37\lib\site-packages (from requests ->requests_oauth2) (1.25.3) Requirement already satisfied: certifi>=2017.4.17 in c:\users\xyz\appdata\loca l\programs\python\python37\lib\site-packages (from requests->requests_oauth2) (2 019.3.9) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\users\xyz\appdata\l ocal\programs\python\python37\lib\site-packages (from requests->requests_oauth2) (3.0.4) Requirement already satisfied: idna<2.9,>=2.5 in c:\users\xyz\appdata\local\pr ograms\python\python37\lib\site-packages (from requests->requests_oauth2) (2.8) Building wheels for collected packages: requests-oauth2 Building wheel for requests-oauth2 (setup.py) ... done Stored in directory: C:\Users\xyz\AppData\Local\pip\Cache\wheels\90\ef\b4\43 3743cbbc488463491da7df510d41c4e5aa28213caeedd586 Successfully built requests-oauth2 We are done installing “requests-oauth2”. To use the API’s of Google, Twitter we need its consent and the same is done using OAuth2 authentication. For OAuth2 authentication we will need Client ID and a Secret Key. The details of how to get it, is mentioned on https://developers.google.com/identity/protocols/OAuth2. Later on, login to Google API Console which is available at https://console.developers.google.com/and get the client id and secret key. Here is an example of how to use "requests-oauth2". import requests from requests_oauth2.services import GoogleClient google_auth = GoogleClient( client_id="xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", redirect_uri="http://localhost/auth/success.html", ) a = google_auth.authorize_url( scope=["profile", "email"], response_type="code", ) res = requests.get(a) print(res.url) We will not be able to redirect to the URL given, as it needs to login to the Gmail account, but here, you will see from the example, that google_auth works and the authorized URL is given. E:\prequests>python oauthRequest.py https://accounts.google.com/o/oauth2/auth?redirect_uri= http%3A%2F%2Flocalhost%2Fauth%2Fsuccess.html& client_id=xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com& scope=profile+email&response_type=code Print Add Notes Bookmark this page
[ { "code": null, "e": 2276, "s": 2188, "text": "This chapter will discuss the types of authentication available in the Requests module." }, { "code": null, "e": 2316, "s": 2276, "text": "We are going to discuss the following −" }, { "code": null, "e": 2359, "s": 2316, "text": "Working of Authentication in HTTP Requests" }, { "code": null, "e": 2380, "s": 2359, "text": "Basic Authentication" }, { "code": null, "e": 2402, "s": 2380, "text": "Digest Authentication" }, { "code": null, "e": 2424, "s": 2402, "text": "OAuth2 Authentication" }, { "code": null, "e": 2677, "s": 2424, "text": "HTTP authentication is on the server-side asking for some authentication information like username, password when the client requests a URL. This is additional security for the request and the response being exchanged between the client and the server." }, { "code": null, "e": 2938, "s": 2677, "text": "From the client-side these additional authentication information i.e. username and password can be sent in the headers, which later on the server side will be validated. The response will be delivered from the server-side only when the authentication is valid." }, { "code": null, "e": 3102, "s": 2938, "text": "Requests library has most commonly used authentication in requests.auth, which are Basic Authentication (HTTPBasicAuth) and Digest Authentication (HTTPDigestAuth)." }, { "code": null, "e": 3279, "s": 3102, "text": "This is the simplest form of providing authentication to the server. To work with basic authentication, we are going to use HTTPBasicAuth class available with requests library." }, { "code": null, "e": 3323, "s": 3279, "text": "Here is a working example of how to use it." }, { "code": null, "e": 3523, "s": 3323, "text": "import requests\nfrom requests.auth import HTTPBasicAuth\nresponse_data = \nrequests.get('httpbin.org/basic-auth/admin/admin123', \nauth = HTTPDigestAuth('admin', 'admin123'))\nprint(response_data.text) " }, { "code": null, "e": 3638, "s": 3523, "text": "We are calling the url, https://httpbin.org/basic-auth/admin/admin123 with user as admin and password as admin123." }, { "code": null, "e": 3818, "s": 3638, "text": "So, this URL will not work without authentication, i.e. user and password. Once you give the authentication using the auth param, then only the server will give back the response." }, { "code": null, "e": 3903, "s": 3818, "text": "E:\\prequests>python makeRequest.py\n{\n \"authenticated\": true,\n \"user\": \"admin\"\n}\n" }, { "code": null, "e": 4031, "s": 3903, "text": "This is another form of authentication available with requests. We are going to make use of HTTPDigestAuth class from requests." }, { "code": null, "e": 4244, "s": 4031, "text": "import requests\nfrom requests.auth import HTTPDigestAuth\nresponse_data = \nrequests.get('https://httpbin.org/digest-auth/auth/admin/admin123', \nauth = HTTPDigestAuth('admin', 'admin123'))\nprint(response_data.text)" }, { "code": null, "e": 4329, "s": 4244, "text": "E:\\prequests>python makeRequest.py\n{\n \"authenticated\": true,\n \"user\": \"admin\"\n}\n" }, { "code": null, "e": 4442, "s": 4329, "text": "To use OAuth2 Authentication, we need “requests_oauth2” library. To install “requests_oauth2” do the following −" }, { "code": null, "e": 4471, "s": 4442, "text": "pip install requests_oauth2\n" }, { "code": null, "e": 4552, "s": 4471, "text": "The display in your terminal while installing will be something as shown below −" }, { "code": null, "e": 6013, "s": 4552, "text": "E:\\prequests>pip install requests_oauth2\nCollecting requests_oauth2\nDownloading https://files.pythonhosted.org/packages/52/dc/01c3c75e6e7341a2c7a9\n71d111d7105df230ddb74b5d4e10a3dabb61750c/requests-oauth2-0.3.0.tar.gz\nRequirement already satisfied: requests in c:\\users\\xyz\\appdata\\local\\programs\n\\python\\python37\\lib\\site-packages (from requests_oauth2) (2.22.0)\nRequirement already satisfied: six in c:\\users\\xyz\\appdata\\local\\programs\\pyth\non\\python37\\lib\\site-packages (from requests_oauth2) (1.12.0)\nRequirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\\use\nrs\\xyz\\appdata\\local\\programs\\python\\python37\\lib\\site-packages (from requests\n->requests_oauth2) (1.25.3)\nRequirement already satisfied: certifi>=2017.4.17 in c:\\users\\xyz\\appdata\\loca\nl\\programs\\python\\python37\\lib\\site-packages (from requests->requests_oauth2) (2\n019.3.9)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\\users\\xyz\\appdata\\l\nocal\\programs\\python\\python37\\lib\\site-packages (from requests->requests_oauth2)\n(3.0.4)\nRequirement already satisfied: idna<2.9,>=2.5 in c:\\users\\xyz\\appdata\\local\\pr\nograms\\python\\python37\\lib\\site-packages (from requests->requests_oauth2) (2.8)\nBuilding wheels for collected packages: requests-oauth2\nBuilding wheel for requests-oauth2 (setup.py) ... done\nStored in directory: C:\\Users\\xyz\\AppData\\Local\\pip\\Cache\\wheels\\90\\ef\\b4\\43\n3743cbbc488463491da7df510d41c4e5aa28213caeedd586\nSuccessfully built requests-oauth2\n" }, { "code": null, "e": 6161, "s": 6013, "text": "We are done installing “requests-oauth2”. To use the API’s of Google, Twitter we need its consent and the same is done using OAuth2 authentication." }, { "code": null, "e": 6331, "s": 6161, "text": "For OAuth2 authentication we will need Client ID and a Secret Key. The details of how to get it, is mentioned on https://developers.google.com/identity/protocols/OAuth2." }, { "code": null, "e": 6468, "s": 6331, "text": "Later on, login to Google API Console which is available at https://console.developers.google.com/and get the client id and secret key." }, { "code": null, "e": 6520, "s": 6468, "text": "Here is an example of how to use \"requests-oauth2\"." }, { "code": null, "e": 6866, "s": 6520, "text": "import requests\nfrom requests_oauth2.services import GoogleClient\ngoogle_auth = GoogleClient(\n client_id=\"xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com\",\n redirect_uri=\"http://localhost/auth/success.html\",\n)\na = google_auth.authorize_url(\n scope=[\"profile\", \"email\"],\n response_type=\"code\",\n)\nres = requests.get(a)\nprint(res.url)" }, { "code": null, "e": 7056, "s": 6866, "text": "We will not be able to redirect to the URL given, as it needs to login to the Gmail account, but here, you will see from the example, that google_auth works and the authorized URL is given." }, { "code": null, "e": 7294, "s": 7056, "text": "E:\\prequests>python oauthRequest.py\nhttps://accounts.google.com/o/oauth2/auth?redirect_uri=\nhttp%3A%2F%2Flocalhost%2Fauth%2Fsuccess.html&\nclient_id=xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&\nscope=profile+email&response_type=code\n" }, { "code": null, "e": 7301, "s": 7294, "text": " Print" }, { "code": null, "e": 7312, "s": 7301, "text": " Add Notes" } ]
How to add 5 hours to current time in MySQL?
To add 5 hours in current time, we will use now() function from MySQL. The syntax is as follows − SELECT date_add(now(),interval some integer value hour); Now, I am applying the above query to add 5 hours to current time. The query is as follows − mysql> SELECT date_add(now(),interval 5 hour); The following is the output +---------------------------------+ | date_add(now(),interval 5 hour) | +---------------------------------+ | 2018-10-11 15:59:23 | +---------------------------------+ 1 row in set (0.00 sec) Look at the output above, it has increased the current time by 5 hours
[ { "code": null, "e": 1160, "s": 1062, "text": "To add 5 hours in current time, we will use now() function from MySQL. The syntax is as\nfollows −" }, { "code": null, "e": 1217, "s": 1160, "text": "SELECT date_add(now(),interval some integer value hour);" }, { "code": null, "e": 1310, "s": 1217, "text": "Now, I am applying the above query to add 5 hours to current time. The query is as follows −" }, { "code": null, "e": 1358, "s": 1310, "text": "mysql> SELECT date_add(now(),interval 5 hour);\n" }, { "code": null, "e": 1386, "s": 1358, "text": "The following is the output" }, { "code": null, "e": 1590, "s": 1386, "text": "+---------------------------------+\n| date_add(now(),interval 5 hour) |\n+---------------------------------+\n| 2018-10-11 15:59:23 |\n+---------------------------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1661, "s": 1590, "text": "Look at the output above, it has increased the current time by 5 hours" } ]
How to integrate Emojis Keyboard in an Android app?
This example demonstrates how do I integrate emogis keyboard in android app Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:emojicon="http://schemas.android.com/apk/res-auto" android:id="@+id/root_view" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff"> <ImageView android:id="@+id/emoji_btn" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:padding="4dp" /> <ImageView android:id="@+id/submit_btn" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:padding="4dp" android:src="@android:drawable/ic_menu_send" /> <hani.momanii.supernova_emoji_library.Helper.EmojiconEditText android:id="@+id/emojicon_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_toLeftOf="@id/submit_btn" android:layout_toRightOf="@id/emoji_btn" android:imeOptions="actionSend" android:inputType="text" emojicon:emojiconSize="28sp"/> <hani.momanii.supernova_emoji_library.Helper.EmojiconEditText android:id="@+id/emojicon_edit_text2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/emojicon_edit_text" android:imeOptions="actionSend" android:inputType="text" emojicon:emojiconSize="28sp"/> <CheckBox android:id="@+id/use_system_default" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:checked="false" android:text="Use System Default?"/> <hani.momanii.supernova_emoji_library.Helper.EmojiconTextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_marginTop="26dp" android:lineSpacingExtra="17sp" android:text="Hello Emojis !" android:textAppearance="@style/TextAppearance.AppCompat.Large" android:textColor="#000000" emojicon:emojiconAlignment="bottom"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import hani.momanii.supernova_emoji_library.Actions.EmojIconActions; import hani.momanii.supernova_emoji_library.Helper.EmojiconEditText; import hani.momanii.supernova_emoji_library.Helper.EmojiconTextView; public class MainActivity extends AppCompatActivity { CheckBox mCheckBox; EmojiconEditText emojiconEditText, emojiconEditText2; EmojiconTextView textView; ImageView emojiButton; ImageView submitButton; View rootView; EmojIconActions emojIcon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rootView = findViewById(R.id.root_view); emojiButton = (ImageView) findViewById(R.id.emoji_btn); submitButton = (ImageView) findViewById(R.id.submit_btn); mCheckBox = (CheckBox)findViewById(R.id.use_system_default); emojiconEditText = (EmojiconEditText) findViewById(R.id.emojicon_edit_text); emojiconEditText2 = (EmojiconEditText) findViewById(R.id.emojicon_edit_text2); textView = (EmojiconTextView) findViewById(R.id.textView); emojIcon = new EmojIconActions(this, rootView, emojiconEditText, emojiButton); emojIcon.ShowEmojIcon(); emojIcon.setKeyboardListener(new EmojIconActions.KeyboardListener() { @Override public void onKeyboardOpen() { Log.e("Keyboard", "open"); } @Override public void onKeyboardClose() { Log.e("Keyboard", "close"); } }); mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { emojIcon.setUseSystemEmoji(b); textView.setUseSystemDefault(b); } }); emojIcon.addEmojiconEditTextList(emojiconEditText2); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String newText = emojiconEditText.getText().toString(); textView.setText(newText); } }); } } Step 4 − In the build.gradle(Project: Sample4) add the following code − repositories { maven { url 'https://jitpack.io' } Step 5 − build.gradle (Module: app) implementation 'com.github.hani-momanii:SuperNova-Emoji:1.1' Step 6 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code.
[ { "code": null, "e": 1138, "s": 1062, "text": "This example demonstrates how do I integrate emogis keyboard in android app" }, { "code": null, "e": 1267, "s": 1138, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1331, "s": 1267, "text": "Step 2 − Add the following code to res/layout/activity_main.xml" }, { "code": null, "e": 3821, "s": 1331, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:emojicon=\"http://schemas.android.com/apk/res-auto\"\n android:id=\"@+id/root_view\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:background=\"#ffffff\">\n <ImageView\n android:id=\"@+id/emoji_btn\"\n android:layout_width=\"40dp\"\n android:layout_height=\"40dp\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignParentLeft=\"true\"\n android:padding=\"4dp\" />\n <ImageView\n android:id=\"@+id/submit_btn\"\n android:layout_width=\"40dp\"\n android:layout_height=\"40dp\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignParentRight=\"true\"\n android:padding=\"4dp\"\n android:src=\"@android:drawable/ic_menu_send\" />\n <hani.momanii.supernova_emoji_library.Helper.EmojiconEditText\n android:id=\"@+id/emojicon_edit_text\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_toLeftOf=\"@id/submit_btn\"\n android:layout_toRightOf=\"@id/emoji_btn\"\n android:imeOptions=\"actionSend\"\n android:inputType=\"text\"\n emojicon:emojiconSize=\"28sp\"/>\n <hani.momanii.supernova_emoji_library.Helper.EmojiconEditText\n android:id=\"@+id/emojicon_edit_text2\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@id/emojicon_edit_text\"\n android:imeOptions=\"actionSend\"\n android:inputType=\"text\"\n emojicon:emojiconSize=\"28sp\"/>\n <CheckBox\n android:id=\"@+id/use_system_default\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:checked=\"false\"\n android:text=\"Use System Default?\"/>\n <hani.momanii.supernova_emoji_library.Helper.EmojiconTextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\"\n android:layout_marginTop=\"26dp\"\n android:lineSpacingExtra=\"17sp\"\n android:text=\"Hello Emojis !\"\n android:textAppearance=\"@style/TextAppearance.AppCompat.Large\"\n android:textColor=\"#000000\"\n emojicon:emojiconAlignment=\"bottom\"/>\n</RelativeLayout>" }, { "code": null, "e": 3878, "s": 3821, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6251, "s": 3878, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.CheckBox;\nimport android.widget.CompoundButton;\nimport android.widget.ImageView;\nimport hani.momanii.supernova_emoji_library.Actions.EmojIconActions;\nimport hani.momanii.supernova_emoji_library.Helper.EmojiconEditText;\nimport hani.momanii.supernova_emoji_library.Helper.EmojiconTextView;\npublic class MainActivity extends AppCompatActivity {\n CheckBox mCheckBox;\n EmojiconEditText emojiconEditText, emojiconEditText2;\n EmojiconTextView textView;\n ImageView emojiButton;\n ImageView submitButton;\n View rootView;\n EmojIconActions emojIcon;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n rootView = findViewById(R.id.root_view);\n emojiButton = (ImageView) findViewById(R.id.emoji_btn);\n submitButton = (ImageView) findViewById(R.id.submit_btn);\n mCheckBox = (CheckBox)findViewById(R.id.use_system_default);\n emojiconEditText = (EmojiconEditText) findViewById(R.id.emojicon_edit_text);\n emojiconEditText2 = (EmojiconEditText) findViewById(R.id.emojicon_edit_text2);\n textView = (EmojiconTextView) findViewById(R.id.textView);\n emojIcon = new EmojIconActions(this, rootView, emojiconEditText, emojiButton);\n emojIcon.ShowEmojIcon();\n emojIcon.setKeyboardListener(new EmojIconActions.KeyboardListener() {\n @Override\n public void onKeyboardOpen() {\n Log.e(\"Keyboard\", \"open\");\n } \n @Override\n public void onKeyboardClose() {\n Log.e(\"Keyboard\", \"close\");\n }\n });\n mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton compoundButton, boolean b) {\n emojIcon.setUseSystemEmoji(b);\n textView.setUseSystemDefault(b);\n }\n });\n emojIcon.addEmojiconEditTextList(emojiconEditText2);\n submitButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String newText = emojiconEditText.getText().toString();\n textView.setText(newText);\n }\n });\n }\n}" }, { "code": null, "e": 6323, "s": 6251, "text": "Step 4 − In the build.gradle(Project: Sample4) add the following code −" }, { "code": null, "e": 6373, "s": 6323, "text": "repositories {\nmaven { url 'https://jitpack.io' }" }, { "code": null, "e": 6409, "s": 6373, "text": "Step 5 − build.gradle (Module: app)" }, { "code": null, "e": 6470, "s": 6409, "text": "implementation 'com.github.hani-momanii:SuperNova-Emoji:1.1'" }, { "code": null, "e": 6525, "s": 6470, "text": "Step 6 − Add the following code to androidManifest.xml" }, { "code": null, "e": 7195, "s": 6525, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 7542, "s": 7195, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 7583, "s": 7542, "text": "Click here to download the project code." } ]
Playfair Cipher Encryption | by Ruthu S Sanketh | Towards Data Science
IntroductionThe Playfair CipherRules for EncryptionC ImplementationOutputs for Some PlaintextsFurther Reading Introduction The Playfair Cipher Rules for Encryption C Implementation Outputs for Some Plaintexts Further Reading Cryptography is the science or art of secret writing. The fundamental objective of cryptography is to enable 2 people to communicate over an insecure channel in such a way that an opponent cannot understand what is being said. There are 2 main types of cryptography in use - Symmetric key cryptography -when the same key is used for both encryption and decryptionAsymmetric key cryptography -when one key is used for encryption and another for decryption Symmetric key cryptography -when the same key is used for both encryption and decryption Asymmetric key cryptography -when one key is used for encryption and another for decryption There are many other types of ciphers such as monoalphabetic and polyalphabetic, stream and block, etc. This article looks at the Playfair cipher and its application using a C function. The Playfair cipher, invented by Charles Wheatstone, is a polyalphabetic substitution cipher, meaning that one letter can be denoted by different letters in its encryption, depending on the keyword used, which is given to both parties. For example, let us assume that the keyword is ‘Charles’. A 5x5 matrix is drawn, and letters are filled in each cell, starting with the keyword, followed by the letters in the alphabet. I/J are filled in the same cell. All repeating letters are removed, giving us this matrix - Given a plaintext sentence, it is split into digrams, removing all spaces, and padding with the letter x in case of an odd number of letters. Repeating plaintext letters are separated with a filler letter such as x. Given the sentence ‘Meet me at the bridge’, the digrams would be - me et me at th eb ri dg ex Two plaintext letters in the same row of the matrix are each replaced by the letter to the right, with the first element of the row circularly following the last. Two plaintext letters in the same row of the matrix are each replaced by the letter to the right, with the first element of the row circularly following the last. eb would be replaced by sd ng would be replaced by gi/gj 2. Two plaintext letters that fall in the same column of the matrix are replaced by the letters beneath, with the top element of the column circularly following the bottom. dt would be replaced by my ty would be replaced by yr 3. Otherwise, each plaintext letter in a pair is replaced by the letter that lies in its own row and the column occupied by the other plaintext letter. me would be replaced by gd et would be replaced by do Following these rules, the ciphertext becomes ‘gd do gd rq pr sd hm em bv’. This cipher is more secure than simple substitution, but is still susceptible to ciphertext-only attacks by doing statistical frequency counts of pairs of letters, since each pair of letters always gets encrypted in the same fashion. Moreover, short keywords make the Playfair cipher even easier to crack. First we import the required libraries and define a large enough size for allocation of the string to be encrypted. #include <stdio.h>#include <stdlib.h>#include <string.h> #define SIZE 100 Now we write a function to encrypt a plaintext using the Playfair cipher. The string is converted to upper case and all spaces are removed. The plaintext is padded to an even length and alphabet pairs are made unidentical. The 5x5 key square is generated. For this, first a 26 character hashmap is used to store the count of each alphabet in the key string. Using this, each cell in the matrix is populated with the key string alphabets first, and only once by reducing the count in the hashmap. Then the remaining alphabets are populated. Each character in the plaintext is then searched for in the digraph and its position is found. Based on the relative positions of characters in a pair, following the above detailed rules, encryption is performed, and the encrypted pair is returned. // Function to encrypt using the Playfair Ciphervoid PlayfairCrypt(char str[], char keystr[]){ char keyT[5][5], ks, ps; // Key ks = strlen(keystr); // Plaintext ps = strlen(str); // Function to convert the string to uppercase // Can also use the library function toUpper here, but a function was written for better understanding of ascii values. void toUpperCase(char encrypt[], int ps) { int i; for (i = 0; i < ps; i++) { if (encrypt[i] > 96 && encrypt[i] < 123) encrypt[i] -= 32; } } // Function to remove all spaces in a string int removeSpaces(char* plain, int ps) { int i, count = 0; for (i = 0; i < ps; i++) if (plain[i] != ' ') plain[count++] = plain[i]; plain[count] = '\0'; return count; } // Function to generate the 5x5 key square void generateKeyTable(char keystr[], int ks, char keyT[5][5]) { int i, j, k, flag = 0, *dicty; // a 26 character hashmap to store count of the alphabet dicty = (int*)calloc(26, sizeof(int)); for (i = 0; i < ks; i++) { if (keystr[i] != 'j') dicty[keystr[i] - 97] = 2; } dicty['j' - 97] = 1; i = 0; j = 0; for (k = 0; k < ks; k++) { if (dicty[keystr[k] - 97] == 2) { dicty[keystr[k] - 97] -= 1; keyT[i][j] = keystr[k]; j++; if (j == 5) { i++; j = 0; } } } for (k = 0; k < 26; k++) { if (dicty[k] == 0) { keyT[i][j] = (char)(k + 97); j++; if (j == 5) { i++; j = 0; } } } } // Function to search for the characters of a digraph in the key square and return their position void search(char keyT[5][5], char a, char b, int arr[]) { int i, j; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (keyT[i][j] == a) { arr[0] = i; arr[1] = j; } else if (keyT[i][j] == b) { arr[2] = i; arr[3] = j; } } } } // Function to make the plain text length even, and make pairs unidentical. int prepare(char str[], int ptrs) { int i, j, subs_s = ptrs; for (i = 0; i < subs_s; i += 2) { if(str[i]==str[i+1]){ for(j=subs_s; j>i+1; j--){ str[j]=str[j-1]; } str[i+1]='x'; subs_s+=1; } } str[subs_s]='\0'; if (subs_s % 2 != 0) { str[subs_s++] = 'z'; str[subs_s] = '\0'; } return subs_s; } // Function for performing the encryption void encrypt(char str[], char keyT[5][5], int ps) { int i, a[4]; for(i=0; i<ps; i+=2){ search(keyT, str[i], str[i + 1], a); if (a[0] == a[2]) { str[i] = keyT[a[0]][(a[1] + 1)%5]; str[i + 1] = keyT[a[0]][(a[3] + 1)%5]; } else if (a[1] == a[3]) { str[i] = keyT[(a[0] + 1)%5][a[1]]; str[i + 1] = keyT[(a[2] + 1)%5][a[1]]; } else { str[i] = keyT[a[0]][a[3]]; str[i + 1] = keyT[a[2]][a[1]]; } } } ks = removeSpaces(keystr, ks); ps = removeSpaces(str, ps); ps = prepare(str, ps); generateKeyTable(keystr, ks, keyT); encrypt(str, keyT, ps); toUpperCase(str, ps); //cipher text - printed in upper case letters printf("Cipher text: %s\n", str);} The driver code just takes the input key string and input plaintext, and calls the PlayfairCrypt function which outputs the encrypted string. // Driver codeint main(){ char str[SIZE], keystr[SIZE]; //Key used - to be entered in lower case letters printf("Enter the key: "); scanf("%[^\n]s", &keystr); printf("Key text: %s\n", keystr); // Plaintext to be encrypted - entered in lower case letters printf("Enter the plaintext: "); scanf("\n"); scanf("%[^\n]s", &str); printf("Plain text: %s\n", str); //Calling the PlayfairCrypt function PlayfairCrypt(str, keystr); return 0;} The above code is compiled, run and tested for some plaintexts using a key string ‘diskjockey’. The shipment will arrive at noonLay low until FridayAlways use the back doorThe phone is bugged The shipment will arrive at noon Lay low until Friday Always use the back door The phone is bugged The entire code used and explained in this article can be found here. Project -Implementation of the Encoding and Decoding of the Playfair CipherErin Baldwin -An Essay on the Playfair CipherPal, Ramani, Iyengar, Sunitha. A Variation in the Working of the Playfair CipherPlayfair Cipher Decryption Project -Implementation of the Encoding and Decoding of the Playfair Cipher Erin Baldwin -An Essay on the Playfair Cipher Pal, Ramani, Iyengar, Sunitha. A Variation in the Working of the Playfair Cipher Playfair Cipher Decryption
[ { "code": null, "e": 157, "s": 47, "text": "IntroductionThe Playfair CipherRules for EncryptionC ImplementationOutputs for Some PlaintextsFurther Reading" }, { "code": null, "e": 170, "s": 157, "text": "Introduction" }, { "code": null, "e": 190, "s": 170, "text": "The Playfair Cipher" }, { "code": null, "e": 211, "s": 190, "text": "Rules for Encryption" }, { "code": null, "e": 228, "s": 211, "text": "C Implementation" }, { "code": null, "e": 256, "s": 228, "text": "Outputs for Some Plaintexts" }, { "code": null, "e": 272, "s": 256, "text": "Further Reading" }, { "code": null, "e": 547, "s": 272, "text": "Cryptography is the science or art of secret writing. The fundamental objective of cryptography is to enable 2 people to communicate over an insecure channel in such a way that an opponent cannot understand what is being said. There are 2 main types of cryptography in use -" }, { "code": null, "e": 727, "s": 547, "text": "Symmetric key cryptography -when the same key is used for both encryption and decryptionAsymmetric key cryptography -when one key is used for encryption and another for decryption" }, { "code": null, "e": 816, "s": 727, "text": "Symmetric key cryptography -when the same key is used for both encryption and decryption" }, { "code": null, "e": 908, "s": 816, "text": "Asymmetric key cryptography -when one key is used for encryption and another for decryption" }, { "code": null, "e": 1094, "s": 908, "text": "There are many other types of ciphers such as monoalphabetic and polyalphabetic, stream and block, etc. This article looks at the Playfair cipher and its application using a C function." }, { "code": null, "e": 1608, "s": 1094, "text": "The Playfair cipher, invented by Charles Wheatstone, is a polyalphabetic substitution cipher, meaning that one letter can be denoted by different letters in its encryption, depending on the keyword used, which is given to both parties. For example, let us assume that the keyword is ‘Charles’. A 5x5 matrix is drawn, and letters are filled in each cell, starting with the keyword, followed by the letters in the alphabet. I/J are filled in the same cell. All repeating letters are removed, giving us this matrix -" }, { "code": null, "e": 1891, "s": 1608, "text": "Given a plaintext sentence, it is split into digrams, removing all spaces, and padding with the letter x in case of an odd number of letters. Repeating plaintext letters are separated with a filler letter such as x. Given the sentence ‘Meet me at the bridge’, the digrams would be -" }, { "code": null, "e": 1918, "s": 1891, "text": "me et me at th eb ri dg ex" }, { "code": null, "e": 2081, "s": 1918, "text": "Two plaintext letters in the same row of the matrix are each replaced by the letter to the right, with the first element of the row circularly following the last." }, { "code": null, "e": 2244, "s": 2081, "text": "Two plaintext letters in the same row of the matrix are each replaced by the letter to the right, with the first element of the row circularly following the last." }, { "code": null, "e": 2271, "s": 2244, "text": "eb would be replaced by sd" }, { "code": null, "e": 2301, "s": 2271, "text": "ng would be replaced by gi/gj" }, { "code": null, "e": 2474, "s": 2301, "text": "2. Two plaintext letters that fall in the same column of the matrix are replaced by the letters beneath, with the top element of the column circularly following the bottom." }, { "code": null, "e": 2501, "s": 2474, "text": "dt would be replaced by my" }, { "code": null, "e": 2528, "s": 2501, "text": "ty would be replaced by yr" }, { "code": null, "e": 2680, "s": 2528, "text": "3. Otherwise, each plaintext letter in a pair is replaced by the letter that lies in its own row and the column occupied by the other plaintext letter." }, { "code": null, "e": 2707, "s": 2680, "text": "me would be replaced by gd" }, { "code": null, "e": 2734, "s": 2707, "text": "et would be replaced by do" }, { "code": null, "e": 2810, "s": 2734, "text": "Following these rules, the ciphertext becomes ‘gd do gd rq pr sd hm em bv’." }, { "code": null, "e": 3116, "s": 2810, "text": "This cipher is more secure than simple substitution, but is still susceptible to ciphertext-only attacks by doing statistical frequency counts of pairs of letters, since each pair of letters always gets encrypted in the same fashion. Moreover, short keywords make the Playfair cipher even easier to crack." }, { "code": null, "e": 3232, "s": 3116, "text": "First we import the required libraries and define a large enough size for allocation of the string to be encrypted." }, { "code": null, "e": 3306, "s": 3232, "text": "#include <stdio.h>#include <stdlib.h>#include <string.h> #define SIZE 100" }, { "code": null, "e": 3846, "s": 3306, "text": "Now we write a function to encrypt a plaintext using the Playfair cipher. The string is converted to upper case and all spaces are removed. The plaintext is padded to an even length and alphabet pairs are made unidentical. The 5x5 key square is generated. For this, first a 26 character hashmap is used to store the count of each alphabet in the key string. Using this, each cell in the matrix is populated with the key string alphabets first, and only once by reducing the count in the hashmap. Then the remaining alphabets are populated." }, { "code": null, "e": 4095, "s": 3846, "text": "Each character in the plaintext is then searched for in the digraph and its position is found. Based on the relative positions of characters in a pair, following the above detailed rules, encryption is performed, and the encrypted pair is returned." }, { "code": null, "e": 7987, "s": 4095, "text": "// Function to encrypt using the Playfair Ciphervoid PlayfairCrypt(char str[], char keystr[]){ char keyT[5][5], ks, ps; // Key ks = strlen(keystr); // Plaintext ps = strlen(str); // Function to convert the string to uppercase // Can also use the library function toUpper here, but a function was written for better understanding of ascii values. void toUpperCase(char encrypt[], int ps) { int i; for (i = 0; i < ps; i++) { if (encrypt[i] > 96 && encrypt[i] < 123) encrypt[i] -= 32; } } // Function to remove all spaces in a string int removeSpaces(char* plain, int ps) { int i, count = 0; for (i = 0; i < ps; i++) if (plain[i] != ' ') plain[count++] = plain[i]; plain[count] = '\\0'; return count; } // Function to generate the 5x5 key square void generateKeyTable(char keystr[], int ks, char keyT[5][5]) { int i, j, k, flag = 0, *dicty; // a 26 character hashmap to store count of the alphabet dicty = (int*)calloc(26, sizeof(int)); for (i = 0; i < ks; i++) { if (keystr[i] != 'j') dicty[keystr[i] - 97] = 2; } dicty['j' - 97] = 1; i = 0; j = 0; for (k = 0; k < ks; k++) { if (dicty[keystr[k] - 97] == 2) { dicty[keystr[k] - 97] -= 1; keyT[i][j] = keystr[k]; j++; if (j == 5) { i++; j = 0; } } } for (k = 0; k < 26; k++) { if (dicty[k] == 0) { keyT[i][j] = (char)(k + 97); j++; if (j == 5) { i++; j = 0; } } } } // Function to search for the characters of a digraph in the key square and return their position void search(char keyT[5][5], char a, char b, int arr[]) { int i, j; if (a == 'j') a = 'i'; else if (b == 'j') b = 'i'; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { if (keyT[i][j] == a) { arr[0] = i; arr[1] = j; } else if (keyT[i][j] == b) { arr[2] = i; arr[3] = j; } } } } // Function to make the plain text length even, and make pairs unidentical. int prepare(char str[], int ptrs) { int i, j, subs_s = ptrs; for (i = 0; i < subs_s; i += 2) { if(str[i]==str[i+1]){ for(j=subs_s; j>i+1; j--){ str[j]=str[j-1]; } str[i+1]='x'; subs_s+=1; } } str[subs_s]='\\0'; if (subs_s % 2 != 0) { str[subs_s++] = 'z'; str[subs_s] = '\\0'; } return subs_s; } // Function for performing the encryption void encrypt(char str[], char keyT[5][5], int ps) { int i, a[4]; for(i=0; i<ps; i+=2){ search(keyT, str[i], str[i + 1], a); if (a[0] == a[2]) { str[i] = keyT[a[0]][(a[1] + 1)%5]; str[i + 1] = keyT[a[0]][(a[3] + 1)%5]; } else if (a[1] == a[3]) { str[i] = keyT[(a[0] + 1)%5][a[1]]; str[i + 1] = keyT[(a[2] + 1)%5][a[1]]; } else { str[i] = keyT[a[0]][a[3]]; str[i + 1] = keyT[a[2]][a[1]]; } } } ks = removeSpaces(keystr, ks); ps = removeSpaces(str, ps); ps = prepare(str, ps); generateKeyTable(keystr, ks, keyT); encrypt(str, keyT, ps); toUpperCase(str, ps); //cipher text - printed in upper case letters printf(\"Cipher text: %s\\n\", str);}" }, { "code": null, "e": 8129, "s": 7987, "text": "The driver code just takes the input key string and input plaintext, and calls the PlayfairCrypt function which outputs the encrypted string." }, { "code": null, "e": 8601, "s": 8129, "text": "// Driver codeint main(){ char str[SIZE], keystr[SIZE]; //Key used - to be entered in lower case letters printf(\"Enter the key: \"); scanf(\"%[^\\n]s\", &keystr); printf(\"Key text: %s\\n\", keystr); // Plaintext to be encrypted - entered in lower case letters printf(\"Enter the plaintext: \"); scanf(\"\\n\"); scanf(\"%[^\\n]s\", &str); printf(\"Plain text: %s\\n\", str); //Calling the PlayfairCrypt function PlayfairCrypt(str, keystr); return 0;}" }, { "code": null, "e": 8697, "s": 8601, "text": "The above code is compiled, run and tested for some plaintexts using a key string ‘diskjockey’." }, { "code": null, "e": 8793, "s": 8697, "text": "The shipment will arrive at noonLay low until FridayAlways use the back doorThe phone is bugged" }, { "code": null, "e": 8826, "s": 8793, "text": "The shipment will arrive at noon" }, { "code": null, "e": 8847, "s": 8826, "text": "Lay low until Friday" }, { "code": null, "e": 8872, "s": 8847, "text": "Always use the back door" }, { "code": null, "e": 8892, "s": 8872, "text": "The phone is bugged" }, { "code": null, "e": 8962, "s": 8892, "text": "The entire code used and explained in this article can be found here." }, { "code": null, "e": 9189, "s": 8962, "text": "Project -Implementation of the Encoding and Decoding of the Playfair CipherErin Baldwin -An Essay on the Playfair CipherPal, Ramani, Iyengar, Sunitha. A Variation in the Working of the Playfair CipherPlayfair Cipher Decryption" }, { "code": null, "e": 9265, "s": 9189, "text": "Project -Implementation of the Encoding and Decoding of the Playfair Cipher" }, { "code": null, "e": 9311, "s": 9265, "text": "Erin Baldwin -An Essay on the Playfair Cipher" }, { "code": null, "e": 9392, "s": 9311, "text": "Pal, Ramani, Iyengar, Sunitha. A Variation in the Working of the Playfair Cipher" } ]
Practical Data Analysis Guide with Pandas: Direct Marketing | by Soner Yıldırım | Towards Data Science
Pandas provides numerous functions and methods for data analysis and manipulation. In this post, we will use Pandas to gain insight into a direct marketing dataset. The dataset is available on Kaggle. It contains relevant data of a marketing campaign done via direct mail. We will explore this dataset and try to understand which customers are likely to spend more money. Let’s start by reading the dataset into a dataframe. import numpy as npimport pandas as pddf = pd.read_csv("/content/DirectMarketing.csv")print(df.shape)df.head() The data consists of 1000 observations (i.e. rows) and 10 features (i.e. columns). The focus is the “AmountSpent” column which indicates how much a customer has spent so far. Before we start on the analysis, it is best to make sure there are no missing values. df.isna().sum()Age 0Gender 0OwnHome 0Married 0Location 0Salary 0Children 0History 303Catalogs 0AmountSpent 0dtype: int64 The “History” column contains 303 missing values. These are used to indicate a customer has not made purchase yet. We can check the other values in the column and then decide how to handle the missing values. df.History.value_counts()High 255Low 230Medium 212Name: History, dtype: int64 Since it is a categorical column, we can replace the missing values with the word “Nothing” that indicates no purchase has been made yet. df.History.fillna("Nothing", inplace=True)df.isna().sum().sum()0 We start with checking the statistics of the “AmountSpent” column. print(f'The average money spent is {df.AmountSpent.mean()}. The median is {df.AmountSpent.median()}')The average money spent is 1216.77. The median is 962.0 The mean is much higher than the median which shows that this column does not have a normal distribution. There are outliers with high values. Thus, we expect the “AmountSpent” column to have a right skewed distribution. Let’s check it with a histogram. df['AmountSpent'].plot(kind='hist', figsize=(10,6)) It overlaps with the statistics. Most observations are in the low section with a small number of outliers reaching toward the higher end. Age might be an important feature because direct mail marketing tends to appeal older people. The groupby function will give us an overview. df[['Age','AmountSpent']].groupby('Age').mean() The average amount of money spent is much higher for middle and old aged people than for young people. I also want to see if the campaign is more focused on older people. We can check the number of catalogs sent to each group along with average money spent. df[['Age','Catalogs','AmountSpent']].groupby('Age').agg(['mean','count']) The count shows the number of observations in a group. We see that more middle aged people are involved in the campaign. The average number of catalogs sent to young customers are a little less than that of older customers. As you notice, we can apply multiple aggregations on the group values by passing a list to the aggregate function. Before calculating the correlations, I will briefly explain what correlation means with regards to variables. Correlation is a normalization of covariance by the standard deviation of each variable. Covariance is a quantitative measure that represents how much the variations of two variables match each other. In simpler terms, correlation and covariance indicate if the values tend to change in similar ways. The normalization of covariance cancels out the units. Thus, the correlation value is always between 0 and 1 in case of positive correlation and 0 and -1 in case of negative correlation. To calculate the correlations between numerical variables, we will use the corr function of pandas and visualize the results with a heat map. #importing visualization librariesimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlineplt.figure(figsize=(10,6))corr = df.corr()sns.heatmap(corr, annot=True) There is a highly strong correlation between the salary and spent amount. The number of catalogs also has a positive correlation with spent amount. On the other hand, number of children and spent amount have a small negative correlation. The correlation matrix shows a negative correlation between the number of children and spent amount. Thus, we expect to see a decreasing spent amount as the number of children increases. Let’s also check it with the groupby function. I will also include the age column. The groupby function accepts multiple columns and creates a group for each set of categories. df[['Age','Children','AmountSpent']]\.groupby(['Age','Children']).agg(['mean','count']) In general, the average money spent decreases as the number of children increases. There are a few exceptions though. We will check a couple of measures with the gender and marriage columns. The groupby function allows applying different aggregate functions to different columns. Furthermore, we can rename the columns of aggregations. It will be more clear with the example. I want to create groups based on gender and marriage columns. Then I will calculate: The average number of catalogs sent to each group (mean) The total amount of purchases made by each group (sum) I also want to rename the columns appropriately. Here is the groupby syntax that does this operation: df[['Gender','Married','AmountSpent','Catalogs']]\.groupby(['Gender','Married'])\.agg( Average_number_of_catalogs = pd.NamedAgg('Catalogs','mean'), Total_purchase_amount = pd.NamedAgg('AmountSpent','sum')) The NamedAgg method is used to rename the columns. Another way to change the column names is the rename function of Pandas. This retailer should definitely focus on married people. The location might also be an important indicator. Let’s check the “AmountSpent” column based on the location. df[['Location','AmountSpent']].groupby('Location')\.agg(['mean','count','sum']) The number of customers who live close by is more than double the customers that are far. However, they spend more on average than the customers who live close by. The retailer might want to focus a little more on people who live far. We can dig more into the dataset and try to gain more insight. We haven’t check some of the features yet. However, the techniques are quite similar. The main purpose of this post is to introduce different techniques and methods to use in data exploration. There are, of course, more functions and methods that Pandas provides. The best way to learn and master them is to practice a lot. I suggest to work on sample data sets and try to explore them. There are free resources that you can find sample data sets. For instance, Jeff Hale lists 10 great places to find datasets in this article. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 337, "s": 172, "text": "Pandas provides numerous functions and methods for data analysis and manipulation. In this post, we will use Pandas to gain insight into a direct marketing dataset." }, { "code": null, "e": 544, "s": 337, "text": "The dataset is available on Kaggle. It contains relevant data of a marketing campaign done via direct mail. We will explore this dataset and try to understand which customers are likely to spend more money." }, { "code": null, "e": 597, "s": 544, "text": "Let’s start by reading the dataset into a dataframe." }, { "code": null, "e": 707, "s": 597, "text": "import numpy as npimport pandas as pddf = pd.read_csv(\"/content/DirectMarketing.csv\")print(df.shape)df.head()" }, { "code": null, "e": 882, "s": 707, "text": "The data consists of 1000 observations (i.e. rows) and 10 features (i.e. columns). The focus is the “AmountSpent” column which indicates how much a customer has spent so far." }, { "code": null, "e": 968, "s": 882, "text": "Before we start on the analysis, it is best to make sure there are no missing values." }, { "code": null, "e": 1176, "s": 968, "text": "df.isna().sum()Age 0Gender 0OwnHome 0Married 0Location 0Salary 0Children 0History 303Catalogs 0AmountSpent 0dtype: int64" }, { "code": null, "e": 1385, "s": 1176, "text": "The “History” column contains 303 missing values. These are used to indicate a customer has not made purchase yet. We can check the other values in the column and then decide how to handle the missing values." }, { "code": null, "e": 1477, "s": 1385, "text": "df.History.value_counts()High 255Low 230Medium 212Name: History, dtype: int64" }, { "code": null, "e": 1615, "s": 1477, "text": "Since it is a categorical column, we can replace the missing values with the word “Nothing” that indicates no purchase has been made yet." }, { "code": null, "e": 1680, "s": 1615, "text": "df.History.fillna(\"Nothing\", inplace=True)df.isna().sum().sum()0" }, { "code": null, "e": 1747, "s": 1680, "text": "We start with checking the statistics of the “AmountSpent” column." }, { "code": null, "e": 1904, "s": 1747, "text": "print(f'The average money spent is {df.AmountSpent.mean()}. The median is {df.AmountSpent.median()}')The average money spent is 1216.77. The median is 962.0" }, { "code": null, "e": 2125, "s": 1904, "text": "The mean is much higher than the median which shows that this column does not have a normal distribution. There are outliers with high values. Thus, we expect the “AmountSpent” column to have a right skewed distribution." }, { "code": null, "e": 2158, "s": 2125, "text": "Let’s check it with a histogram." }, { "code": null, "e": 2210, "s": 2158, "text": "df['AmountSpent'].plot(kind='hist', figsize=(10,6))" }, { "code": null, "e": 2348, "s": 2210, "text": "It overlaps with the statistics. Most observations are in the low section with a small number of outliers reaching toward the higher end." }, { "code": null, "e": 2489, "s": 2348, "text": "Age might be an important feature because direct mail marketing tends to appeal older people. The groupby function will give us an overview." }, { "code": null, "e": 2537, "s": 2489, "text": "df[['Age','AmountSpent']].groupby('Age').mean()" }, { "code": null, "e": 2640, "s": 2537, "text": "The average amount of money spent is much higher for middle and old aged people than for young people." }, { "code": null, "e": 2795, "s": 2640, "text": "I also want to see if the campaign is more focused on older people. We can check the number of catalogs sent to each group along with average money spent." }, { "code": null, "e": 2869, "s": 2795, "text": "df[['Age','Catalogs','AmountSpent']].groupby('Age').agg(['mean','count'])" }, { "code": null, "e": 3093, "s": 2869, "text": "The count shows the number of observations in a group. We see that more middle aged people are involved in the campaign. The average number of catalogs sent to young customers are a little less than that of older customers." }, { "code": null, "e": 3208, "s": 3093, "text": "As you notice, we can apply multiple aggregations on the group values by passing a list to the aggregate function." }, { "code": null, "e": 3318, "s": 3208, "text": "Before calculating the correlations, I will briefly explain what correlation means with regards to variables." }, { "code": null, "e": 3619, "s": 3318, "text": "Correlation is a normalization of covariance by the standard deviation of each variable. Covariance is a quantitative measure that represents how much the variations of two variables match each other. In simpler terms, correlation and covariance indicate if the values tend to change in similar ways." }, { "code": null, "e": 3806, "s": 3619, "text": "The normalization of covariance cancels out the units. Thus, the correlation value is always between 0 and 1 in case of positive correlation and 0 and -1 in case of negative correlation." }, { "code": null, "e": 3948, "s": 3806, "text": "To calculate the correlations between numerical variables, we will use the corr function of pandas and visualize the results with a heat map." }, { "code": null, "e": 4124, "s": 3948, "text": "#importing visualization librariesimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlineplt.figure(figsize=(10,6))corr = df.corr()sns.heatmap(corr, annot=True)" }, { "code": null, "e": 4272, "s": 4124, "text": "There is a highly strong correlation between the salary and spent amount. The number of catalogs also has a positive correlation with spent amount." }, { "code": null, "e": 4362, "s": 4272, "text": "On the other hand, number of children and spent amount have a small negative correlation." }, { "code": null, "e": 4549, "s": 4362, "text": "The correlation matrix shows a negative correlation between the number of children and spent amount. Thus, we expect to see a decreasing spent amount as the number of children increases." }, { "code": null, "e": 4726, "s": 4549, "text": "Let’s also check it with the groupby function. I will also include the age column. The groupby function accepts multiple columns and creates a group for each set of categories." }, { "code": null, "e": 4814, "s": 4726, "text": "df[['Age','Children','AmountSpent']]\\.groupby(['Age','Children']).agg(['mean','count'])" }, { "code": null, "e": 4932, "s": 4814, "text": "In general, the average money spent decreases as the number of children increases. There are a few exceptions though." }, { "code": null, "e": 5150, "s": 4932, "text": "We will check a couple of measures with the gender and marriage columns. The groupby function allows applying different aggregate functions to different columns. Furthermore, we can rename the columns of aggregations." }, { "code": null, "e": 5275, "s": 5150, "text": "It will be more clear with the example. I want to create groups based on gender and marriage columns. Then I will calculate:" }, { "code": null, "e": 5332, "s": 5275, "text": "The average number of catalogs sent to each group (mean)" }, { "code": null, "e": 5387, "s": 5332, "text": "The total amount of purchases made by each group (sum)" }, { "code": null, "e": 5489, "s": 5387, "text": "I also want to rename the columns appropriately. Here is the groupby syntax that does this operation:" }, { "code": null, "e": 5701, "s": 5489, "text": "df[['Gender','Married','AmountSpent','Catalogs']]\\.groupby(['Gender','Married'])\\.agg( Average_number_of_catalogs = pd.NamedAgg('Catalogs','mean'), Total_purchase_amount = pd.NamedAgg('AmountSpent','sum'))" }, { "code": null, "e": 5825, "s": 5701, "text": "The NamedAgg method is used to rename the columns. Another way to change the column names is the rename function of Pandas." }, { "code": null, "e": 5882, "s": 5825, "text": "This retailer should definitely focus on married people." }, { "code": null, "e": 5993, "s": 5882, "text": "The location might also be an important indicator. Let’s check the “AmountSpent” column based on the location." }, { "code": null, "e": 6073, "s": 5993, "text": "df[['Location','AmountSpent']].groupby('Location')\\.agg(['mean','count','sum'])" }, { "code": null, "e": 6237, "s": 6073, "text": "The number of customers who live close by is more than double the customers that are far. However, they spend more on average than the customers who live close by." }, { "code": null, "e": 6308, "s": 6237, "text": "The retailer might want to focus a little more on people who live far." }, { "code": null, "e": 6457, "s": 6308, "text": "We can dig more into the dataset and try to gain more insight. We haven’t check some of the features yet. However, the techniques are quite similar." }, { "code": null, "e": 6695, "s": 6457, "text": "The main purpose of this post is to introduce different techniques and methods to use in data exploration. There are, of course, more functions and methods that Pandas provides. The best way to learn and master them is to practice a lot." }, { "code": null, "e": 6899, "s": 6695, "text": "I suggest to work on sample data sets and try to explore them. There are free resources that you can find sample data sets. For instance, Jeff Hale lists 10 great places to find datasets in this article." } ]
Black and White | Practice | GeeksforGeeks
Given the chessboard dimensions. Find out the number of ways we can place a black and a white Knight on this chessboard such that they cannot attack each other. Note: The knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically (L shaped), or two squares vertically and one square horizontally (L shaped). The knights attack each other if one can reach the other in one move. Example 1: Input: N = 2, M = 2 Output: 12 Example 2: Input: N = 2, M = 3 Output: 26 Your Task: Your task is to complete the function numOfWays() which takes the chessboard dimensions N and M as inputs and returns the number of ways we can place 2 Knights on this chessboard such that they cannot attack each other. Since this number can be very large, return it modulo 109+7. Expected Time Complexity: O(N*M). Expected Auxiliary Space: O(1). Constraints: 1 <= N * M <= 105 0 debajyoti dev1 month ago What Rubbish nowhere mentioned what M and N ! 0 vinamrajha2 months ago bool issafe(int i, int j, int N, int M){ return(i>=0 && i<N && j>=0 && j<M);}long long numOfWays(int N, int M){ // write code here long long d = 1e9+7; long long count =0; int dx[8] = {1,-1,1,-1,2,2,-2,-2}; // all moves of knight int dy[8] = {2,2,-2,-2,1,-1,1,-1}; for(int i =0; i<N; ++i){ for(int j =0; j<M; ++j){ for(int k =0; k<8; k++){ int xdx = i + dx[k]; int ydy = j + dy[k]; if(issafe(xdx, ydy, N, M)) count--; } count +=(N*M - 1); // remaining pos where we can put other knight. count %= d; // prompt by the Q. } } return count;} +1 parikhsharan62 months ago class BlackAndWhite{ static final long MOD = (long)Math.pow(10, 9) + 7; //Function to find out the number of ways we can place a black and a //white Knight on this chessboard such that they cannot attack each other. static long numOfWays(int N, int M) { int[][] moves = new int[][]{ {-1, 2}, {1, 2}, {-1, -2}, {1, -2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1} }; long answer = 0; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { long count = 0; for(int k = 0; k < moves.length; k++) { if(isAttackPossible(N, M, i + moves[k][0], j + moves[k][1])) { count++; } } count++; answer = (answer % MOD) + ((M*N) % MOD - (count % MOD)) % MOD; } } return answer; } static boolean isAttackPossible(int N, int M, int i, int j) { if(i < 0 || j < 0 || i >= N || j >= M) { return false; } return true; }} 0 amanpandey30072 months ago long long numOfWays(int N, int M){ long long ans=0; long long count=0; long long mod=1e9+7; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { count=0; if(i+2<N and j+1<M) count++; if(i+2<N and j-1>=0) count++; if(i-2>=0 and j+1<M) count++; if(i-2>=0 and j-1>=0) count++; if(i+1<N and j+2<M) count++; if(i+1<N and j-2>=0) count++; if(i-1>=0 and j+2<M) count++; if(i-1>=0 and j-2>=0) count++; count++; // obivously cannot place the two Knight at same place ans=ans%mod+(((N%mod)*(M%mod))%mod-count)%mod; } } return ans;} 0 jayeshkhurana6853 months ago Why is everyone taking modulus? 0 lindan1233 months ago int mod =1000000007; long long numOfWays(int n, int m) { long long count=0; long long res=0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { count=0; if(i-1>=0 && j-2>=0) { count++; } if(i+1<n && j-2>=0) { count++; } if(j+2<m && i+1<n) { count++; } if(j+2<m && i-1>=0) { count++; } if(i-2>=0 && j-1>=0) { count++; } if(i-2>=0 && j+1<m) { count++; } if(i+2<n && j-1>=0) { count++; } if(i+2<n && j+1<m) { count++; } count++; res = res%mod + (((n%mod)*(m%mod))%mod- count)%mod; } } return res; } Time Taken : 0.0 Cpp 0 anjalipatel94313 months ago int count(int i,int j,int N,int M){ int countt=0; if(i+2<N && j+1<M ){ countt++; } if(i+2<N && j-1>=0){ //down countt++; } if(i-2>=0 && j+1<M ){ //up countt++; } if(i-2>=0 && j-1>=0){ countt++; } if(i+1<N && j+2<M ){ //right countt++; } if(i-1>=0&& j+2<M ){ countt++; } if(i+1<N && j-2>=0){ //left countt++; } if(i-1>=0 && j-2>=0){ countt++; } return (N*M)-countt-1;}long long numOfWays(int N, int M){ // write code here int mod=1e9+7; int sum=0; for(int i=0;i<N;i++) for(int j=0;j<M;j++){ sum+=count(i,j,N,M); sum%=mod; } return sum;} 0 ayushnautiyal11104 months ago C++ IMPLEMENTATION:) Time Taken 0.6/1.3 😎😎😎😎 vector<pair<int,int>>v={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};const long long mod=1e9+7;bool isSafe(int i,int j,int N,int M){ return (i<N && j<M && i>=0 && j>=0);}long long numOfWays(int N, int M){ long long res=0; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ int a=i; int b=j; for(auto x:v){ int dx=a+x.first; int dy=b+x.second; if(isSafe(dx,dy,N,M)==true){ res--; } } res+=N*M-1; res%=mod; } } return res;} +1 anutiger6 months ago long long numOfWays(int N, int M) { int mod = 1e9 + 7; long long res = 0; int dx[] = {1,1,-1,-1,2,2,-2,-2}; int dy[] = {2,-2,2,-2,1,-1,1,-1}; for(int i = 0; i < N ; i ++){ for(int j = 0; j < M ; j++){ int x = i; int y = j; for(int k = 0 ; k < 8 ; k ++){ int x1 = x + dx[k]; int y1 = y + dy[k]; if(x1 >= 0 and x1 < N and y1 >= 0 and y1 < M){ res--; } } res += N * M - 1; res %= mod; } } return res; } +9 sachin shet6 months ago I wonder why this is placed in backtracking section. This should be in Matrix Section. We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 387, "s": 226, "text": "Given the chessboard dimensions. Find out the number of ways we can place a black and a white Knight on this chessboard such that they cannot attack each other." }, { "code": null, "e": 662, "s": 387, "text": "Note:\nThe knights have to be placed on different squares. A knight can move two squares horizontally and one square vertically (L shaped), or two squares vertically and one square horizontally (L shaped). The knights attack each other if one can reach the other in one move." }, { "code": null, "e": 673, "s": 662, "text": "Example 1:" }, { "code": null, "e": 706, "s": 673, "text": "Input:\nN = 2, M = 2\nOutput: 12 \n" }, { "code": null, "e": 717, "s": 706, "text": "Example 2:" }, { "code": null, "e": 748, "s": 717, "text": "Input:\nN = 2, M = 3\nOutput: 26" }, { "code": null, "e": 1040, "s": 748, "text": "Your Task:\nYour task is to complete the function numOfWays() which takes the chessboard dimensions N and M as inputs and returns the number of ways we can place 2 Knights on this chessboard such that they cannot attack each other. Since this number can be very large, return it modulo 109+7." }, { "code": null, "e": 1106, "s": 1040, "text": "Expected Time Complexity: O(N*M).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1137, "s": 1106, "text": "Constraints:\n1 <= N * M <= 105" }, { "code": null, "e": 1139, "s": 1137, "text": "0" }, { "code": null, "e": 1164, "s": 1139, "text": "debajyoti dev1 month ago" }, { "code": null, "e": 1210, "s": 1164, "text": "What Rubbish nowhere mentioned what M and N !" }, { "code": null, "e": 1214, "s": 1212, "text": "0" }, { "code": null, "e": 1237, "s": 1214, "text": "vinamrajha2 months ago" }, { "code": null, "e": 1946, "s": 1237, "text": "bool issafe(int i, int j, int N, int M){ return(i>=0 && i<N && j>=0 && j<M);}long long numOfWays(int N, int M){ // write code here long long d = 1e9+7; long long count =0; int dx[8] = {1,-1,1,-1,2,2,-2,-2}; // all moves of knight int dy[8] = {2,2,-2,-2,1,-1,1,-1}; for(int i =0; i<N; ++i){ for(int j =0; j<M; ++j){ for(int k =0; k<8; k++){ int xdx = i + dx[k]; int ydy = j + dy[k]; if(issafe(xdx, ydy, N, M)) count--; } count +=(N*M - 1); // remaining pos where we can put other knight. count %= d; // prompt by the Q. } } return count;}" }, { "code": null, "e": 1949, "s": 1946, "text": "+1" }, { "code": null, "e": 1975, "s": 1949, "text": "parikhsharan62 months ago" }, { "code": null, "e": 3126, "s": 1975, "text": "class BlackAndWhite{ static final long MOD = (long)Math.pow(10, 9) + 7; //Function to find out the number of ways we can place a black and a //white Knight on this chessboard such that they cannot attack each other. static long numOfWays(int N, int M) { int[][] moves = new int[][]{ {-1, 2}, {1, 2}, {-1, -2}, {1, -2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1} }; long answer = 0; for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { long count = 0; for(int k = 0; k < moves.length; k++) { if(isAttackPossible(N, M, i + moves[k][0], j + moves[k][1])) { count++; } } count++; answer = (answer % MOD) + ((M*N) % MOD - (count % MOD)) % MOD; } } return answer; } static boolean isAttackPossible(int N, int M, int i, int j) { if(i < 0 || j < 0 || i >= N || j >= M) { return false; } return true; }}" }, { "code": null, "e": 3128, "s": 3126, "text": "0" }, { "code": null, "e": 3155, "s": 3128, "text": "amanpandey30072 months ago" }, { "code": null, "e": 4047, "s": 3155, "text": "long long numOfWays(int N, int M){ long long ans=0; long long count=0; long long mod=1e9+7; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { count=0; if(i+2<N and j+1<M) count++; if(i+2<N and j-1>=0) count++; if(i-2>=0 and j+1<M) count++; if(i-2>=0 and j-1>=0) count++; if(i+1<N and j+2<M) count++; if(i+1<N and j-2>=0) count++; if(i-1>=0 and j+2<M) count++; if(i-1>=0 and j-2>=0) count++; count++; // obivously cannot place the two Knight at same place ans=ans%mod+(((N%mod)*(M%mod))%mod-count)%mod; } } return ans;}" }, { "code": null, "e": 4049, "s": 4047, "text": "0" }, { "code": null, "e": 4078, "s": 4049, "text": "jayeshkhurana6853 months ago" }, { "code": null, "e": 4110, "s": 4078, "text": "Why is everyone taking modulus?" }, { "code": null, "e": 4112, "s": 4110, "text": "0" }, { "code": null, "e": 4134, "s": 4112, "text": "lindan1233 months ago" }, { "code": null, "e": 5138, "s": 4134, "text": "int mod =1000000007;\nlong long numOfWays(int n, int m)\n{\n long long count=0;\n long long res=0;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n count=0;\n if(i-1>=0 && j-2>=0)\n {\n count++;\n }\n if(i+1<n && j-2>=0)\n {\n count++;\n }\n if(j+2<m && i+1<n)\n {\n count++;\n }\n if(j+2<m && i-1>=0)\n {\n count++;\n }\n if(i-2>=0 && j-1>=0)\n {\n count++;\n }\n if(i-2>=0 && j+1<m)\n {\n count++;\n }\n if(i+2<n && j-1>=0)\n {\n count++;\n }\n if(i+2<n && j+1<m)\n {\n count++;\n }\n count++;\n \n res = res%mod + (((n%mod)*(m%mod))%mod- count)%mod;\n }\n }\n return res;\n}" }, { "code": null, "e": 5155, "s": 5138, "text": "Time Taken : 0.0" }, { "code": null, "e": 5159, "s": 5155, "text": "Cpp" }, { "code": null, "e": 5161, "s": 5159, "text": "0" }, { "code": null, "e": 5189, "s": 5161, "text": "anjalipatel94313 months ago" }, { "code": null, "e": 5925, "s": 5189, "text": "int count(int i,int j,int N,int M){ int countt=0; if(i+2<N && j+1<M ){ countt++; } if(i+2<N && j-1>=0){ //down countt++; } if(i-2>=0 && j+1<M ){ //up countt++; } if(i-2>=0 && j-1>=0){ countt++; } if(i+1<N && j+2<M ){ //right countt++; } if(i-1>=0&& j+2<M ){ countt++; } if(i+1<N && j-2>=0){ //left countt++; } if(i-1>=0 && j-2>=0){ countt++; } return (N*M)-countt-1;}long long numOfWays(int N, int M){ // write code here int mod=1e9+7; int sum=0; for(int i=0;i<N;i++) for(int j=0;j<M;j++){ sum+=count(i,j,N,M); sum%=mod; } return sum;}" }, { "code": null, "e": 5927, "s": 5925, "text": "0" }, { "code": null, "e": 5957, "s": 5927, "text": "ayushnautiyal11104 months ago" }, { "code": null, "e": 5978, "s": 5957, "text": "C++ IMPLEMENTATION:)" }, { "code": null, "e": 5997, "s": 5978, "text": "Time Taken 0.6/1.3" }, { "code": null, "e": 6002, "s": 5997, "text": "😎😎😎😎" }, { "code": null, "e": 6585, "s": 6002, "text": "vector<pair<int,int>>v={{-2,-1},{-2,1},{-1,-2},{-1,2},{1,-2},{1,2},{2,-1},{2,1}};const long long mod=1e9+7;bool isSafe(int i,int j,int N,int M){ return (i<N && j<M && i>=0 && j>=0);}long long numOfWays(int N, int M){ long long res=0; for(int i=0;i<N;i++){ for(int j=0;j<M;j++){ int a=i; int b=j; for(auto x:v){ int dx=a+x.first; int dy=b+x.second; if(isSafe(dx,dy,N,M)==true){ res--; } } res+=N*M-1; res%=mod; } } return res;}" }, { "code": null, "e": 6588, "s": 6585, "text": "+1" }, { "code": null, "e": 6609, "s": 6588, "text": "anutiger6 months ago" }, { "code": null, "e": 7211, "s": 6609, "text": "long long numOfWays(int N, int M)\n{\n int mod = 1e9 + 7;\n long long res = 0;\n int dx[] = {1,1,-1,-1,2,2,-2,-2};\n int dy[] = {2,-2,2,-2,1,-1,1,-1};\n for(int i = 0; i < N ; i ++){\n for(int j = 0; j < M ; j++){\n int x = i;\n int y = j;\n for(int k = 0 ; k < 8 ; k ++){\n int x1 = x + dx[k];\n int y1 = y + dy[k];\n if(x1 >= 0 and x1 < N and y1 >= 0 and y1 < M){\n res--;\n }\n }\n res += N * M - 1;\n res %= mod;\n }\n }\n return res;\n}" }, { "code": null, "e": 7214, "s": 7211, "text": "+9" }, { "code": null, "e": 7238, "s": 7214, "text": "sachin shet6 months ago" }, { "code": null, "e": 7325, "s": 7238, "text": "I wonder why this is placed in backtracking section. This should be in Matrix Section." }, { "code": null, "e": 7471, "s": 7325, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 7507, "s": 7471, "text": " Login to access your submissions. " }, { "code": null, "e": 7517, "s": 7507, "text": "\nProblem\n" }, { "code": null, "e": 7527, "s": 7517, "text": "\nContest\n" }, { "code": null, "e": 7590, "s": 7527, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7738, "s": 7590, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7946, "s": 7738, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8052, "s": 7946, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C# program to find the most frequent element
Let’s say our string is − String s = "HeathLedger!"; Now create a new array. int []cal = new int[maxCHARS]; Create a new method and pass both the string and the new array in it. Find the maximum occurrence of a character. static void calculate(String s, int[] cal) { for (int i = 0; i < s.Length; i++) cal[s[i]]++; } Let us see the complete code − Live Demo using System; class Demo { static int maxCHARS = 256; static void calculate(String s, int[] cal) { for (int i = 0; i < s.Length; i++) cal[s[i]]++; } public static void Main() { String s = "thisisit!"; int []cal = new int[maxCHARS]; calculate(s, cal); for (int i = 0; i < maxCHARS; i++) if(cal[i] > 1) { Console.WriteLine("Character "+(char)i); Console.WriteLine("Occurrence = " + cal[i] + " times"); } } } Character i Occurrence = 3 times Character s Occurrence = 2 times Character t Occurrence = 2 times
[ { "code": null, "e": 1088, "s": 1062, "text": "Let’s say our string is −" }, { "code": null, "e": 1115, "s": 1088, "text": "String s = \"HeathLedger!\";" }, { "code": null, "e": 1139, "s": 1115, "text": "Now create a new array." }, { "code": null, "e": 1170, "s": 1139, "text": "int []cal = new int[maxCHARS];" }, { "code": null, "e": 1284, "s": 1170, "text": "Create a new method and pass both the string and the new array in it. Find the maximum occurrence of a character." }, { "code": null, "e": 1385, "s": 1284, "text": "static void calculate(String s, int[] cal) {\n for (int i = 0; i < s.Length; i++)\n cal[s[i]]++;\n}" }, { "code": null, "e": 1416, "s": 1385, "text": "Let us see the complete code −" }, { "code": null, "e": 1427, "s": 1416, "text": " Live Demo" }, { "code": null, "e": 1915, "s": 1427, "text": "using System;\nclass Demo {\n static int maxCHARS = 256;\n static void calculate(String s, int[] cal) {\n for (int i = 0; i < s.Length; i++)\n cal[s[i]]++;\n }\n\n public static void Main() {\n String s = \"thisisit!\";\n int []cal = new int[maxCHARS];\n calculate(s, cal);\n for (int i = 0; i < maxCHARS; i++)\n if(cal[i] > 1) {\n Console.WriteLine(\"Character \"+(char)i);\n Console.WriteLine(\"Occurrence = \" + cal[i] + \" times\");\n }\n }\n}" }, { "code": null, "e": 2014, "s": 1915, "text": "Character i\nOccurrence = 3 times\nCharacter s\nOccurrence = 2 times\nCharacter t\nOccurrence = 2 times" } ]
Laravel | Migration Basics - GeeksforGeeks
30 Dec, 2019 In Laravel, Migration provides a way for easily sharing the schema of the database. It also makes the modification of the schema much easier. It is like creating a schema once and then sharing it many times. It gets very useful when you have multiple tables and columns as it would reduce the work over creating the tables manually. To Create Migration: It can be created by using the artisan command as shown below: php artisan make:migration create_articles_table Here, articles are going to be the table and in place of that you can write any other table name which you want to create and is appropriate for the application but the table name as you saw, is to be in plural form. So, it is written as articles and not article. This is the naming scheme used by Laravel and it is important to specify create at the start and table at the end according to the naming scheme of a Migration file in Laravel. All the migration file that we create using the artisan command are located at database/migrations directory. So, after we run the above command, it will generate a PHP file with the name we specified with the current date and time. And the file will be created with some predefined class and functions as shown in the code below: <?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; class CreateArticlesTable extends Migration{ public function up() { Schema::create('articles', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('articles'); }} If you want to specify the name of the table different than the name that you specified as the file name then you can use an option as –create with the command as follows: php artisan make:migration create_articles_table --create=gfg With this command, the table name contained in the create() method will be gfg and not articles, which is specified in the name of the file. <?php use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema; class CreateArticlesTable extends Migration{ public function up() { Schema::create('gfg', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('gfg'); }} Basic Structure of a Migration: A migration file contains a class with the name of the file specified while creating the migration and it extends Migration. In that we have two functions, the first one is up() function and the second one is down() function. The up() is called when we run the migration to create a table and columns specified and the ‘down()’ function is called when we want to undo the creation of ‘up()’ function. In the up() function, we have create method of the Schema facade (schema builder) and as we say before, the first argument in this function is the name of the table to be created. The second argument is a function with a Blueprint object as a parameter and for defining the table. In the down() function, we have a dropIfExists method of the schema builder which when called will drop the table. To Run Migration: Before running a migration, we first have to create a MySQL Database and Connect to it. After that is done, to Run a Migration, we can use an Artisan command as follows: php artisan migrate This command will run the up() function in the migration class file and will create the table with the all columns specified.Note: This command will run the up() function and create all the tables in the database for all the migration file in the database/migrations directory. To rollback any last migration which is done, we can use the following Artisan command: php artisan migrate:rollback This command will run the down() function in the migration class file. Reference: https://laravel.com/docs/6.x/migrations Laravel PHP Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to pass form variables from one page to other page in PHP ? Create a drop-down list that options fetched from a MySQL database in PHP How to create admin login page using PHP? Different ways for passing data to view in Laravel Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24581, "s": 24553, "text": "\n30 Dec, 2019" }, { "code": null, "e": 24914, "s": 24581, "text": "In Laravel, Migration provides a way for easily sharing the schema of the database. It also makes the modification of the schema much easier. It is like creating a schema once and then sharing it many times. It gets very useful when you have multiple tables and columns as it would reduce the work over creating the tables manually." }, { "code": null, "e": 24998, "s": 24914, "text": "To Create Migration: It can be created by using the artisan command as shown below:" }, { "code": null, "e": 25047, "s": 24998, "text": "php artisan make:migration create_articles_table" }, { "code": null, "e": 25488, "s": 25047, "text": "Here, articles are going to be the table and in place of that you can write any other table name which you want to create and is appropriate for the application but the table name as you saw, is to be in plural form. So, it is written as articles and not article. This is the naming scheme used by Laravel and it is important to specify create at the start and table at the end according to the naming scheme of a Migration file in Laravel." }, { "code": null, "e": 25721, "s": 25488, "text": "All the migration file that we create using the artisan command are located at database/migrations directory. So, after we run the above command, it will generate a PHP file with the name we specified with the current date and time." }, { "code": null, "e": 25819, "s": 25721, "text": "And the file will be created with some predefined class and functions as shown in the code below:" }, { "code": "<?php use Illuminate\\Database\\Migrations\\Migration;use Illuminate\\Database\\Schema\\Blueprint;use Illuminate\\Support\\Facades\\Schema; class CreateArticlesTable extends Migration{ public function up() { Schema::create('articles', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('articles'); }}", "e": 26259, "s": 25819, "text": null }, { "code": null, "e": 26431, "s": 26259, "text": "If you want to specify the name of the table different than the name that you specified as the file name then you can use an option as –create with the command as follows:" }, { "code": null, "e": 26493, "s": 26431, "text": "php artisan make:migration create_articles_table --create=gfg" }, { "code": null, "e": 26634, "s": 26493, "text": "With this command, the table name contained in the create() method will be gfg and not articles, which is specified in the name of the file." }, { "code": "<?php use Illuminate\\Database\\Migrations\\Migration;use Illuminate\\Database\\Schema\\Blueprint;use Illuminate\\Support\\Facades\\Schema; class CreateArticlesTable extends Migration{ public function up() { Schema::create('gfg', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('gfg'); }}", "e": 27062, "s": 26634, "text": null }, { "code": null, "e": 27495, "s": 27062, "text": "Basic Structure of a Migration: A migration file contains a class with the name of the file specified while creating the migration and it extends Migration. In that we have two functions, the first one is up() function and the second one is down() function. The up() is called when we run the migration to create a table and columns specified and the ‘down()’ function is called when we want to undo the creation of ‘up()’ function." }, { "code": null, "e": 27776, "s": 27495, "text": "In the up() function, we have create method of the Schema facade (schema builder) and as we say before, the first argument in this function is the name of the table to be created. The second argument is a function with a Blueprint object as a parameter and for defining the table." }, { "code": null, "e": 27891, "s": 27776, "text": "In the down() function, we have a dropIfExists method of the schema builder which when called will drop the table." }, { "code": null, "e": 28079, "s": 27891, "text": "To Run Migration: Before running a migration, we first have to create a MySQL Database and Connect to it. After that is done, to Run a Migration, we can use an Artisan command as follows:" }, { "code": null, "e": 28099, "s": 28079, "text": "php artisan migrate" }, { "code": null, "e": 28377, "s": 28099, "text": "This command will run the up() function in the migration class file and will create the table with the all columns specified.Note: This command will run the up() function and create all the tables in the database for all the migration file in the database/migrations directory." }, { "code": null, "e": 28465, "s": 28377, "text": "To rollback any last migration which is done, we can use the following Artisan command:" }, { "code": null, "e": 28494, "s": 28465, "text": "php artisan migrate:rollback" }, { "code": null, "e": 28565, "s": 28494, "text": "This command will run the down() function in the migration class file." }, { "code": null, "e": 28616, "s": 28565, "text": "Reference: https://laravel.com/docs/6.x/migrations" }, { "code": null, "e": 28624, "s": 28616, "text": "Laravel" }, { "code": null, "e": 28628, "s": 28624, "text": "PHP" }, { "code": null, "e": 28647, "s": 28628, "text": "Technical Scripter" }, { "code": null, "e": 28664, "s": 28647, "text": "Web Technologies" }, { "code": null, "e": 28668, "s": 28664, "text": "PHP" }, { "code": null, "e": 28766, "s": 28668, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28775, "s": 28766, "text": "Comments" }, { "code": null, "e": 28788, "s": 28775, "text": "Old Comments" }, { "code": null, "e": 28870, "s": 28788, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 28934, "s": 28870, "text": "How to pass form variables from one page to other page in PHP ?" }, { "code": null, "e": 29008, "s": 28934, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 29050, "s": 29008, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 29101, "s": 29050, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 29157, "s": 29101, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29190, "s": 29157, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29252, "s": 29190, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29295, "s": 29252, "text": "How to fetch data from an API in ReactJS ?" } ]
Reversing a Queue - GeeksforGeeks
30 Aug, 2021 Give an algorithm for reversing a queue Q. Only following standard operations are allowed on queue. enqueue(x) : Add an item x to rear of queue.dequeue() : Remove an item from front of queue.empty() : Checks if a queue is empty or not. enqueue(x) : Add an item x to rear of queue. dequeue() : Remove an item from front of queue. empty() : Checks if a queue is empty or not. Examples: Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] Output : Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] Input : [1, 2, 3, 4, 5] Output : [5, 4, 3, 2, 1] Approach: For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such data-structure which can serve the purpose. According to the approach, the data-structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should actually be the first element of the reversed queue. The stack could help in approaching this problem. This will be a two-step process: Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue) Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue) Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue) C++ Java Python3 C# Javascript // CPP program to reverse a Queue#include <bits/stdc++.h>using namespace std; // Utility function to print the queuevoid Print(queue<int>& Queue){ while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); }} // Function to reverse the queuevoid reverseQueue(queue<int>& Queue){ stack<int> Stack; while (!Queue.empty()) { Stack.push(Queue.front()); Queue.pop(); } while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); }} // Driver codeint main(){ queue<int> Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); Print(Queue);} // Java program to reverse a Queueimport java.util.LinkedList;import java.util.Queue;import java.util.Stack; // Java program to reverse a queuepublic class Queue_reverse { static Queue<Integer> queue; // Utility function to print the queue static void Print() { while (!queue.isEmpty()) { System.out.print( queue.peek() + ", "); queue.remove(); } } // Function to reverse the queue static void reversequeue() { Stack<Integer> stack = new Stack<>(); while (!queue.isEmpty()) { stack.add(queue.peek()); queue.remove(); } while (!stack.isEmpty()) { queue.add(stack.peek()); stack.pop(); } } // Driver code public static void main(String args[]) { queue = new LinkedList<Integer>(); queue.add(10); queue.add(20); queue.add(30); queue.add(40); queue.add(50); queue.add(60); queue.add(70); queue.add(80); queue.add(90); queue.add(100); reversequeue(); Print(); }}//This code is contributed by Sumit Ghosh # Python3 program to reverse a queuefrom queue import Queue # Utility function to print the queuedef Print(queue): while (not queue.empty()): print(queue.queue[0], end = ", ") queue.get() # Function to reverse the queuedef reversequeue(queue): Stack = [] while (not queue.empty()): Stack.append(queue.queue[0]) queue.get() while (len(Stack) != 0): queue.put(Stack[-1]) Stack.pop() # Driver codeif __name__ == '__main__': queue = Queue() queue.put(10) queue.put(20) queue.put(30) queue.put(40) queue.put(50) queue.put(60) queue.put(70) queue.put(80) queue.put(90) queue.put(100) reversequeue(queue) Print(queue) # This code is contributed by PranchalK // c# program to reverse a Queueusing System;using System.Collections.Generic; public class GFG{ public static LinkedList<int> queue; // Utility function to print the queuepublic static void Print(){ while (queue.Count > 0) { Console.Write(queue.First.Value + ", "); queue.RemoveFirst(); }} // Function to reverse the queuepublic static void reversequeue(){ Stack<int> stack = new Stack<int>(); while (queue.Count > 0) { stack.Push(queue.First.Value); queue.RemoveFirst(); } while (stack.Count > 0) { queue.AddLast(stack.Peek()); stack.Pop(); }} // Driver codepublic static void Main(string[] args){ queue = new LinkedList<int>(); queue.AddLast(10); queue.AddLast(20); queue.AddLast(30); queue.AddLast(40); queue.AddLast(50); queue.AddLast(60); queue.AddLast(70); queue.AddLast(80); queue.AddLast(90); queue.AddLast(100); reversequeue(); Print();}} // This code is contributed by Shrikant13 <script> // Javascript program to reverse a Queue let queue = []; // Utility function to print the queue function Print() { while (queue.length > 0) { document.write( queue[0] + ", "); queue.shift(); } } // Function to reverse the queue function reversequeue() { let stack = []; while (queue.length > 0) { stack.push(queue[0]); queue.shift(); } while (stack.length > 0) { queue.push(stack[stack.length - 1]); stack.pop(); } } queue = [] queue.push(10); queue.push(20); queue.push(30); queue.push(40); queue.push(50); queue.push(60); queue.push(70); queue.push(80); queue.push(90); queue.push(100); reversequeue(); Print(); </script> Output: 100, 90, 80, 70, 60, 50, 40, 30, 20, 10 Complexity Analysis: Time Complexity: O(n). As we need to insert all the elements in the stack and later to the queue. Auxiliary Space: O(N). Use of stack to store values. YouTubeGeeksforGeeks500K subscribersReversing a Queue | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=aUU23JDaErs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Raghav Sharma. 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. shrikanth13 PranchalKatiyar bidibaaz123 rameshtravel07 Queue Stack Stack Queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Queue | Set 1 (Introduction and Array Implementation) Priority Queue | Set 1 (Introduction) LRU Cache Implementation Queue - Linked List Implementation Circular Queue | Set 1 (Introduction and Array Implementation) Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Inorder Tree Traversal without Recursion Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 24149, "s": 24121, "text": "\n30 Aug, 2021" }, { "code": null, "e": 24251, "s": 24149, "text": "Give an algorithm for reversing a queue Q. Only following standard operations are allowed on queue. " }, { "code": null, "e": 24387, "s": 24251, "text": "enqueue(x) : Add an item x to rear of queue.dequeue() : Remove an item from front of queue.empty() : Checks if a queue is empty or not." }, { "code": null, "e": 24432, "s": 24387, "text": "enqueue(x) : Add an item x to rear of queue." }, { "code": null, "e": 24480, "s": 24432, "text": "dequeue() : Remove an item from front of queue." }, { "code": null, "e": 24525, "s": 24480, "text": "empty() : Checks if a queue is empty or not." }, { "code": null, "e": 24537, "s": 24525, "text": "Examples: " }, { "code": null, "e": 24697, "s": 24537, "text": "Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\nOutput : Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]\n\nInput : [1, 2, 3, 4, 5]\nOutput : [5, 4, 3, 2, 1]" }, { "code": null, "e": 25287, "s": 24699, "text": "Approach: For reversing the queue one approach could be to store the elements of the queue in a temporary data structure in a manner such that if we re-insert the elements in the queue they would get inserted in reverse order. So now our task is to choose such data-structure which can serve the purpose. According to the approach, the data-structure should have the property of ‘LIFO’ as the last element to be inserted in the data structure should actually be the first element of the reversed queue. The stack could help in approaching this problem. This will be a two-step process: " }, { "code": null, "e": 25536, "s": 25287, "text": "Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue)" }, { "code": null, "e": 25659, "s": 25536, "text": "Pop the elements from the queue and insert into the stack. (Topmost element of the stack is the last element of the queue)" }, { "code": null, "e": 25786, "s": 25659, "text": "Pop the elements of the stack to insert back into the queue. (The last element is the first one to be inserted into the queue)" }, { "code": null, "e": 25792, "s": 25788, "text": "C++" }, { "code": null, "e": 25797, "s": 25792, "text": "Java" }, { "code": null, "e": 25805, "s": 25797, "text": "Python3" }, { "code": null, "e": 25808, "s": 25805, "text": "C#" }, { "code": null, "e": 25819, "s": 25808, "text": "Javascript" }, { "code": "// CPP program to reverse a Queue#include <bits/stdc++.h>using namespace std; // Utility function to print the queuevoid Print(queue<int>& Queue){ while (!Queue.empty()) { cout << Queue.front() << \" \"; Queue.pop(); }} // Function to reverse the queuevoid reverseQueue(queue<int>& Queue){ stack<int> Stack; while (!Queue.empty()) { Stack.push(Queue.front()); Queue.pop(); } while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); }} // Driver codeint main(){ queue<int> Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); Print(Queue);}", "e": 26602, "s": 25819, "text": null }, { "code": "// Java program to reverse a Queueimport java.util.LinkedList;import java.util.Queue;import java.util.Stack; // Java program to reverse a queuepublic class Queue_reverse { static Queue<Integer> queue; // Utility function to print the queue static void Print() { while (!queue.isEmpty()) { System.out.print( queue.peek() + \", \"); queue.remove(); } } // Function to reverse the queue static void reversequeue() { Stack<Integer> stack = new Stack<>(); while (!queue.isEmpty()) { stack.add(queue.peek()); queue.remove(); } while (!stack.isEmpty()) { queue.add(stack.peek()); stack.pop(); } } // Driver code public static void main(String args[]) { queue = new LinkedList<Integer>(); queue.add(10); queue.add(20); queue.add(30); queue.add(40); queue.add(50); queue.add(60); queue.add(70); queue.add(80); queue.add(90); queue.add(100); reversequeue(); Print(); }}//This code is contributed by Sumit Ghosh", "e": 27755, "s": 26602, "text": null }, { "code": "# Python3 program to reverse a queuefrom queue import Queue # Utility function to print the queuedef Print(queue): while (not queue.empty()): print(queue.queue[0], end = \", \") queue.get() # Function to reverse the queuedef reversequeue(queue): Stack = [] while (not queue.empty()): Stack.append(queue.queue[0]) queue.get() while (len(Stack) != 0): queue.put(Stack[-1]) Stack.pop() # Driver codeif __name__ == '__main__': queue = Queue() queue.put(10) queue.put(20) queue.put(30) queue.put(40) queue.put(50) queue.put(60) queue.put(70) queue.put(80) queue.put(90) queue.put(100) reversequeue(queue) Print(queue) # This code is contributed by PranchalK", "e": 28500, "s": 27755, "text": null }, { "code": "// c# program to reverse a Queueusing System;using System.Collections.Generic; public class GFG{ public static LinkedList<int> queue; // Utility function to print the queuepublic static void Print(){ while (queue.Count > 0) { Console.Write(queue.First.Value + \", \"); queue.RemoveFirst(); }} // Function to reverse the queuepublic static void reversequeue(){ Stack<int> stack = new Stack<int>(); while (queue.Count > 0) { stack.Push(queue.First.Value); queue.RemoveFirst(); } while (stack.Count > 0) { queue.AddLast(stack.Peek()); stack.Pop(); }} // Driver codepublic static void Main(string[] args){ queue = new LinkedList<int>(); queue.AddLast(10); queue.AddLast(20); queue.AddLast(30); queue.AddLast(40); queue.AddLast(50); queue.AddLast(60); queue.AddLast(70); queue.AddLast(80); queue.AddLast(90); queue.AddLast(100); reversequeue(); Print();}} // This code is contributed by Shrikant13", "e": 29503, "s": 28500, "text": null }, { "code": "<script> // Javascript program to reverse a Queue let queue = []; // Utility function to print the queue function Print() { while (queue.length > 0) { document.write( queue[0] + \", \"); queue.shift(); } } // Function to reverse the queue function reversequeue() { let stack = []; while (queue.length > 0) { stack.push(queue[0]); queue.shift(); } while (stack.length > 0) { queue.push(stack[stack.length - 1]); stack.pop(); } } queue = [] queue.push(10); queue.push(20); queue.push(30); queue.push(40); queue.push(50); queue.push(60); queue.push(70); queue.push(80); queue.push(90); queue.push(100); reversequeue(); Print(); </script>", "e": 30341, "s": 29503, "text": null }, { "code": null, "e": 30351, "s": 30341, "text": "Output: " }, { "code": null, "e": 30391, "s": 30351, "text": "100, 90, 80, 70, 60, 50, 40, 30, 20, 10" }, { "code": null, "e": 30414, "s": 30391, "text": "Complexity Analysis: " }, { "code": null, "e": 30512, "s": 30414, "text": "Time Complexity: O(n). As we need to insert all the elements in the stack and later to the queue." }, { "code": null, "e": 30567, "s": 30512, "text": "Auxiliary Space: O(N). Use of stack to store values. " }, { "code": null, "e": 31385, "s": 30569, "text": "YouTubeGeeksforGeeks500K subscribersReversing a Queue | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=aUU23JDaErs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 31807, "s": 31385, "text": "This article is contributed by Raghav Sharma. 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": 31819, "s": 31807, "text": "shrikanth13" }, { "code": null, "e": 31835, "s": 31819, "text": "PranchalKatiyar" }, { "code": null, "e": 31847, "s": 31835, "text": "bidibaaz123" }, { "code": null, "e": 31862, "s": 31847, "text": "rameshtravel07" }, { "code": null, "e": 31868, "s": 31862, "text": "Queue" }, { "code": null, "e": 31874, "s": 31868, "text": "Stack" }, { "code": null, "e": 31880, "s": 31874, "text": "Stack" }, { "code": null, "e": 31886, "s": 31880, "text": "Queue" }, { "code": null, "e": 31984, "s": 31886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31993, "s": 31984, "text": "Comments" }, { "code": null, "e": 32006, "s": 31993, "text": "Old Comments" }, { "code": null, "e": 32060, "s": 32006, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 32098, "s": 32060, "text": "Priority Queue | Set 1 (Introduction)" }, { "code": null, "e": 32123, "s": 32098, "text": "LRU Cache Implementation" }, { "code": null, "e": 32158, "s": 32123, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 32221, "s": 32158, "text": "Circular Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 32269, "s": 32221, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32289, "s": 32269, "text": "Stack Class in Java" }, { "code": null, "e": 32305, "s": 32289, "text": "Stack in Python" }, { "code": null, "e": 32346, "s": 32305, "text": "Inorder Tree Traversal without Recursion" } ]
Deploy models in PyTorch with Torchserve 🚀 | by Francesco Zuppichini | Towards Data Science | Towards Data Science
All the code used in this article is here Recently, PyTorch has introduced its new production framework to properly serve models, called torchserve.So, without further due, let’s present today’s roadmap: Installation with DockerExport your modelDefine a handlerServe our model Installation with Docker Export your model Define a handler Serve our model To showcase torchserve, we will serve a fully trained ResNet34 to perform image classification. Official doc here The best way to install torchserve is with docker. You just need to pull the image. You can use the following command to save the latest image. docker pull pytorch/torchserve:latest All the tags are available here More about docker and torchserve here Official doc here Handlers are the ones responsible to make a prediction using your model from one or more HTTP requests. Default handlers Torchserve supports the following default handlers image_classifierobject_detectortext_classifierimage_segmenter image_classifier object_detector text_classifier image_segmenter But keep in mind that none of them supports batching requests! Custom handlers torchserve exposes a rich interface to do almost everything you want. An Handler is just a class that must have three functions preprocess inference postprocess You can create your own class or just subclassBaseHandler . The main advantage of subclasssing BaseHandler is to have the model loaded accessible at self.model . The following snippet shows how to subclass BaseHandler Going back to our image classification example. We need to get the images from each request and preprocess them get the prediction from the model send back a response Preprocess The .preprocess function takes an array of requests. Assuming we are sending an image to the server, the serialized image can be accessed from the data or body field of the request. Thus, we can just iterate over all requests and preprocess individually each image. The full code is shown below. self.transform is our preprocess transformation, nothing fancy. This is a classic preprocessing step for models trained on ImageNet. After we have preprocessed each image in each request we concatenate them to create a pytorch Tensor. Inference This step is very easy, we get the tensor from the .preprocess function and we extract the prediction for each image. Postprocess Now we have our predictions for each image, we need to return something to the client. Torchserve always expects an array to be returned. BaseHandler also automatically opens a .json file with the mapping index -> label (we are going to see it later how to provide such file) and store it at self.mapping . We can return an array of dictionaries with the label and index class for each prediction Wrapping everything together, our glorious handler looks like Since all the handling logic encapsulated in a class, you can easily unit test it! Official doc here Torchserve expects a .mar file to be provided. In a nutshell, the file is just your model and all the dependencies packed together. To create one need to first export our trained model. Export the model There are three ways to export your model for torchserve. The best way that I have found so far is to trace the model and store the results. By doing so we do not need to add any additional files to torchserve. Let’s see an example, we are going to deploy a fully trained ResNet34 model. In order, we: load the model create a dummy input trace the input through the model using torch.jit.trace save the model Create the .mar file Official doc here You need to install torch-model-archiver git clone https://github.com/pytorch/serve.gitcd serve/model-archiverpip install . Then, we are ready to create the .mar file by using the following command torch-model-archiver --model-name resnet34 \--version 1.0 \--serialized-file resnet34.pt \--extra-files ./index_to_name.json,./MyHandler.py \--handler my_handler.py \--export-path model-store -f In order. The variable --model-name defines the final name of our model. This is very important since it will be the namespace of the endpoint that will be responsible for its predictions. You can also specify a --version . --serialized-file points to the stored .pt model we created before. --handler is a python file where we call our custom handler. In general, it always looks like this: It exposes a handle function from which we call the methods in the custom handler. You can use the default names to use the default handled (e.g. --handler image_classifier ). In --extra-files you need to pass the path to all the files your handlers are using. In our case, we have to add the path to the .json file with all the human-readable labels names and MyHandler.py file in which we have the class definition for MyHandler. One minor thing, if you pass an index_to_name.json file, it will be automatically loaded into the handler and be accessible at self.mapping . --export-path is where the .mar file will be stored, I also added the -f to overwrite everything in it. If everything went smooth, you should see resnet34.mar stored into ./model-store . This is an easy step, we can run the torchserve docker container with all the required parameters docker run --rm -it \-p 3000:8080 -p 3001:8081 \-v $(pwd)/model-store:/home/model-server/model-store pytorch/torchserve:0.1-cpu \torchserve --start --model-store model-store --models resnet34=resnet34.mar I am binding the container port 8080 and 8081 to 3000 and 3001 respectively (8080/8081 were already in used in my machine). Then, I am creating a volume from ./model-store (where we stored the .mar file) to the container default model-store folder. Lastly, I am calling torchserve by padding the model-store path and a list of key-value pairs in which we specify the model name for each .mar file. At this point, torchserve has one endpoint /predictions/resnet34 to which we can get a prediction by sending an image. This can be done using curl curl -X POST http://127.0.0.1:3000/predictions/resnet34 -T inputs/kitten.jpg The response { "label": "tiger_cat", "index": 282} It worked! 🥳 To recap, in this article we have covered: torchserve installation with docker default and custom handlers model archive generation serving the final model with docker All the code is here If you like this article and pytorch, you may also be interested in these my other articles towardsdatascience.com towardsdatascience.com Thank you for reading.
[ { "code": null, "e": 214, "s": 172, "text": "All the code used in this article is here" }, { "code": null, "e": 376, "s": 214, "text": "Recently, PyTorch has introduced its new production framework to properly serve models, called torchserve.So, without further due, let’s present today’s roadmap:" }, { "code": null, "e": 449, "s": 376, "text": "Installation with DockerExport your modelDefine a handlerServe our model" }, { "code": null, "e": 474, "s": 449, "text": "Installation with Docker" }, { "code": null, "e": 492, "s": 474, "text": "Export your model" }, { "code": null, "e": 509, "s": 492, "text": "Define a handler" }, { "code": null, "e": 525, "s": 509, "text": "Serve our model" }, { "code": null, "e": 621, "s": 525, "text": "To showcase torchserve, we will serve a fully trained ResNet34 to perform image classification." }, { "code": null, "e": 639, "s": 621, "text": "Official doc here" }, { "code": null, "e": 723, "s": 639, "text": "The best way to install torchserve is with docker. You just need to pull the image." }, { "code": null, "e": 783, "s": 723, "text": "You can use the following command to save the latest image." }, { "code": null, "e": 821, "s": 783, "text": "docker pull pytorch/torchserve:latest" }, { "code": null, "e": 853, "s": 821, "text": "All the tags are available here" }, { "code": null, "e": 891, "s": 853, "text": "More about docker and torchserve here" }, { "code": null, "e": 909, "s": 891, "text": "Official doc here" }, { "code": null, "e": 1013, "s": 909, "text": "Handlers are the ones responsible to make a prediction using your model from one or more HTTP requests." }, { "code": null, "e": 1030, "s": 1013, "text": "Default handlers" }, { "code": null, "e": 1081, "s": 1030, "text": "Torchserve supports the following default handlers" }, { "code": null, "e": 1143, "s": 1081, "text": "image_classifierobject_detectortext_classifierimage_segmenter" }, { "code": null, "e": 1160, "s": 1143, "text": "image_classifier" }, { "code": null, "e": 1176, "s": 1160, "text": "object_detector" }, { "code": null, "e": 1192, "s": 1176, "text": "text_classifier" }, { "code": null, "e": 1208, "s": 1192, "text": "image_segmenter" }, { "code": null, "e": 1271, "s": 1208, "text": "But keep in mind that none of them supports batching requests!" }, { "code": null, "e": 1287, "s": 1271, "text": "Custom handlers" }, { "code": null, "e": 1415, "s": 1287, "text": "torchserve exposes a rich interface to do almost everything you want. An Handler is just a class that must have three functions" }, { "code": null, "e": 1426, "s": 1415, "text": "preprocess" }, { "code": null, "e": 1436, "s": 1426, "text": "inference" }, { "code": null, "e": 1448, "s": 1436, "text": "postprocess" }, { "code": null, "e": 1666, "s": 1448, "text": "You can create your own class or just subclassBaseHandler . The main advantage of subclasssing BaseHandler is to have the model loaded accessible at self.model . The following snippet shows how to subclass BaseHandler" }, { "code": null, "e": 1725, "s": 1666, "text": "Going back to our image classification example. We need to" }, { "code": null, "e": 1778, "s": 1725, "text": "get the images from each request and preprocess them" }, { "code": null, "e": 1812, "s": 1778, "text": "get the prediction from the model" }, { "code": null, "e": 1833, "s": 1812, "text": "send back a response" }, { "code": null, "e": 1844, "s": 1833, "text": "Preprocess" }, { "code": null, "e": 2140, "s": 1844, "text": "The .preprocess function takes an array of requests. Assuming we are sending an image to the server, the serialized image can be accessed from the data or body field of the request. Thus, we can just iterate over all requests and preprocess individually each image. The full code is shown below." }, { "code": null, "e": 2273, "s": 2140, "text": "self.transform is our preprocess transformation, nothing fancy. This is a classic preprocessing step for models trained on ImageNet." }, { "code": null, "e": 2375, "s": 2273, "text": "After we have preprocessed each image in each request we concatenate them to create a pytorch Tensor." }, { "code": null, "e": 2385, "s": 2375, "text": "Inference" }, { "code": null, "e": 2503, "s": 2385, "text": "This step is very easy, we get the tensor from the .preprocess function and we extract the prediction for each image." }, { "code": null, "e": 2515, "s": 2503, "text": "Postprocess" }, { "code": null, "e": 2912, "s": 2515, "text": "Now we have our predictions for each image, we need to return something to the client. Torchserve always expects an array to be returned. BaseHandler also automatically opens a .json file with the mapping index -> label (we are going to see it later how to provide such file) and store it at self.mapping . We can return an array of dictionaries with the label and index class for each prediction" }, { "code": null, "e": 2974, "s": 2912, "text": "Wrapping everything together, our glorious handler looks like" }, { "code": null, "e": 3057, "s": 2974, "text": "Since all the handling logic encapsulated in a class, you can easily unit test it!" }, { "code": null, "e": 3075, "s": 3057, "text": "Official doc here" }, { "code": null, "e": 3261, "s": 3075, "text": "Torchserve expects a .mar file to be provided. In a nutshell, the file is just your model and all the dependencies packed together. To create one need to first export our trained model." }, { "code": null, "e": 3278, "s": 3261, "text": "Export the model" }, { "code": null, "e": 3489, "s": 3278, "text": "There are three ways to export your model for torchserve. The best way that I have found so far is to trace the model and store the results. By doing so we do not need to add any additional files to torchserve." }, { "code": null, "e": 3566, "s": 3489, "text": "Let’s see an example, we are going to deploy a fully trained ResNet34 model." }, { "code": null, "e": 3580, "s": 3566, "text": "In order, we:" }, { "code": null, "e": 3595, "s": 3580, "text": "load the model" }, { "code": null, "e": 3616, "s": 3595, "text": "create a dummy input" }, { "code": null, "e": 3672, "s": 3616, "text": "trace the input through the model using torch.jit.trace" }, { "code": null, "e": 3687, "s": 3672, "text": "save the model" }, { "code": null, "e": 3708, "s": 3687, "text": "Create the .mar file" }, { "code": null, "e": 3726, "s": 3708, "text": "Official doc here" }, { "code": null, "e": 3767, "s": 3726, "text": "You need to install torch-model-archiver" }, { "code": null, "e": 3850, "s": 3767, "text": "git clone https://github.com/pytorch/serve.gitcd serve/model-archiverpip install ." }, { "code": null, "e": 3924, "s": 3850, "text": "Then, we are ready to create the .mar file by using the following command" }, { "code": null, "e": 4120, "s": 3924, "text": "torch-model-archiver --model-name resnet34 \\--version 1.0 \\--serialized-file resnet34.pt \\--extra-files ./index_to_name.json,./MyHandler.py \\--handler my_handler.py \\--export-path model-store -f" }, { "code": null, "e": 4512, "s": 4120, "text": "In order. The variable --model-name defines the final name of our model. This is very important since it will be the namespace of the endpoint that will be responsible for its predictions. You can also specify a --version . --serialized-file points to the stored .pt model we created before. --handler is a python file where we call our custom handler. In general, it always looks like this:" }, { "code": null, "e": 4688, "s": 4512, "text": "It exposes a handle function from which we call the methods in the custom handler. You can use the default names to use the default handled (e.g. --handler image_classifier )." }, { "code": null, "e": 4944, "s": 4688, "text": "In --extra-files you need to pass the path to all the files your handlers are using. In our case, we have to add the path to the .json file with all the human-readable labels names and MyHandler.py file in which we have the class definition for MyHandler." }, { "code": null, "e": 5086, "s": 4944, "text": "One minor thing, if you pass an index_to_name.json file, it will be automatically loaded into the handler and be accessible at self.mapping ." }, { "code": null, "e": 5190, "s": 5086, "text": "--export-path is where the .mar file will be stored, I also added the -f to overwrite everything in it." }, { "code": null, "e": 5273, "s": 5190, "text": "If everything went smooth, you should see resnet34.mar stored into ./model-store ." }, { "code": null, "e": 5371, "s": 5273, "text": "This is an easy step, we can run the torchserve docker container with all the required parameters" }, { "code": null, "e": 5576, "s": 5371, "text": "docker run --rm -it \\-p 3000:8080 -p 3001:8081 \\-v $(pwd)/model-store:/home/model-server/model-store pytorch/torchserve:0.1-cpu \\torchserve --start --model-store model-store --models resnet34=resnet34.mar" }, { "code": null, "e": 5974, "s": 5576, "text": "I am binding the container port 8080 and 8081 to 3000 and 3001 respectively (8080/8081 were already in used in my machine). Then, I am creating a volume from ./model-store (where we stored the .mar file) to the container default model-store folder. Lastly, I am calling torchserve by padding the model-store path and a list of key-value pairs in which we specify the model name for each .mar file." }, { "code": null, "e": 6121, "s": 5974, "text": "At this point, torchserve has one endpoint /predictions/resnet34 to which we can get a prediction by sending an image. This can be done using curl" }, { "code": null, "e": 6198, "s": 6121, "text": "curl -X POST http://127.0.0.1:3000/predictions/resnet34 -T inputs/kitten.jpg" }, { "code": null, "e": 6211, "s": 6198, "text": "The response" }, { "code": null, "e": 6251, "s": 6211, "text": "{ \"label\": \"tiger_cat\", \"index\": 282}" }, { "code": null, "e": 6264, "s": 6251, "text": "It worked! 🥳" }, { "code": null, "e": 6307, "s": 6264, "text": "To recap, in this article we have covered:" }, { "code": null, "e": 6343, "s": 6307, "text": "torchserve installation with docker" }, { "code": null, "e": 6371, "s": 6343, "text": "default and custom handlers" }, { "code": null, "e": 6396, "s": 6371, "text": "model archive generation" }, { "code": null, "e": 6432, "s": 6396, "text": "serving the final model with docker" }, { "code": null, "e": 6453, "s": 6432, "text": "All the code is here" }, { "code": null, "e": 6545, "s": 6453, "text": "If you like this article and pytorch, you may also be interested in these my other articles" }, { "code": null, "e": 6568, "s": 6545, "text": "towardsdatascience.com" }, { "code": null, "e": 6591, "s": 6568, "text": "towardsdatascience.com" } ]
How to add google search functionality in an android app?
This example demonstrates how do I add google search functionality in an android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" tools:context=".MainActivity"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_centerInParent="true" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btnSearch" android:text="Search"/> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { EditText editText; Button btnSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.editText); btnSearch = findViewById(R.id.btnSearch); btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); String term = editText.getText().toString(); intent.putExtra(SearchManager.QUERY, term); startActivity(intent); } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrates how do I add google search functionality in an android." }, { "code": null, "e": 1273, "s": 1144, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1338, "s": 1273, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2029, "s": 1338, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:layout_centerInParent=\"true\" />\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/btnSearch\"\n android:text=\"Search\"/>\n</LinearLayout>\n" }, { "code": null, "e": 2086, "s": 2029, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3026, "s": 2086, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.app.SearchManager;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n EditText editText;\n Button btnSearch;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n editText = findViewById(R.id.editText);\n btnSearch = findViewById(R.id.btnSearch);\n btnSearch.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);\n String term = editText.getText().toString();\n intent.putExtra(SearchManager.QUERY, term);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 3081, "s": 3026, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3853, "s": 3081, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>\n" }, { "code": null, "e": 4205, "s": 3853, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Program to find the Largest Number using Ternary Operator in C++
In this problem, we are given some numbers. Our task is to create a Program to Find the Largest Number using Ternary Operator in C++. The elements can be − Two Numbers Three Numbers Four Numbers Code Description − Here, we are given some numbers (two or three or four). We need to find the maximum element out of these numbers using a ternary operator. Let’s take a few examples to understand the problem, Input − 4, 54 Output − 54 Input − 14, 40, 26 Output − 40 Input − 10, 54, 26, 62 Output − 62 We will use ternary Operator, for two, three and four element for finding the maximum element of the four. Implementing Ternary operator for Two numbers (a, b), a > b ? a : b Three numbers (a, b, c), (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) Four numbers (a, b, c, d), (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d)? c : d Program to illustrate the working of our solution for two numbers − Live Demo #include <iostream> using namespace std; int main() { int a = 4, b = 9; cout<<"The greater element of the two elements is "<<( (a > b) ? a :b ); return 0; } The greater element of the two elements is 9 Program to illustrate the working of our solution for three numbers − Live Demo #include <iostream> using namespace std; int findMax(int a, int b, int c){ int maxVal = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c); return maxVal; } int main() { int a = 4, b = 13, c = 7; cout<<"The greater element of the two elements is "<<findMax(a, b,c); return 0; } The greater element of the two elements is 13 Program to illustrate the working of our solution for four numbers − Live Demo #include <iostream> using namespace std; int findMax(int a, int b, int c, int d){ int maxVal= ( (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d)? c : d ); return maxVal; } int main() { int a = 4, b = 13, c = 7, d = 53; cout<<"The greater element of the two elements is "<<findMax(a, b, c, d); return 0; } The greater element of the two elements is 53
[ { "code": null, "e": 1196, "s": 1062, "text": "In this problem, we are given some numbers. Our task is to create a Program\nto Find the Largest Number using Ternary Operator in C++." }, { "code": null, "e": 1218, "s": 1196, "text": "The elements can be −" }, { "code": null, "e": 1230, "s": 1218, "text": "Two Numbers" }, { "code": null, "e": 1244, "s": 1230, "text": "Three Numbers" }, { "code": null, "e": 1257, "s": 1244, "text": "Four Numbers" }, { "code": null, "e": 1415, "s": 1257, "text": "Code Description − Here, we are given some numbers (two or three or four). We need to find the maximum element out of these numbers using a ternary\noperator." }, { "code": null, "e": 1468, "s": 1415, "text": "Let’s take a few examples to understand the problem," }, { "code": null, "e": 1482, "s": 1468, "text": "Input − 4, 54" }, { "code": null, "e": 1494, "s": 1482, "text": "Output − 54" }, { "code": null, "e": 1513, "s": 1494, "text": "Input − 14, 40, 26" }, { "code": null, "e": 1525, "s": 1513, "text": "Output − 40" }, { "code": null, "e": 1548, "s": 1525, "text": "Input − 10, 54, 26, 62" }, { "code": null, "e": 1560, "s": 1548, "text": "Output − 62" }, { "code": null, "e": 1667, "s": 1560, "text": "We will use ternary Operator, for two, three and four element for finding the\nmaximum element of the four." }, { "code": null, "e": 1701, "s": 1667, "text": "Implementing Ternary operator for" }, { "code": null, "e": 1721, "s": 1701, "text": "Two numbers (a, b)," }, { "code": null, "e": 1735, "s": 1721, "text": "a > b ? a : b" }, { "code": null, "e": 1760, "s": 1735, "text": "Three numbers (a, b, c)," }, { "code": null, "e": 1802, "s": 1760, "text": "(a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c)" }, { "code": null, "e": 1829, "s": 1802, "text": "Four numbers (a, b, c, d)," }, { "code": null, "e": 1905, "s": 1829, "text": "(a>b && a>c && a>d) ?\n a :\n (b>c && b>d) ?\n b :\n (c>d)? c : d" }, { "code": null, "e": 1973, "s": 1905, "text": "Program to illustrate the working of our solution for two numbers −" }, { "code": null, "e": 1984, "s": 1973, "text": " Live Demo" }, { "code": null, "e": 2150, "s": 1984, "text": "#include <iostream>\nusing namespace std;\nint main() {\n int a = 4, b = 9;\n cout<<\"The greater element of the two elements is \"<<( (a > b) ? a :b );\n return 0;\n}" }, { "code": null, "e": 2195, "s": 2150, "text": "The greater element of the two elements is 9" }, { "code": null, "e": 2265, "s": 2195, "text": "Program to illustrate the working of our solution for three numbers −" }, { "code": null, "e": 2276, "s": 2265, "text": " Live Demo" }, { "code": null, "e": 2572, "s": 2276, "text": "#include <iostream>\nusing namespace std;\nint findMax(int a, int b, int c){\n int maxVal = (a>b) ?\n ((a>c) ?\n a : c) :\n ((b>c) ?\n b : c);\n return maxVal;\n}\nint main() {\n int a = 4, b = 13, c = 7;\n cout<<\"The greater element of the two elements is \"<<findMax(a, b,c);\n return 0;\n}" }, { "code": null, "e": 2618, "s": 2572, "text": "The greater element of the two elements is 13" }, { "code": null, "e": 2687, "s": 2618, "text": "Program to illustrate the working of our solution for four numbers −" }, { "code": null, "e": 2698, "s": 2687, "text": " Live Demo" }, { "code": null, "e": 3020, "s": 2698, "text": "#include <iostream>\nusing namespace std;\nint findMax(int a, int b, int c, int d){\n int maxVal= ( (a>b && a>c && a>d) ? a : (b>c && b>d) ? b : (c>d)? c : d );\n return maxVal;\n}\nint main() {\n int a = 4, b = 13, c = 7, d = 53;\n cout<<\"The greater element of the two elements is \"<<findMax(a, b, c, d);\n return 0;\n}" }, { "code": null, "e": 3066, "s": 3020, "text": "The greater element of the two elements is 53" } ]
Deploying a Keras Deep Learning Model as a Web Application in Python | by Will Koehrsen | Towards Data Science
Building a cool machine learning project is one thing, but at the end of the day, you want other people to be able to see your hard work. Sure, you could put the whole project on GitHub, but how are your grandparents supposed to figure that out? No, what we want is to deploy our deep learning model as a web application accessible to anyone in the world. In this article, we’ll see how to write a web application that takes a trained Keras recurrent neural network and allows users to generate new patent abstracts. This project builds on work from the Recurrent Neural Networks by Example article, but knowing how to create the RNN isn’t necessary. We’ll just treat it as a black box for now: we put in a starting sequence, and it outputs an entirely new patent abstract that we can display in the browser! Traditionally, data scientists develop the models and front end engineers show them to the world. In this project, we’ll have to play both roles, and dive into web development (almost all in Python though). This project requires joining together numerous topics: Flask: creating a basic web application in Python Keras: deploying a trained recurrent neural network Templating with the Jinja template library HTML and CSS for writing web pages The final result is a web application that allows users to generate entirely new patent abstracts with a trained recurrent neural network: The complete code for this project is available on GitHub. The goal was to get a web application up and running as quickly as possible. For that, I went with Flask, which allows us to write the app in Python. I don’t like to mess with styling (which clearly shows) so almost all of the CSS is copied and pasted. This article by the Keras team was helpful for the basics and this article is a useful guide as well. Overall, this project adheres to my design principles: get a prototype up and running quickly — copying and pasting as much as required — and then iterate to make a better product. The quickest way to build a web app in Python is with Flask. To make our own app, we can use just the following: from flask import Flaskapp = Flask(__name__)@app.route("/")def hello(): return "<h1>Not Much Going On Here</h1>"app.run(host='0.0.0.0', port=50000) If you copy and paste this code and run it, you’ll be able to view your own web app at localhost:50000. Of course, we want to do more than that, so we’ll use a slightly more complicated function which basically does the same thing: handles requests from your browser and serves up some content as HTML. For our main page, we want to present the user with a form to enter some details. When our users arrive at the main page of the application, we’ll show them a form with three parameters to select: Input a starting sequence for RNN or select randomlyChoose diversity of RNN predictionsChoose the number of words RNN outputs Input a starting sequence for RNN or select randomly Choose diversity of RNN predictions Choose the number of words RNN outputs To build a form in Python we’ll use wtforms .The code to make the form is: This creates a form shown below (with styling from main.css): The validator in the code make sure the user enters the correct information. For example, we check all boxes are filled and that the diversity is between 0.5 and 5. These conditions must be met for the form to be accepted. The way we actually serve the form is with Flask is using templates. A template is a document with a basic framework that we need to fill in with details. For a Flask web application, we can use the Jinja templating library to pass Python code to an HTML document. For example, in our main function, we’ll send the contents of the form to a template called index.html. When the user arrives on the home page, our app will serve up index.html with the details from form. The template is a simple html scaffolding where we refer to python variables with {{variable}} syntax. For each of the errors in the form (those entries that can’t be validated) an error will flash. Other than that, this file will show the form as above. When the user enters information and hits submit (a POST request) if the information is correct, we want to divert the input to the appropriate function to make predictions with the trained RNN. This means modifying home() . Now, when the user hits submit and the information is correct, the input is sent either to generate_random_start or generate_from_seed depending on the input. These functions use the trained Keras model to generate a novel patent with a diversity and num_words specified by the user. The output of these functions in turn is sent to either of the templates random.html or seeded.html to be served as a web page. The model parameter is the trained Keras model which load in as follows: (The tf.get_default_graph() is a workaround based on this gist.) I won’t show the entirety of the two util functions (here is the code), and all you need to understand is they take the trained Keras model along with the parameters and make predictions of a new patent abstract. These functions both return a Python string with formatted HTML. This string is sent to another template to be rendered as a web page. For example, the generate_random_start returns formatted html which goes into random.html: Here we are again using the Jinja template engine to display the formatted HTML. Since the Python string is already formatted as HTML, all we have to do is use {{input|safe}} (where input is the Python variable) to display it. We can then style this page in main.css as with the other html templates. The functiongenerate_random_start picks a random patent abstract as the starting sequence and makes predictions building from it. It then displays the starting sequence, RNN generated output, and the actual output: The functiongenerate_from_seed takes a user-supplied starting sequence and then builds off of it using the trained RNN. The output appears as follows: While the results are not always entirely on-point, they do show the recurrent neural network has learned the basics of English. It was trained to predict the next word from the previous 50 words and has picked up how to write a slightly-convincing patent abstract! Depending on the diversity of the predictions, the output might appear to be completely random or a loop. To run the app for yourself, all you need to do is download the repository, navigate to the deployment directory and type python run_keras_server.py . This will immediately make the web app available at localhost:10000. Depending on how your home WiFi is configured, you should be able to access the application from any computer on the network using your IP address. The web application running on your personal computer is great for sharing with friends and family. I’d definitely not recommend opening this up to everyone on your home network though! For that, we’ll want to set the app up on an AWS EC2 instance and serve it to the world (coming later) . To improve the app, we can alter the styling (through main.css ) and perhaps add more options, such as the ability to choose the pre-trained network. The great thing about personal projects is you can take them as far as you want. If you want to play around with the app, download the code and get started. In this article, we saw how to deploy a trained Keras deep learning model as a web application. This requires bringing together a number of different technologies including recurrent neural networks, web applications, templating, HTML, CSS, and of course Python. While this is only a basic application, it shows that you can start building web applications using deep learning with relatively little effort. There aren’t many people who can say they’ve deployed a deep learning model as a web application, but if you follow this article, count yourself among them! As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or through my personal website willk.online. submit = SubmitField("Enter") Loading in Trained Model
[ { "code": null, "e": 528, "s": 172, "text": "Building a cool machine learning project is one thing, but at the end of the day, you want other people to be able to see your hard work. Sure, you could put the whole project on GitHub, but how are your grandparents supposed to figure that out? No, what we want is to deploy our deep learning model as a web application accessible to anyone in the world." }, { "code": null, "e": 981, "s": 528, "text": "In this article, we’ll see how to write a web application that takes a trained Keras recurrent neural network and allows users to generate new patent abstracts. This project builds on work from the Recurrent Neural Networks by Example article, but knowing how to create the RNN isn’t necessary. We’ll just treat it as a black box for now: we put in a starting sequence, and it outputs an entirely new patent abstract that we can display in the browser!" }, { "code": null, "e": 1188, "s": 981, "text": "Traditionally, data scientists develop the models and front end engineers show them to the world. In this project, we’ll have to play both roles, and dive into web development (almost all in Python though)." }, { "code": null, "e": 1244, "s": 1188, "text": "This project requires joining together numerous topics:" }, { "code": null, "e": 1294, "s": 1244, "text": "Flask: creating a basic web application in Python" }, { "code": null, "e": 1346, "s": 1294, "text": "Keras: deploying a trained recurrent neural network" }, { "code": null, "e": 1389, "s": 1346, "text": "Templating with the Jinja template library" }, { "code": null, "e": 1424, "s": 1389, "text": "HTML and CSS for writing web pages" }, { "code": null, "e": 1563, "s": 1424, "text": "The final result is a web application that allows users to generate entirely new patent abstracts with a trained recurrent neural network:" }, { "code": null, "e": 1622, "s": 1563, "text": "The complete code for this project is available on GitHub." }, { "code": null, "e": 1977, "s": 1622, "text": "The goal was to get a web application up and running as quickly as possible. For that, I went with Flask, which allows us to write the app in Python. I don’t like to mess with styling (which clearly shows) so almost all of the CSS is copied and pasted. This article by the Keras team was helpful for the basics and this article is a useful guide as well." }, { "code": null, "e": 2158, "s": 1977, "text": "Overall, this project adheres to my design principles: get a prototype up and running quickly — copying and pasting as much as required — and then iterate to make a better product." }, { "code": null, "e": 2271, "s": 2158, "text": "The quickest way to build a web app in Python is with Flask. To make our own app, we can use just the following:" }, { "code": null, "e": 2422, "s": 2271, "text": "from flask import Flaskapp = Flask(__name__)@app.route(\"/\")def hello(): return \"<h1>Not Much Going On Here</h1>\"app.run(host='0.0.0.0', port=50000)" }, { "code": null, "e": 2807, "s": 2422, "text": "If you copy and paste this code and run it, you’ll be able to view your own web app at localhost:50000. Of course, we want to do more than that, so we’ll use a slightly more complicated function which basically does the same thing: handles requests from your browser and serves up some content as HTML. For our main page, we want to present the user with a form to enter some details." }, { "code": null, "e": 2922, "s": 2807, "text": "When our users arrive at the main page of the application, we’ll show them a form with three parameters to select:" }, { "code": null, "e": 3048, "s": 2922, "text": "Input a starting sequence for RNN or select randomlyChoose diversity of RNN predictionsChoose the number of words RNN outputs" }, { "code": null, "e": 3101, "s": 3048, "text": "Input a starting sequence for RNN or select randomly" }, { "code": null, "e": 3137, "s": 3101, "text": "Choose diversity of RNN predictions" }, { "code": null, "e": 3176, "s": 3137, "text": "Choose the number of words RNN outputs" }, { "code": null, "e": 3251, "s": 3176, "text": "To build a form in Python we’ll use wtforms .The code to make the form is:" }, { "code": null, "e": 3313, "s": 3251, "text": "This creates a form shown below (with styling from main.css):" }, { "code": null, "e": 3536, "s": 3313, "text": "The validator in the code make sure the user enters the correct information. For example, we check all boxes are filled and that the diversity is between 0.5 and 5. These conditions must be met for the form to be accepted." }, { "code": null, "e": 3605, "s": 3536, "text": "The way we actually serve the form is with Flask is using templates." }, { "code": null, "e": 3905, "s": 3605, "text": "A template is a document with a basic framework that we need to fill in with details. For a Flask web application, we can use the Jinja templating library to pass Python code to an HTML document. For example, in our main function, we’ll send the contents of the form to a template called index.html." }, { "code": null, "e": 4109, "s": 3905, "text": "When the user arrives on the home page, our app will serve up index.html with the details from form. The template is a simple html scaffolding where we refer to python variables with {{variable}} syntax." }, { "code": null, "e": 4261, "s": 4109, "text": "For each of the errors in the form (those entries that can’t be validated) an error will flash. Other than that, this file will show the form as above." }, { "code": null, "e": 4486, "s": 4261, "text": "When the user enters information and hits submit (a POST request) if the information is correct, we want to divert the input to the appropriate function to make predictions with the trained RNN. This means modifying home() ." }, { "code": null, "e": 4898, "s": 4486, "text": "Now, when the user hits submit and the information is correct, the input is sent either to generate_random_start or generate_from_seed depending on the input. These functions use the trained Keras model to generate a novel patent with a diversity and num_words specified by the user. The output of these functions in turn is sent to either of the templates random.html or seeded.html to be served as a web page." }, { "code": null, "e": 4971, "s": 4898, "text": "The model parameter is the trained Keras model which load in as follows:" }, { "code": null, "e": 5036, "s": 4971, "text": "(The tf.get_default_graph() is a workaround based on this gist.)" }, { "code": null, "e": 5249, "s": 5036, "text": "I won’t show the entirety of the two util functions (here is the code), and all you need to understand is they take the trained Keras model along with the parameters and make predictions of a new patent abstract." }, { "code": null, "e": 5475, "s": 5249, "text": "These functions both return a Python string with formatted HTML. This string is sent to another template to be rendered as a web page. For example, the generate_random_start returns formatted html which goes into random.html:" }, { "code": null, "e": 5776, "s": 5475, "text": "Here we are again using the Jinja template engine to display the formatted HTML. Since the Python string is already formatted as HTML, all we have to do is use {{input|safe}} (where input is the Python variable) to display it. We can then style this page in main.css as with the other html templates." }, { "code": null, "e": 5991, "s": 5776, "text": "The functiongenerate_random_start picks a random patent abstract as the starting sequence and makes predictions building from it. It then displays the starting sequence, RNN generated output, and the actual output:" }, { "code": null, "e": 6142, "s": 5991, "text": "The functiongenerate_from_seed takes a user-supplied starting sequence and then builds off of it using the trained RNN. The output appears as follows:" }, { "code": null, "e": 6514, "s": 6142, "text": "While the results are not always entirely on-point, they do show the recurrent neural network has learned the basics of English. It was trained to predict the next word from the previous 50 words and has picked up how to write a slightly-convincing patent abstract! Depending on the diversity of the predictions, the output might appear to be completely random or a loop." }, { "code": null, "e": 6734, "s": 6514, "text": "To run the app for yourself, all you need to do is download the repository, navigate to the deployment directory and type python run_keras_server.py . This will immediately make the web app available at localhost:10000." }, { "code": null, "e": 6882, "s": 6734, "text": "Depending on how your home WiFi is configured, you should be able to access the application from any computer on the network using your IP address." }, { "code": null, "e": 7173, "s": 6882, "text": "The web application running on your personal computer is great for sharing with friends and family. I’d definitely not recommend opening this up to everyone on your home network though! For that, we’ll want to set the app up on an AWS EC2 instance and serve it to the world (coming later) ." }, { "code": null, "e": 7480, "s": 7173, "text": "To improve the app, we can alter the styling (through main.css ) and perhaps add more options, such as the ability to choose the pre-trained network. The great thing about personal projects is you can take them as far as you want. If you want to play around with the app, download the code and get started." }, { "code": null, "e": 7743, "s": 7480, "text": "In this article, we saw how to deploy a trained Keras deep learning model as a web application. This requires bringing together a number of different technologies including recurrent neural networks, web applications, templating, HTML, CSS, and of course Python." }, { "code": null, "e": 8045, "s": 7743, "text": "While this is only a basic application, it shows that you can start building web applications using deep learning with relatively little effort. There aren’t many people who can say they’ve deployed a deep learning model as a web application, but if you follow this article, count yourself among them!" }, { "code": null, "e": 8191, "s": 8045, "text": "As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or through my personal website willk.online." }, { "code": null, "e": 8221, "s": 8191, "text": "submit = SubmitField(\"Enter\")" } ]
How to display image from database in Django
Theory of Computation In this article, you will learn how to display images from the MySQL database using Django. In the previous post, we have explained how to upload an image using Django. The uploaded image is stored into a static directory. In most of the applications, we may need the display image somewhere in the application. Django comes with pre-defined packages and methods that make this task easier. Django is a free, open-source python-based framework. It enables fast development of any type of web applications. It is secure, maintainable, portable and scalable. The main advantages of using Django are that it has fully loaded common web development tasks, like administration, authentication, site maps etc. If you had not installed the Django package, please follow the Django documentation for initial setup. Suppose we have the following MySQL table 'gallery' - CREATE TABLE IF NOT EXISTS `gallery` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` char(200) NOT NULL, `img` varchar(200) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8; INSERT INTO `gallery` (`id`, `title`, `img`) VALUES (9, 'Flowers', 'media/flowers.jpg'), (10, 'Deer', 'media/deer.jpg'), (11, 'Cat', 'media/cat.jpg'); A model is a definitive source of information about your data. Each model maps a single database table and each attribute represents a database field. The given model defines a gallery which has an image title and image source. from django.db import models class GetImage(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to="media") class Meta: db_table = "gallery" First, configure the database. We need to tell Django we're going to use the MySQL database. Do this by editing your settings file and changing the DATABASES setting to add the name of the database with configurations. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'demo', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } Also, add the following codes in your settings file. MEDIA_URL is the URL that will serve the media files and MEDIA_ROOT is the path to the root directory where the files are getting stored. MEDIA_ROOT = os.path.join(BASE_DIR, 'image') MEDIA_URL = '/image/' Next, we have created a template directory under 'imageapp' app and where we have created an HTML template file 'show.html' that calls on the browser for displaying images. <!DOCTYPE html> <html lang="en"> <head> <title>Django Display Images</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>Title</th> <th>Image</th> </tr> </thead> <tbody> {% for img in images %} <tr> <td>{{img.title}}</td> <td><img src="/{{ BASIC_DIR }}/{{img.img}}" width="120"/></td> </tr> {% endfor %} </tbody> </table> </div> </body> </html> We have placed the following code in 'views.py'. from django.shortcuts import render,redirect from imageapp.models import GetImage # Create your views here. def display_images(request): # getting all the objects of hotel. allimages = GetImage.objects.all() return render(request, 'show.html',{'images' : allimages}) At last, we have added a path to the route page to the particular link. Make sure you've got your MEDIA_URL and MEDIA_ROOT correct in your settings.py then you can append the following to your url conf - from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static from imageapp import views urlpatterns = [ path('show', views.display_images), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When we migrate and run the application, we will get the result something like this - Jan 3 Stateful vs Stateless A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities... A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities... Dec 29 Best programming language to learn in 2021 In this article, we have mentioned the analyzed results of the best programming language for 2021... In this article, we have mentioned the analyzed results of the best programming language for 2021... Dec 20 How is Python best for mobile app development? Python has a set of useful Libraries and Packages that minimize the use of code... Python has a set of useful Libraries and Packages that minimize the use of code... July 18 Learn all about Emoji In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more... In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more... Jan 10 Data Science Recruitment of Freshers In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician... In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician... eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 503, "s": 112, "text": "In this article, you will learn how to display images from the MySQL database using Django. In the previous post, we have explained how to upload an image using Django. The uploaded image is stored into a static directory. In most of the applications, we may need the display image somewhere in the application. Django comes with pre-defined packages and methods that make this task easier." }, { "code": null, "e": 919, "s": 503, "text": "Django is a free, open-source python-based framework. It enables fast development of any type of web applications. It is secure, maintainable, portable and scalable. The main advantages of using Django are that it has fully loaded common web development tasks, like administration, authentication, site maps etc. If you had not installed the Django package, please follow the Django documentation for initial setup." }, { "code": null, "e": 973, "s": 919, "text": "Suppose we have the following MySQL table 'gallery' -" }, { "code": null, "e": 1190, "s": 973, "text": "CREATE TABLE IF NOT EXISTS `gallery` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `title` char(200) NOT NULL,\n `img` varchar(200) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=MyISAM AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;" }, { "code": null, "e": 1341, "s": 1190, "text": "INSERT INTO `gallery` (`id`, `title`, `img`) VALUES\n(9, 'Flowers', 'media/flowers.jpg'),\n(10, 'Deer', 'media/deer.jpg'),\n(11, 'Cat', 'media/cat.jpg');" }, { "code": null, "e": 1569, "s": 1341, "text": "A model is a definitive source of information about your data. Each model maps a single database table and each attribute represents a database field. The given model defines a gallery which has an image title and image source." }, { "code": null, "e": 1769, "s": 1569, "text": "from django.db import models\n\nclass GetImage(models.Model): \n title = models.CharField(max_length=100)\n img = models.ImageField(upload_to=\"media\")\n class Meta:\n db_table = \"gallery\"" }, { "code": null, "e": 1988, "s": 1769, "text": "First, configure the database. We need to tell Django we're going to use the MySQL database. Do this by editing your settings file and changing the DATABASES setting to add the name of the database with configurations." }, { "code": null, "e": 2197, "s": 1988, "text": "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'demo',\n 'USER': 'root',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '3306'\n }\n}" }, { "code": null, "e": 2388, "s": 2197, "text": "Also, add the following codes in your settings file. MEDIA_URL is the URL that will serve the media files and MEDIA_ROOT is the path to the root directory where the files are getting stored." }, { "code": null, "e": 2457, "s": 2388, "text": "MEDIA_ROOT = os.path.join(BASE_DIR, 'image') \nMEDIA_URL = '/image/'" }, { "code": null, "e": 2630, "s": 2457, "text": "Next, we have created a template directory under 'imageapp' app and where we have created an HTML template file 'show.html' that calls on the browser for displaying images." }, { "code": null, "e": 3212, "s": 2630, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <title>Django Display Images</title>\n <meta charset=\"utf-8\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\">\n</head>\n<body>\n<div class=\"container\">\n<table class=\"table table-striped\">\n <thead>\n <tr>\n\t\t<th>Title</th>\n\t\t<th>Image</th>\n </tr>\n </thead>\n <tbody>\n\t{% for img in images %} \n <tr>\n <td>{{img.title}}</td>\n\t\t<td><img src=\"/{{ BASIC_DIR }}/{{img.img}}\" width=\"120\"/></td>\n </tr>\n\t {% endfor %} \n\t</tbody>\n</table>\t\n</div>\n</body>\n</html>" }, { "code": null, "e": 3261, "s": 3212, "text": "We have placed the following code in 'views.py'." }, { "code": null, "e": 3550, "s": 3261, "text": "from django.shortcuts import render,redirect\nfrom imageapp.models import GetImage \n\n# Create your views here.\ndef display_images(request): \n \n # getting all the objects of hotel. \n allimages = GetImage.objects.all() \n return render(request, 'show.html',{'images' : allimages})\n" }, { "code": null, "e": 3754, "s": 3550, "text": "At last, we have added a path to the route page to the particular link. Make sure you've got your MEDIA_URL and MEDIA_ROOT correct in your settings.py then you can append the following to your url conf -" }, { "code": null, "e": 4113, "s": 3754, "text": "from django.contrib import admin\nfrom django.urls import path\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom imageapp import views\n\nurlpatterns = [\n path('show', views.display_images),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)" }, { "code": null, "e": 4199, "s": 4113, "text": "When we migrate and run the application, we will get the result something like this -" }, { "code": null, "e": 4345, "s": 4199, "text": "\nJan 3\nStateful vs Stateless\nA Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...\n" }, { "code": null, "e": 4461, "s": 4345, "text": "A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities..." }, { "code": null, "e": 4614, "s": 4461, "text": "\nDec 29\nBest programming language to learn in 2021\nIn this article, we have mentioned the analyzed results of the best programming language for 2021...\n" }, { "code": null, "e": 4715, "s": 4614, "text": "In this article, we have mentioned the analyzed results of the best programming language for 2021..." }, { "code": null, "e": 4854, "s": 4715, "text": "\nDec 20\nHow is Python best for mobile app development?\nPython has a set of useful Libraries and Packages that minimize the use of code...\n" }, { "code": null, "e": 4937, "s": 4854, "text": "Python has a set of useful Libraries and Packages that minimize the use of code..." }, { "code": null, "e": 5103, "s": 4937, "text": "\nJuly 18\nLearn all about Emoji\nIn this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...\n" }, { "code": null, "e": 5237, "s": 5103, "text": "In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more..." }, { "code": null, "e": 5404, "s": 5237, "text": "\nJan 10\nData Science Recruitment of Freshers\nIn this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...\n" }, { "code": null, "e": 5525, "s": 5404, "text": "In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician..." } ]
How to find the sum of every n values if missing values exists in the R data frame?
To find the sum of every n values in R data frame columns if there exist missing values, we can use rowsum function along with rep function that will repeat the sum for rows and na.rm=TRUE to exclude the rows with missing values. For example, if we have a data frame called df that contains 4 columns each containing twenty values with some missing values then we can find the row sums for every 5 rows by using the command rowsum(df,rep(1:5,each=4),na.rm=TRUE). Live Demo x1<-sample(c(NA,rpois(2,5)),20,replace=TRUE) x2<-sample(c(NA,rpois(2,10)),20,replace=TRUE) df1<-data.frame(x1,x2) df1 x1 x2 1 4 10 2 5 10 3 NA 7 4 4 7 5 4 NA 6 5 7 7 4 NA 8 NA NA 9 5 10 10 4 NA 11 NA NA 12 5 NA 13 4 NA 14 4 NA 15 5 NA 16 NA 10 17 NA NA 18 4 7 19 5 7 20 NA NA Finding the column sums for every 5 rows in df1 if missing values exists in the data frame − rowsum(df1,rep(1:5,each=4),na.rm=TRUE) x1 x2 1 13 34 2 13 7 3 14 10 4 13 10 5 9 14 Live Demo y1<-sample(c(NA,rnorm(2)),20,replace=TRUE) y2<-sample(c(NA,rnorm(2)),20,replace=TRUE) y3<-sample(c(NA,rnorm(2)),20,replace=TRUE) df2<-data.frame(y1,y2,y3) df2 y1 y2 y3 1 0.9563337 -1.1412663 0.1873961 2 2.4693175 0.5661012 0.1873961 3 NA 0.5661012 NA 4 2.4693175 NA 0.4860115 5 NA NA NA 6 0.9563337 NA NA 7 0.9563337 -1.1412663 0.1873961 8 2.4693175 -1.1412663 NA 9 0.9563337 NA 0.1873961 10 2.4693175 0.5661012 0.4860115 11 NA NA 0.4860115 12 NA -1.1412663 0.1873961 13 NA -1.1412663 NA 14 NA NA 0.1873961 15 0.9563337 -1.1412663 0.4860115 16 0.9563337 -1.1412663 0.1873961 17 NA NA 0.4860115 18 0.9563337 -1.1412663 NA 19 0.9563337 -1.1412663 NA 20 2.4693175 0.5661012 0.4860115 Finding the column sums for every 5 rows in df2 if missing values exists in the data frame − rowsum(df2,rep(1:5,each=4),na.rm=TRUE) y1 y2 y3 1 5.894969 -0.009063996 0.8608037 2 4.381985 -2.282532593 0.1873961 3 3.425651 -0.575165146 1.3468152 4 1.912667 -3.423798889 0.8608037 5 4.381985 -1.716431443 0.9720230
[ { "code": null, "e": 1525, "s": 1062, "text": "To find the sum of every n values in R data frame columns if there exist missing values, we can use rowsum function along with rep function that will repeat the sum for rows and na.rm=TRUE to exclude the rows with missing values. For example, if we have a data frame called df that contains 4 columns each containing twenty values with some missing values then we can find the row sums for every 5 rows by using the command rowsum(df,rep(1:5,each=4),na.rm=TRUE)." }, { "code": null, "e": 1536, "s": 1525, "text": " Live Demo" }, { "code": null, "e": 1654, "s": 1536, "text": "x1<-sample(c(NA,rpois(2,5)),20,replace=TRUE)\nx2<-sample(c(NA,rpois(2,10)),20,replace=TRUE)\ndf1<-data.frame(x1,x2)\ndf1" }, { "code": null, "e": 1904, "s": 1654, "text": " x1 x2\n1 4 10\n2 5 10\n3 NA 7\n4 4 7\n5 4 NA\n6 5 7\n7 4 NA\n8 NA NA\n9 5 10\n10 4 NA\n11 NA NA\n12 5 NA\n13 4 NA\n14 4 NA\n15 5 NA\n16 NA 10\n17 NA NA\n18 4 7\n19 5 7\n20 NA NA" }, { "code": null, "e": 1997, "s": 1904, "text": "Finding the column sums for every 5 rows in df1 if missing values exists in the data frame −" }, { "code": null, "e": 2036, "s": 1997, "text": "rowsum(df1,rep(1:5,each=4),na.rm=TRUE)" }, { "code": null, "e": 2102, "s": 2036, "text": " x1 x2\n1 13 34\n2 13 7\n3 14 10\n4 13 10\n5 9 14" }, { "code": null, "e": 2113, "s": 2102, "text": " Live Demo" }, { "code": null, "e": 2272, "s": 2113, "text": "y1<-sample(c(NA,rnorm(2)),20,replace=TRUE)\ny2<-sample(c(NA,rnorm(2)),20,replace=TRUE)\ny3<-sample(c(NA,rnorm(2)),20,replace=TRUE)\ndf2<-data.frame(y1,y2,y3)\ndf2" }, { "code": null, "e": 3050, "s": 2272, "text": " y1 y2 y3\n1 0.9563337 -1.1412663 0.1873961\n2 2.4693175 0.5661012 0.1873961\n3 NA 0.5661012 NA\n4 2.4693175 NA 0.4860115\n5 NA NA NA\n6 0.9563337 NA NA\n7 0.9563337 -1.1412663 0.1873961\n8 2.4693175 -1.1412663 NA\n9 0.9563337 NA 0.1873961\n10 2.4693175 0.5661012 0.4860115\n11 NA NA 0.4860115\n12 NA -1.1412663 0.1873961\n13 NA -1.1412663 NA\n14 NA NA 0.1873961\n15 0.9563337 -1.1412663 0.4860115\n16 0.9563337 -1.1412663 0.1873961\n17 NA NA 0.4860115\n18 0.9563337 -1.1412663 NA\n19 0.9563337 -1.1412663 NA\n20 2.4693175 0.5661012 0.4860115" }, { "code": null, "e": 3143, "s": 3050, "text": "Finding the column sums for every 5 rows in df2 if missing values exists in the data frame −" }, { "code": null, "e": 3182, "s": 3143, "text": "rowsum(df2,rep(1:5,each=4),na.rm=TRUE)" }, { "code": null, "e": 3400, "s": 3182, "text": " y1 y2 y3\n1 5.894969 -0.009063996 0.8608037\n2 4.381985 -2.282532593 0.1873961\n3 3.425651 -0.575165146 1.3468152\n4 1.912667 -3.423798889 0.8608037\n5 4.381985 -1.716431443 0.9720230" } ]
How to use if...else statement at the command line in Python?
There are multiple ways in which you can use if else construct in the command line in python. For example, bash supports multiline statements, which you can use like: $ python -c ' > a = True > if a: > print("a is true") > ' This will give the output: a is true If you prefer to have the python statement in a single line, you can use the \n newline between the commands. For example, $ python -c $'a = True\nif a: print("a is true");' This will give the output: a is true
[ { "code": null, "e": 1229, "s": 1062, "text": "There are multiple ways in which you can use if else construct in the command line in python. For example, bash supports multiline statements, which you can use like:" }, { "code": null, "e": 1287, "s": 1229, "text": "$ python -c '\n> a = True\n> if a:\n> print(\"a is true\")\n> '" }, { "code": null, "e": 1314, "s": 1287, "text": "This will give the output:" }, { "code": null, "e": 1324, "s": 1314, "text": "a is true" }, { "code": null, "e": 1447, "s": 1324, "text": "If you prefer to have the python statement in a single line, you can use the \\n newline between the commands. For example," }, { "code": null, "e": 1498, "s": 1447, "text": "$ python -c $'a = True\\nif a: print(\"a is true\");'" }, { "code": null, "e": 1525, "s": 1498, "text": "This will give the output:" }, { "code": null, "e": 1535, "s": 1525, "text": "a is true" } ]
Stack Program in C
We shall see the stack implementation in C programming language here. You can try the program by clicking on the Try-it button. To learn the theory aspect of stacks, click on visit previous page. #include <stdio.h> int MAXSIZE = 8; int stack[8]; int top = -1; int isempty() { if(top == -1) return 1; else return 0; } int isfull() { if(top == MAXSIZE) return 1; else return 0; } int peek() { return stack[top]; } int pop() { int data; if(!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.\n"); } } int push(int data) { if(!isfull()) { top = top + 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.\n"); } } int main() { // push items on to the stack push(3); push(5); push(9); push(1); push(12); push(15); printf("Element at top of the stack: %d\n" ,peek()); printf("Elements: \n"); // print stack data while(!isempty()) { int data = pop(); printf("%d\n",data); } printf("Stack full: %s\n" , isfull()?"true":"false"); printf("Stack empty: %s\n" , isempty()?"true":"false"); return 0; } If we compile and run the above program, it will produce the following result − Element at top of the stack: 15 Elements: 15 12 1 9 5 3 Stack full: false Stack empty: true 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2776, "s": 2580, "text": "We shall see the stack implementation in C programming language here. You can try the program by clicking on the Try-it button. To learn the theory aspect of stacks, click on visit previous page." }, { "code": null, "e": 3872, "s": 2776, "text": "#include <stdio.h>\n\nint MAXSIZE = 8; \nint stack[8]; \nint top = -1; \n\nint isempty() {\n\n if(top == -1)\n return 1;\n else\n return 0;\n}\n \nint isfull() {\n\n if(top == MAXSIZE)\n return 1;\n else\n return 0;\n}\n\nint peek() {\n return stack[top];\n}\n\nint pop() {\n int data;\n\t\n if(!isempty()) {\n data = stack[top];\n top = top - 1; \n return data;\n } else {\n printf(\"Could not retrieve data, Stack is empty.\\n\");\n }\n}\n\nint push(int data) {\n\n if(!isfull()) {\n top = top + 1; \n stack[top] = data;\n } else {\n printf(\"Could not insert data, Stack is full.\\n\");\n }\n}\n\nint main() {\n // push items on to the stack \n push(3);\n push(5);\n push(9);\n push(1);\n push(12);\n push(15);\n\n printf(\"Element at top of the stack: %d\\n\" ,peek());\n printf(\"Elements: \\n\");\n\n // print stack data \n while(!isempty()) {\n int data = pop();\n printf(\"%d\\n\",data);\n }\n\n printf(\"Stack full: %s\\n\" , isfull()?\"true\":\"false\");\n printf(\"Stack empty: %s\\n\" , isempty()?\"true\":\"false\");\n \n return 0;\n}" }, { "code": null, "e": 3952, "s": 3872, "text": "If we compile and run the above program, it will produce the following result −" }, { "code": null, "e": 4049, "s": 3952, "text": "Element at top of the stack: 15\nElements:\n15\n12\n1 \n9 \n5 \n3 \nStack full: false\nStack empty: true\n" }, { "code": null, "e": 4084, "s": 4049, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4096, "s": 4084, "text": " Ravi Kiran" }, { "code": null, "e": 4131, "s": 4096, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 4150, "s": 4131, "text": " Arnab Chakraborty" }, { "code": null, "e": 4185, "s": 4150, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4200, "s": 4185, "text": " Parth Panjabi" }, { "code": null, "e": 4233, "s": 4200, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 4252, "s": 4233, "text": " Arnab Chakraborty" }, { "code": null, "e": 4286, "s": 4252, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4314, "s": 4286, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4350, "s": 4314, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 4378, "s": 4350, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4385, "s": 4378, "text": " Print" }, { "code": null, "e": 4396, "s": 4385, "text": " Add Notes" } ]
SQL Tryit Editor v1.6
SELECT * FROM Customers WHERE City LIKE '_ondon'; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, Opera, and Edge(79). If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 24, "s": 0, "text": "SELECT * FROM Customers" }, { "code": null, "e": 50, "s": 24, "text": "WHERE City LIKE '_ondon';" }, { "code": null, "e": 52, "s": 50, "text": "​" }, { "code": null, "e": 115, "s": 52, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 175, "s": 115, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 243, "s": 175, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 281, "s": 243, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 366, "s": 281, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 540, "s": 366, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 591, "s": 540, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 659, "s": 591, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 830, "s": 659, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 930, "s": 830, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 990, "s": 930, "text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)." } ]
How to convert an integer into a date object in Python?
You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp. import datetime timestamp = datetime.datetime.fromtimestamp(1500000000) print(timestamp.strftime('%Y-%m-%d %H:%M:%S')) This will give the output − 2017-07-14 08:10:00
[ { "code": null, "e": 1270, "s": 1062, "text": "You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp." }, { "code": null, "e": 1389, "s": 1270, "text": "import datetime\ntimestamp = datetime.datetime.fromtimestamp(1500000000)\nprint(timestamp.strftime('%Y-%m-%d %H:%M:%S'))" }, { "code": null, "e": 1417, "s": 1389, "text": "This will give the output −" }, { "code": null, "e": 1437, "s": 1417, "text": "2017-07-14 08:10:00" } ]
How to “return an object” in C++?
An object is an instance of a class. Memory is only allocated when an object is created and not when a class is defined. An object can be returned by a function using the return keyword. A program that demonstrates this is given as follows − Live Demo #include <iostream> using namespace std; class Point { private: int x; int y; public: Point(int x1 = 0, int y1 = 0) { x = x1; y = y1; } Point addPoint(Point p) { Point temp; temp.x = x + p.x; temp.y = y + p.y; return temp; } void display() { cout<<"x = "<< x <<"\n"; cout<<"y = "<< y <<"\n"; } }; int main() { Point p1(5,3); Point p2(12,6); Point p3; cout<<"Point 1\n"; p1.display(); cout<<"Point 2\n"; p2.display(); p3 = p1.addPoint(p2); cout<<"The sum of the two points is:\n"; p3.display(); return 0; } The output of the above program is as follows. Point 1 x = 5 y = 3 Point 2 x = 12 y = 6 The sum of the two points is: x = 17 y = 9 Now, let us understand the above program. The class Point has two data members i.e. x and y. It has a parameterized constructor and also 2 member functions. The function addPoint() adds two Point values and returns an object temp that stores the sum. The function display() prints the values of x and y. The code snippet for this is given as follows. class Point { private: int x; int y; public: Point(int x1 = 0, int y1 = 0) { x = x1; y = y1; } Point addPoint(Point p) { Point temp; temp.x = x + p.x; temp.y = y + p.y; return temp; } void display() { cout<<"x = "<< x <<"\n"; cout<<"y = "<< y <<"\n"; } }; In the function main(), 3 objects of class Point are created. First values of p1 and p2 are displayed. Then the sum of values in p1 and p2 is found and stored in p3 by calling function addPoint(). Value of p3 is displayed. The code snippet for this is given as follows. Point p1(5,3); Point p2(12,6); Point p3; cout<<"Point 1\n"; p1.display(); cout<<"Point 2\n"; p2.display(); p3 = p1.addPoint(p2); cout<<"The sum of the two points is:\n"; p3.display();
[ { "code": null, "e": 1183, "s": 1062, "text": "An object is an instance of a class. Memory is only allocated when an object is created and not when a class is defined." }, { "code": null, "e": 1304, "s": 1183, "text": "An object can be returned by a function using the return keyword. A program that demonstrates this is given as follows −" }, { "code": null, "e": 1315, "s": 1304, "text": " Live Demo" }, { "code": null, "e": 1932, "s": 1315, "text": "#include <iostream>\nusing namespace std;\nclass Point {\n private:\n int x;\n int y;\n public:\n Point(int x1 = 0, int y1 = 0) {\n x = x1;\n y = y1;\n }\n Point addPoint(Point p) {\n Point temp;\n temp.x = x + p.x;\n temp.y = y + p.y;\n return temp;\n }\n void display() {\n cout<<\"x = \"<< x <<\"\\n\";\n cout<<\"y = \"<< y <<\"\\n\";\n }\n};\nint main() {\n Point p1(5,3);\n Point p2(12,6);\n Point p3;\n cout<<\"Point 1\\n\";\n p1.display();\n cout<<\"Point 2\\n\";\n p2.display();\n p3 = p1.addPoint(p2);\n cout<<\"The sum of the two points is:\\n\";\n p3.display();\n return 0;\n}" }, { "code": null, "e": 1979, "s": 1932, "text": "The output of the above program is as follows." }, { "code": null, "e": 2063, "s": 1979, "text": "Point 1\nx = 5\ny = 3\nPoint 2\nx = 12\ny = 6\nThe sum of the two points is:\nx = 17\ny = 9" }, { "code": null, "e": 2105, "s": 2063, "text": "Now, let us understand the above program." }, { "code": null, "e": 2414, "s": 2105, "text": "The class Point has two data members i.e. x and y. It has a parameterized constructor and also 2 member functions. The function addPoint() adds two Point values and returns an object temp that stores the sum. The function display() prints the values of x and y. The code snippet for this is given as follows." }, { "code": null, "e": 2748, "s": 2414, "text": "class Point {\n private:\n int x;\n int y;\n public:\n Point(int x1 = 0, int y1 = 0) {\n x = x1;\n y = y1;\n }\n Point addPoint(Point p) {\n Point temp;\n temp.x = x + p.x;\n temp.y = y + p.y;\n return temp;\n }\n void display() {\n cout<<\"x = \"<< x <<\"\\n\";\n cout<<\"y = \"<< y <<\"\\n\";\n }\n};" }, { "code": null, "e": 3018, "s": 2748, "text": "In the function main(), 3 objects of class Point are created. First values of p1 and p2 are displayed. Then the sum of values in p1 and p2 is found and stored in p3 by calling function addPoint(). Value of p3 is displayed. The code snippet for this is given as follows." }, { "code": null, "e": 3202, "s": 3018, "text": "Point p1(5,3);\nPoint p2(12,6);\nPoint p3;\ncout<<\"Point 1\\n\";\np1.display();\ncout<<\"Point 2\\n\";\np2.display();\np3 = p1.addPoint(p2);\ncout<<\"The sum of the two points is:\\n\";\np3.display();" } ]
Python – Get next key in Dictionary
30 Dec, 2021 Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the next key in order of dictionary. This can have application as from Python 3.6 onwards the dictionaries are ordered. Lets discuss certain ways in which this task can be performed. Method #1 : Using index() + loop (O (n)) The combination of above functions can be used to perform this task. In this, we perform the conversion of dictionary elements to list. And then index() is used to check for index and append the index count to get the next item. Python3 # Python3 code to demonstrate working of# Get next key in Dictionary# Using index() + loop # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing keytest_key = 'is' # Get next key in Dictionary# Using index() + looptemp = list(test_dict)try: res = temp[temp.index(test_key) + 1]except (ValueError, IndexError): res = None # printing resultprint("The next key is : " + str(res)) The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2} The next key is : best Method #2 : Using iter() + next() (O (n)) This is yet another way in which this task can be performed. In this, we convert the dictionary to iterator using iter() and then extract the next key using next(). Python3 # Python3 code to demonstrate working of# Get next key in Dictionary# Using iter() + next() # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing keytest_key = 'is' # Get next key in Dictionary# Using iter() + next()res = Nonetemp = iter(test_dict)for key in temp: if key == test_key: res = next(temp, None) # printing resultprint("The next key is : " + str(res)) The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2} The next key is : best Method #3 : If you have lots of queries, they should be fast -> (O (1)) Create two additional dictionaries “index_of_key” and “key_of_index” in O (n). Then it is easy finding an index of any key of original dictionary and choose any other plus or minus this, check if it is in dictionary “key_of_index” and if, then get it. Python3 #!/usr/bin/python3 # Python3 code to demonstrate working of# Get next key in Dictionary# Using two additional dictionaries# "index_of_key" and "key_of_index" # initializing dictionarytest_dict = {'gfg': 1, 'is': 2, 'best': 3} # prepare additional dictionarieski = dict()ik = dict()for i, k in enumerate(test_dict): ki[k] = i # dictionary index_of_key ik[i] = k # dictionary key_of_index # printing original dictionaryprint("The original dictionary is:", test_dict) # initializing key and offsettest_key = 'is'offset = 1 # (1 for next key, but can be any existing distance) # Get next key in Dictionaryindex_of_test_key = ki['is']index_of_next_key = index_of_test_key + offsetres = ik[index_of_next_key] if index_of_next_key in ik else None # printing resultprint("The next key is:", res) Output : The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2} The next key is : best JosefHope Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2021" }, { "code": null, "e": 313, "s": 28, "text": "Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the next key in order of dictionary. This can have application as from Python 3.6 onwards the dictionaries are ordered. Lets discuss certain ways in which this task can be performed. " }, { "code": null, "e": 354, "s": 313, "text": "Method #1 : Using index() + loop (O (n))" }, { "code": null, "e": 583, "s": 354, "text": "The combination of above functions can be used to perform this task. In this, we perform the conversion of dictionary elements to list. And then index() is used to check for index and append the index count to get the next item." }, { "code": null, "e": 591, "s": 583, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Get next key in Dictionary# Using index() + loop # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing keytest_key = 'is' # Get next key in Dictionary# Using index() + looptemp = list(test_dict)try: res = temp[temp.index(test_key) + 1]except (ValueError, IndexError): res = None # printing resultprint(\"The next key is : \" + str(res))", "e": 1092, "s": 591, "text": null }, { "code": null, "e": 1175, "s": 1092, "text": "The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2}\nThe next key is : best" }, { "code": null, "e": 1220, "s": 1177, "text": " Method #2 : Using iter() + next() (O (n))" }, { "code": null, "e": 1386, "s": 1220, "text": "This is yet another way in which this task can be performed. In this, we convert the dictionary to iterator using iter() and then extract the next key using next(). " }, { "code": null, "e": 1394, "s": 1386, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Get next key in Dictionary# Using iter() + next() # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing keytest_key = 'is' # Get next key in Dictionary# Using iter() + next()res = Nonetemp = iter(test_dict)for key in temp: if key == test_key: res = next(temp, None) # printing resultprint(\"The next key is : \" + str(res))", "e": 1886, "s": 1394, "text": null }, { "code": null, "e": 1969, "s": 1886, "text": "The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2}\nThe next key is : best" }, { "code": null, "e": 2044, "s": 1971, "text": "Method #3 : If you have lots of queries, they should be fast -> (O (1))" }, { "code": null, "e": 2296, "s": 2044, "text": "Create two additional dictionaries “index_of_key” and “key_of_index” in O (n). Then it is easy finding an index of any key of original dictionary and choose any other plus or minus this, check if it is in dictionary “key_of_index” and if, then get it." }, { "code": null, "e": 2304, "s": 2296, "text": "Python3" }, { "code": "#!/usr/bin/python3 # Python3 code to demonstrate working of# Get next key in Dictionary# Using two additional dictionaries# \"index_of_key\" and \"key_of_index\" # initializing dictionarytest_dict = {'gfg': 1, 'is': 2, 'best': 3} # prepare additional dictionarieski = dict()ik = dict()for i, k in enumerate(test_dict): ki[k] = i # dictionary index_of_key ik[i] = k # dictionary key_of_index # printing original dictionaryprint(\"The original dictionary is:\", test_dict) # initializing key and offsettest_key = 'is'offset = 1 # (1 for next key, but can be any existing distance) # Get next key in Dictionaryindex_of_test_key = ki['is']index_of_next_key = index_of_test_key + offsetres = ik[index_of_next_key] if index_of_next_key in ik else None # printing resultprint(\"The next key is:\", res)", "e": 3105, "s": 2304, "text": null }, { "code": null, "e": 3115, "s": 3105, "text": "Output : " }, { "code": null, "e": 3198, "s": 3115, "text": "The original dictionary is : {'gfg': 1, 'best': 3, 'is': 2}\nThe next key is : best" }, { "code": null, "e": 3208, "s": 3198, "text": "JosefHope" }, { "code": null, "e": 3235, "s": 3208, "text": "Python dictionary-programs" }, { "code": null, "e": 3242, "s": 3235, "text": "Python" }, { "code": null, "e": 3258, "s": 3242, "text": "Python Programs" }, { "code": null, "e": 3356, "s": 3258, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3388, "s": 3356, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3415, "s": 3388, "text": "Python Classes and Objects" }, { "code": null, "e": 3446, "s": 3415, "text": "Python | os.path.join() method" }, { "code": null, "e": 3469, "s": 3446, "text": "Introduction To PYTHON" }, { "code": null, "e": 3490, "s": 3469, "text": "Python OOPs Concepts" }, { "code": null, "e": 3512, "s": 3490, "text": "Defaultdict in Python" }, { "code": null, "e": 3551, "s": 3512, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3589, "s": 3551, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3638, "s": 3589, "text": "Python | Convert string dictionary to dictionary" } ]
PyQt5 – How to add multiple items to the ComboBox ?
24 Jun, 2021 In this article we will see how we can add multiple items to the combo box at single time. We know we can add item to the combo box with the help of addItem method but this method add only single item at a time. In order to add multiple items at a single time we have to use addItems method which will add all the items at once instead of one by one. Syntax : combo_box.addItems(item_list)Argument : It takes list as argumentAction performed : It will add all the list item to the combo box Below is the implementation – Python3 # importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget combo_box = QComboBox(self) # setting geometry of combo box combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"] # adding list of items to combo box combo_box.addItems(geek_list) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : sagar0719kumar Python PyQt5-ComboBox Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 380, "s": 28, "text": "In this article we will see how we can add multiple items to the combo box at single time. We know we can add item to the combo box with the help of addItem method but this method add only single item at a time. In order to add multiple items at a single time we have to use addItems method which will add all the items at once instead of one by one. " }, { "code": null, "e": 522, "s": 380, "text": "Syntax : combo_box.addItems(item_list)Argument : It takes list as argumentAction performed : It will add all the list item to the combo box " }, { "code": null, "e": 554, "s": 522, "text": "Below is the implementation – " }, { "code": null, "e": 562, "s": 554, "text": "Python3" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a combo box widget combo_box = QComboBox(self) # setting geometry of combo box combo_box.setGeometry(200, 150, 120, 30) # geek list geek_list = [\"Geek\", \"Geeky Geek\", \"Legend Geek\", \"Ultra Legend Geek\"] # adding list of items to combo box combo_box.addItems(geek_list) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1549, "s": 562, "text": null }, { "code": null, "e": 1560, "s": 1549, "text": "Output : " }, { "code": null, "e": 1577, "s": 1562, "text": "sagar0719kumar" }, { "code": null, "e": 1599, "s": 1577, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 1610, "s": 1599, "text": "Python-gui" }, { "code": null, "e": 1622, "s": 1610, "text": "Python-PyQt" }, { "code": null, "e": 1629, "s": 1622, "text": "Python" } ]
How to check if ul has li with the given text ?
30 Jan, 2020 Method 1: Using the each() method on the list to check the innerText property Each of the list elements of the unordered list is first selected using a jQuery selector. The each() method is used on this list to iterate through it. This method has a callback function that returns the current index and the element of the iteration. The text inside the returned element is checked for the innerText property to see if it matches the text required. A successful match means that the text inside the selected unordered list has the required text. Syntax: let found = false; $("#list li").each((id, elem) => { if (elem.innerText == requiredText) { found = true; }}); return found; Example: <!DOCTYPE html><html> <head> <title> Check if ul has li with a specific text in jQuery. </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check if ul has li with a specific text in jQuery? </b> <ul id="list"> <li>GeeksforGeeks</li> <li>Computer</li> <li>Science</li> <li>Portal</li> </ul> <p> The li elements contain the text "Computer": <span class="output"> </span> </p> <p> The li elements contain the text "Python": <span class="output2"> </span> </p> <button onclick="runChecks()"> Check for the text </button> <script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script> <script> function checkforText(requiredText) { let found = false; $("#list li").each((id, elem) => { if (elem.innerText == requiredText) { found = true; } }); return found; } function runChecks() { ans1 = checkforText('Computer'); document.querySelector(".output").textContent = ans1; ans2 = checkforText('Python'); document.querySelector(".output2").textContent = ans2; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Using the contains() selectorThe contains() selector is used to select elements that have the text matching to the given one. This text could be present in any of the element’s descendants or the element itself. It takes one parameter that is the case-sensitive text to be matched. The contains() selector is used along with the selector used for selecting the list elements. If no element is selected, that is, if the given text is not present, the number of elements returned would be 0. The number of returned elements could be checked with the length property and used to verify if the list contains the specified text. Syntax: let found = false; selector = `#list :contains('${requiredText}')`selectedList = $(selector); if (selectedList.length) { found = true;}return found; Example: <!DOCTYPE html><html> <head> <title> Check if ul has li with a specific text in jQuery. </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check if ul has li with a specific text in jQuery? </b> <ul id="list"> <li>GeeksforGeeks</li> <li>Computer</li> <li>Science</li> <li>Portal</li> </ul> <p> The li elements contain the text "Computer": <span class="output"> </span> </p> <p> The li elements contain the text "Python": <span class="output2"> </span> </p> <button onclick="runChecks()"> Check for the text </button> <script src="https://code.jquery.com/jquery-3.4.1.min.js"> </script> <script> function checkforText(requiredText) { let found = false; selector = `#list :contains('${requiredText}')` selectedList = $(selector); if (selectedList.length) { found = true; } return found; } function runChecks() { ans1 = checkforText('Computer'); document.querySelector(".output").textContent = ans1; ans2 = checkforText('Python'); document.querySelector(".output2").textContent = ans2; } </script></body> </html> Output: Before clicking the button: After clicking the button: jQuery-Misc Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to get the value in an input text box using jQuery ? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples jQuery | parent() & parents() with Examples Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jan, 2020" }, { "code": null, "e": 132, "s": 54, "text": "Method 1: Using the each() method on the list to check the innerText property" }, { "code": null, "e": 386, "s": 132, "text": "Each of the list elements of the unordered list is first selected using a jQuery selector. The each() method is used on this list to iterate through it. This method has a callback function that returns the current index and the element of the iteration." }, { "code": null, "e": 598, "s": 386, "text": "The text inside the returned element is checked for the innerText property to see if it matches the text required. A successful match means that the text inside the selected unordered list has the required text." }, { "code": null, "e": 606, "s": 598, "text": "Syntax:" }, { "code": "let found = false; $(\"#list li\").each((id, elem) => { if (elem.innerText == requiredText) { found = true; }}); return found;", "e": 736, "s": 606, "text": null }, { "code": null, "e": 745, "s": 736, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Check if ul has li with a specific text in jQuery. </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check if ul has li with a specific text in jQuery? </b> <ul id=\"list\"> <li>GeeksforGeeks</li> <li>Computer</li> <li>Science</li> <li>Portal</li> </ul> <p> The li elements contain the text \"Computer\": <span class=\"output\"> </span> </p> <p> The li elements contain the text \"Python\": <span class=\"output2\"> </span> </p> <button onclick=\"runChecks()\"> Check for the text </button> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"> </script> <script> function checkforText(requiredText) { let found = false; $(\"#list li\").each((id, elem) => { if (elem.innerText == requiredText) { found = true; } }); return found; } function runChecks() { ans1 = checkforText('Computer'); document.querySelector(\".output\").textContent = ans1; ans2 = checkforText('Python'); document.querySelector(\".output2\").textContent = ans2; } </script></body> </html>", "e": 2065, "s": 745, "text": null }, { "code": null, "e": 2073, "s": 2065, "text": "Output:" }, { "code": null, "e": 2101, "s": 2073, "text": "Before clicking the button:" }, { "code": null, "e": 2128, "s": 2101, "text": "After clicking the button:" }, { "code": null, "e": 2420, "s": 2128, "text": "Method 2: Using the contains() selectorThe contains() selector is used to select elements that have the text matching to the given one. This text could be present in any of the element’s descendants or the element itself. It takes one parameter that is the case-sensitive text to be matched." }, { "code": null, "e": 2762, "s": 2420, "text": "The contains() selector is used along with the selector used for selecting the list elements. If no element is selected, that is, if the given text is not present, the number of elements returned would be 0. The number of returned elements could be checked with the length property and used to verify if the list contains the specified text." }, { "code": null, "e": 2770, "s": 2762, "text": "Syntax:" }, { "code": "let found = false; selector = `#list :contains('${requiredText}')`selectedList = $(selector); if (selectedList.length) { found = true;}return found;", "e": 2920, "s": 2770, "text": null }, { "code": null, "e": 2929, "s": 2920, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Check if ul has li with a specific text in jQuery. </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check if ul has li with a specific text in jQuery? </b> <ul id=\"list\"> <li>GeeksforGeeks</li> <li>Computer</li> <li>Science</li> <li>Portal</li> </ul> <p> The li elements contain the text \"Computer\": <span class=\"output\"> </span> </p> <p> The li elements contain the text \"Python\": <span class=\"output2\"> </span> </p> <button onclick=\"runChecks()\"> Check for the text </button> <script src=\"https://code.jquery.com/jquery-3.4.1.min.js\"> </script> <script> function checkforText(requiredText) { let found = false; selector = `#list :contains('${requiredText}')` selectedList = $(selector); if (selectedList.length) { found = true; } return found; } function runChecks() { ans1 = checkforText('Computer'); document.querySelector(\".output\").textContent = ans1; ans2 = checkforText('Python'); document.querySelector(\".output2\").textContent = ans2; } </script></body> </html>", "e": 4278, "s": 2929, "text": null }, { "code": null, "e": 4286, "s": 4278, "text": "Output:" }, { "code": null, "e": 4314, "s": 4286, "text": "Before clicking the button:" }, { "code": null, "e": 4341, "s": 4314, "text": "After clicking the button:" }, { "code": null, "e": 4353, "s": 4341, "text": "jQuery-Misc" }, { "code": null, "e": 4360, "s": 4353, "text": "Picked" }, { "code": null, "e": 4367, "s": 4360, "text": "JQuery" }, { "code": null, "e": 4384, "s": 4367, "text": "Web Technologies" }, { "code": null, "e": 4482, "s": 4384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4539, "s": 4482, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 4612, "s": 4539, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 4635, "s": 4612, "text": "jQuery | ajax() Method" }, { "code": null, "e": 4671, "s": 4635, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 4715, "s": 4671, "text": "jQuery | parent() & parents() with Examples" }, { "code": null, "e": 4748, "s": 4715, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4810, "s": 4748, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4871, "s": 4810, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4921, "s": 4871, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What is the meaning of –save for NPM install ?
30 Jun, 2020 NPM (Node Package Manager) is the default package manager employed in JavaScript runtime environment in Node.js. It has a very frequently used command npm install [Package Name] –save. But the fact is there is no difference between npm install [Package Name] and npm install [Package Name] –save in the later version after npm 5.0.0 onwards. Before npm 5.0.0, it was necessary to add --save after package name because it will save the installed package to package.json file in the dependency section. If you are using a recent version of npm save yourself from unnecessary typing and use npm install [Package Name] instead of npm install [Package Name] --save by default it will add the installed package to the dependency list in the package.json file. NPM has several commands which are listed below: –save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.npm install --save–save-prod or -P: The following command is introduced in the later version of npm it will perform the same task as the --save command unless any other command such as -D or -O is present.npm install --save-prod–save-dev or -D: With --save-dev or -D command your installed packages will be added to devDependency section of the package.json file. Development dependencies are those packages which only meant for development purpose it will not affect the application’s result.npm install --save-dev–save-optional or -O: When this command is used the install the that packages will be listed under the optional Dependency section of the package.json file. Optional dependencies are those packages which are only used when a particular feature of the application is used and will not be required if that functionality isn’t used.npm install --save-optional–no-save: When this command is used with npm install it will not allow the installed packages from being saved into the dependency section.npm install --no-save –save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.npm install --save npm install --save –save-prod or -P: The following command is introduced in the later version of npm it will perform the same task as the --save command unless any other command such as -D or -O is present.npm install --save-prod npm install --save-prod –save-dev or -D: With --save-dev or -D command your installed packages will be added to devDependency section of the package.json file. Development dependencies are those packages which only meant for development purpose it will not affect the application’s result.npm install --save-dev npm install --save-dev –save-optional or -O: When this command is used the install the that packages will be listed under the optional Dependency section of the package.json file. Optional dependencies are those packages which are only used when a particular feature of the application is used and will not be required if that functionality isn’t used.npm install --save-optional npm install --save-optional –no-save: When this command is used with npm install it will not allow the installed packages from being saved into the dependency section.npm install --no-save npm install --no-save Note: NPM provides two additional options to save dependencies into package.json file. –save-exact or -E: This is an additional or optional command provided by the npm that will save the exact version of the installed packages which are configured at the time of development. It will not download the dependencies from npm’s default server range operator.npm install --save-exact–save-bundle or -B: The following command is also an optional command when --save-bundle or -B is used. This will also add the saved dependencies under the bundleDependency list.npm install --save-bundle –save-exact or -E: This is an additional or optional command provided by the npm that will save the exact version of the installed packages which are configured at the time of development. It will not download the dependencies from npm’s default server range operator.npm install --save-exact npm install --save-exact –save-bundle or -B: The following command is also an optional command when --save-bundle or -B is used. This will also add the saved dependencies under the bundleDependency list.npm install --save-bundle npm install --save-bundle Node.js-Misc Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows 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": 52, "s": 24, "text": "\n30 Jun, 2020" }, { "code": null, "e": 394, "s": 52, "text": "NPM (Node Package Manager) is the default package manager employed in JavaScript runtime environment in Node.js. It has a very frequently used command npm install [Package Name] –save. But the fact is there is no difference between npm install [Package Name] and npm install [Package Name] –save in the later version after npm 5.0.0 onwards." }, { "code": null, "e": 806, "s": 394, "text": "Before npm 5.0.0, it was necessary to add --save after package name because it will save the installed package to package.json file in the dependency section. If you are using a recent version of npm save yourself from unnecessary typing and use npm install [Package Name] instead of npm install [Package Name] --save by default it will add the installed package to the dependency list in the package.json file." }, { "code": null, "e": 855, "s": 806, "text": "NPM has several commands which are listed below:" }, { "code": null, "e": 2241, "s": 855, "text": "–save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.npm install --save–save-prod or -P: The following command is introduced in the later version of npm it will perform the same task as the --save command unless any other command such as -D or -O is present.npm install --save-prod–save-dev or -D: With --save-dev or -D command your installed packages will be added to devDependency section of the package.json file. Development dependencies are those packages which only meant for development purpose it will not affect the application’s result.npm install --save-dev–save-optional or -O: When this command is used the install the that packages will be listed under the optional Dependency section of the package.json file. Optional dependencies are those packages which are only used when a particular feature of the application is used and will not be required if that functionality isn’t used.npm install --save-optional–no-save: When this command is used with npm install it will not allow the installed packages from being saved into the dependency section.npm install --no-save" }, { "code": null, "e": 2614, "s": 2241, "text": "–save or -S: When the following command is used with npm install this will save all your installed core packages into the dependency section in the package.json file. Core dependencies are those packages without which your application will not give desired results. But as mentioned earlier, it is an unnecessary feature in the npm 5.0.0 version onwards.npm install --save" }, { "code": null, "e": 2633, "s": 2614, "text": "npm install --save" }, { "code": null, "e": 2844, "s": 2633, "text": "–save-prod or -P: The following command is introduced in the later version of npm it will perform the same task as the --save command unless any other command such as -D or -O is present.npm install --save-prod" }, { "code": null, "e": 2868, "s": 2844, "text": "npm install --save-prod" }, { "code": null, "e": 3156, "s": 2868, "text": "–save-dev or -D: With --save-dev or -D command your installed packages will be added to devDependency section of the package.json file. Development dependencies are those packages which only meant for development purpose it will not affect the application’s result.npm install --save-dev" }, { "code": null, "e": 3179, "s": 3156, "text": "npm install --save-dev" }, { "code": null, "e": 3536, "s": 3179, "text": "–save-optional or -O: When this command is used the install the that packages will be listed under the optional Dependency section of the package.json file. Optional dependencies are those packages which are only used when a particular feature of the application is used and will not be required if that functionality isn’t used.npm install --save-optional" }, { "code": null, "e": 3564, "s": 3536, "text": "npm install --save-optional" }, { "code": null, "e": 3725, "s": 3564, "text": "–no-save: When this command is used with npm install it will not allow the installed packages from being saved into the dependency section.npm install --no-save" }, { "code": null, "e": 3747, "s": 3725, "text": "npm install --no-save" }, { "code": null, "e": 3834, "s": 3747, "text": "Note: NPM provides two additional options to save dependencies into package.json file." }, { "code": null, "e": 4330, "s": 3834, "text": "–save-exact or -E: This is an additional or optional command provided by the npm that will save the exact version of the installed packages which are configured at the time of development. It will not download the dependencies from npm’s default server range operator.npm install --save-exact–save-bundle or -B: The following command is also an optional command when --save-bundle or -B is used. This will also add the saved dependencies under the bundleDependency list.npm install --save-bundle" }, { "code": null, "e": 4623, "s": 4330, "text": "–save-exact or -E: This is an additional or optional command provided by the npm that will save the exact version of the installed packages which are configured at the time of development. It will not download the dependencies from npm’s default server range operator.npm install --save-exact" }, { "code": null, "e": 4648, "s": 4623, "text": "npm install --save-exact" }, { "code": null, "e": 4852, "s": 4648, "text": "–save-bundle or -B: The following command is also an optional command when --save-bundle or -B is used. This will also add the saved dependencies under the bundleDependency list.npm install --save-bundle" }, { "code": null, "e": 4878, "s": 4852, "text": "npm install --save-bundle" }, { "code": null, "e": 4891, "s": 4878, "text": "Node.js-Misc" }, { "code": null, "e": 4898, "s": 4891, "text": "Picked" }, { "code": null, "e": 4906, "s": 4898, "text": "Node.js" }, { "code": null, "e": 4923, "s": 4906, "text": "Web Technologies" }, { "code": null, "e": 5021, "s": 4923, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5051, "s": 5021, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 5108, "s": 5051, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 5162, "s": 5108, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 5202, "s": 5162, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 5237, "s": 5202, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 5299, "s": 5237, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5360, "s": 5299, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5410, "s": 5360, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5453, "s": 5410, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Counter Objects | elements()
08 Aug, 2021 Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-class that is used to count hashable objects. It implicitly creates a hash table of an iterable when invoked. elements() is one of the functions of Counter class, when invoked on the Counter object will return an itertool of all the known elements in the Counter object. Parameters : Doesn’t take any parametersReturn type : Returns an itertool for all the elements with positive count in the Counter objectErrors and Exceptions : -> It will print garbage value when directly printed because it returns an itertool, not a specific data-container. -> If the count of an item is already initialized in Counter object, then it will ignore the ones with zero and negative values. Code #1: Working of elements() on a simple data container Python3 # import counter class from collections modulefrom collections import Counter # Creation of a Counter Class object using# string as an iterable data containerx = Counter("geeksforgeeks") # printing the elements of counter objectfor i in x.elements(): print ( i, end = " ") Output: g g e e e e k k s s f o r Code #2: Elements on a variety of Counter Objects with different data-containers Python3 # import counter class from collections modulefrom collections import Counter # Creation of a Counter Class object using# a string as an iterable data container# Example - 1a = Counter("geeksforgeeks") # Elements of counter objectfor i in a.elements(): print ( i, end = " ")print() # Example - 2b = Counter({'geeks' : 4, 'for' : 1, 'gfg' : 2, 'python' : 3}) for i in b.elements(): print ( i, end = " ")print() # Example - 3c = Counter([1, 2, 21, 12, 2, 44, 5, 13, 15, 5, 19, 21, 5]) for i in c.elements(): print ( i, end = " ")print() # Example - 4d = Counter( a = 2, b = 3, c = 6, d = 1, e = 5) for i in d.elements(): print ( i, end = " ") Output: g g e e e e k k s s f o r geeks geeks geeks geeks for gfg gfg python python python 1 2 2 21 21 12 44 5 5 5 13 15 19 a a b b b c c c c c c d e e e e e Code #3: To demonstrate what elements() return when it is printed directly Python3 # import Counter from collectionsfrom collections import Counter # creating a raw data-setx = Counter ("geeksforgeeks") # will return a itertools chain object# which is basically a pseudo iterable container whose# elements can be used when called with a iterable toolprint(x.elements()) Output: itertools.chain object at 0x037209F0 Code #4: When the count of an item in Counter is initialized with negative values or zero. Python3 # import Counter from collectionsfrom collections import Counter # creating a raw data-set using keyword argumentsx = Counter (a = 2, x = 3, b = 3, z = 1, y = 5, c = 0, d = -3) # printing out the elementsfor i in x.elements(): print( "% s : % s" % (i, x[i]), end ="\n") Output: a : 2 a : 2 x : 3 x : 3 x : 3 b : 3 b : 3 b : 3 z : 1 y : 5 y : 5 y : 5 y : 5 y : 5 Note: We can infer from the output that items with values less than 1 are omitted by elements(). Applications: Counter object along with its functions are used collectively for processing huge amounts of data. We can see that Counter() creates a hash-map for the data container invoked with it which is very useful than by manual processing of elements. It is one of a very high processing and functioning tools and can even function with a wide range of data too. gabaa406 Mitrajit Python-Built-in-functions 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Aug, 2021" }, { "code": null, "e": 335, "s": 52, "text": "Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists, and tuples. " }, { "code": null, "e": 462, "s": 335, "text": "Counter is a sub-class that is used to count hashable objects. It implicitly creates a hash table of an iterable when invoked." }, { "code": null, "e": 623, "s": 462, "text": "elements() is one of the functions of Counter class, when invoked on the Counter object will return an itertool of all the known elements in the Counter object." }, { "code": null, "e": 1030, "s": 623, "text": "Parameters : Doesn’t take any parametersReturn type : Returns an itertool for all the elements with positive count in the Counter objectErrors and Exceptions : -> It will print garbage value when directly printed because it returns an itertool, not a specific data-container. -> If the count of an item is already initialized in Counter object, then it will ignore the ones with zero and negative values. " }, { "code": null, "e": 1090, "s": 1030, "text": "Code #1: Working of elements() on a simple data container " }, { "code": null, "e": 1098, "s": 1090, "text": "Python3" }, { "code": "# import counter class from collections modulefrom collections import Counter # Creation of a Counter Class object using# string as an iterable data containerx = Counter(\"geeksforgeeks\") # printing the elements of counter objectfor i in x.elements(): print ( i, end = \" \")", "e": 1374, "s": 1098, "text": null }, { "code": null, "e": 1383, "s": 1374, "text": "Output: " }, { "code": null, "e": 1410, "s": 1383, "text": "g g e e e e k k s s f o r " }, { "code": null, "e": 1493, "s": 1410, "text": "Code #2: Elements on a variety of Counter Objects with different data-containers " }, { "code": null, "e": 1501, "s": 1493, "text": "Python3" }, { "code": "# import counter class from collections modulefrom collections import Counter # Creation of a Counter Class object using# a string as an iterable data container# Example - 1a = Counter(\"geeksforgeeks\") # Elements of counter objectfor i in a.elements(): print ( i, end = \" \")print() # Example - 2b = Counter({'geeks' : 4, 'for' : 1, 'gfg' : 2, 'python' : 3}) for i in b.elements(): print ( i, end = \" \")print() # Example - 3c = Counter([1, 2, 21, 12, 2, 44, 5, 13, 15, 5, 19, 21, 5]) for i in c.elements(): print ( i, end = \" \")print() # Example - 4d = Counter( a = 2, b = 3, c = 6, d = 1, e = 5) for i in d.elements(): print ( i, end = \" \")", "e": 2209, "s": 1501, "text": null }, { "code": null, "e": 2217, "s": 2209, "text": "Output:" }, { "code": null, "e": 2371, "s": 2217, "text": "g g e e e e k k s s f o r \ngeeks geeks geeks geeks for gfg gfg python python python \n1 2 2 21 21 12 44 5 5 5 13 15 19 \na a b b b c c c c c c d e e e e e " }, { "code": null, "e": 2448, "s": 2371, "text": "Code #3: To demonstrate what elements() return when it is printed directly " }, { "code": null, "e": 2456, "s": 2448, "text": "Python3" }, { "code": "# import Counter from collectionsfrom collections import Counter # creating a raw data-setx = Counter (\"geeksforgeeks\") # will return a itertools chain object# which is basically a pseudo iterable container whose# elements can be used when called with a iterable toolprint(x.elements())", "e": 2743, "s": 2456, "text": null }, { "code": null, "e": 2752, "s": 2743, "text": "Output: " }, { "code": null, "e": 2789, "s": 2752, "text": "itertools.chain object at 0x037209F0" }, { "code": null, "e": 2882, "s": 2789, "text": "Code #4: When the count of an item in Counter is initialized with negative values or zero. " }, { "code": null, "e": 2890, "s": 2882, "text": "Python3" }, { "code": "# import Counter from collectionsfrom collections import Counter # creating a raw data-set using keyword argumentsx = Counter (a = 2, x = 3, b = 3, z = 1, y = 5, c = 0, d = -3) # printing out the elementsfor i in x.elements(): print( \"% s : % s\" % (i, x[i]), end =\"\\n\")", "e": 3163, "s": 2890, "text": null }, { "code": null, "e": 3172, "s": 3163, "text": "Output: " }, { "code": null, "e": 3256, "s": 3172, "text": "a : 2\na : 2\nx : 3\nx : 3\nx : 3\nb : 3\nb : 3\nb : 3\nz : 1\ny : 5\ny : 5\ny : 5\ny : 5\ny : 5" }, { "code": null, "e": 3353, "s": 3256, "text": "Note: We can infer from the output that items with values less than 1 are omitted by elements()." }, { "code": null, "e": 3722, "s": 3353, "text": "Applications: Counter object along with its functions are used collectively for processing huge amounts of data. We can see that Counter() creates a hash-map for the data container invoked with it which is very useful than by manual processing of elements. It is one of a very high processing and functioning tools and can even function with a wide range of data too. " }, { "code": null, "e": 3731, "s": 3722, "text": "gabaa406" }, { "code": null, "e": 3740, "s": 3731, "text": "Mitrajit" }, { "code": null, "e": 3766, "s": 3740, "text": "Python-Built-in-functions" }, { "code": null, "e": 3773, "s": 3766, "text": "Python" }, { "code": null, "e": 3871, "s": 3773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3889, "s": 3871, "text": "Python Dictionary" }, { "code": null, "e": 3931, "s": 3889, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3953, "s": 3931, "text": "Enumerate() in Python" }, { "code": null, "e": 3979, "s": 3953, "text": "Python String | replace()" }, { "code": null, "e": 4011, "s": 3979, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4040, "s": 4011, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4067, "s": 4040, "text": "Python Classes and Objects" }, { "code": null, "e": 4103, "s": 4067, "text": "Convert integer to string in Python" }, { "code": null, "e": 4134, "s": 4103, "text": "Python | os.path.join() method" } ]
Java Program to Get the Union & Intersection of Two TreeSet
28 Dec, 2020 The union of two TreeSets is a Set of all the elements present in the two TreeSets. As the set does not contain duplicate values, so the union of two TreeSets also does not have duplicate values. Union of two TreeSets can be done using the addAll() method from java.util.TreeSet. TreeSet stores distinct values in sorted order, so the union can be done using the addition of set2 to set1, the addAll() method adds all the values of set2 that not present in set1 in sorted order. The intersection of two TreeSet is a Set of all the same elements of set1 and set2. The intersection of two TreeSets also does not contain duplicate values. The intersection of two TreeSets can be done using the retainAll() method from java.util.TreeSet. The retainAll() method removes all the elements that are not same in both the TreeSets. Example: Input : set1 = {10, 20, 30} set2 = {20, 30, 40, 50} Output: Union = {10, 20, 30, 40, 50} Intersection = {20, 30} Input : set1 = {a, b, c} set2 = {b, d, e} Output: Union = {a, b, c, d, e} Intersection = {b} Below is the implementation: Java // Java Program to Get the Union//& Intersection of Two TreeSet import java.util.*; public class GFG { public static void main(String[] args) { // New TreeSet1 TreeSet<Integer> treeSet1 = new TreeSet<>(); // Add elements to treeSet1 treeSet1.add(10); treeSet1.add(20); treeSet1.add(30); // New TreeSet1 TreeSet<Integer> treeSet2 = new TreeSet<>(); // Add elements to treeSet2 treeSet2.add(20); treeSet2.add(30); treeSet2.add(40); treeSet2.add(50); // Print the TreeSet1 System.out.println("TreeSet1: " + treeSet1); // Print the TreeSet1 System.out.println("TreeSet2: " + treeSet2); // New TreeSet TreeSet<Integer> union = new TreeSet<>(); // Get a Union using addAll() method union.addAll(treeSet2); union.addAll(treeSet1); // Print the Union System.out.println("Union: " + union); // New TreeSet TreeSet<Integer> intersection = new TreeSet<>(); intersection.addAll(treeSet1); intersection.retainAll(treeSet2); // Print the intersection System.out.println("Intersection: " + intersection); }} TreeSet1: [10, 20, 30] TreeSet2: [20, 30, 40, 50] Union: [10, 20, 30, 40, 50] Intersection: [20, 30] java-treeset Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Introduction to Java Exceptions in Java Java Programming Examples Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Traverse Through a HashMap in Java Extends vs Implements in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Dec, 2020" }, { "code": null, "e": 533, "s": 54, "text": "The union of two TreeSets is a Set of all the elements present in the two TreeSets. As the set does not contain duplicate values, so the union of two TreeSets also does not have duplicate values. Union of two TreeSets can be done using the addAll() method from java.util.TreeSet. TreeSet stores distinct values in sorted order, so the union can be done using the addition of set2 to set1, the addAll() method adds all the values of set2 that not present in set1 in sorted order." }, { "code": null, "e": 876, "s": 533, "text": "The intersection of two TreeSet is a Set of all the same elements of set1 and set2. The intersection of two TreeSets also does not contain duplicate values. The intersection of two TreeSets can be done using the retainAll() method from java.util.TreeSet. The retainAll() method removes all the elements that are not same in both the TreeSets." }, { "code": null, "e": 885, "s": 876, "text": "Example:" }, { "code": null, "e": 1113, "s": 885, "text": "Input : set1 = {10, 20, 30}\n set2 = {20, 30, 40, 50}\n\nOutput: Union = {10, 20, 30, 40, 50}\n Intersection = {20, 30}\n \nInput : set1 = {a, b, c}\n set2 = {b, d, e}\nOutput: Union = {a, b, c, d, e}\n Intersection = {b}" }, { "code": null, "e": 1142, "s": 1113, "text": "Below is the implementation:" }, { "code": null, "e": 1147, "s": 1142, "text": "Java" }, { "code": "// Java Program to Get the Union//& Intersection of Two TreeSet import java.util.*; public class GFG { public static void main(String[] args) { // New TreeSet1 TreeSet<Integer> treeSet1 = new TreeSet<>(); // Add elements to treeSet1 treeSet1.add(10); treeSet1.add(20); treeSet1.add(30); // New TreeSet1 TreeSet<Integer> treeSet2 = new TreeSet<>(); // Add elements to treeSet2 treeSet2.add(20); treeSet2.add(30); treeSet2.add(40); treeSet2.add(50); // Print the TreeSet1 System.out.println(\"TreeSet1: \" + treeSet1); // Print the TreeSet1 System.out.println(\"TreeSet2: \" + treeSet2); // New TreeSet TreeSet<Integer> union = new TreeSet<>(); // Get a Union using addAll() method union.addAll(treeSet2); union.addAll(treeSet1); // Print the Union System.out.println(\"Union: \" + union); // New TreeSet TreeSet<Integer> intersection = new TreeSet<>(); intersection.addAll(treeSet1); intersection.retainAll(treeSet2); // Print the intersection System.out.println(\"Intersection: \" + intersection); }}", "e": 2379, "s": 1147, "text": null }, { "code": null, "e": 2480, "s": 2379, "text": "TreeSet1: [10, 20, 30]\nTreeSet2: [20, 30, 40, 50]\nUnion: [10, 20, 30, 40, 50]\nIntersection: [20, 30]" }, { "code": null, "e": 2493, "s": 2480, "text": "java-treeset" }, { "code": null, "e": 2500, "s": 2493, "text": "Picked" }, { "code": null, "e": 2505, "s": 2500, "text": "Java" }, { "code": null, "e": 2519, "s": 2505, "text": "Java Programs" }, { "code": null, "e": 2524, "s": 2519, "text": "Java" }, { "code": null, "e": 2622, "s": 2524, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2637, "s": 2622, "text": "Stream In Java" }, { "code": null, "e": 2658, "s": 2637, "text": "Constructors in Java" }, { "code": null, "e": 2679, "s": 2658, "text": "Introduction to Java" }, { "code": null, "e": 2698, "s": 2679, "text": "Exceptions in Java" }, { "code": null, "e": 2724, "s": 2698, "text": "Java Programming Examples" }, { "code": null, "e": 2750, "s": 2724, "text": "Java Programming Examples" }, { "code": null, "e": 2784, "s": 2750, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2831, "s": 2784, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2866, "s": 2831, "text": "Traverse Through a HashMap in Java" } ]
JP Morgan Interview Experience for Quantitative Researcher | On-Campus 2022
30 Dec, 2021 JP Morgan visited our campus for a QR role for placements in Dec 2021. The whole process consisted of 4 rounds. Round 1(Online Assessment Test): They held an online test on cocubes platform in which there were 2 Papers, First paper consisted of 3 sections that had MCQs and the Second paper consisted of one coding section. In the first paper, the first section consisted of math questions (5) and they were of moderate level. The second section consisted of Probability and Counting questions – medium-hard (14). The third section consisted of Data structure and Algorithm MCQs – Easy (11). The second paper consisted of 2 Coding questions (Easy-medium). They shortlisted around 30 students for the interviews. Round 2(Interview 1 – 1hr 10mins): This round mostly tested my C++ and Math skills. The interviewer asked me in which language do I code and I answered C++. He asked about OOP in C++. He started with basics and moved on to the more complex ones. He asked about Encapsulation, Abstraction, asked me to explain Polymorphism with a real-world example and how internally run time polymorphism works (vtables and vpointers). He then asked about the Multiple Inheritance and Diamond Problem. He asked about why do we need a Copy constructor and can It be private. He then moved on to the differences between shallow copy and deep copy and what does the copy constructor does. He then asked me whether I know any design patterns and I answered yes and I named singleton and factory. He asked deeply about singleton when and where do we use it and an example of it where it is used. He then asked me a probability question: Find the expected value of the number of coin tosses to get 2 consecutive heads i.e, “HH”. (Link). I wrote the recurrence relation and he was satisfied. He then moved on to the Coding question, he asked me to code to detect whether there is a cycle in a) directed graph and b) undirected graph. He asked me if I have any questions. I asked about the work-life at JPMC and how the current team is going to be. (Be prepared with some nice questions beforehand) . I answered all the questions and I got the call for the next round. Round 3(Interview 2 – 45 mins): This round is mostly tested my Coding and Probability skills. He started with probability puzzles. If I flip a fair coin 10 times, what’s the expected number of “HH” observed. For this, I was trying to write a recurrence as well, but I couldn’t exactly get it. He then gave a clue of defining a random variable X_i if both the ith and (i+1)th toss are heads and then apply the Linearity of expectation to it. I picked up on the clue and solved it. Later I found the same question being on stackexchange.What is the probability that n points lie on the same side of the semi-circle. This is a very standard question which I saw before and hence answered it. If I flip a fair coin 10 times, what’s the expected number of “HH” observed. For this, I was trying to write a recurrence as well, but I couldn’t exactly get it. He then gave a clue of defining a random variable X_i if both the ith and (i+1)th toss are heads and then apply the Linearity of expectation to it. I picked up on the clue and solved it. Later I found the same question being on stackexchange. What is the probability that n points lie on the same side of the semi-circle. This is a very standard question which I saw before and hence answered it. He then moved on to coding questions which were pretty standard ones, https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/ Detect Cycle in a graph https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/ Detect Cycle in a graph I answered all the above questions and then the interviewer asked if I had any questions. I asked him regarding the work at JPMC and how different JPMC is doing compared to GS and other investment banks. It’s always good if you make the interviewer that you are keen on working with the company and wanted to know more about it. Round 4(HR Round – 15mins): This is a general HR round where she asked why I was interested in working at JPMC. Where do I live? Am I willing to relocate etc. All the rounds went well and JPMC hired 3 students from our college. NOTE: Do practice Quant, Probability, and puzzles as they play a very important role in interviews in many companies. There are many resources out there, I followed Heard on Street Practical Guide to Quant Finance(https://usermanual.wiki/Document/Practical20Guide20To20Quantitative20Finance20Interview.604244935.pdf) Don’t lose your hope if not selected in your dream companies. I lost my whole confidence when I didn’t get selected for Apple and Google even though I answered all the questions in the online rounds. The thing with interviews is they are hugely dependent on LUCK. It would highly depend on the interviewer and questions too. So being panic, and talking about other easy interviews with your friends, just makes you feel more demotivated. On the day of the interview be calm as you will be interviewing many companies immediately, don’t lose your patience. JP Morgan Marketing On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience for SDE 1 Amazon Interview Experience SDE-2 (3 Years Experienced) TCS Ninja Interview Experience (2020 batch) Write It Up: Share Your Interview Experiences Samsung RnD Coding Round Questions Nagarro Interview Experience Amazon Interview Experience for SDE-1 Tiger Analytics Interview Experience for Data Analyst (On-Campus)
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Dec, 2021" }, { "code": null, "e": 140, "s": 28, "text": "JP Morgan visited our campus for a QR role for placements in Dec 2021. The whole process consisted of 4 rounds." }, { "code": null, "e": 353, "s": 140, "text": "Round 1(Online Assessment Test): They held an online test on cocubes platform in which there were 2 Papers, First paper consisted of 3 sections that had MCQs and the Second paper consisted of one coding section. " }, { "code": null, "e": 687, "s": 353, "text": "In the first paper, the first section consisted of math questions (5) and they were of moderate level. The second section consisted of Probability and Counting questions – medium-hard (14). The third section consisted of Data structure and Algorithm MCQs – Easy (11). The second paper consisted of 2 Coding questions (Easy-medium). " }, { "code": null, "e": 743, "s": 687, "text": "They shortlisted around 30 students for the interviews." }, { "code": null, "e": 829, "s": 743, "text": "Round 2(Interview 1 – 1hr 10mins): This round mostly tested my C++ and Math skills. " }, { "code": null, "e": 903, "s": 829, "text": "The interviewer asked me in which language do I code and I answered C++. " }, { "code": null, "e": 931, "s": 903, "text": "He asked about OOP in C++. " }, { "code": null, "e": 994, "s": 931, "text": "He started with basics and moved on to the more complex ones. " }, { "code": null, "e": 1169, "s": 994, "text": "He asked about Encapsulation, Abstraction, asked me to explain Polymorphism with a real-world example and how internally run time polymorphism works (vtables and vpointers). " }, { "code": null, "e": 1237, "s": 1169, "text": "He then asked about the Multiple Inheritance and Diamond Problem. " }, { "code": null, "e": 1310, "s": 1237, "text": "He asked about why do we need a Copy constructor and can It be private. " }, { "code": null, "e": 1529, "s": 1310, "text": "He then moved on to the differences between shallow copy and deep copy and what does the copy constructor does. He then asked me whether I know any design patterns and I answered yes and I named singleton and factory. " }, { "code": null, "e": 1629, "s": 1529, "text": "He asked deeply about singleton when and where do we use it and an example of it where it is used. " }, { "code": null, "e": 1824, "s": 1629, "text": "He then asked me a probability question: Find the expected value of the number of coin tosses to get 2 consecutive heads i.e, “HH”. (Link). I wrote the recurrence relation and he was satisfied. " }, { "code": null, "e": 2200, "s": 1824, "text": "He then moved on to the Coding question, he asked me to code to detect whether there is a cycle in a) directed graph and b) undirected graph. He asked me if I have any questions. I asked about the work-life at JPMC and how the current team is going to be. (Be prepared with some nice questions beforehand) . I answered all the questions and I got the call for the next round." }, { "code": null, "e": 2331, "s": 2200, "text": "Round 3(Interview 2 – 45 mins): This round is mostly tested my Coding and Probability skills. He started with probability puzzles." }, { "code": null, "e": 2891, "s": 2331, "text": "If I flip a fair coin 10 times, what’s the expected number of “HH” observed. For this, I was trying to write a recurrence as well, but I couldn’t exactly get it. He then gave a clue of defining a random variable X_i if both the ith and (i+1)th toss are heads and then apply the Linearity of expectation to it. I picked up on the clue and solved it. Later I found the same question being on stackexchange.What is the probability that n points lie on the same side of the semi-circle. This is a very standard question which I saw before and hence answered it. " }, { "code": null, "e": 3297, "s": 2891, "text": "If I flip a fair coin 10 times, what’s the expected number of “HH” observed. For this, I was trying to write a recurrence as well, but I couldn’t exactly get it. He then gave a clue of defining a random variable X_i if both the ith and (i+1)th toss are heads and then apply the Linearity of expectation to it. I picked up on the clue and solved it. Later I found the same question being on stackexchange." }, { "code": null, "e": 3452, "s": 3297, "text": "What is the probability that n points lie on the same side of the semi-circle. This is a very standard question which I saw before and hence answered it. " }, { "code": null, "e": 3522, "s": 3452, "text": "He then moved on to coding questions which were pretty standard ones," }, { "code": null, "e": 3634, "s": 3522, "text": "https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/ Detect Cycle in a graph " }, { "code": null, "e": 3722, "s": 3634, "text": "https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/ " }, { "code": null, "e": 3747, "s": 3722, "text": "Detect Cycle in a graph " }, { "code": null, "e": 4076, "s": 3747, "text": "I answered all the above questions and then the interviewer asked if I had any questions. I asked him regarding the work at JPMC and how different JPMC is doing compared to GS and other investment banks. It’s always good if you make the interviewer that you are keen on working with the company and wanted to know more about it." }, { "code": null, "e": 4189, "s": 4076, "text": "Round 4(HR Round – 15mins): This is a general HR round where she asked why I was interested in working at JPMC. " }, { "code": null, "e": 4207, "s": 4189, "text": "Where do I live? " }, { "code": null, "e": 4237, "s": 4207, "text": "Am I willing to relocate etc." }, { "code": null, "e": 4306, "s": 4237, "text": "All the rounds went well and JPMC hired 3 students from our college." }, { "code": null, "e": 4313, "s": 4306, "text": "NOTE: " }, { "code": null, "e": 4473, "s": 4313, "text": "Do practice Quant, Probability, and puzzles as they play a very important role in interviews in many companies. There are many resources out there, I followed " }, { "code": null, "e": 4489, "s": 4473, "text": "Heard on Street" }, { "code": null, "e": 4625, "s": 4489, "text": "Practical Guide to Quant Finance(https://usermanual.wiki/Document/Practical20Guide20To20Quantitative20Finance20Interview.604244935.pdf)" }, { "code": null, "e": 5064, "s": 4625, "text": "Don’t lose your hope if not selected in your dream companies. I lost my whole confidence when I didn’t get selected for Apple and Google even though I answered all the questions in the online rounds. The thing with interviews is they are hugely dependent on LUCK. It would highly depend on the interviewer and questions too. So being panic, and talking about other easy interviews with your friends, just makes you feel more demotivated. " }, { "code": null, "e": 5182, "s": 5064, "text": "On the day of the interview be calm as you will be interviewing many companies immediately, don’t lose your patience." }, { "code": null, "e": 5192, "s": 5182, "text": "JP Morgan" }, { "code": null, "e": 5202, "s": 5192, "text": "Marketing" }, { "code": null, "e": 5212, "s": 5202, "text": "On-Campus" }, { "code": null, "e": 5234, "s": 5212, "text": "Interview Experiences" }, { "code": null, "e": 5332, "s": 5234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5402, "s": 5332, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 5475, "s": 5402, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 5513, "s": 5475, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 5569, "s": 5513, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 5613, "s": 5569, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 5659, "s": 5613, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 5694, "s": 5659, "text": "Samsung RnD Coding Round Questions" }, { "code": null, "e": 5723, "s": 5694, "text": "Nagarro Interview Experience" }, { "code": null, "e": 5761, "s": 5723, "text": "Amazon Interview Experience for SDE-1" } ]
Moore – Penrose Pseudoinverse in R Programming
27 Sep, 2021 The concept used to generalize the solution of a linear equation is known as Moore – Penrose Pseudoinverse of a matrix. Moore – Penrose inverse is the most widely known type of matrix pseudoinverse. In linear algebra pseudoinverse of a matrix A is a generalization of the inverse matrix. The most common use of pseudoinverse is to compute the best fit solution to a system of linear equations that lacks a unique solution. The term generalized inverse is sometimes used as a synonym of pseudoinverse. R Language provides a very simple method to calculate Moore – Penrose Pseudoinverse. The pseudoinverse is used as follows: where, A+: Single value decomposition used to calculate the pseudoinverse or the generalized inverse of a numerical matrix x and b: vectors Note: Moore – Penrose pseudoinverse solves the problem in the least squared error sense. In general, there is no exact solution to overdetermined problems. So if you cross check the solution you will not get the exact required b but an approx value of b. R provides two functions ginv() which is available in MASS library and pinv() which is available in pracma library to compute the Moore-Penrose generalized inverse of a matrix. These two functions return an arbitrary generalized inverse of a matrix, using gaussianElimination. Syntax: ginv(A) pinv(A)Parameter: A: numerical matrix Example 1: Consider below 3 linear equations: Equivalently one can write above equations in matrix form as shown below: # Using ginv() Python3 # R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(MASS) # Representing A in# matrics form in RA = matrix( c(1, 5, 11, 3, 7, 13), nrow = 3, ncol = 2, )cat("A = :\n")print(A) # Representing b in# matrics form in Rb = matrix( c(17, 19, 23), nrow = 3, ncol = 1, )cat("b = :\n")print(b) # Calculating x using ginv()cat("Solution of linear equations using pseudoinverse:\n")x = ginv(A) %*% bprint(x) Output: A = : [, 1] [, 2] [1, ] 1 3 [2, ] 5 7 [3, ] 11 13 b = : [, 1] [1, ] 17 [2, ] 19 [3, ] 23 Solution of linear equations using pseudoinverse: [, 1] [1, ] -7.513158 [2, ] 8.118421 # Using pinv() Python3 # R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(pracma) # Representing A in# matrics form in RA = matrix( c(1, 5, 11, 3, 7, 13), nrow = 3, ncol = 2, )cat("A = :\n")print(A) # Representing b in# matrics form in Rb = matrix( c(17, 19, 23), nrow = 3, ncol = 1, )cat("b = :\n")print(b) # Calculating x using pinv()cat("Solution of linear equations using pseudoinverse:\n")x = pinv(A) %*% bprint(x) Output: A = : [, 1] [, 2] [1, ] 1 3 [2, ] 5 7 [3, ] 11 13 b = : [, 1] [1, ] 17 [2, ] 19 [3, ] 23 Solution of linear equations using pseudoinverse: [, 1] [1, ] -7.513158 [2, ] 8.118421 Example 2: Similarly, let we have linear equations in matrix form as shown below: # Using ginv() Python3 # R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(MASS) # Representing A in# matrics form in RA = matrix( c(1, 0, 2, 0, 3, 1), ncol = 3, byrow = F)cat("A = :\n")print(A) # Representing b in# matrics form in Rb = matrix( c(2, 1),)cat("b = :\n")print(b) # Calculating x using ginv()cat("Solution of linear equations using pseudoinverse:\n")x = ginv(A) %*% bprint(x) Output: A = : [, 1] [, 2] [, 3] [1, ] 1 2 3 [2, ] 0 0 1 b = : [, 1] [1, ] 2 [2, ] 1 Solution of linear equations using pseudoinverse: [, 1] [1, ] -0.2 [2, ] -0.4 [3, ] 1.0 # Using pinv() Python3 # R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(pracma) # Representing A in# matrics form in RA = matrix( c(1, 0, 2, 0, 3, 1), ncol = 3, byrow = F)cat("A = :\n")print(A) # Representing b in# matrics form in Rb = matrix( c(2, 1),)cat("b = :\n")print(b) # Calculating x using pinv()cat("Solution of linear equations using pseudoinverse:\n")x = pinv(A) %*% bprint(x) Output: A = : [, 1] [, 2] [, 3] [1, ] 1 2 3 [2, ] 0 0 1 b = : [, 1] [1, ] 2 [2, ] 1 Solution of linear equations using pseudoinverse: [, 1] [1, ] -0.2 [2, ] -0.4 [3, ] 1.0 sagar0719kumar data-science R Machine-Learning R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Joining of Dataframes in R Programming Control Statements in R Programming How to import an Excel File into R ? How to change Colors in ggplot2 Line Plot in R ? Normal Distribution in R
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 654, "s": 28, "text": "The concept used to generalize the solution of a linear equation is known as Moore – Penrose Pseudoinverse of a matrix. Moore – Penrose inverse is the most widely known type of matrix pseudoinverse. In linear algebra pseudoinverse of a matrix A is a generalization of the inverse matrix. The most common use of pseudoinverse is to compute the best fit solution to a system of linear equations that lacks a unique solution. The term generalized inverse is sometimes used as a synonym of pseudoinverse. R Language provides a very simple method to calculate Moore – Penrose Pseudoinverse. The pseudoinverse is used as follows: " }, { "code": null, "e": 798, "s": 656, "text": "where, A+: Single value decomposition used to calculate the pseudoinverse or the generalized inverse of a numerical matrix x and b: vectors " }, { "code": null, "e": 1057, "s": 800, "text": "Note: Moore – Penrose pseudoinverse solves the problem in the least squared error sense. In general, there is no exact solution to overdetermined problems. So if you cross check the solution you will not get the exact required b but an approx value of b. " }, { "code": null, "e": 1337, "s": 1059, "text": "R provides two functions ginv() which is available in MASS library and pinv() which is available in pracma library to compute the Moore-Penrose generalized inverse of a matrix. These two functions return an arbitrary generalized inverse of a matrix, using gaussianElimination. " }, { "code": null, "e": 1393, "s": 1337, "text": "Syntax: ginv(A) pinv(A)Parameter: A: numerical matrix " }, { "code": null, "e": 1441, "s": 1393, "text": "Example 1: Consider below 3 linear equations: " }, { "code": null, "e": 1517, "s": 1441, "text": "Equivalently one can write above equations in matrix form as shown below: " }, { "code": null, "e": 1536, "s": 1519, "text": "# Using ginv() " }, { "code": null, "e": 1544, "s": 1536, "text": "Python3" }, { "code": "# R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(MASS) # Representing A in# matrics form in RA = matrix( c(1, 5, 11, 3, 7, 13), nrow = 3, ncol = 2, )cat(\"A = :\\n\")print(A) # Representing b in# matrics form in Rb = matrix( c(17, 19, 23), nrow = 3, ncol = 1, )cat(\"b = :\\n\")print(b) # Calculating x using ginv()cat(\"Solution of linear equations using pseudoinverse:\\n\")x = ginv(A) %*% bprint(x)", "e": 2105, "s": 1544, "text": null }, { "code": null, "e": 2115, "s": 2105, "text": "Output: " }, { "code": null, "e": 2339, "s": 2115, "text": "A = :\n [, 1] [, 2]\n[1, ] 1 3\n[2, ] 5 7\n[3, ] 11 13\nb = :\n [, 1]\n[1, ] 17\n[2, ] 19\n[3, ] 23\nSolution of linear equations \n using pseudoinverse:\n [, 1]\n[1, ] -7.513158\n[2, ] 8.118421" }, { "code": null, "e": 2355, "s": 2339, "text": "# Using pinv() " }, { "code": null, "e": 2363, "s": 2355, "text": "Python3" }, { "code": "# R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(pracma) # Representing A in# matrics form in RA = matrix( c(1, 5, 11, 3, 7, 13), nrow = 3, ncol = 2, )cat(\"A = :\\n\")print(A) # Representing b in# matrics form in Rb = matrix( c(17, 19, 23), nrow = 3, ncol = 1, )cat(\"b = :\\n\")print(b) # Calculating x using pinv()cat(\"Solution of linear equations using pseudoinverse:\\n\")x = pinv(A) %*% bprint(x)", "e": 2914, "s": 2363, "text": null }, { "code": null, "e": 2924, "s": 2914, "text": "Output: " }, { "code": null, "e": 3148, "s": 2924, "text": "A = :\n [, 1] [, 2]\n[1, ] 1 3\n[2, ] 5 7\n[3, ] 11 13\nb = :\n [, 1]\n[1, ] 17\n[2, ] 19\n[3, ] 23\nSolution of linear equations \n using pseudoinverse:\n [, 1]\n[1, ] -7.513158\n[2, ] 8.118421" }, { "code": null, "e": 3232, "s": 3148, "text": "Example 2: Similarly, let we have linear equations in matrix form as shown below: " }, { "code": null, "e": 3249, "s": 3232, "text": "# Using ginv() " }, { "code": null, "e": 3257, "s": 3249, "text": "Python3" }, { "code": "# R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(MASS) # Representing A in# matrics form in RA = matrix( c(1, 0, 2, 0, 3, 1), ncol = 3, byrow = F)cat(\"A = :\\n\")print(A) # Representing b in# matrics form in Rb = matrix( c(2, 1),)cat(\"b = :\\n\")print(b) # Calculating x using ginv()cat(\"Solution of linear equations using pseudoinverse:\\n\")x = ginv(A) %*% bprint(x)", "e": 3740, "s": 3257, "text": null }, { "code": null, "e": 3750, "s": 3740, "text": "Output: " }, { "code": null, "e": 3959, "s": 3750, "text": "A = :\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 0 0 1\nb = :\n [, 1]\n[1, ] 2\n[2, ] 1\nSolution of linear equations \n using pseudoinverse:\n [, 1]\n[1, ] -0.2\n[2, ] -0.4\n[3, ] 1.0" }, { "code": null, "e": 3975, "s": 3959, "text": "# Using pinv() " }, { "code": null, "e": 3983, "s": 3975, "text": "Python3" }, { "code": "# R program to illustrate# solve a linear matrix# equation of metrics using# moore – Penrose Pseudoinverse # Importing library for# applying pseudoinverselibrary(pracma) # Representing A in# matrics form in RA = matrix( c(1, 0, 2, 0, 3, 1), ncol = 3, byrow = F)cat(\"A = :\\n\")print(A) # Representing b in# matrics form in Rb = matrix( c(2, 1),)cat(\"b = :\\n\")print(b) # Calculating x using pinv()cat(\"Solution of linear equations using pseudoinverse:\\n\")x = pinv(A) %*% bprint(x)", "e": 4468, "s": 3983, "text": null }, { "code": null, "e": 4478, "s": 4468, "text": "Output: " }, { "code": null, "e": 4687, "s": 4478, "text": "A = :\n [, 1] [, 2] [, 3]\n[1, ] 1 2 3\n[2, ] 0 0 1\nb = :\n [, 1]\n[1, ] 2\n[2, ] 1\nSolution of linear equations \n using pseudoinverse:\n [, 1]\n[1, ] -0.2\n[2, ] -0.4\n[3, ] 1.0" }, { "code": null, "e": 4704, "s": 4689, "text": "sagar0719kumar" }, { "code": null, "e": 4717, "s": 4704, "text": "data-science" }, { "code": null, "e": 4736, "s": 4717, "text": "R Machine-Learning" }, { "code": null, "e": 4749, "s": 4736, "text": "R-Statistics" }, { "code": null, "e": 4760, "s": 4749, "text": "R Language" }, { "code": null, "e": 4858, "s": 4760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4893, "s": 4858, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 4951, "s": 4893, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 5000, "s": 4951, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 5052, "s": 5000, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 5090, "s": 5052, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 5129, "s": 5090, "text": "Joining of Dataframes in R Programming" }, { "code": null, "e": 5165, "s": 5129, "text": "Control Statements in R Programming" }, { "code": null, "e": 5202, "s": 5165, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 5251, "s": 5202, "text": "How to change Colors in ggplot2 Line Plot in R ?" } ]
Kruskal Wallis Test
26 Nov, 2020 Kruskal Wallis Test: It is a nonparametric test. It is sometimes referred to as One-Way ANOVA on ranks. It is a nonparametric alternative to One-Way ANOVA. It is an extension of the Man-Whitney Test to situations where more than two levels/populations are involved. This test falls under the family of Rank Sum tests. It depends on the ranks of the sample observations. Non-Parametric Test: It is a test which does not follow normal distribution. Elements of a Kruskal Wallis Test One independent variable with two or more levels. This independent variable is Categorical. One dependent variable which can be in Ordinal, Interval or Ratio level of measurement. Assumptions of Kruskal Wallis Test Independence of Observations – Each observation can belong to only one level. No assumption of normality. Additional Assumption – The distributions of the dependent variable for all levels of the independent variable must have similar shapes. We can male use of Histograms or Boxplots to determine if the distributions have similar shapes. If this assumption is met it allows you to interpret the results of the Kruskal Wallis Test in terms of medians and not just mean ranks. Null Hypothesis of Kruskal Wallis Test The Kruskal Wallis Test has one Null Hypothesis i.e. – The distributions are Equal. H Statistics of Kruskal Wallis Test ni = number of items in sample i Ri = sum of ranks of all items in sample i K = total number of samples n = n1 + n2 + ...... +nK ; Total number of observations in all samples. Steps to perform Kruskal Wallis Test Let us take an example to understand how to perform this test. Example:- The score of a sample of 20 students in their university examination are arranged according to the method used in their training : 1) Video Lectures 2) Books and Articles 3) Class Room Training. Evaluate the Effectiveness of these training methods at 0.10 level of significance. Step 1: Identify Independent and Dependent variables Here,Independent variable – method of training. It has three levels.Dependent variable – examination scores. Step 2: State the Hypothesis H0 = The mean examination scores of students trained by each of the three methods are equal. u1=u2=u3. H1 = At least one of the mean examination scores is not equal. Step 3: Sort the data for all groups in ascending order and allot them ranks. If more than one entry has the same score then take the average of the ranks and allot the same rank to each of those entries. In this the score 80 had three ranks 10, 11 and 12. So we took the average of these ranks which was 11. Step 4: Arrange back according to the levels an calculate the sum of ranks for each level. Step 5: Calculate H Statistics H = 0.0938 Step 6: Find the critical chi-square value The chi-square distribution can be used when all the sample sizes are at least 5. Degree of freedom = K-1 => 3-1=2 Alpha = 0.10 Use this chi-square table to find the value. X2 = 4.605 Step 7: Compare H value and Critical Chi- Square value If H calc < X2 ; Accept the Null Hypothesis If H calc > X2 ; Reject the Null Hypothesis Here, 0.0938 < 4.605. Since, Hcalc < X2 . We accept the Null Hypothesis. We can say that there is no difference in the result obtained by using the three training methods. This is all about the Kruskal Wallis Test. For any queries do leave a comment down below. statistical-algorithms Machine Learning Mathematical Mathematical Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Nov, 2020" }, { "code": null, "e": 398, "s": 28, "text": "Kruskal Wallis Test: It is a nonparametric test. It is sometimes referred to as One-Way ANOVA on ranks. It is a nonparametric alternative to One-Way ANOVA. It is an extension of the Man-Whitney Test to situations where more than two levels/populations are involved. This test falls under the family of Rank Sum tests. It depends on the ranks of the sample observations." }, { "code": null, "e": 476, "s": 398, "text": "Non-Parametric Test: It is a test which does not follow normal distribution." }, { "code": null, "e": 510, "s": 476, "text": "Elements of a Kruskal Wallis Test" }, { "code": null, "e": 602, "s": 510, "text": "One independent variable with two or more levels. This independent variable is Categorical." }, { "code": null, "e": 690, "s": 602, "text": "One dependent variable which can be in Ordinal, Interval or Ratio level of measurement." }, { "code": null, "e": 725, "s": 690, "text": "Assumptions of Kruskal Wallis Test" }, { "code": null, "e": 803, "s": 725, "text": "Independence of Observations – Each observation can belong to only one level." }, { "code": null, "e": 831, "s": 803, "text": "No assumption of normality." }, { "code": null, "e": 1202, "s": 831, "text": "Additional Assumption – The distributions of the dependent variable for all levels of the independent variable must have similar shapes. We can male use of Histograms or Boxplots to determine if the distributions have similar shapes. If this assumption is met it allows you to interpret the results of the Kruskal Wallis Test in terms of medians and not just mean ranks." }, { "code": null, "e": 1241, "s": 1202, "text": "Null Hypothesis of Kruskal Wallis Test" }, { "code": null, "e": 1325, "s": 1241, "text": "The Kruskal Wallis Test has one Null Hypothesis i.e. – The distributions are Equal." }, { "code": null, "e": 1361, "s": 1325, "text": "H Statistics of Kruskal Wallis Test" }, { "code": null, "e": 1539, "s": 1361, "text": "ni = number of items in sample i\nRi = sum of ranks of all items in sample i\nK = total number of samples\nn = n1 + n2 + ...... +nK ; Total number of observations in all samples.\n\n" }, { "code": null, "e": 1576, "s": 1539, "text": "Steps to perform Kruskal Wallis Test" }, { "code": null, "e": 1639, "s": 1576, "text": "Let us take an example to understand how to perform this test." }, { "code": null, "e": 1928, "s": 1639, "text": "Example:- The score of a sample of 20 students in their university examination are arranged according to the method used in their training : 1) Video Lectures 2) Books and Articles 3) Class Room Training. Evaluate the Effectiveness of these training methods at 0.10 level of significance." }, { "code": null, "e": 1981, "s": 1928, "text": "Step 1: Identify Independent and Dependent variables" }, { "code": null, "e": 2090, "s": 1981, "text": "Here,Independent variable – method of training. It has three levels.Dependent variable – examination scores." }, { "code": null, "e": 2119, "s": 2090, "text": "Step 2: State the Hypothesis" }, { "code": null, "e": 2222, "s": 2119, "text": "H0 = The mean examination scores of students trained by each of the three methods are equal. u1=u2=u3." }, { "code": null, "e": 2285, "s": 2222, "text": "H1 = At least one of the mean examination scores is not equal." }, { "code": null, "e": 2490, "s": 2285, "text": "Step 3: Sort the data for all groups in ascending order and allot them ranks. If more than one entry has the same score then take the average of the ranks and allot the same rank to each of those entries." }, { "code": null, "e": 2594, "s": 2490, "text": "In this the score 80 had three ranks 10, 11 and 12. So we took the average of these ranks which was 11." }, { "code": null, "e": 2685, "s": 2594, "text": "Step 4: Arrange back according to the levels an calculate the sum of ranks for each level." }, { "code": null, "e": 2716, "s": 2685, "text": "Step 5: Calculate H Statistics" }, { "code": null, "e": 2727, "s": 2716, "text": "H = 0.0938" }, { "code": null, "e": 2770, "s": 2727, "text": "Step 6: Find the critical chi-square value" }, { "code": null, "e": 2852, "s": 2770, "text": "The chi-square distribution can be used when all the sample sizes are at least 5." }, { "code": null, "e": 2898, "s": 2852, "text": "Degree of freedom = K-1 => 3-1=2 Alpha = 0.10" }, { "code": null, "e": 2943, "s": 2898, "text": "Use this chi-square table to find the value." }, { "code": null, "e": 2954, "s": 2943, "text": "X2 = 4.605" }, { "code": null, "e": 3009, "s": 2954, "text": "Step 7: Compare H value and Critical Chi- Square value" }, { "code": null, "e": 3053, "s": 3009, "text": "If H calc < X2 ; Accept the Null Hypothesis" }, { "code": null, "e": 3097, "s": 3053, "text": "If H calc > X2 ; Reject the Null Hypothesis" }, { "code": null, "e": 3119, "s": 3097, "text": "Here, 0.0938 < 4.605." }, { "code": null, "e": 3269, "s": 3119, "text": "Since, Hcalc < X2 . We accept the Null Hypothesis. We can say that there is no difference in the result obtained by using the three training methods." }, { "code": null, "e": 3359, "s": 3269, "text": "This is all about the Kruskal Wallis Test. For any queries do leave a comment down below." }, { "code": null, "e": 3382, "s": 3359, "text": "statistical-algorithms" }, { "code": null, "e": 3399, "s": 3382, "text": "Machine Learning" }, { "code": null, "e": 3412, "s": 3399, "text": "Mathematical" }, { "code": null, "e": 3425, "s": 3412, "text": "Mathematical" }, { "code": null, "e": 3442, "s": 3425, "text": "Machine Learning" }, { "code": null, "e": 3540, "s": 3442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3576, "s": 3540, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3617, "s": 3576, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3641, "s": 3617, "text": "Markov Decision Process" }, { "code": null, "e": 3674, "s": 3641, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 3725, "s": 3674, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 3755, "s": 3725, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 3798, "s": 3755, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3858, "s": 3798, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 3873, "s": 3858, "text": "C++ Data Types" } ]