title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Creating and Viewing HTML files with Python - GeeksforGeeks
24 Jan, 2021 Python is one of the most versatile programming languages. It emphasizes code readability with extensive use of white space. It comes with the support of a vast collection of libraries which serve for various purposes, making our programming experience smoother and enjoyable. Python programs are used for: Connecting with databases and performing backend development. Making web applications. Writing effective system scripts. And especially in data science and artificial intelligence. With this said, let us see how we can use python programs to generate HTML files as output. This is very effective for those programs which are automatically creating hyperlinks and graphic entities. We will be storing HTML tags in a multi-line Python string and saving the contents to a new file. This file will be saved with a .html extension rather than a .txt extension. Note: We would be omitting the standard <!DOCTYPE HTML> declaration! Python3 # to open/create a new html file in the write modef = open('GFG.html', 'w') # the html code which will go in the file GFG.htmlhtml_template = """<html><head><title>Title</title></head><body><h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> </body></html>""" # writing the code into the filef.write(html_template) # close the filef.close() The above program will create an HTML file: In order to display the HTML file as a python output, we will be using the codecs library. This library is used to open files which have a certain encoding. It takes a parameter encoding which makes it different from the built-in open() function. The open() function does not contain any parameter to specify the file encoding, which most of the time makes it difficult for viewing files which are not ASCII but UTF-8. Python3 # import moduleimport codecs # to open/create a new html file in the write modef = open('GFG.html', 'w') # the html code which will go in the file GFG.htmlhtml_template = """<html><head></head><body><p>Hello World! </p> </body></html>""" # writing the code into the filef.write(html_template) # close the filef.close() # viewing html files# below code creates a # codecs.StreamReaderWriter objectfile = codecs.open("GFG.html", 'r', "utf-8") # using .read method to view the html # code from our objectprint(file.read()) Output: In Python, webbrowser module provides a high-level interface which allows displaying Web-based documents to users. The webbrowser module can be used to launch a browser in a platform-independent manner as shown below: Python3 # import moduleimport webbrowser # open html filewebbrowser.open('GFG.html') Output: True Picked python-utility Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24544, "s": 24516, "text": "\n24 Jan, 2021" }, { "code": null, "e": 24822, "s": 24544, "text": "Python is one of the most versatile programming languages. It emphasizes code readability with extensive use of white space. It comes with the support of a vast collection of libraries which serve for various purposes, making our programming experience smoother and enjoyable. " }, { "code": null, "e": 24852, "s": 24822, "text": "Python programs are used for:" }, { "code": null, "e": 24914, "s": 24852, "text": "Connecting with databases and performing backend development." }, { "code": null, "e": 24939, "s": 24914, "text": "Making web applications." }, { "code": null, "e": 24973, "s": 24939, "text": "Writing effective system scripts." }, { "code": null, "e": 25033, "s": 24973, "text": "And especially in data science and artificial intelligence." }, { "code": null, "e": 25233, "s": 25033, "text": "With this said, let us see how we can use python programs to generate HTML files as output. This is very effective for those programs which are automatically creating hyperlinks and graphic entities." }, { "code": null, "e": 25408, "s": 25233, "text": "We will be storing HTML tags in a multi-line Python string and saving the contents to a new file. This file will be saved with a .html extension rather than a .txt extension." }, { "code": null, "e": 25477, "s": 25408, "text": "Note: We would be omitting the standard <!DOCTYPE HTML> declaration!" }, { "code": null, "e": 25485, "s": 25477, "text": "Python3" }, { "code": "# to open/create a new html file in the write modef = open('GFG.html', 'w') # the html code which will go in the file GFG.htmlhtml_template = \"\"\"<html><head><title>Title</title></head><body><h2>Welcome To GFG</h2> <p>Default code has been loaded into the Editor.</p> </body></html>\"\"\" # writing the code into the filef.write(html_template) # close the filef.close()", "e": 25856, "s": 25485, "text": null }, { "code": null, "e": 25900, "s": 25856, "text": "The above program will create an HTML file:" }, { "code": null, "e": 26320, "s": 25900, "text": "In order to display the HTML file as a python output, we will be using the codecs library. This library is used to open files which have a certain encoding. It takes a parameter encoding which makes it different from the built-in open() function. The open() function does not contain any parameter to specify the file encoding, which most of the time makes it difficult for viewing files which are not ASCII but UTF-8." }, { "code": null, "e": 26328, "s": 26320, "text": "Python3" }, { "code": "# import moduleimport codecs # to open/create a new html file in the write modef = open('GFG.html', 'w') # the html code which will go in the file GFG.htmlhtml_template = \"\"\"<html><head></head><body><p>Hello World! </p> </body></html>\"\"\" # writing the code into the filef.write(html_template) # close the filef.close() # viewing html files# below code creates a # codecs.StreamReaderWriter objectfile = codecs.open(\"GFG.html\", 'r', \"utf-8\") # using .read method to view the html # code from our objectprint(file.read())", "e": 26855, "s": 26328, "text": null }, { "code": null, "e": 26863, "s": 26855, "text": "Output:" }, { "code": null, "e": 27081, "s": 26863, "text": "In Python, webbrowser module provides a high-level interface which allows displaying Web-based documents to users. The webbrowser module can be used to launch a browser in a platform-independent manner as shown below:" }, { "code": null, "e": 27089, "s": 27081, "text": "Python3" }, { "code": "# import moduleimport webbrowser # open html filewebbrowser.open('GFG.html') ", "e": 27168, "s": 27089, "text": null }, { "code": null, "e": 27176, "s": 27168, "text": "Output:" }, { "code": null, "e": 27181, "s": 27176, "text": "True" }, { "code": null, "e": 27188, "s": 27181, "text": "Picked" }, { "code": null, "e": 27203, "s": 27188, "text": "python-utility" }, { "code": null, "e": 27227, "s": 27203, "text": "Technical Scripter 2020" }, { "code": null, "e": 27234, "s": 27227, "text": "Python" }, { "code": null, "e": 27253, "s": 27234, "text": "Technical Scripter" }, { "code": null, "e": 27351, "s": 27253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27360, "s": 27351, "text": "Comments" }, { "code": null, "e": 27373, "s": 27360, "text": "Old Comments" }, { "code": null, "e": 27391, "s": 27373, "text": "Python Dictionary" }, { "code": null, "e": 27423, "s": 27391, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27445, "s": 27423, "text": "Enumerate() in Python" }, { "code": null, "e": 27480, "s": 27445, "text": "Read a file line by line in Python" }, { "code": null, "e": 27510, "s": 27480, "text": "Iterate over a list in Python" }, { "code": null, "e": 27552, "s": 27510, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27595, "s": 27552, "text": "Python program to convert a list to string" }, { "code": null, "e": 27639, "s": 27595, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27660, "s": 27639, "text": "Python OOPs Concepts" } ]
Common Words in Two Strings in Python
Suppose we have two strings s0 and s1, they are representing a sentence, we have to find the number of unique words that are shared between these two sentences. We have to keep in mind that, the words are case-insensitive so "tom" and "ToM" are the same word. So, if the input is like s0 = "i love python coding", s1 = "coding in python is easy", then the output will be 2 as there are 2 common words, ['python', 'coding'] To solve this, we will follow these steps − convert s0 and s1 into lowercase s0List := a list of words in s0 s1List := a list of words in s1 convert set from words in s0List and s1List, then intersect them to get common words, and return the count of the intersection result. Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, s0, s1): s0 = s0.lower() s1 = s1.lower() s0List = s0.split(" ") s1List = s1.split(" ") return len(list(set(s0List)&set(s1List))) ob = Solution() S = "i love python coding" T = "coding in python is easy" print(ob.solve(S,T)) "i love python coding", "coding in python is easy" 2
[ { "code": null, "e": 1322, "s": 1062, "text": "Suppose we have two strings s0 and s1, they are representing a sentence, we have to find the\nnumber of unique words that are shared between these two sentences. We have to keep in\nmind that, the words are case-insensitive so \"tom\" and \"ToM\" are the same word." }, { "code": null, "e": 1485, "s": 1322, "text": "So, if the input is like s0 = \"i love python coding\", s1 = \"coding in python is easy\", then the\noutput will be 2 as there are 2 common words, ['python', 'coding']" }, { "code": null, "e": 1529, "s": 1485, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1562, "s": 1529, "text": "convert s0 and s1 into lowercase" }, { "code": null, "e": 1594, "s": 1562, "text": "s0List := a list of words in s0" }, { "code": null, "e": 1626, "s": 1594, "text": "s1List := a list of words in s1" }, { "code": null, "e": 1761, "s": 1626, "text": "convert set from words in s0List and s1List, then intersect them to get common words,\nand return the count of the intersection result." }, { "code": null, "e": 1831, "s": 1761, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1842, "s": 1831, "text": " Live Demo" }, { "code": null, "e": 2128, "s": 1842, "text": "class Solution:\n def solve(self, s0, s1):\n s0 = s0.lower()\n s1 = s1.lower()\n s0List = s0.split(\" \")\n s1List = s1.split(\" \")\n return len(list(set(s0List)&set(s1List)))\nob = Solution()\nS = \"i love python coding\"\nT = \"coding in python is easy\"\nprint(ob.solve(S,T))" }, { "code": null, "e": 2179, "s": 2128, "text": "\"i love python coding\", \"coding in python is easy\"" }, { "code": null, "e": 2181, "s": 2179, "text": "2" } ]
How to add a primary key constraint to a column of a table in a database using JDBC API?
You can add a primary key constraint to a column of a table using the ALTER TABLE command. ALTER TABLE table_name ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...); Assume we have a table named Dispatches in the database with 7 columns namely id, CustomerName, DispatchDate, DeliveryTime, Price and, Location with description as shown below: +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+ | ProductName | varchar(255) | YES | | NULL | | | CustomerName | varchar(255) | YES | | NULL | | | DispatchDate | date | YES | | NULL | | | DeliveryTime | time | YES | | NULL | | | Price | int(11) | YES | | NULL | | | Location | text | YES | | NULL | | | ID | int(11) | NO | | NULL | | +--------------+--------------+------+-----+---------+-------+ Following JDBC program establishes connection with MySQL database, and adds a primary-key constraint to the column named id. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class Adding_PrimaryKey_Constraint { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to alter the table String query = "ALTER TABLE Sales ADD CONSTRAINT MyPrimaryKey PRIMARY KEY(ID)"; //Executing the query stmt.executeUpdate(query); System.out.println("Constraint added......"); } } Connection established...... Constraint added...... Since we added primary constraint on the column named id column, if you get the description of the Sales table using the describe command you can observe that the Key value PRI added opposite to Id. mysql> describe sales; +--------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------------+--------------+------+-----+---------+-------+ | ProductName | varchar(255) | YES | | NULL | | | CustomerName | varchar(255) | YES | | NULL | | | DispatchDate | date | YES | | NULL | | | DeliveryTime | time | YES | | NULL | | | Price | int(11) | YES | | NULL | | | Location | text | YES | | NULL | | | ID | int(11) | NO | PRI | NULL | | +--------------+--------------+------+-----+---------+-------+ 7 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "You can add a primary key constraint to a column of a table using the ALTER TABLE command." }, { "code": null, "e": 1239, "s": 1153, "text": "ALTER TABLE table_name\nADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);" }, { "code": null, "e": 1416, "s": 1239, "text": "Assume we have a table named Dispatches in the database with 7 columns namely id, CustomerName, DispatchDate, DeliveryTime, Price and, Location with description as shown below:" }, { "code": null, "e": 2109, "s": 1416, "text": "+--------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+--------------+------+-----+---------+-------+\n| ProductName | varchar(255) | YES | | NULL | |\n| CustomerName | varchar(255) | YES | | NULL | |\n| DispatchDate | date | YES | | NULL | |\n| DeliveryTime | time | YES | | NULL | |\n| Price | int(11) | YES | | NULL | |\n| Location | text | YES | | NULL | |\n| ID | int(11) | NO | | NULL | |\n+--------------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 2234, "s": 2109, "text": "Following JDBC program establishes connection with MySQL database, and adds a primary-key constraint to the column named id." }, { "code": null, "e": 3102, "s": 2234, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class Adding_PrimaryKey_Constraint {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to alter the table\n String query = \"ALTER TABLE Sales ADD CONSTRAINT MyPrimaryKey PRIMARY KEY(ID)\";\n //Executing the query\n stmt.executeUpdate(query);\n System.out.println(\"Constraint added......\");\n }\n}" }, { "code": null, "e": 3154, "s": 3102, "text": "Connection established......\nConstraint added......" }, { "code": null, "e": 3353, "s": 3154, "text": "Since we added primary constraint on the column named id column, if you get the description of the Sales table using the describe command you can observe that the Key value PRI added opposite to Id." }, { "code": null, "e": 4094, "s": 3353, "text": "mysql> describe sales;\n+--------------+--------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------+--------------+------+-----+---------+-------+\n| ProductName | varchar(255) | YES | | NULL | |\n| CustomerName | varchar(255) | YES | | NULL | |\n| DispatchDate | date | YES | | NULL | |\n| DeliveryTime | time | YES | | NULL | |\n| Price | int(11) | YES | | NULL | |\n| Location | text | YES | | NULL | |\n| ID | int(11) | NO | PRI | NULL | |\n+--------------+--------------+------+-----+---------+-------+\n7 rows in set (0.00 sec)" } ]
Best exponential transformation to linearize your data with Scipy | by Teo Argentieri | Towards Data Science
An iterative search is necessary for any application in which we would like to find an optimum, but the solution to the problem is not expressible in an explicit form. For instance, there are plenty of algorithms in machine learning that use iterative approaches to find the best set of parameters, like Lasso linear regression, gradient boosting machines, etcetera.In this article, we will try to use a numerical approach in the ETL process, by transforming a non-linear relationship between two variable in a linear one with the optimum exponential transformation. As a Data Scientist, I often have to check the relationship between different variables and summarize some key indicator with them. I recently came across a project for the evaluation of motor efficiency, where I would like to express a sort of fuel consumption/speed ratio during a conveyance lifetime. The relation between the case study variables was non-linear and monotonically increasing, so I started searching on google if there is a statistical test that can exploit a transformation on my data to make it more linear, like the box-cox for the normality.At this point, I would like to perform an experiment: an iterative process that linearizes my data by minimizing a cost function. In my ordinary work, I often make use of scipy.optimize module to find function minima, why don’t use it for other purposes?You can better read of scipy.optimize in the official documentation that provides useful explanation and examples. In my search, I have focused on exponential transformation because we can easily set the exponent as a parameter and provide a continuous range to explore. Although this choice excludes some strongly non-linear bounds, it returns good results in general. Let us prepare test data and create two related variables x,y, where y is equal to x elevated to an exponent e, plus some Gaussian noise. For convenience I have set the Gaussian noise variance dependent to the exponent too. #test data settinge = 2.465 #expx = np.arange(0,25,0.01)y = x**e + np.random.normal(0,10**e,x.shape) If we plot the data with a seaborn regression plot, we can easily spot a non-linear relation. What we need now is a cost function, a measure of the ‘goodness’ of the linear relation that we want to maximize. A good indicator is the Pearson product-moment correlation coefficient r, which identifies the strength of the linear correlation between two variables.Pearson r has values between -1 and 1, where 1 is a perfect positive linear correlation, 0 is no linear correlation, and −1 reveals a perfect negative linear correlation; it means that r = -1 is good as r = 1.Thus, to use Pearson r properly, we will take its absolute value and negate it, because scipy.optimize functions search for minima, whereas we want its maximum. Let us define the cost function: #define cost functiondef cost_function(e): #y and x are already defined r = np.corrcoef(y,x**e) #returns correlation matrix #print each iteration print('r value: {:0.4f} exp: {:.4f}'.format(r[0][1],e)) return -abs(r[0][1]) At this point, we have to call one of the Scipy methods. A suitable choice could be the minimize_scalar method since our cost function is a scalar function. The algorithm behind this package is Brent’s method, a root finding algorithm without gradient estimation. I’ve found a very exhaustive video by Oscar Veliz channel on Brent’s method and its dependency on Dekker’s and secant methods. Check it out if you want to know more about this, and others, optimization function. Let us import and call minimize_scalar function: from scipy.optimize import minimize_scalarminimize_scalar(cost_function) We can also set a search range, avoiding the 0 value for the exponent which implies the Pearson r to return an invalid value, even if numpy.corrcoeff can handle it. The coefficient is, in fact, defined as: If x is elevated to 0 the standard deviation is 0, and the ratio returns an invalid value. To perform a bounded search let us call: minimize_scalar(cost_function,bounds=(0.1, 10), method='bounded') The resulting listing is: r value: 0.9242 exp: 3.8815r value: 0.8681 exp: 6.2185r value: 0.9416 exp: 2.4371r value: 0.9100 exp: 1.2663r value: 0.9407 exp: 2.7565r value: 0.9416 exp: 2.4255r value: 0.9416 exp: 2.4861r value: 0.9416 exp: 2.4815r value: 0.9416 exp: 2.4819r value: 0.9416 exp: 2.4819r value: 0.9416 exp: 2.4819r value: 0.9416 exp: 2.4819fun: -0.9416331392353501 message: 'Solution found.' nfev: 12 status: 0 success: True x: 2.4818969221255713 The resulting exponent found, in just 12 iterations, is 2.482, really close to the exponent we have used to generate the data that is 2.465. The voice fun shows the value of the negative absolute value of Pearson r, which seems to be quite high. Let us plot again y and x applying the exponent found on x, we will notice a strong linear relationship: If we store each iteration exponent and related Pearson coefficient, we can plot the r-exponent curve. What if we increase the impact of noise in the testing data? Let us increment Gaussian variance in the noise generator: y = (x**e) + np.random.normal(0,20**e,x.shape) The execution of the optimization function returns the following result: fun: -0.42597730774659237 message: 'Solution found.' nfev: 13 status: 0 success: True x: 2.2958258442618553 The optimum exponent found is not as precise as the previous result, but it still performs a good approximation. Increasing more the noise impact will lead to misleading results due to the overcome of noise on core data. Optimization methods are a gold mine for many application ready to be explored. With this article, I don’t want to teach a new technique but I want to promote the experimentation of these effective methods on ‘unusual’ problems.
[ { "code": null, "e": 739, "s": 172, "text": "An iterative search is necessary for any application in which we would like to find an optimum, but the solution to the problem is not expressible in an explicit form. For instance, there are plenty of algorithms in machine learning that use iterative approaches to find the best set of parameters, like Lasso linear regression, gradient boosting machines, etcetera.In this article, we will try to use a numerical approach in the ETL process, by transforming a non-linear relationship between two variable in a linear one with the optimum exponential transformation." }, { "code": null, "e": 1671, "s": 739, "text": "As a Data Scientist, I often have to check the relationship between different variables and summarize some key indicator with them. I recently came across a project for the evaluation of motor efficiency, where I would like to express a sort of fuel consumption/speed ratio during a conveyance lifetime. The relation between the case study variables was non-linear and monotonically increasing, so I started searching on google if there is a statistical test that can exploit a transformation on my data to make it more linear, like the box-cox for the normality.At this point, I would like to perform an experiment: an iterative process that linearizes my data by minimizing a cost function. In my ordinary work, I often make use of scipy.optimize module to find function minima, why don’t use it for other purposes?You can better read of scipy.optimize in the official documentation that provides useful explanation and examples." }, { "code": null, "e": 1926, "s": 1671, "text": "In my search, I have focused on exponential transformation because we can easily set the exponent as a parameter and provide a continuous range to explore. Although this choice excludes some strongly non-linear bounds, it returns good results in general." }, { "code": null, "e": 2150, "s": 1926, "text": "Let us prepare test data and create two related variables x,y, where y is equal to x elevated to an exponent e, plus some Gaussian noise. For convenience I have set the Gaussian noise variance dependent to the exponent too." }, { "code": null, "e": 2251, "s": 2150, "text": "#test data settinge = 2.465 #expx = np.arange(0,25,0.01)y = x**e + np.random.normal(0,10**e,x.shape)" }, { "code": null, "e": 2345, "s": 2251, "text": "If we plot the data with a seaborn regression plot, we can easily spot a non-linear relation." }, { "code": null, "e": 2981, "s": 2345, "text": "What we need now is a cost function, a measure of the ‘goodness’ of the linear relation that we want to maximize. A good indicator is the Pearson product-moment correlation coefficient r, which identifies the strength of the linear correlation between two variables.Pearson r has values between -1 and 1, where 1 is a perfect positive linear correlation, 0 is no linear correlation, and −1 reveals a perfect negative linear correlation; it means that r = -1 is good as r = 1.Thus, to use Pearson r properly, we will take its absolute value and negate it, because scipy.optimize functions search for minima, whereas we want its maximum." }, { "code": null, "e": 3014, "s": 2981, "text": "Let us define the cost function:" }, { "code": null, "e": 3253, "s": 3014, "text": "#define cost functiondef cost_function(e): #y and x are already defined r = np.corrcoef(y,x**e) #returns correlation matrix #print each iteration print('r value: {:0.4f} exp: {:.4f}'.format(r[0][1],e)) return -abs(r[0][1])" }, { "code": null, "e": 3517, "s": 3253, "text": "At this point, we have to call one of the Scipy methods. A suitable choice could be the minimize_scalar method since our cost function is a scalar function. The algorithm behind this package is Brent’s method, a root finding algorithm without gradient estimation." }, { "code": null, "e": 3729, "s": 3517, "text": "I’ve found a very exhaustive video by Oscar Veliz channel on Brent’s method and its dependency on Dekker’s and secant methods. Check it out if you want to know more about this, and others, optimization function." }, { "code": null, "e": 3778, "s": 3729, "text": "Let us import and call minimize_scalar function:" }, { "code": null, "e": 3851, "s": 3778, "text": "from scipy.optimize import minimize_scalarminimize_scalar(cost_function)" }, { "code": null, "e": 4016, "s": 3851, "text": "We can also set a search range, avoiding the 0 value for the exponent which implies the Pearson r to return an invalid value, even if numpy.corrcoeff can handle it." }, { "code": null, "e": 4057, "s": 4016, "text": "The coefficient is, in fact, defined as:" }, { "code": null, "e": 4189, "s": 4057, "text": "If x is elevated to 0 the standard deviation is 0, and the ratio returns an invalid value. To perform a bounded search let us call:" }, { "code": null, "e": 4255, "s": 4189, "text": "minimize_scalar(cost_function,bounds=(0.1, 10), method='bounded')" }, { "code": null, "e": 4281, "s": 4255, "text": "The resulting listing is:" }, { "code": null, "e": 4722, "s": 4281, "text": "r value: 0.9242 exp: 3.8815r value: 0.8681 exp: 6.2185r value: 0.9416 exp: 2.4371r value: 0.9100 exp: 1.2663r value: 0.9407 exp: 2.7565r value: 0.9416 exp: 2.4255r value: 0.9416 exp: 2.4861r value: 0.9416 exp: 2.4815r value: 0.9416 exp: 2.4819r value: 0.9416 exp: 2.4819r value: 0.9416 exp: 2.4819r value: 0.9416 exp: 2.4819fun: -0.9416331392353501 message: 'Solution found.' nfev: 12 status: 0 success: True x: 2.4818969221255713" }, { "code": null, "e": 4863, "s": 4722, "text": "The resulting exponent found, in just 12 iterations, is 2.482, really close to the exponent we have used to generate the data that is 2.465." }, { "code": null, "e": 5073, "s": 4863, "text": "The voice fun shows the value of the negative absolute value of Pearson r, which seems to be quite high. Let us plot again y and x applying the exponent found on x, we will notice a strong linear relationship:" }, { "code": null, "e": 5176, "s": 5073, "text": "If we store each iteration exponent and related Pearson coefficient, we can plot the r-exponent curve." }, { "code": null, "e": 5296, "s": 5176, "text": "What if we increase the impact of noise in the testing data? Let us increment Gaussian variance in the noise generator:" }, { "code": null, "e": 5343, "s": 5296, "text": "y = (x**e) + np.random.normal(0,20**e,x.shape)" }, { "code": null, "e": 5416, "s": 5343, "text": "The execution of the optimization function returns the following result:" }, { "code": null, "e": 5534, "s": 5416, "text": "fun: -0.42597730774659237 message: 'Solution found.' nfev: 13 status: 0 success: True x: 2.2958258442618553" }, { "code": null, "e": 5647, "s": 5534, "text": "The optimum exponent found is not as precise as the previous result, but it still performs a good approximation." }, { "code": null, "e": 5755, "s": 5647, "text": "Increasing more the noise impact will lead to misleading results due to the overcome of noise on core data." } ]
Illustrated: Self-Attention. A step-by-step guide to self-attention... | by Raimi Karim | Towards Data Science
The illustrations are best viewed on the Desktop. A Colab version can be found here (thanks to Manuel Romero!). Changelog:12 Jan 2022 — Improve clarity5 Jan 2022 — Fix typos and improve clarity What do BERT, RoBERTa, ALBERT, SpanBERT, DistilBERT, SesameBERT, SemBERT, SciBERT, BioBERT, MobileBERT, TinyBERT and CamemBERT all have in common? And I’m not looking for the answer “BERT” 🤭. Answer: self-attention 🤗. We are not only talking about architectures bearing the name “BERT’ but, more correctly, Transformer-based architectures. Transformer-based architectures, which are primarily used in modelling language understanding tasks, eschew recurrence in neural networks and instead trust entirely on self-attention mechanisms to draw global dependencies between inputs and outputs. But what’s the math behind this? That’s what we’re going to find out today. The main content of this post is to walk you through the mathematical operations involved in a self-attention module. By the end of this article, you should be able to write or code a self-attention module from scratch. This article does not aim to provide the intuitions and explanations behind the different numerical representations and mathematical operations in the self-attention module. It also does not seek to demonstrate the why’s and how-exactly’s of self-attention in Transformers (I believe there’s a lot out there already). Note that the difference between attention and self-attention is also not detailed in this article. IllustrationsCodeExtending to Transformers Illustrations Code Extending to Transformers Now let’s get on to it! If you think that self-attention is similar, the answer is yes! They fundamentally share the same concept and many common mathematical operations. A self-attention module takes in n inputs and returns n outputs. What happens in this module? In layman’s terms, the self-attention mechanism allows the inputs to interact with each other (“self”) and find out who they should pay more attention to (“attention”). The outputs are aggregates of these interactions and attention scores. The illustrations are divided into the following steps: Prepare inputsInitialise weightsDerive key, query and valueCalculate attention scores for Input 1Calculate softmaxMultiply scores with valuesSum weighted values to get Output 1Repeat steps 4–7 for Input 2 & Input 3 Prepare inputs Initialise weights Derive key, query and value Calculate attention scores for Input 1 Calculate softmax Multiply scores with values Sum weighted values to get Output 1 Repeat steps 4–7 for Input 2 & Input 3 NoteIn practice, the mathematical operations are vectorised, i.e. all the inputs undergo the mathematical operations together. We’ll see this later in the Code section. Step 1: Prepare inputs We start with 3 inputs for this tutorial, each with dimension 4. Input 1: [1, 0, 1, 0] Input 2: [0, 2, 0, 2]Input 3: [1, 1, 1, 1] Step 2: Initialise weights Every input must have three representations (see diagram below). These representations are called key (orange), query (red), and value (purple). For this example, let’s take that we want these representations to have a dimension of 3. Because every input has a dimension of 4, each set of the weights must have a shape of 4×3. NoteWe’ll see later that the dimension of value is also the output dimension. To obtain these representations, every input (green) is multiplied with a set of weights for keys, a set of weights for querys (I know that’s not the correct spelling), and a set of weights for values. In our example, we initialise the three sets of weights as follows. Weights for key: [[0, 0, 1], [1, 1, 0], [0, 1, 0], [1, 1, 0]] Weights for query: [[1, 0, 1], [1, 0, 0], [0, 0, 1], [0, 1, 1]] Weights for value: [[0, 2, 0], [0, 3, 0], [1, 0, 3], [1, 1, 0]] NotesIn a neural network setting, these weights are usually small numbers, initialised randomly using an appropriate random distribution like Gaussian, Xavier and Kaiming distributions. This initialisation is done once before training. Step 3: Derive key, query and value Now that we have the three sets of weights, let’s obtain the key, query and value representations for every input. Key representation for Input 1: [0, 0, 1][1, 0, 1, 0] x [1, 1, 0] = [0, 1, 1] [0, 1, 0] [1, 1, 0] Use the same set of weights to get the key representation for Input 2: [0, 0, 1][0, 2, 0, 2] x [1, 1, 0] = [4, 4, 0] [0, 1, 0] [1, 1, 0] Use the same set of weights to get the key representation for Input 3: [0, 0, 1][1, 1, 1, 1] x [1, 1, 0] = [2, 3, 1] [0, 1, 0] [1, 1, 0] A faster way is to vectorise the above operations: [0, 0, 1][1, 0, 1, 0] [1, 1, 0] [0, 1, 1][0, 2, 0, 2] x [0, 1, 0] = [4, 4, 0][1, 1, 1, 1] [1, 1, 0] [2, 3, 1] Let’s do the same to obtain the value representations for every input: [0, 2, 0][1, 0, 1, 0] [0, 3, 0] [1, 2, 3] [0, 2, 0, 2] x [1, 0, 3] = [2, 8, 0][1, 1, 1, 1] [1, 1, 0] [2, 6, 3] and finally the query representations: [1, 0, 1][1, 0, 1, 0] [1, 0, 0] [1, 0, 2][0, 2, 0, 2] x [0, 0, 1] = [2, 2, 2][1, 1, 1, 1] [0, 1, 1] [2, 1, 3] NotesIn practice, a bias vector may be added to the product of matrix multiplication. Step 4: Calculate attention scores for Input 1 To obtain attention scores, we start with taking a dot product between Input 1’s query (red) with all keys (orange), including itself. Since there are 3 key representations (because we have 3 inputs), we obtain 3 attention scores (blue). [0, 4, 2][1, 0, 2] x [1, 4, 3] = [2, 4, 4] [1, 0, 1] Notice that we only use the query from Input 1. Later we’ll work on repeating this same step for the other querys. NoteThe above operation is known as dot product attention, one of the several score functions. Other score functions include scaled dot product and additive/concat. Step 5: Calculate softmax Take the softmax across these attention scores (blue). softmax([2, 4, 4]) = [0.0, 0.5, 0.5] Note that we round off to 1 decimal place here for readability. Step 6: Multiply scores with values The softmaxed attention scores for each input (blue) is multiplied by its corresponding value (purple). This results in 3 alignment vectors (yellow). In this tutorial, we’ll refer to them as weighted values. 1: 0.0 * [1, 2, 3] = [0.0, 0.0, 0.0]2: 0.5 * [2, 8, 0] = [1.0, 4.0, 0.0]3: 0.5 * [2, 6, 3] = [1.0, 3.0, 1.5] Step 7: Sum weighted values to get Output 1 Take all the weighted values (yellow) and sum them element-wise: [0.0, 0.0, 0.0]+ [1.0, 4.0, 0.0]+ [1.0, 3.0, 1.5]-----------------= [2.0, 7.0, 1.5] The resulting vector [2.0, 7.0, 1.5] (dark green) is Output 1, which is based on the query representation from Input 1 interacting with all other keys, including itself. Step 8: Repeat for Input 2 & Input 3 Now that we’re done with Output 1, we repeat Steps 4 to 7 for Output 2 and Output 3. I trust that I can leave you to work out the operations yourself 👍🏼. NotesThe dimension of query and key must always be the same because of the dot product score function. However, the dimension of value may be different from query and key. The resulting output will consequently follow the dimension of value. Here is the code in PyTorch 🤗, a popular deep learning framework in Python. To enjoy the APIs for @ operator, .T and None indexing in the following code snippets, make sure you’re on Python≥3.6 and PyTorch 1.3.1. Just follow along and copy-paste these in a Python/IPython REPL or Jupyter Notebook. Step 1: Prepare inputs Step 2: Initialise weights Step 3: Derive key, query and value Step 4: Calculate attention scores Step 5: Calculate softmax Step 6: Multiply scores with values Step 7: Sum weighted values NotePyTorch has provided an API for this called nn.MultiheadAttention. However, this API requires that you feed in key, query and value PyTorch tensors. Moreover, the outputs of this module undergo a linear transformation. So, where do we go from here? Transformers! Indeed we live in exciting times of deep learning research and high compute resources. The transformer is the incarnation from Attention Is All You Need, originally born to perform neural machine translation. Researchers picked up from here, reassembling, cutting, adding and extending the parts, and extending its usage to more language tasks. Here I will briefly mention how we can extend self-attention to a Transformer architecture. Within the self-attention module: Dimension Bias Inputs to the self-attention module: Embedding module Positional encoding Truncating Masking Adding more self-attention modules: Multihead Layer stacking Modules between self-attention modules: Linear transformations LayerNorm That’s all folks! Hope you find the content easy to digest. Is there something that you think I should add or elaborate on further in this article? Do drop a comment! Also, do check out an illustration I created for attention below Attention Is All You Need (arxiv.org) The Illustrated Transformer (jalammar.github.io) Attn: Illustrated Attention (towardsdatascience.com) If you like my content and haven’t already subscribed to Medium, subscribe via my referral link here! NOTE: A portion of your membership fees will be apportioned to me as referral fees. Special thanks to Xin Jie, Serene, Ren Jie, Kevin and Wei Yih for ideas, suggestions and corrections to this article. Follow me on Twitter @remykarem for digested articles and other tweets on AI, ML, Deep Learning and Python.
[ { "code": null, "e": 284, "s": 172, "text": "The illustrations are best viewed on the Desktop. A Colab version can be found here (thanks to Manuel Romero!)." }, { "code": null, "e": 366, "s": 284, "text": "Changelog:12 Jan 2022 — Improve clarity5 Jan 2022 — Fix typos and improve clarity" }, { "code": null, "e": 558, "s": 366, "text": "What do BERT, RoBERTa, ALBERT, SpanBERT, DistilBERT, SesameBERT, SemBERT, SciBERT, BioBERT, MobileBERT, TinyBERT and CamemBERT all have in common? And I’m not looking for the answer “BERT” 🤭." }, { "code": null, "e": 989, "s": 558, "text": "Answer: self-attention 🤗. We are not only talking about architectures bearing the name “BERT’ but, more correctly, Transformer-based architectures. Transformer-based architectures, which are primarily used in modelling language understanding tasks, eschew recurrence in neural networks and instead trust entirely on self-attention mechanisms to draw global dependencies between inputs and outputs. But what’s the math behind this?" }, { "code": null, "e": 1252, "s": 989, "text": "That’s what we’re going to find out today. The main content of this post is to walk you through the mathematical operations involved in a self-attention module. By the end of this article, you should be able to write or code a self-attention module from scratch." }, { "code": null, "e": 1670, "s": 1252, "text": "This article does not aim to provide the intuitions and explanations behind the different numerical representations and mathematical operations in the self-attention module. It also does not seek to demonstrate the why’s and how-exactly’s of self-attention in Transformers (I believe there’s a lot out there already). Note that the difference between attention and self-attention is also not detailed in this article." }, { "code": null, "e": 1713, "s": 1670, "text": "IllustrationsCodeExtending to Transformers" }, { "code": null, "e": 1727, "s": 1713, "text": "Illustrations" }, { "code": null, "e": 1732, "s": 1727, "text": "Code" }, { "code": null, "e": 1758, "s": 1732, "text": "Extending to Transformers" }, { "code": null, "e": 1782, "s": 1758, "text": "Now let’s get on to it!" }, { "code": null, "e": 1929, "s": 1782, "text": "If you think that self-attention is similar, the answer is yes! They fundamentally share the same concept and many common mathematical operations." }, { "code": null, "e": 2263, "s": 1929, "text": "A self-attention module takes in n inputs and returns n outputs. What happens in this module? In layman’s terms, the self-attention mechanism allows the inputs to interact with each other (“self”) and find out who they should pay more attention to (“attention”). The outputs are aggregates of these interactions and attention scores." }, { "code": null, "e": 2319, "s": 2263, "text": "The illustrations are divided into the following steps:" }, { "code": null, "e": 2534, "s": 2319, "text": "Prepare inputsInitialise weightsDerive key, query and valueCalculate attention scores for Input 1Calculate softmaxMultiply scores with valuesSum weighted values to get Output 1Repeat steps 4–7 for Input 2 & Input 3" }, { "code": null, "e": 2549, "s": 2534, "text": "Prepare inputs" }, { "code": null, "e": 2568, "s": 2549, "text": "Initialise weights" }, { "code": null, "e": 2596, "s": 2568, "text": "Derive key, query and value" }, { "code": null, "e": 2635, "s": 2596, "text": "Calculate attention scores for Input 1" }, { "code": null, "e": 2653, "s": 2635, "text": "Calculate softmax" }, { "code": null, "e": 2681, "s": 2653, "text": "Multiply scores with values" }, { "code": null, "e": 2717, "s": 2681, "text": "Sum weighted values to get Output 1" }, { "code": null, "e": 2756, "s": 2717, "text": "Repeat steps 4–7 for Input 2 & Input 3" }, { "code": null, "e": 2925, "s": 2756, "text": "NoteIn practice, the mathematical operations are vectorised, i.e. all the inputs undergo the mathematical operations together. We’ll see this later in the Code section." }, { "code": null, "e": 2948, "s": 2925, "text": "Step 1: Prepare inputs" }, { "code": null, "e": 3013, "s": 2948, "text": "We start with 3 inputs for this tutorial, each with dimension 4." }, { "code": null, "e": 3078, "s": 3013, "text": "Input 1: [1, 0, 1, 0] Input 2: [0, 2, 0, 2]Input 3: [1, 1, 1, 1]" }, { "code": null, "e": 3105, "s": 3078, "text": "Step 2: Initialise weights" }, { "code": null, "e": 3432, "s": 3105, "text": "Every input must have three representations (see diagram below). These representations are called key (orange), query (red), and value (purple). For this example, let’s take that we want these representations to have a dimension of 3. Because every input has a dimension of 4, each set of the weights must have a shape of 4×3." }, { "code": null, "e": 3510, "s": 3432, "text": "NoteWe’ll see later that the dimension of value is also the output dimension." }, { "code": null, "e": 3780, "s": 3510, "text": "To obtain these representations, every input (green) is multiplied with a set of weights for keys, a set of weights for querys (I know that’s not the correct spelling), and a set of weights for values. In our example, we initialise the three sets of weights as follows." }, { "code": null, "e": 3797, "s": 3780, "text": "Weights for key:" }, { "code": null, "e": 3842, "s": 3797, "text": "[[0, 0, 1], [1, 1, 0], [0, 1, 0], [1, 1, 0]]" }, { "code": null, "e": 3861, "s": 3842, "text": "Weights for query:" }, { "code": null, "e": 3906, "s": 3861, "text": "[[1, 0, 1], [1, 0, 0], [0, 0, 1], [0, 1, 1]]" }, { "code": null, "e": 3925, "s": 3906, "text": "Weights for value:" }, { "code": null, "e": 3970, "s": 3925, "text": "[[0, 2, 0], [0, 3, 0], [1, 0, 3], [1, 1, 0]]" }, { "code": null, "e": 4206, "s": 3970, "text": "NotesIn a neural network setting, these weights are usually small numbers, initialised randomly using an appropriate random distribution like Gaussian, Xavier and Kaiming distributions. This initialisation is done once before training." }, { "code": null, "e": 4242, "s": 4206, "text": "Step 3: Derive key, query and value" }, { "code": null, "e": 4357, "s": 4242, "text": "Now that we have the three sets of weights, let’s obtain the key, query and value representations for every input." }, { "code": null, "e": 4389, "s": 4357, "text": "Key representation for Input 1:" }, { "code": null, "e": 4498, "s": 4389, "text": " [0, 0, 1][1, 0, 1, 0] x [1, 1, 0] = [0, 1, 1] [0, 1, 0] [1, 1, 0]" }, { "code": null, "e": 4569, "s": 4498, "text": "Use the same set of weights to get the key representation for Input 2:" }, { "code": null, "e": 4678, "s": 4569, "text": " [0, 0, 1][0, 2, 0, 2] x [1, 1, 0] = [4, 4, 0] [0, 1, 0] [1, 1, 0]" }, { "code": null, "e": 4749, "s": 4678, "text": "Use the same set of weights to get the key representation for Input 3:" }, { "code": null, "e": 4858, "s": 4749, "text": " [0, 0, 1][1, 1, 1, 1] x [1, 1, 0] = [2, 3, 1] [0, 1, 0] [1, 1, 0]" }, { "code": null, "e": 4909, "s": 4858, "text": "A faster way is to vectorise the above operations:" }, { "code": null, "e": 5042, "s": 4909, "text": " [0, 0, 1][1, 0, 1, 0] [1, 1, 0] [0, 1, 1][0, 2, 0, 2] x [0, 1, 0] = [4, 4, 0][1, 1, 1, 1] [1, 1, 0] [2, 3, 1]" }, { "code": null, "e": 5113, "s": 5042, "text": "Let’s do the same to obtain the value representations for every input:" }, { "code": null, "e": 5247, "s": 5113, "text": " [0, 2, 0][1, 0, 1, 0] [0, 3, 0] [1, 2, 3] [0, 2, 0, 2] x [1, 0, 3] = [2, 8, 0][1, 1, 1, 1] [1, 1, 0] [2, 6, 3]" }, { "code": null, "e": 5286, "s": 5247, "text": "and finally the query representations:" }, { "code": null, "e": 5419, "s": 5286, "text": " [1, 0, 1][1, 0, 1, 0] [1, 0, 0] [1, 0, 2][0, 2, 0, 2] x [0, 0, 1] = [2, 2, 2][1, 1, 1, 1] [0, 1, 1] [2, 1, 3]" }, { "code": null, "e": 5505, "s": 5419, "text": "NotesIn practice, a bias vector may be added to the product of matrix multiplication." }, { "code": null, "e": 5552, "s": 5505, "text": "Step 4: Calculate attention scores for Input 1" }, { "code": null, "e": 5790, "s": 5552, "text": "To obtain attention scores, we start with taking a dot product between Input 1’s query (red) with all keys (orange), including itself. Since there are 3 key representations (because we have 3 inputs), we obtain 3 attention scores (blue)." }, { "code": null, "e": 5866, "s": 5790, "text": " [0, 4, 2][1, 0, 2] x [1, 4, 3] = [2, 4, 4] [1, 0, 1]" }, { "code": null, "e": 5981, "s": 5866, "text": "Notice that we only use the query from Input 1. Later we’ll work on repeating this same step for the other querys." }, { "code": null, "e": 6146, "s": 5981, "text": "NoteThe above operation is known as dot product attention, one of the several score functions. Other score functions include scaled dot product and additive/concat." }, { "code": null, "e": 6172, "s": 6146, "text": "Step 5: Calculate softmax" }, { "code": null, "e": 6227, "s": 6172, "text": "Take the softmax across these attention scores (blue)." }, { "code": null, "e": 6264, "s": 6227, "text": "softmax([2, 4, 4]) = [0.0, 0.5, 0.5]" }, { "code": null, "e": 6328, "s": 6264, "text": "Note that we round off to 1 decimal place here for readability." }, { "code": null, "e": 6364, "s": 6328, "text": "Step 6: Multiply scores with values" }, { "code": null, "e": 6572, "s": 6364, "text": "The softmaxed attention scores for each input (blue) is multiplied by its corresponding value (purple). This results in 3 alignment vectors (yellow). In this tutorial, we’ll refer to them as weighted values." }, { "code": null, "e": 6681, "s": 6572, "text": "1: 0.0 * [1, 2, 3] = [0.0, 0.0, 0.0]2: 0.5 * [2, 8, 0] = [1.0, 4.0, 0.0]3: 0.5 * [2, 6, 3] = [1.0, 3.0, 1.5]" }, { "code": null, "e": 6725, "s": 6681, "text": "Step 7: Sum weighted values to get Output 1" }, { "code": null, "e": 6790, "s": 6725, "text": "Take all the weighted values (yellow) and sum them element-wise:" }, { "code": null, "e": 6876, "s": 6790, "text": " [0.0, 0.0, 0.0]+ [1.0, 4.0, 0.0]+ [1.0, 3.0, 1.5]-----------------= [2.0, 7.0, 1.5]" }, { "code": null, "e": 7046, "s": 6876, "text": "The resulting vector [2.0, 7.0, 1.5] (dark green) is Output 1, which is based on the query representation from Input 1 interacting with all other keys, including itself." }, { "code": null, "e": 7083, "s": 7046, "text": "Step 8: Repeat for Input 2 & Input 3" }, { "code": null, "e": 7237, "s": 7083, "text": "Now that we’re done with Output 1, we repeat Steps 4 to 7 for Output 2 and Output 3. I trust that I can leave you to work out the operations yourself 👍🏼." }, { "code": null, "e": 7479, "s": 7237, "text": "NotesThe dimension of query and key must always be the same because of the dot product score function. However, the dimension of value may be different from query and key. The resulting output will consequently follow the dimension of value." }, { "code": null, "e": 7777, "s": 7479, "text": "Here is the code in PyTorch 🤗, a popular deep learning framework in Python. To enjoy the APIs for @ operator, .T and None indexing in the following code snippets, make sure you’re on Python≥3.6 and PyTorch 1.3.1. Just follow along and copy-paste these in a Python/IPython REPL or Jupyter Notebook." }, { "code": null, "e": 7800, "s": 7777, "text": "Step 1: Prepare inputs" }, { "code": null, "e": 7827, "s": 7800, "text": "Step 2: Initialise weights" }, { "code": null, "e": 7863, "s": 7827, "text": "Step 3: Derive key, query and value" }, { "code": null, "e": 7898, "s": 7863, "text": "Step 4: Calculate attention scores" }, { "code": null, "e": 7924, "s": 7898, "text": "Step 5: Calculate softmax" }, { "code": null, "e": 7960, "s": 7924, "text": "Step 6: Multiply scores with values" }, { "code": null, "e": 7988, "s": 7960, "text": "Step 7: Sum weighted values" }, { "code": null, "e": 8211, "s": 7988, "text": "NotePyTorch has provided an API for this called nn.MultiheadAttention. However, this API requires that you feed in key, query and value PyTorch tensors. Moreover, the outputs of this module undergo a linear transformation." }, { "code": null, "e": 8600, "s": 8211, "text": "So, where do we go from here? Transformers! Indeed we live in exciting times of deep learning research and high compute resources. The transformer is the incarnation from Attention Is All You Need, originally born to perform neural machine translation. Researchers picked up from here, reassembling, cutting, adding and extending the parts, and extending its usage to more language tasks." }, { "code": null, "e": 8692, "s": 8600, "text": "Here I will briefly mention how we can extend self-attention to a Transformer architecture." }, { "code": null, "e": 8726, "s": 8692, "text": "Within the self-attention module:" }, { "code": null, "e": 8736, "s": 8726, "text": "Dimension" }, { "code": null, "e": 8741, "s": 8736, "text": "Bias" }, { "code": null, "e": 8778, "s": 8741, "text": "Inputs to the self-attention module:" }, { "code": null, "e": 8795, "s": 8778, "text": "Embedding module" }, { "code": null, "e": 8815, "s": 8795, "text": "Positional encoding" }, { "code": null, "e": 8826, "s": 8815, "text": "Truncating" }, { "code": null, "e": 8834, "s": 8826, "text": "Masking" }, { "code": null, "e": 8870, "s": 8834, "text": "Adding more self-attention modules:" }, { "code": null, "e": 8880, "s": 8870, "text": "Multihead" }, { "code": null, "e": 8895, "s": 8880, "text": "Layer stacking" }, { "code": null, "e": 8935, "s": 8895, "text": "Modules between self-attention modules:" }, { "code": null, "e": 8958, "s": 8935, "text": "Linear transformations" }, { "code": null, "e": 8968, "s": 8958, "text": "LayerNorm" }, { "code": null, "e": 9200, "s": 8968, "text": "That’s all folks! Hope you find the content easy to digest. Is there something that you think I should add or elaborate on further in this article? Do drop a comment! Also, do check out an illustration I created for attention below" }, { "code": null, "e": 9238, "s": 9200, "text": "Attention Is All You Need (arxiv.org)" }, { "code": null, "e": 9287, "s": 9238, "text": "The Illustrated Transformer (jalammar.github.io)" }, { "code": null, "e": 9340, "s": 9287, "text": "Attn: Illustrated Attention (towardsdatascience.com)" }, { "code": null, "e": 9526, "s": 9340, "text": "If you like my content and haven’t already subscribed to Medium, subscribe via my referral link here! NOTE: A portion of your membership fees will be apportioned to me as referral fees." }, { "code": null, "e": 9644, "s": 9526, "text": "Special thanks to Xin Jie, Serene, Ren Jie, Kevin and Wei Yih for ideas, suggestions and corrections to this article." } ]
Console printf(String, Object) method in Java with Examples - GeeksforGeeks
12 Jun, 2020 The printf(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. It is a convenience method. Syntax: public Console printf(String fmt, Object... args) Parameters: This method accepts two parameters: fmt – It represents the format of the string. args – It represents the arguments that are referenced by the format specifiers in the string format. Return value: This method returns the console. Exceptions: This method throws IllegalFormatException if string format contains an illegal syntax or a format specifier is not compatible with the given arguments or insufficient arguments given the format string or other conditions that are illegal. Note: System.console() returns null in an online IDE. Below programs illustrate printf(String, Object) method in Console class in IO package: Program 1: // Java program to illustrate// Console printf(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( "No console available"); return; } String fmt = "%1$4s %2$10s %3$10s%n"; cnsl.printf(fmt, "Books", "Author", "Price"); cnsl.printf(fmt, "-----", "------", "-----"); cnsl.printf(fmt, "DBMS", "Navathe", "800"); cnsl.printf(fmt, "Algorithm", "Cormen", "925"); cnsl.printf(fmt, "Operating System", "Rajib Mall", "750"); }} Program 2: // Java program to illustrate// Console printf(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( "No console available"); return; } String fmt = "%1$4s %2$10s %3$10s%n"; cnsl.printf(fmt, "Items", "Quantity", "Price"); cnsl.printf(fmt, "-----", "------", "-----"); cnsl.printf(fmt, "Tomato", "1 Kg", "80"); cnsl.printf(fmt, "Apple", "3 Kg", "500"); cnsl.printf(fmt, "Potato", "2 Kg", "75"); }} References:https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#printf(java.lang.String, java.lang.Object...) Java-Functions Java-IO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Overriding in Java Stack Class in Java Collections in Java
[ { "code": null, "e": 24418, "s": 24390, "text": "\n12 Jun, 2020" }, { "code": null, "e": 24629, "s": 24418, "text": "The printf(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. It is a convenience method." }, { "code": null, "e": 24637, "s": 24629, "text": "Syntax:" }, { "code": null, "e": 24710, "s": 24637, "text": "public Console printf(String fmt,\n Object... args)\n" }, { "code": null, "e": 24758, "s": 24710, "text": "Parameters: This method accepts two parameters:" }, { "code": null, "e": 24804, "s": 24758, "text": "fmt – It represents the format of the string." }, { "code": null, "e": 24906, "s": 24804, "text": "args – It represents the arguments that are referenced by the format specifiers in the string format." }, { "code": null, "e": 24953, "s": 24906, "text": "Return value: This method returns the console." }, { "code": null, "e": 25204, "s": 24953, "text": "Exceptions: This method throws IllegalFormatException if string format contains an illegal syntax or a format specifier is not compatible with the given arguments or insufficient arguments given the format string or other conditions that are illegal." }, { "code": null, "e": 25258, "s": 25204, "text": "Note: System.console() returns null in an online IDE." }, { "code": null, "e": 25346, "s": 25258, "text": "Below programs illustrate printf(String, Object) method in Console class in IO package:" }, { "code": null, "e": 25357, "s": 25346, "text": "Program 1:" }, { "code": "// Java program to illustrate// Console printf(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( \"No console available\"); return; } String fmt = \"%1$4s %2$10s %3$10s%n\"; cnsl.printf(fmt, \"Books\", \"Author\", \"Price\"); cnsl.printf(fmt, \"-----\", \"------\", \"-----\"); cnsl.printf(fmt, \"DBMS\", \"Navathe\", \"800\"); cnsl.printf(fmt, \"Algorithm\", \"Cormen\", \"925\"); cnsl.printf(fmt, \"Operating System\", \"Rajib Mall\", \"750\"); }}", "e": 26061, "s": 25357, "text": null }, { "code": null, "e": 26072, "s": 26061, "text": "Program 2:" }, { "code": "// Java program to illustrate// Console printf(String, Object) method import java.io.*; public class GFG { public static void main(String[] args) { // Create the console object Console cnsl = System.console(); if (cnsl == null) { System.out.println( \"No console available\"); return; } String fmt = \"%1$4s %2$10s %3$10s%n\"; cnsl.printf(fmt, \"Items\", \"Quantity\", \"Price\"); cnsl.printf(fmt, \"-----\", \"------\", \"-----\"); cnsl.printf(fmt, \"Tomato\", \"1 Kg\", \"80\"); cnsl.printf(fmt, \"Apple\", \"3 Kg\", \"500\"); cnsl.printf(fmt, \"Potato\", \"2 Kg\", \"75\"); }}", "e": 26753, "s": 26072, "text": null }, { "code": null, "e": 26874, "s": 26753, "text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/Console.html#printf(java.lang.String, java.lang.Object...)" }, { "code": null, "e": 26889, "s": 26874, "text": "Java-Functions" }, { "code": null, "e": 26905, "s": 26889, "text": "Java-IO package" }, { "code": null, "e": 26910, "s": 26905, "text": "Java" }, { "code": null, "e": 26915, "s": 26910, "text": "Java" }, { "code": null, "e": 27013, "s": 26915, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27022, "s": 27013, "text": "Comments" }, { "code": null, "e": 27035, "s": 27022, "text": "Old Comments" }, { "code": null, "e": 27065, "s": 27035, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27084, "s": 27065, "text": "Interfaces in Java" }, { "code": null, "e": 27116, "s": 27084, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27167, "s": 27116, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27185, "s": 27167, "text": "ArrayList in Java" }, { "code": null, "e": 27216, "s": 27185, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27248, "s": 27216, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27267, "s": 27248, "text": "Overriding in Java" }, { "code": null, "e": 27287, "s": 27267, "text": "Stack Class in Java" } ]
Mathematics | Propositional Equivalences - GeeksforGeeks
02 Apr, 2019 IntroductionTwo logical expressions are said to be equivalent if they have the same truth value in all cases. Sometimes this fact helps in proving a mathematical result by replacing one expression with another equivalent expression, without changing the truth value of the original compound proposition. Types of propositions based on Truth values There are three types of propositions when classified according to their truth valuesTautology – A proposition which is always true, is called a tautology.Contradiction – A proposition which is always false, is called a contradiction.Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency. Tautology – A proposition which is always true, is called a tautology. Contradiction – A proposition which is always false, is called a contradiction. Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency. Example, 1. is a tautology. 2. is a contradiction. 3. is a contingency. Definition of Logical EquivalenceFormally,Two propositions and are said to be logically equivalent if is a Tautology. The notation is used to denote that and are logically equivalent.One way of proving that two propositions are logically equivalent is to use a truth table. The truth table must be identical for all combinations for the given propositions to be equivalent. But this method is not always feasible since the propositions can be increasingly complex both in the number of propositional variables used and size of the expression.In this case, there needs to be a better way to prove that the two given propositions are logically equivalent. That better way is to construct a mathematical proof which uses already established logical equivalences to construct additional more useful logical equivalences.Some basic established logical equivalences are tabulated below- The above Logical Equivalences used only conjunction, disjunction and negation. Other logical Equivalences using conditionals and bi-conditionals are- Example,Show that . Considering LHS, Another example,Show that . Considering LHS, The above examples could easily be solved using a truth table. But this can only be done for a proposition having a small number of propositional variables. When the number of variables grows the truth table method becomes impractical.For a proposition having 20 variables, rows have to be evaluated in the truth table. This may be easy to do with a computer, but even a computer would fail in computing the truth table of a proposition having 1000 variables. GATE CS Corner Questions Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.1. GATE CS 2008, Question 332. GATE CS 2014 Set-2, Question 633. GATE CS 2006, Question 274. GATE CS 2015 Set-3, Question 65 References,Logical Equivalence – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. VaibhavRai3 Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inequalities in LaTeX Newton's Divided Difference Interpolation Formula Univariate, Bivariate and Multivariate data and its analysis Activation Functions Arrow Symbols in LaTeX Layers of OSI Model ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 29952, "s": 29924, "text": "\n02 Apr, 2019" }, { "code": null, "e": 30256, "s": 29952, "text": "IntroductionTwo logical expressions are said to be equivalent if they have the same truth value in all cases. Sometimes this fact helps in proving a mathematical result by replacing one expression with another equivalent expression, without changing the truth value of the original compound proposition." }, { "code": null, "e": 30300, "s": 30256, "text": "Types of propositions based on Truth values" }, { "code": null, "e": 30635, "s": 30300, "text": "There are three types of propositions when classified according to their truth valuesTautology – A proposition which is always true, is called a tautology.Contradiction – A proposition which is always false, is called a contradiction.Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency." }, { "code": null, "e": 30706, "s": 30635, "text": "Tautology – A proposition which is always true, is called a tautology." }, { "code": null, "e": 30786, "s": 30706, "text": "Contradiction – A proposition which is always false, is called a contradiction." }, { "code": null, "e": 30887, "s": 30786, "text": "Contingency – A proposition that is neither a tautology nor a contradiction is called a contingency." }, { "code": null, "e": 30896, "s": 30887, "text": "Example," }, { "code": null, "e": 30963, "s": 30896, "text": "1. is a tautology.\n2. is a contradiction.\n3. is a contingency.\n" }, { "code": null, "e": 31850, "s": 30963, "text": "Definition of Logical EquivalenceFormally,Two propositions and are said to be logically equivalent if is a Tautology. The notation is used to denote that and are logically equivalent.One way of proving that two propositions are logically equivalent is to use a truth table. The truth table must be identical for all combinations for the given propositions to be equivalent. But this method is not always feasible since the propositions can be increasingly complex both in the number of propositional variables used and size of the expression.In this case, there needs to be a better way to prove that the two given propositions are logically equivalent. That better way is to construct a mathematical proof which uses already established logical equivalences to construct additional more useful logical equivalences.Some basic established logical equivalences are tabulated below-" }, { "code": null, "e": 32001, "s": 31850, "text": "The above Logical Equivalences used only conjunction, disjunction and negation. Other logical Equivalences using conditionals and bi-conditionals are-" }, { "code": null, "e": 32021, "s": 32001, "text": "Example,Show that ." }, { "code": null, "e": 32046, "s": 32021, "text": "Considering LHS,\n \n" }, { "code": null, "e": 32082, "s": 32054, "text": "Another example,Show that ." }, { "code": null, "e": 32107, "s": 32082, "text": "Considering LHS,\n \n" }, { "code": null, "e": 32576, "s": 32115, "text": "The above examples could easily be solved using a truth table. But this can only be done for a proposition having a small number of propositional variables. When the number of variables grows the truth table method becomes impractical.For a proposition having 20 variables, rows have to be evaluated in the truth table. This may be easy to do with a computer, but even a computer would fail in computing the truth table of a proposition having 1000 variables." }, { "code": null, "e": 32601, "s": 32576, "text": "GATE CS Corner Questions" }, { "code": null, "e": 32923, "s": 32601, "text": "Practicing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.1. GATE CS 2008, Question 332. GATE CS 2014 Set-2, Question 633. GATE CS 2006, Question 274. GATE CS 2015 Set-3, Question 65" }, { "code": null, "e": 33027, "s": 32923, "text": "References,Logical Equivalence – WikipediaDiscrete Mathematics and its Applications, by Kenneth H Rosen" }, { "code": null, "e": 33329, "s": 33027, "text": "This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 33454, "s": 33329, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33466, "s": 33454, "text": "VaibhavRai3" }, { "code": null, "e": 33490, "s": 33466, "text": "Engineering Mathematics" }, { "code": null, "e": 33498, "s": 33490, "text": "GATE CS" }, { "code": null, "e": 33596, "s": 33498, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33605, "s": 33596, "text": "Comments" }, { "code": null, "e": 33618, "s": 33605, "text": "Old Comments" }, { "code": null, "e": 33640, "s": 33618, "text": "Inequalities in LaTeX" }, { "code": null, "e": 33690, "s": 33640, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 33751, "s": 33690, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 33772, "s": 33751, "text": "Activation Functions" }, { "code": null, "e": 33795, "s": 33772, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 33815, "s": 33795, "text": "Layers of OSI Model" }, { "code": null, "e": 33839, "s": 33815, "text": "ACID Properties in DBMS" }, { "code": null, "e": 33866, "s": 33839, "text": "Types of Operating Systems" }, { "code": null, "e": 33887, "s": 33866, "text": "Normal Forms in DBMS" } ]
Explain Python class method chaining
Method chaining is a technique that is used for making multiple method calls on the same object, using the object reference just once. Example − Assume we have a class Foo that has two methods, bar and baz. We create an instance of the class Foo − foo = Foo() Without method chaining, to call both bar and baz, on the object foo, we do this − foo.bar() foo.baz() With method chaining, we do this − Chain calls to both methods bar() and baz() on object foo. foo.bar().baz() Simple method chaining can be implemented easily in Python. class Foo(object): def bar(self): print "Foo.bar called" return self def baz(self): print "Foo.baz called" return self foo = Foo() foo2 = foo.bar().baz() print " id(foo):", id(foo) print "id(foo2):", id(foo2) Here is the output of running the above program − Foo.bar called Foo.baz called id(foo): 87108128 id(foo2): 87108128
[ { "code": null, "e": 1207, "s": 1062, "text": "Method chaining is a technique that is used for making multiple method calls on the same object, using the object reference just once. Example −" }, { "code": null, "e": 1269, "s": 1207, "text": "Assume we have a class Foo that has two methods, bar and baz." }, { "code": null, "e": 1310, "s": 1269, "text": "We create an instance of the class Foo −" }, { "code": null, "e": 1322, "s": 1310, "text": "foo = Foo()" }, { "code": null, "e": 1405, "s": 1322, "text": "Without method chaining, to call both bar and baz, on the object foo, we do this −" }, { "code": null, "e": 1425, "s": 1405, "text": "foo.bar()\nfoo.baz()" }, { "code": null, "e": 1460, "s": 1425, "text": "With method chaining, we do this −" }, { "code": null, "e": 1519, "s": 1460, "text": "Chain calls to both methods bar() and baz() on object foo." }, { "code": null, "e": 1535, "s": 1519, "text": "foo.bar().baz()" }, { "code": null, "e": 1595, "s": 1535, "text": "Simple method chaining can be implemented easily in Python." }, { "code": null, "e": 1844, "s": 1595, "text": "class Foo(object):\n def bar(self):\n print \"Foo.bar called\"\n return self\n def baz(self):\n print \"Foo.baz called\"\n return self\nfoo = Foo()\nfoo2 = foo.bar().baz()\nprint \" id(foo):\", id(foo)\nprint \"id(foo2):\", id(foo2)" }, { "code": null, "e": 1894, "s": 1844, "text": "Here is the output of running the above program −" }, { "code": null, "e": 1961, "s": 1894, "text": "Foo.bar called\nFoo.baz called\nid(foo): 87108128\nid(foo2): 87108128" } ]
PHP | eval() Function - GeeksforGeeks
20 Jun, 2018 The eval() function in PHP is an inbuilt function that evaluates a string as PHP code. Syntax: eval( $string ) Parameters: This function accepts a single parameter as shown in above syntax and and described below. $string: It must consist of a valid PHP code to be evaluated but should not contain opening and closing PHP tags. Note: All statements must be properly terminated using a semicolon. For example, initializing the string as ‘echo “Geeks for Geeks”‘ will cause a parse error. In order to rectify, need to initialize as ‘echo “Geeks for Geeks”;’. Return Value: Returns NULL unless a return statement is called in the input string containing PHP code. Then the value is returned. In case of a parse error in the input string, the function returns FALSE. Examples: Input : $age = 20; $str = "I am $age years old" eval("\$str = \"$str\";"); Output : I am 20 years old Input : $str = 'echo "Geeks for Geeks";'; echo eval($str). "\n"; Output : Geeks for Geeks Below programs illustrate the use of eval() function: Program 1: <?php $age = 20;$str = 'My age is $age';echo $str. "\n"; eval("\$str = \"$str\";");echo $str. "\n";?> My age is $age My age is 20 Program 2: <?php $str = 'echo "Geeks for Geeks";';echo eval($str). "\n";?> Geeks for Geeks Reference : http://php.net/manual/en/function.eval.php PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? Comparing two dates in PHP How to fetch data from localserver database and display on HTML table using PHP ? PHP | Converting string to Date and DateTime Roadmap to Become a Web Developer 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": 24706, "s": 24678, "text": "\n20 Jun, 2018" }, { "code": null, "e": 24793, "s": 24706, "text": "The eval() function in PHP is an inbuilt function that evaluates a string as PHP code." }, { "code": null, "e": 24801, "s": 24793, "text": "Syntax:" }, { "code": null, "e": 24817, "s": 24801, "text": "eval( $string )" }, { "code": null, "e": 24920, "s": 24817, "text": "Parameters: This function accepts a single parameter as shown in above syntax and and described below." }, { "code": null, "e": 25034, "s": 24920, "text": "$string: It must consist of a valid PHP code to be evaluated but should not contain opening and closing PHP tags." }, { "code": null, "e": 25263, "s": 25034, "text": "Note: All statements must be properly terminated using a semicolon. For example, initializing the string as ‘echo “Geeks for Geeks”‘ will cause a parse error. In order to rectify, need to initialize as ‘echo “Geeks for Geeks”;’." }, { "code": null, "e": 25469, "s": 25263, "text": "Return Value: Returns NULL unless a return statement is called in the input string containing PHP code. Then the value is returned. In case of a parse error in the input string, the function returns FALSE." }, { "code": null, "e": 25479, "s": 25469, "text": "Examples:" }, { "code": null, "e": 25689, "s": 25479, "text": "Input : $age = 20; $str = \"I am $age years old\"\n eval(\"\\$str = \\\"$str\\\";\");\nOutput : I am 20 years old\n\nInput : $str = 'echo \"Geeks for Geeks\";';\n echo eval($str). \"\\n\";\nOutput : Geeks for Geeks\n" }, { "code": null, "e": 25743, "s": 25689, "text": "Below programs illustrate the use of eval() function:" }, { "code": null, "e": 25754, "s": 25743, "text": "Program 1:" }, { "code": "<?php $age = 20;$str = 'My age is $age';echo $str. \"\\n\"; eval(\"\\$str = \\\"$str\\\";\");echo $str. \"\\n\";?>", "e": 25858, "s": 25754, "text": null }, { "code": null, "e": 25887, "s": 25858, "text": "My age is $age\nMy age is 20\n" }, { "code": null, "e": 25898, "s": 25887, "text": "Program 2:" }, { "code": "<?php $str = 'echo \"Geeks for Geeks\";';echo eval($str). \"\\n\";?>", "e": 25963, "s": 25898, "text": null }, { "code": null, "e": 25980, "s": 25963, "text": "Geeks for Geeks\n" }, { "code": null, "e": 26035, "s": 25980, "text": "Reference : http://php.net/manual/en/function.eval.php" }, { "code": null, "e": 26048, "s": 26035, "text": "PHP-function" }, { "code": null, "e": 26052, "s": 26048, "text": "PHP" }, { "code": null, "e": 26069, "s": 26052, "text": "Web Technologies" }, { "code": null, "e": 26073, "s": 26069, "text": "PHP" }, { "code": null, "e": 26171, "s": 26073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26180, "s": 26171, "text": "Comments" }, { "code": null, "e": 26193, "s": 26180, "text": "Old Comments" }, { "code": null, "e": 26243, "s": 26193, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26283, "s": 26243, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26310, "s": 26283, "text": "Comparing two dates in PHP" }, { "code": null, "e": 26392, "s": 26310, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26437, "s": 26392, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 26479, "s": 26437, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26512, "s": 26479, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26574, "s": 26512, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26617, "s": 26574, "text": "How to fetch data from an API in ReactJS ?" } ]
How to find 95% confidence interval for binomial data in R?
The binomial data has two parameters, the sample size and the number of successes. To find the 95% confidence interval we just need to use prop.test function in R but we need to make sure that we put correct argument to FALSE so that the confidence interval will be calculated without continuity correction. In the below examples, we have found the 95% confidence interval for different values of sample size and number of successes. Live Demo prop.test(x=25,n=100,conf.level=0.95,correct=FALSE) 1-sample proportions test without continuity correction data: 25 out of 100, null probability 0.5 X-squared = 25, df = 1, p-value = 5.733e-07 alternative hypothesis: true p is not equal to 0.5 95 percent confidence interval: 0.1754521 0.3430446 sample estimates: p 0.25 Live Demo prop.test(x=5,n=100,conf.level=0.95,correct=FALSE) 1-sample proportions test without continuity correction data: 5 out of 100, null probability 0.5 X-squared = 81, df = 1, p-value < 2.2e-16 alternative hypothesis: true p is not equal to 0.5 95 percent confidence interval: 0.02154368 0.11175047 sample estimates: p 0.05 Live Demo prop.test(x=5,n=1000,conf.level=0.95,correct=FALSE) 1-sample proportions test without continuity correction data: 5 out of 1000, null probability 0.5 X-squared = 980.1, df = 1, p-value < 2.2e-16 alternative hypothesis: true p is not equal to 0.5 95 percent confidence interval: 0.002137536 0.011650955 sample estimates: p 0.005 Live Demo prop.test(x=5,n=10,conf.level=0.95,correct=FALSE) 1-sample proportions test without continuity correction data: 5 out of 1000, null probability 0.5 X-squared = 980.1, df = 1, p-value < 2.2e-16 alternative hypothesis: true p is not equal to 0.5 95 percent confidence interval: 0.002137536 0.011650955 sample estimates: p 0.005 Live Demo prop.test(x=50,n=100,conf.level=0.95,correct=FALSE) 1-sample proportions test without continuity correction data: 50 out of 100, null probability 0.5 X-squared = 0, df = 1, p-value = 1 alternative hypothesis: true p is not equal to 0.5 95 percent confidence interval: 0.4038315 0.5961685 sample estimates: p 0.5 Live Demo prop.test(x=500,n=1125,conf.level=0.95,correct=FALSE) 1-sample proportions test without continuity correction data: 500 out of 1125, null probability 0.5 X-squared = 13.889, df = 1, p-value = 0.0001939 alternative hypothesis: true p is not equal to 0.5 95 percent confidence interval: 0.4156458 0.4736212 sample estimates: p 0.4444444 Live Demo prop.test(x=5000,n=9874,conf.level=0.95,correct=FALSE) 1-sample proportions test without continuity correction data: 5000 out of 9874, null probability 0.5 X-squared = 1.6079, df = 1, p-value = 0.2048 alternative hypothesis: true p is not equal to 0.5 95 percent confidence interval: 0.4965185 0.5162373 sample estimates: p 0.5063804
[ { "code": null, "e": 1496, "s": 1062, "text": "The binomial data has two parameters, the sample size and the number of successes. To find the 95% confidence interval we just need to use prop.test function in R but we need to make sure that we put correct argument to FALSE so that the confidence interval will be calculated without continuity correction. In the below examples, we have found the 95% confidence interval for different values of sample size and number of successes." }, { "code": null, "e": 1507, "s": 1496, "text": " Live Demo" }, { "code": null, "e": 1559, "s": 1507, "text": "prop.test(x=25,n=100,conf.level=0.95,correct=FALSE)" }, { "code": null, "e": 1829, "s": 1559, "text": "1-sample proportions test without continuity correction\ndata: 25 out of 100, null probability 0.5\nX-squared = 25, df = 1, p-value = 5.733e-07\nalternative hypothesis: true p is not equal to 0.5\n95 percent confidence interval:\n0.1754521 0.3430446\nsample estimates:\np\n0.25" }, { "code": null, "e": 1840, "s": 1829, "text": " Live Demo" }, { "code": null, "e": 1891, "s": 1840, "text": "prop.test(x=5,n=100,conf.level=0.95,correct=FALSE)" }, { "code": null, "e": 2160, "s": 1891, "text": "1-sample proportions test without continuity correction\ndata: 5 out of 100, null probability 0.5\nX-squared = 81, df = 1, p-value < 2.2e-16\nalternative hypothesis: true p is not equal to 0.5\n95 percent confidence interval:\n0.02154368 0.11175047\nsample estimates:\np\n0.05" }, { "code": null, "e": 2171, "s": 2160, "text": " Live Demo" }, { "code": null, "e": 2223, "s": 2171, "text": "prop.test(x=5,n=1000,conf.level=0.95,correct=FALSE)" }, { "code": null, "e": 2501, "s": 2223, "text": "1-sample proportions test without continuity correction\ndata: 5 out of 1000, null probability 0.5\nX-squared = 980.1, df = 1, p-value < 2.2e-16\nalternative hypothesis: true p is not equal to 0.5\n95 percent confidence interval:\n0.002137536 0.011650955\nsample estimates:\np\n0.005\n\n" }, { "code": null, "e": 2512, "s": 2501, "text": " Live Demo" }, { "code": null, "e": 2562, "s": 2512, "text": "prop.test(x=5,n=10,conf.level=0.95,correct=FALSE)" }, { "code": null, "e": 2838, "s": 2562, "text": "1-sample proportions test without continuity correction\ndata: 5 out of 1000, null probability 0.5\nX-squared = 980.1, df = 1, p-value < 2.2e-16\nalternative hypothesis: true p is not equal to 0.5\n95 percent confidence interval:\n0.002137536 0.011650955\nsample estimates:\np\n0.005" }, { "code": null, "e": 2849, "s": 2838, "text": " Live Demo" }, { "code": null, "e": 2901, "s": 2849, "text": "prop.test(x=50,n=100,conf.level=0.95,correct=FALSE)" }, { "code": null, "e": 3163, "s": 2901, "text": "1-sample proportions test without continuity correction\ndata: 50 out of 100, null probability 0.5\nX-squared = 0, df = 1, p-value = 1\nalternative hypothesis: true p is not equal to 0.5\n95 percent confidence interval:\n0.4038315 0.5961685\nsample estimates:\n p\n 0.5" }, { "code": null, "e": 3174, "s": 3163, "text": " Live Demo" }, { "code": null, "e": 3228, "s": 3174, "text": "prop.test(x=500,n=1125,conf.level=0.95,correct=FALSE)" }, { "code": null, "e": 3511, "s": 3228, "text": "1-sample proportions test without continuity correction\ndata: 500 out of 1125, null probability 0.5\nX-squared = 13.889, df = 1, p-value = 0.0001939\nalternative hypothesis: true p is not equal to 0.5\n95 percent confidence interval:\n0.4156458 0.4736212\nsample estimates:\n p\n 0.4444444" }, { "code": null, "e": 3522, "s": 3511, "text": " Live Demo" }, { "code": null, "e": 3577, "s": 3522, "text": "prop.test(x=5000,n=9874,conf.level=0.95,correct=FALSE)" }, { "code": null, "e": 3856, "s": 3577, "text": "1-sample proportions test without continuity correction\ndata: 5000 out of 9874, null probability 0.5\nX-squared = 1.6079, df = 1, p-value = 0.2048\nalternative hypothesis: true p is not equal to 0.5\n95 percent confidence interval:\n0.4965185 0.5162373\nsample estimates:\np\n0.5063804" } ]
DDA Line generation Algorithm in Computer Graphics - GeeksforGeeks
10 Mar, 2022 In any 2-Dimensional plane if we connect two points (x0, y0) and (x1, y1), we get a line segment. But in the case of computer graphics, we can not directly join any two coordinate points, for that we should calculate intermediate points’ coordinates and put a pixel for each intermediate point, of the desired color with help of functions like putpixel(x, y, K) in C, where (x,y) is our co-ordinate and K denotes some color.Examples: Input: For line segment between (2, 2) and (6, 6) : we need (3, 3) (4, 4) and (5, 5) as our intermediate points. Input: For line segment between (0, 2) and (0, 6) : we need (0, 3) (0, 4) and (0, 5) as our intermediate points. For using graphics functions, our system output screen is treated as a coordinate system where the coordinate of the top-left corner is (0, 0) and as we move down our y-ordinate increases and as we move right our x-ordinate increases for any point (x, y). Now, for generating any line segment we need intermediate points and for calculating them we can use a basic algorithm called DDA(Digital differential analyzer) line generating algorithm. DDA Algorithm : Consider one point of the line as (X0,Y0) and the second point of the line as (X1,Y1). // calculate dx , dy dx = X1 - X0; dy = Y1 - Y0; // Depending upon absolute value of dx & dy // choose number of steps to put pixel as // steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy) steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy); // calculate increment in x & y for each steps Xinc = dx / (float) steps; Yinc = dy / (float) steps; // Put pixel for each step X = X0; Y = Y0; for (int i = 0; i <= steps; i++) { putpixel (round(X),round(Y),WHITE); X += Xinc; Y += Yinc; } C Python3 // C program for DDA line generation#include<stdio.h>#include<graphics.h>#include<math.h>//Function for finding absolute valueint abs (int n){ return ( (n>0) ? n : ( n * (-1)));} //DDA Function for line generationvoid DDA(int X0, int Y0, int X1, int Y1){ // calculate dx & dy int dx = X1 - X0; int dy = Y1 - Y0; // calculate steps required for generating pixels int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy); // calculate increment in x & y for each steps float Xinc = dx / (float) steps; float Yinc = dy / (float) steps; // Put pixel for each step float X = X0; float Y = Y0; for (int i = 0; i <= steps; i++) { putpixel (round(X),round(Y),RED); // put pixel at (X,Y) X += Xinc; // increment in x at each step Y += Yinc; // increment in y at each step delay(100); // for visualization of line- // generation step by step }} // Driver programint main(){ int gd = DETECT, gm; // Initialize graphics function initgraph (&gd, &gm, ""); int X0 = 2, Y0 = 2, X1 = 14, Y1 = 16; DDA(2, 2, 14, 16); return 0;} # Python program for DDA line generationfrom matplotlib import pyplot as plt # DDA Function for line generationdef DDA(x0, y0, x1, y1): # find absolute differences dx = abs(x0 - x1) dy = abs(y0 - y1) # find maximum difference steps = max(dx, dy) # calculate the increment in x and y xinc = dx/steps yinc = dy/steps # start with 1st point x = float(x0) y = float(y0) # make a list for coordinates x_coorinates = [] y_coorinates = [] for i in range(steps): # append the x,y coordinates in respective list x_coorinates.append(x) y_coorinates.append(y) # increment the values x = x + xinc y = y + yinc # plot the line with coordinates list plt.plot(x_coorinates, y_coorinates, marker = "o", markersize = 1, markerfacecolor = "green") plt.show() if __name__ == "__main__": # coordinates of 1st point x0, y0 = 20, 20 # coordinates of 2nd point x1, y1 = 60, 50 DDA(x0, y0, x1, y1) # This code is contributed by 111arpit1 Output: Advantages : It is simple and easy to implement algorithm. It avoid using multiple operations which have high time complexities. It is faster than the direct use of the line equation because it does not use any floating point multiplication and it calculates points on the line. Disadvantages : It deals with the rounding off operation and floating point arithmetic so it has high time complexity. As it is orientation dependent, so it has poor endpoint accuracy. Due to the limited precision in the floating point representation it produces cumulative error. Bresenham’s Line Generation AlgorithmThis article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SayedAbdulTawabSadaat alpeshyadav itskawal2000 ashutoshsangra 111arpit1 computer-graphics Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? How to Start Learning DSA? Understanding Time Complexity with Simple Examples Introduction to Algorithms Playfair Cipher with Examples Recursive Practice Problems with Solutions Difference between NP hard and NP complete problem Quick Sort vs Merge Sort
[ { "code": null, "e": 25851, "s": 25823, "text": "\n10 Mar, 2022" }, { "code": null, "e": 26287, "s": 25851, "text": "In any 2-Dimensional plane if we connect two points (x0, y0) and (x1, y1), we get a line segment. But in the case of computer graphics, we can not directly join any two coordinate points, for that we should calculate intermediate points’ coordinates and put a pixel for each intermediate point, of the desired color with help of functions like putpixel(x, y, K) in C, where (x,y) is our co-ordinate and K denotes some color.Examples: " }, { "code": null, "e": 26514, "s": 26287, "text": "Input: For line segment between (2, 2) and (6, 6) :\nwe need (3, 3) (4, 4) and (5, 5) as our intermediate\npoints.\n\nInput: For line segment between (0, 2) and (0, 6) :\nwe need (0, 3) (0, 4) and (0, 5) as our intermediate\npoints." }, { "code": null, "e": 26959, "s": 26514, "text": "For using graphics functions, our system output screen is treated as a coordinate system where the coordinate of the top-left corner is (0, 0) and as we move down our y-ordinate increases and as we move right our x-ordinate increases for any point (x, y). Now, for generating any line segment we need intermediate points and for calculating them we can use a basic algorithm called DDA(Digital differential analyzer) line generating algorithm. " }, { "code": null, "e": 27064, "s": 26959, "text": "DDA Algorithm : Consider one point of the line as (X0,Y0) and the second point of the line as (X1,Y1). " }, { "code": null, "e": 27549, "s": 27064, "text": "// calculate dx , dy\ndx = X1 - X0;\ndy = Y1 - Y0;\n\n// Depending upon absolute value of dx & dy\n// choose number of steps to put pixel as\n// steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy)\nsteps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);\n\n// calculate increment in x & y for each steps\nXinc = dx / (float) steps;\nYinc = dy / (float) steps;\n\n// Put pixel for each step\nX = X0;\nY = Y0;\nfor (int i = 0; i <= steps; i++)\n{\n putpixel (round(X),round(Y),WHITE);\n X += Xinc;\n Y += Yinc;\n}" }, { "code": null, "e": 27555, "s": 27553, "text": "C" }, { "code": null, "e": 27563, "s": 27555, "text": "Python3" }, { "code": "// C program for DDA line generation#include<stdio.h>#include<graphics.h>#include<math.h>//Function for finding absolute valueint abs (int n){ return ( (n>0) ? n : ( n * (-1)));} //DDA Function for line generationvoid DDA(int X0, int Y0, int X1, int Y1){ // calculate dx & dy int dx = X1 - X0; int dy = Y1 - Y0; // calculate steps required for generating pixels int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy); // calculate increment in x & y for each steps float Xinc = dx / (float) steps; float Yinc = dy / (float) steps; // Put pixel for each step float X = X0; float Y = Y0; for (int i = 0; i <= steps; i++) { putpixel (round(X),round(Y),RED); // put pixel at (X,Y) X += Xinc; // increment in x at each step Y += Yinc; // increment in y at each step delay(100); // for visualization of line- // generation step by step }} // Driver programint main(){ int gd = DETECT, gm; // Initialize graphics function initgraph (&gd, &gm, \"\"); int X0 = 2, Y0 = 2, X1 = 14, Y1 = 16; DDA(2, 2, 14, 16); return 0;}", "e": 28723, "s": 27563, "text": null }, { "code": "# Python program for DDA line generationfrom matplotlib import pyplot as plt # DDA Function for line generationdef DDA(x0, y0, x1, y1): # find absolute differences dx = abs(x0 - x1) dy = abs(y0 - y1) # find maximum difference steps = max(dx, dy) # calculate the increment in x and y xinc = dx/steps yinc = dy/steps # start with 1st point x = float(x0) y = float(y0) # make a list for coordinates x_coorinates = [] y_coorinates = [] for i in range(steps): # append the x,y coordinates in respective list x_coorinates.append(x) y_coorinates.append(y) # increment the values x = x + xinc y = y + yinc # plot the line with coordinates list plt.plot(x_coorinates, y_coorinates, marker = \"o\", markersize = 1, markerfacecolor = \"green\") plt.show() if __name__ == \"__main__\": # coordinates of 1st point x0, y0 = 20, 20 # coordinates of 2nd point x1, y1 = 60, 50 DDA(x0, y0, x1, y1) # This code is contributed by 111arpit1", "e": 29767, "s": 28723, "text": null }, { "code": null, "e": 29777, "s": 29767, "text": "Output: " }, { "code": null, "e": 29794, "s": 29779, "text": "Advantages : " }, { "code": null, "e": 29840, "s": 29794, "text": "It is simple and easy to implement algorithm." }, { "code": null, "e": 29910, "s": 29840, "text": "It avoid using multiple operations which have high time complexities." }, { "code": null, "e": 30060, "s": 29910, "text": "It is faster than the direct use of the line equation because it does not use any floating point multiplication and it calculates points on the line." }, { "code": null, "e": 30078, "s": 30060, "text": "Disadvantages : " }, { "code": null, "e": 30181, "s": 30078, "text": "It deals with the rounding off operation and floating point arithmetic so it has high time complexity." }, { "code": null, "e": 30247, "s": 30181, "text": "As it is orientation dependent, so it has poor endpoint accuracy." }, { "code": null, "e": 30343, "s": 30247, "text": "Due to the limited precision in the floating point representation it produces cumulative error." }, { "code": null, "e": 30816, "s": 30343, "text": "Bresenham’s Line Generation AlgorithmThis article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30838, "s": 30816, "text": "SayedAbdulTawabSadaat" }, { "code": null, "e": 30850, "s": 30838, "text": "alpeshyadav" }, { "code": null, "e": 30863, "s": 30850, "text": "itskawal2000" }, { "code": null, "e": 30878, "s": 30863, "text": "ashutoshsangra" }, { "code": null, "e": 30888, "s": 30878, "text": "111arpit1" }, { "code": null, "e": 30906, "s": 30888, "text": "computer-graphics" }, { "code": null, "e": 30917, "s": 30906, "text": "Algorithms" }, { "code": null, "e": 30928, "s": 30917, "text": "Algorithms" }, { "code": null, "e": 31026, "s": 30928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31075, "s": 31026, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31100, "s": 31075, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31128, "s": 31100, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 31155, "s": 31128, "text": "How to Start Learning DSA?" }, { "code": null, "e": 31206, "s": 31155, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 31233, "s": 31206, "text": "Introduction to Algorithms" }, { "code": null, "e": 31263, "s": 31233, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 31306, "s": 31263, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 31357, "s": 31306, "text": "Difference between NP hard and NP complete problem" } ]
How can I validate EditText input in Android?
This example demonstrate about How can I validate EditText input in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.java <? xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width= "match_parent" android :layout_height= "match_parent" android :layout_margin= "16dp" tools :context= ".MainActivity" > <EditText android :id= "@+id/editText" android :layout_width= "match_parent" android :layout_height= "wrap_content" android :hint= "Enter alpha-numeric text" android :inputType= "text" tools :ignore= "Autofill" /> </RelativeLayout> Step 3 − Add the following code to src/ValidateFilter.java package app.tutorialspoint.com.sample ; import android.text.InputFilter ; import android.text.Spanned ; import android.util.Log ; import java.util.regex.Matcher ; import java.util.regex.Pattern ; public class ValidateFilter implements InputFilter { @Override public CharSequence filter (CharSequence source , int start , int end , Spanned dest , int dstart , int dend) { for ( int i = start ; i < end ; i++) { String checkMe = String. valueOf (source.charAt(i)) ; Pattern pattern = Pattern. compile ( "[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*" ) ; Matcher matcher = pattern.matcher(checkMe) ; boolean valid = matcher.matches() ; if (!valid) { Log. d ( "" , "invalid" ) ; return "" ; } } return null; } } Step 4 − Add the following code to src/MainActivity.java package app.tutorialspoint.com.sample ; import android.os.Bundle ; import android.support.v7.app.AppCompatActivity ; import android.text.InputFilter ; import android.widget.EditText ; public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; EditText editText = findViewById(R.id. editText ) ; editText.setFilters( new InputFilter[]{ new ValidateFilter()}) ; } } Step 5 − Add the following code to androidManifest.xml <? xml version= "1.0" encoding= "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "app.tutorialspoint.com.sample" > <uses-permission android :name= "android.permission.CALL_PHONE" /> <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 –
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrate about How can I validate EditText input in Android." }, { "code": null, "e": 1268, "s": 1139, "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": 1333, "s": 1268, "text": "Step 2 − Add the following code to res/layout/activity_main.java" }, { "code": null, "e": 1932, "s": 1333, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"match_parent\"\n android :layout_margin= \"16dp\"\n tools :context= \".MainActivity\" >\n <EditText\n android :id= \"@+id/editText\"\n android :layout_width= \"match_parent\"\n android :layout_height= \"wrap_content\"\n android :hint= \"Enter alpha-numeric text\"\n android :inputType= \"text\"\n tools :ignore= \"Autofill\" />\n</RelativeLayout>" }, { "code": null, "e": 1991, "s": 1932, "text": "Step 3 − Add the following code to src/ValidateFilter.java" }, { "code": null, "e": 2837, "s": 1991, "text": "package app.tutorialspoint.com.sample ;\nimport android.text.InputFilter ;\nimport android.text.Spanned ;\nimport android.util.Log ;\nimport java.util.regex.Matcher ;\nimport java.util.regex.Pattern ;\npublic class ValidateFilter implements InputFilter {\n @Override\n public CharSequence filter (CharSequence source , int start , int end , Spanned dest ,\n int dstart , int dend) {\n for ( int i = start ; i < end ; i++) {\n String checkMe = String. valueOf (source.charAt(i)) ;\n Pattern pattern =\n Pattern. compile ( \"[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789_]*\" ) ;\n Matcher matcher = pattern.matcher(checkMe) ;\n boolean valid = matcher.matches() ;\n if (!valid) {\n Log. d ( \"\" , \"invalid\" ) ;\n return \"\" ;\n }\n }\n return null;\n }\n}" }, { "code": null, "e": 2894, "s": 2837, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3431, "s": 2894, "text": "package app.tutorialspoint.com.sample ;\nimport android.os.Bundle ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.text.InputFilter ;\nimport android.widget.EditText ;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n EditText editText = findViewById(R.id. editText ) ;\n editText.setFilters( new InputFilter[]{ new ValidateFilter()}) ;\n }\n}" }, { "code": null, "e": 3486, "s": 3431, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4273, "s": 3486, "text": "<? xml version= \"1.0\" encoding= \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package= \"app.tutorialspoint.com.sample\" >\n <uses-permission android :name= \"android.permission.CALL_PHONE\" />\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": 4621, "s": 4273, "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 –" } ]
Key Properties of Material Design EditText in Android - GeeksforGeeks
05 Nov, 2020 In the previous article Material Design EditText in Android with Examples its been discussed how to implement the Material design EditText and how they differ from the normal EditText. In this article its been discussed on how to customize MDC edit text fields with their key properties. Have a look at the following image to get the idea about the key properties of the MDC edit text fields. Invoke the following code inside activity_main.xml file. The attributes need to be concentrated are boxStrokeColor, boxStrokeWidth, boxStrokeWidthFocused. Inside the TextInputLayout. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Filled EditText" /> <!--this is the material design filled EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/filled_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Something" app:boxStrokeColor="@android:color/black" app:boxStrokeWidth="3dp" app:boxStrokeWidthFocused="7dp" app:helperText="Enter in text format only"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Outlined EditText" /> <!--this is the material design outlined EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/outline_edit_text" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Something" app:boxStrokeColor="@android:color/black" app:boxStrokeWidth="3dp" app:boxStrokeWidthFocused="7dp" app:helperText="Enter in text format only"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout> There are 4 types of end icon modes for MDC EditTexts. Those are: clear text.password toggle.custom.dropdown menu. clear text. password toggle. custom. dropdown menu. Note: For password toggle, the input type is required for the MDC EditText. For the start icon, there is a need for a vector icon. So import vector icon by right click on the drawable -> new -> Vector asset. Then select the desired vector icons. Refer to the following image if unable to locate the vector asset dialog in Android Studio. Invoke the following code into activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Filled EditText" /> <!--this is the material design filled EditText with helper text--> <!--the attribute endIconMode will make the end icon mode according to the EditText context--> <!--the startIconDrawable attribute sets the icon at the start of the EditText--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/filled_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Something" app:endIconMode="clear_text" app:helperText="Enter in text format only" app:startIconDrawable="@drawable/ic_text_fields_black_24dp"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Outlined EditText" /> <!--this is the material design outlined EditText with helper text--> <!--the attribute endIconMode will make the end icon mode according to the EditText context--> <!--the startIconDrawable attribute sets the icon at the start of the EditText--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/outline_edit_text" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Password" app:endIconMode="password_toggle" app:helperText="Enter in text format only" app:startIconDrawable="@drawable/ic_vpn_key_black_24dp"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout> This is the small text which can be invoked to inform the user what type of data to be entered to the EditText. Invoke the following to inside the activity_main.xml file. Comments are added inside the code for better understanding. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Filled EditText" /> <!--this is the material design filled EditText with helper text--> <!--the attribute helperText sets the helper text below the EditText box--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/filled_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Height" app:helperText="Height should be in-terms of feet (ft.)"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="64dp" android:text="Material Design Outlined EditText" /> <!--this is the material design outlined EditText with helper text--> <!--the attribute helperText sets the helper text below the EditText box--> <com.google.android.material.textfield.TextInputLayout android:id="@+id/outline_edit_text" style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:hint="Enter Password" app:helperText="Password must be a number"> <com.google.android.material.textfield.TextInputEditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="numberPassword" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout> android Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Flutter - Custom Bottom Navigation Bar Android Listview in Java with Example How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? MVP (Model View Presenter) Architecture Pattern in Android with Example Fragment Lifecycle in Android How to Add Image to Drawable Folder in Android Studio? How to Post Data to API using Retrofit in Android? Animation in Android with Example
[ { "code": null, "e": 25142, "s": 25114, "text": "\n05 Nov, 2020" }, { "code": null, "e": 25535, "s": 25142, "text": "In the previous article Material Design EditText in Android with Examples its been discussed how to implement the Material design EditText and how they differ from the normal EditText. In this article its been discussed on how to customize MDC edit text fields with their key properties. Have a look at the following image to get the idea about the key properties of the MDC edit text fields." }, { "code": null, "e": 25592, "s": 25535, "text": "Invoke the following code inside activity_main.xml file." }, { "code": null, "e": 25718, "s": 25592, "text": "The attributes need to be concentrated are boxStrokeColor, boxStrokeWidth, boxStrokeWidthFocused. Inside the TextInputLayout." }, { "code": null, "e": 25722, "s": 25718, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Filled EditText\" /> <!--this is the material design filled EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/filled_edit_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" app:boxStrokeColor=\"@android:color/black\" app:boxStrokeWidth=\"3dp\" app:boxStrokeWidthFocused=\"7dp\" app:helperText=\"Enter in text format only\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Outlined EditText\" /> <!--this is the material design outlined EditText with helper text--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/outline_edit_text\" style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" app:boxStrokeColor=\"@android:color/black\" app:boxStrokeWidth=\"3dp\" app:boxStrokeWidthFocused=\"7dp\" app:helperText=\"Enter in text format only\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout>", "e": 28325, "s": 25722, "text": null }, { "code": null, "e": 28391, "s": 28325, "text": "There are 4 types of end icon modes for MDC EditTexts. Those are:" }, { "code": null, "e": 28440, "s": 28391, "text": "clear text.password toggle.custom.dropdown menu." }, { "code": null, "e": 28452, "s": 28440, "text": "clear text." }, { "code": null, "e": 28469, "s": 28452, "text": "password toggle." }, { "code": null, "e": 28477, "s": 28469, "text": "custom." }, { "code": null, "e": 28492, "s": 28477, "text": "dropdown menu." }, { "code": null, "e": 28568, "s": 28492, "text": "Note: For password toggle, the input type is required for the MDC EditText." }, { "code": null, "e": 28738, "s": 28568, "text": "For the start icon, there is a need for a vector icon. So import vector icon by right click on the drawable -> new -> Vector asset. Then select the desired vector icons." }, { "code": null, "e": 28830, "s": 28738, "text": "Refer to the following image if unable to locate the vector asset dialog in Android Studio." }, { "code": null, "e": 28885, "s": 28830, "text": "Invoke the following code into activity_main.xml file." }, { "code": null, "e": 28889, "s": 28885, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Filled EditText\" /> <!--this is the material design filled EditText with helper text--> <!--the attribute endIconMode will make the end icon mode according to the EditText context--> <!--the startIconDrawable attribute sets the icon at the start of the EditText--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/filled_edit_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Something\" app:endIconMode=\"clear_text\" app:helperText=\"Enter in text format only\" app:startIconDrawable=\"@drawable/ic_text_fields_black_24dp\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Outlined EditText\" /> <!--this is the material design outlined EditText with helper text--> <!--the attribute endIconMode will make the end icon mode according to the EditText context--> <!--the startIconDrawable attribute sets the icon at the start of the EditText--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/outline_edit_text\" style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Password\" app:endIconMode=\"password_toggle\" app:helperText=\"Enter in text format only\" app:startIconDrawable=\"@drawable/ic_vpn_key_black_24dp\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:inputType=\"textPassword\" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout>", "e": 31900, "s": 28889, "text": null }, { "code": null, "e": 32012, "s": 31900, "text": "This is the small text which can be invoked to inform the user what type of data to be entered to the EditText." }, { "code": null, "e": 32132, "s": 32012, "text": "Invoke the following to inside the activity_main.xml file. Comments are added inside the code for better understanding." }, { "code": null, "e": 32136, "s": 32132, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Filled EditText\" /> <!--this is the material design filled EditText with helper text--> <!--the attribute helperText sets the helper text below the EditText box--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/filled_edit_text\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Height\" app:helperText=\"Height should be in-terms of feet (ft.)\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" /> </com.google.android.material.textfield.TextInputLayout> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"64dp\" android:text=\"Material Design Outlined EditText\" /> <!--this is the material design outlined EditText with helper text--> <!--the attribute helperText sets the helper text below the EditText box--> <com.google.android.material.textfield.TextInputLayout android:id=\"@+id/outline_edit_text\" style=\"@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"16dp\" android:layout_marginEnd=\"16dp\" android:hint=\"Enter Password\" app:helperText=\"Password must be a number\"> <com.google.android.material.textfield.TextInputEditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:inputType=\"numberPassword\" /> </com.google.android.material.textfield.TextInputLayout> </LinearLayout>", "e": 34745, "s": 32136, "text": null }, { "code": null, "e": 34753, "s": 34745, "text": "android" }, { "code": null, "e": 34777, "s": 34753, "text": "Technical Scripter 2020" }, { "code": null, "e": 34785, "s": 34777, "text": "Android" }, { "code": null, "e": 34804, "s": 34785, "text": "Technical Scripter" }, { "code": null, "e": 34812, "s": 34804, "text": "Android" }, { "code": null, "e": 34910, "s": 34812, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34919, "s": 34910, "text": "Comments" }, { "code": null, "e": 34932, "s": 34919, "text": "Old Comments" }, { "code": null, "e": 34974, "s": 34932, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 35013, "s": 34974, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 35051, "s": 35013, "text": "Android Listview in Java with Example" }, { "code": null, "e": 35101, "s": 35051, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 35174, "s": 35101, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 35246, "s": 35174, "text": "MVP (Model View Presenter) Architecture Pattern in Android with Example" }, { "code": null, "e": 35276, "s": 35246, "text": "Fragment Lifecycle in Android" }, { "code": null, "e": 35331, "s": 35276, "text": "How to Add Image to Drawable Folder in Android Studio?" }, { "code": null, "e": 35382, "s": 35331, "text": "How to Post Data to API using Retrofit in Android?" } ]
7 Pandas Functions That I Use the Most | by Soner Yıldırım | Towards Data Science
Pandas is a prominent data analysis and manipulation library. It provides numerous functions and methods that expedite the data analysis and exploration process. Within the rich selection of functions and methods, some of them are more commonly used. They provide a quick way to obtain a basic understanding of the data at hand. In this post, I will go over 7 pandas functions that I most commonly use in my data analysis projects. I will use a diabetes dataset available on Kaggle. Let’s first read the dataset into a pandas dataframe. import pandas as pdimport numpy as npdiabetes = pd.read_csv("/content/diabetes.csv") Once we read a dataset into a pandas dataframe, we want to take a look at it to get an overview. The simplest way is to display some rows. Head and tail allow us to display rows from the top of bottom of dataframe, respectively. diabetes.head() diabetes.tail() 5 rows are displayed by default but we can adjust it just by passing the number of rows we’d like to display. For instance, diabetes.head(10) will display the first 10 rows. When working with categorical data or features that have discrete values, it is very important to know the number of unique values. It is an essential step towards data exploration. One way is to use value_counts function which returns a pandas series with unique values in a column and the number of occurrences of each value. The length of this series is the number of unique values. len(diabetes.Pregnancies.value_counts())17 I find nunique easier to use: diabetes.Pregnancies.nunique()17 We can also apply it to the entire dataframe and see the number of unique values in each column which I think make nunique more functional: diabetes.nunique() Describe function gives a quick overview of numerical columns by providing basic statistics such as mean, median, and standard deviation. diabetes.describe() 25%, 50%, and 75% are the percentiles. 50% is also known as the median which is the value in the middle when all values are sorted. 25% is the first quartile so 25% of the values are below this point. You can think of it as median of the lower half of a column. Similarly, 75% is the third quartile. The basic statistics give us valuable insights. For instance, by comparing mean and median (50%), we have an understanding of the outliers. If mean is much higher than the median, there are outliers on the upper side. The basic statistics also give us an overview of the distribution of data. You can also select different percentiles to display using percentiles parameter. The default values are [.25, .50, .75]. For instance percentiles=[.1, .25, .5, .75, .9] will display 10% and 90% percentiles in addition to default values. Handling missing values is a critical step to build a robust data analysis process. The missing values should be a top priority since they have a significant effect on the accuracy of any analysis. Isna function returns a dataframe filled with boolean values with true indicating missing values. diabetes.describe() Unless you want to analyze the dataframe cell by cell, isna should be combined with an aggregation. isna().any() indicates if there is any missing value in a column whereas isna().sum() returns the number of missing values in columns. diabetes.isna().any() diabetes.isna().sum() The dataset we have does not have any missing values but this is a highly unlikely case in real-life. Pandas groupby function is a great tool in exploring the data. It makes it easier to unveil the underlying relationships among variables. The figure below shows an overview of what groupby function does. Assume we have two features. One is color which is a categorical feature and the other one is a numerical feature, values. We want to group values by color and calculate the mean (or any other aggregation) of values for different colors. Then finally sort the colors based on average values. You can, of course, create more complex grouping operations but the concept will be the same. Let’s create a simple grouping operation with our dataset. The following code will show us the average glucose values of diabetes positive and negative people. diabetes[['Outcome','Glucose']].groupby('Outcome').mean() As expected, glucose values are higher for diabetes positive (1). We do not have many categorical variables in the dataset so what we can do with groupby function on this dataset is kind of limited. However, if you’d like to read more about groupby function and see more complex examples, I have a post dedicated to pandas groupby function. towardsdatascience.com We need to have the values stored in an appropriate data type. Otherwise, we may encounter errors. For large datasets, memory-usage is greatly affected by correct data type selection. For example, “categorical” data type is more appropriate than “object” data type for categorical data especially when the number of categories is much less than the number of rows. Dtypes shows the data type of each column. diabetes.dtypes The data type of “BloodPressure” column is not appropriate. It should be int or float. Object data type can be to store strings or categorical data. We can easily change the data type with astype function. diabetes.BloodPressure = diabetes.BloodPressure.astype('int64')diabetes.dtypes Shape can be used on numpy arrays, pandas series and dataframes. It shows the number of dimensions as well as the size in each dimension. Since dataframes are two-dimensional, what shape returns is the number of rows and columns. It is a measure of how much data we have and a key input to the data analysis process. Furthermore, the ratio of rows and columns is very important when designing and implementing a machine learning model. If we do not have enough observations (rows) with respect to features (columns), we may need to apply some pre-processing techniques such as dimensionality reduction or feature extraction. diabetes.shape(768, 9) Let’s apply it on a column which is actually a pandas series. diabetes.Glucose.shape(768,) Size, as the name suggests, returns the size of a dataframe which is the number of rows multiplied by the number of columns. diabetes.size6912 Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 334, "s": 172, "text": "Pandas is a prominent data analysis and manipulation library. It provides numerous functions and methods that expedite the data analysis and exploration process." }, { "code": null, "e": 501, "s": 334, "text": "Within the rich selection of functions and methods, some of them are more commonly used. They provide a quick way to obtain a basic understanding of the data at hand." }, { "code": null, "e": 604, "s": 501, "text": "In this post, I will go over 7 pandas functions that I most commonly use in my data analysis projects." }, { "code": null, "e": 709, "s": 604, "text": "I will use a diabetes dataset available on Kaggle. Let’s first read the dataset into a pandas dataframe." }, { "code": null, "e": 794, "s": 709, "text": "import pandas as pdimport numpy as npdiabetes = pd.read_csv(\"/content/diabetes.csv\")" }, { "code": null, "e": 1023, "s": 794, "text": "Once we read a dataset into a pandas dataframe, we want to take a look at it to get an overview. The simplest way is to display some rows. Head and tail allow us to display rows from the top of bottom of dataframe, respectively." }, { "code": null, "e": 1039, "s": 1023, "text": "diabetes.head()" }, { "code": null, "e": 1055, "s": 1039, "text": "diabetes.tail()" }, { "code": null, "e": 1229, "s": 1055, "text": "5 rows are displayed by default but we can adjust it just by passing the number of rows we’d like to display. For instance, diabetes.head(10) will display the first 10 rows." }, { "code": null, "e": 1411, "s": 1229, "text": "When working with categorical data or features that have discrete values, it is very important to know the number of unique values. It is an essential step towards data exploration." }, { "code": null, "e": 1615, "s": 1411, "text": "One way is to use value_counts function which returns a pandas series with unique values in a column and the number of occurrences of each value. The length of this series is the number of unique values." }, { "code": null, "e": 1658, "s": 1615, "text": "len(diabetes.Pregnancies.value_counts())17" }, { "code": null, "e": 1688, "s": 1658, "text": "I find nunique easier to use:" }, { "code": null, "e": 1721, "s": 1688, "text": "diabetes.Pregnancies.nunique()17" }, { "code": null, "e": 1861, "s": 1721, "text": "We can also apply it to the entire dataframe and see the number of unique values in each column which I think make nunique more functional:" }, { "code": null, "e": 1880, "s": 1861, "text": "diabetes.nunique()" }, { "code": null, "e": 2018, "s": 1880, "text": "Describe function gives a quick overview of numerical columns by providing basic statistics such as mean, median, and standard deviation." }, { "code": null, "e": 2038, "s": 2018, "text": "diabetes.describe()" }, { "code": null, "e": 2338, "s": 2038, "text": "25%, 50%, and 75% are the percentiles. 50% is also known as the median which is the value in the middle when all values are sorted. 25% is the first quartile so 25% of the values are below this point. You can think of it as median of the lower half of a column. Similarly, 75% is the third quartile." }, { "code": null, "e": 2631, "s": 2338, "text": "The basic statistics give us valuable insights. For instance, by comparing mean and median (50%), we have an understanding of the outliers. If mean is much higher than the median, there are outliers on the upper side. The basic statistics also give us an overview of the distribution of data." }, { "code": null, "e": 2869, "s": 2631, "text": "You can also select different percentiles to display using percentiles parameter. The default values are [.25, .50, .75]. For instance percentiles=[.1, .25, .5, .75, .9] will display 10% and 90% percentiles in addition to default values." }, { "code": null, "e": 3067, "s": 2869, "text": "Handling missing values is a critical step to build a robust data analysis process. The missing values should be a top priority since they have a significant effect on the accuracy of any analysis." }, { "code": null, "e": 3165, "s": 3067, "text": "Isna function returns a dataframe filled with boolean values with true indicating missing values." }, { "code": null, "e": 3185, "s": 3165, "text": "diabetes.describe()" }, { "code": null, "e": 3420, "s": 3185, "text": "Unless you want to analyze the dataframe cell by cell, isna should be combined with an aggregation. isna().any() indicates if there is any missing value in a column whereas isna().sum() returns the number of missing values in columns." }, { "code": null, "e": 3442, "s": 3420, "text": "diabetes.isna().any()" }, { "code": null, "e": 3464, "s": 3442, "text": "diabetes.isna().sum()" }, { "code": null, "e": 3566, "s": 3464, "text": "The dataset we have does not have any missing values but this is a highly unlikely case in real-life." }, { "code": null, "e": 3770, "s": 3566, "text": "Pandas groupby function is a great tool in exploring the data. It makes it easier to unveil the underlying relationships among variables. The figure below shows an overview of what groupby function does." }, { "code": null, "e": 4062, "s": 3770, "text": "Assume we have two features. One is color which is a categorical feature and the other one is a numerical feature, values. We want to group values by color and calculate the mean (or any other aggregation) of values for different colors. Then finally sort the colors based on average values." }, { "code": null, "e": 4156, "s": 4062, "text": "You can, of course, create more complex grouping operations but the concept will be the same." }, { "code": null, "e": 4316, "s": 4156, "text": "Let’s create a simple grouping operation with our dataset. The following code will show us the average glucose values of diabetes positive and negative people." }, { "code": null, "e": 4374, "s": 4316, "text": "diabetes[['Outcome','Glucose']].groupby('Outcome').mean()" }, { "code": null, "e": 4440, "s": 4374, "text": "As expected, glucose values are higher for diabetes positive (1)." }, { "code": null, "e": 4715, "s": 4440, "text": "We do not have many categorical variables in the dataset so what we can do with groupby function on this dataset is kind of limited. However, if you’d like to read more about groupby function and see more complex examples, I have a post dedicated to pandas groupby function." }, { "code": null, "e": 4738, "s": 4715, "text": "towardsdatascience.com" }, { "code": null, "e": 5103, "s": 4738, "text": "We need to have the values stored in an appropriate data type. Otherwise, we may encounter errors. For large datasets, memory-usage is greatly affected by correct data type selection. For example, “categorical” data type is more appropriate than “object” data type for categorical data especially when the number of categories is much less than the number of rows." }, { "code": null, "e": 5146, "s": 5103, "text": "Dtypes shows the data type of each column." }, { "code": null, "e": 5162, "s": 5146, "text": "diabetes.dtypes" }, { "code": null, "e": 5311, "s": 5162, "text": "The data type of “BloodPressure” column is not appropriate. It should be int or float. Object data type can be to store strings or categorical data." }, { "code": null, "e": 5368, "s": 5311, "text": "We can easily change the data type with astype function." }, { "code": null, "e": 5447, "s": 5368, "text": "diabetes.BloodPressure = diabetes.BloodPressure.astype('int64')diabetes.dtypes" }, { "code": null, "e": 5585, "s": 5447, "text": "Shape can be used on numpy arrays, pandas series and dataframes. It shows the number of dimensions as well as the size in each dimension." }, { "code": null, "e": 5764, "s": 5585, "text": "Since dataframes are two-dimensional, what shape returns is the number of rows and columns. It is a measure of how much data we have and a key input to the data analysis process." }, { "code": null, "e": 6072, "s": 5764, "text": "Furthermore, the ratio of rows and columns is very important when designing and implementing a machine learning model. If we do not have enough observations (rows) with respect to features (columns), we may need to apply some pre-processing techniques such as dimensionality reduction or feature extraction." }, { "code": null, "e": 6095, "s": 6072, "text": "diabetes.shape(768, 9)" }, { "code": null, "e": 6157, "s": 6095, "text": "Let’s apply it on a column which is actually a pandas series." }, { "code": null, "e": 6186, "s": 6157, "text": "diabetes.Glucose.shape(768,)" }, { "code": null, "e": 6311, "s": 6186, "text": "Size, as the name suggests, returns the size of a dataframe which is the number of rows multiplied by the number of columns." }, { "code": null, "e": 6329, "s": 6311, "text": "diabetes.size6912" } ]
How to create timer using C++11?
Here we will see how to make timer using C++. Here we are creating one class called later. This class has following properties. int (milliseconds to wait until to run code) bool (If this is true, it returns instantly, and run the code after specified time on another thread) The variable arguments (exactly we want to feed to std::bind) We can change the chrono::milliseconds to nanoseconds or microseconds etc. to change the precision. #include <functional> #include <chrono> #include <future> #include <cstdio> class later { public: template <class callable, class... arguments> later(int after, bool async, callable&& f, arguments&&... args){ std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...)); if (async) { std::thread([after, task]() { std::this_thread::sleep_for(std::chrono::milliseconds(after)); task(); }).detach(); } else { std::this_thread::sleep_for(std::chrono::milliseconds(after)); task(); } } }; void test1(void) { return; } void test2(int a) { printf("result of test 2: %d\n", a); return; } int main() { later later_test1(3000, false, &test1); later later_test2(1000, false, &test2, 75); later later_test3(3000, false, &test2, 101); } $ g++ test.cpp -lpthread $ ./a.out result of test 2: 75 result of test 2: 101 $ first result after 4 seconds. The second result after three seconds from the first one
[ { "code": null, "e": 1190, "s": 1062, "text": "Here we will see how to make timer using C++. Here we are creating one class called later. This class has following properties." }, { "code": null, "e": 1235, "s": 1190, "text": "int (milliseconds to wait until to run code)" }, { "code": null, "e": 1337, "s": 1235, "text": "bool (If this is true, it returns instantly, and run the code after specified time on another thread)" }, { "code": null, "e": 1399, "s": 1337, "text": "The variable arguments (exactly we want to feed to std::bind)" }, { "code": null, "e": 1499, "s": 1399, "text": "We can change the chrono::milliseconds to nanoseconds or microseconds etc. to change the precision." }, { "code": null, "e": 2431, "s": 1499, "text": "#include <functional>\n#include <chrono>\n#include <future>\n#include <cstdio>\nclass later {\n public:\n template <class callable, class... arguments>\n later(int after, bool async, callable&& f, arguments&&... args){\n std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));\n if (async) {\n std::thread([after, task]() {\n std::this_thread::sleep_for(std::chrono::milliseconds(after));\n task();\n }).detach();\n } else {\n std::this_thread::sleep_for(std::chrono::milliseconds(after));\n task();\n }\n }\n};\nvoid test1(void) {\n return;\n}\nvoid test2(int a) {\n printf(\"result of test 2: %d\\n\", a);\n return;\n}\nint main() {\n later later_test1(3000, false, &test1);\n later later_test2(1000, false, &test2, 75);\n later later_test3(3000, false, &test2, 101);\n}" }, { "code": null, "e": 2511, "s": 2431, "text": "$ g++ test.cpp -lpthread\n$ ./a.out\nresult of test 2: 75\nresult of test 2: 101\n$" }, { "code": null, "e": 2598, "s": 2511, "text": "first result after 4 seconds. The second result after three seconds from the first one" } ]
C - strstr function
C - Programming HOME C - Basic Introduction C - Program Structure C - Reserved Keywords C - Basic Datatypes C - Variable Types C - Storage Classes C - Using Constants C - Operator Types C - Control Statements C - Input and Output C - Pointing to Data C - Using Functions C - Play with Strings C - Structured Datatypes C - Working with Files C - Bits Manipulation C - Pre-Processors C - Useful Concepts C - Built-in Functions C - Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <stdio.h> char *strstr(char *string2, char string*1); The strstr function locates the first occurrence of the string string1 in the string string2 and returns a pointer to the beginning of the first occurrence. The strstr function returns a pointer within string2 that points to a string identical to string1. If no such sub string exists in src a null pointer is returned. #include <stdio.h> int main() { char s1 [] = "My House is small"; char s2 [] = "My Car is green"; printf ("Returned String 1: %s\n", strstr (s1, "House")); printf ("Returned String 2: %s\n", strstr (s2, "Car")); } It will proiduce following result: Returned String 1: House is small Returned String 2: Car is green Advertisements 6 Lectures 1.5 hours Mr. Pradeep Kshetrapal 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav Print Add Notes Bookmark this page
[ { "code": null, "e": 1475, "s": 1454, "text": "C - Programming HOME" }, { "code": null, "e": 1498, "s": 1475, "text": "C - Basic Introduction" }, { "code": null, "e": 1520, "s": 1498, "text": "C - Program Structure" }, { "code": null, "e": 1542, "s": 1520, "text": "C - Reserved Keywords" }, { "code": null, "e": 1562, "s": 1542, "text": "C - Basic Datatypes" }, { "code": null, "e": 1581, "s": 1562, "text": "C - Variable Types" }, { "code": null, "e": 1601, "s": 1581, "text": "C - Storage Classes" }, { "code": null, "e": 1621, "s": 1601, "text": "C - Using Constants" }, { "code": null, "e": 1640, "s": 1621, "text": "C - Operator Types" }, { "code": null, "e": 1663, "s": 1640, "text": "C - Control Statements" }, { "code": null, "e": 1684, "s": 1663, "text": "C - Input and Output" }, { "code": null, "e": 1705, "s": 1684, "text": "C - Pointing to Data" }, { "code": null, "e": 1725, "s": 1705, "text": "C - Using Functions" }, { "code": null, "e": 1747, "s": 1725, "text": "C - Play with Strings" }, { "code": null, "e": 1772, "s": 1747, "text": "C - Structured Datatypes" }, { "code": null, "e": 1795, "s": 1772, "text": "C - Working with Files" }, { "code": null, "e": 1817, "s": 1795, "text": "C - Bits Manipulation" }, { "code": null, "e": 1836, "s": 1817, "text": "C - Pre-Processors" }, { "code": null, "e": 1856, "s": 1836, "text": "C - Useful Concepts" }, { "code": null, "e": 1879, "s": 1856, "text": "C - Built-in Functions" }, { "code": null, "e": 1900, "s": 1879, "text": "C - Useful Resources" }, { "code": null, "e": 1918, "s": 1900, "text": "Computer Glossary" }, { "code": null, "e": 1929, "s": 1918, "text": "Who is Who" }, { "code": null, "e": 1964, "s": 1929, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2030, "s": 1964, "text": "#include <stdio.h>\n\nchar *strstr(char *string2, char string*1); \n" }, { "code": null, "e": 2187, "s": 2030, "text": "The strstr function locates the first occurrence of the string string1 in the string string2 and returns a pointer to the beginning of the first occurrence." }, { "code": null, "e": 2350, "s": 2187, "text": "The strstr function returns a pointer within string2 that points to a string identical to string1. If no such sub string exists in src a null pointer is returned." }, { "code": null, "e": 2579, "s": 2350, "text": "#include <stdio.h>\n\nint main() {\n char s1 [] = \"My House is small\";\n char s2 [] = \"My Car is green\";\n\n printf (\"Returned String 1: %s\\n\", strstr (s1, \"House\"));\n printf (\"Returned String 2: %s\\n\", strstr (s2, \"Car\"));\n}\n" }, { "code": null, "e": 2614, "s": 2579, "text": "It will proiduce following result:" }, { "code": null, "e": 2681, "s": 2614, "text": "Returned String 1: House is small\nReturned String 2: Car is green\n" }, { "code": null, "e": 2698, "s": 2681, "text": "\nAdvertisements\n" }, { "code": null, "e": 2732, "s": 2698, "text": "\n 6 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2756, "s": 2732, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 2789, "s": 2756, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 2801, "s": 2789, "text": " AR Shankar" }, { "code": null, "e": 2833, "s": 2801, "text": "\n 11 Lectures \n 58 mins\n" }, { "code": null, "e": 2849, "s": 2833, "text": " Musab Zayadneh" }, { "code": null, "e": 2885, "s": 2849, "text": "\n 59 Lectures \n 15.5 hours \n" }, { "code": null, "e": 2897, "s": 2885, "text": " Narendra P" }, { "code": null, "e": 2930, "s": 2897, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 2943, "s": 2930, "text": " Sagar Mehta" }, { "code": null, "e": 2976, "s": 2943, "text": "\n 39 Lectures \n 4 hours \n" }, { "code": null, "e": 2989, "s": 2976, "text": " Vikas Yadav" }, { "code": null, "e": 2996, "s": 2989, "text": " Print" }, { "code": null, "e": 3007, "s": 2996, "text": " Add Notes" } ]
Conditional Statements | Shell Script - GeeksforGeeks
27 Feb, 2020 Conditional Statements: There are total 5 conditional statements which can be used in bash programming if statementif-else statementif..elif..else..fi statement (Else If ladder)if..then..else..if..then..fi..fi..(Nested if)switch statement if statement if-else statement if..elif..else..fi statement (Else If ladder) if..then..else..if..then..fi..fi..(Nested if) switch statement Their description with syntax is as follows: if statementThis block will process if specified condition is true.Syntax: if [ expression ] then statement fi if-else statementIf specified condition is not true in if part then else part will be execute.Syntax if [ expression ] then statement1 else statement2 fi if..elif..else..fi statement (Else If ladder)To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.Syntax if [ expression1 ] then statement1 statement2 . . elif [ expression2 ] then statement3 statement4 . . else statement5 fi if..then..else..if..then..fi..fi..(Nested if)Nested if-else block can be used when, one condition is satisfies then it again checks another condition. In the syntax, if expression1 is false then it processes else part, and again expression2 will be check.Syntax: if [ expression1 ] then statement1 statement2 . else if [ expression2 ] then statement3 . fi fi switch statementcase statement works as a switch statement if specified value match with the pattern then it will execute a block of that particular patternWhen a match is found all of the associated statements until the double semicolon (;;) is executed.A case will be terminated when the last command is executed.If there is no match, the exit status of the case is zero. Syntax: case in Pattern 1) Statement 1;; Pattern n) Statement n;; esac Example Programs Example 1:Implementing if statement #Initializing two variablesa=10b=20 #Check whether they are equalif [ $a == $b ]then echo "a is equal to b"fi #Check whether they are not equalif [ $a != $b ]then echo "a is not equal to b"fi Output $bash -f main.sh a is not equal to b Example 2:Implementing if.else statement #Initializing two variablesa=20b=20 if [ $a == $b ]then #If they are equal then print this echo "a is equal to b"else #else print this echo "a is not equal to b"fi Output $bash -f main.sh a is equal to b Example 3:Implementing switch statement CARS="bmw" #Pass the variable in stringcase "$CARS" in #case 1 "mercedes") echo "Headquarters - Affalterbach, Germany" ;; #case 2 "audi") echo "Headquarters - Ingolstadt, Germany" ;; #case 3 "bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;;esac Output $bash -f main.sh Headquarters - Chennai, Tamil Nadu, India. Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts. sahuaman Shell Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C 'crontab' in Linux with Examples Cat command in Linux with examples echo command in Linux with Examples touch command in Linux with Examples tee command in Linux with examples Tail command in Linux with examples Mutex lock for Linux Thread Synchronization Compiling with g++
[ { "code": null, "e": 24582, "s": 24554, "text": "\n27 Feb, 2020" }, { "code": null, "e": 24685, "s": 24582, "text": "Conditional Statements: There are total 5 conditional statements which can be used in bash programming" }, { "code": null, "e": 24821, "s": 24685, "text": "if statementif-else statementif..elif..else..fi statement (Else If ladder)if..then..else..if..then..fi..fi..(Nested if)switch statement" }, { "code": null, "e": 24834, "s": 24821, "text": "if statement" }, { "code": null, "e": 24852, "s": 24834, "text": "if-else statement" }, { "code": null, "e": 24898, "s": 24852, "text": "if..elif..else..fi statement (Else If ladder)" }, { "code": null, "e": 24944, "s": 24898, "text": "if..then..else..if..then..fi..fi..(Nested if)" }, { "code": null, "e": 24961, "s": 24944, "text": "switch statement" }, { "code": null, "e": 25006, "s": 24961, "text": "Their description with syntax is as follows:" }, { "code": null, "e": 25081, "s": 25006, "text": "if statementThis block will process if specified condition is true.Syntax:" }, { "code": null, "e": 25120, "s": 25081, "text": "if [ expression ]\nthen\n statement\nfi" }, { "code": null, "e": 25221, "s": 25120, "text": "if-else statementIf specified condition is not true in if part then else part will be execute.Syntax" }, { "code": null, "e": 25280, "s": 25221, "text": "if [ expression ]\nthen\n statement1\nelse\n statement2\nfi" }, { "code": null, "e": 25565, "s": 25280, "text": "if..elif..else..fi statement (Else If ladder)To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.Syntax" }, { "code": null, "e": 25713, "s": 25565, "text": "if [ expression1 ]\nthen\n statement1\n statement2\n .\n .\nelif [ expression2 ]\nthen\n statement3\n statement4\n .\n .\nelse\n statement5\nfi" }, { "code": null, "e": 25976, "s": 25713, "text": "if..then..else..if..then..fi..fi..(Nested if)Nested if-else block can be used when, one condition is satisfies then it again checks another condition. In the syntax, if expression1 is false then it processes else part, and again expression2 will be check.Syntax:" }, { "code": null, "e": 26102, "s": 25976, "text": "if [ expression1 ]\nthen\n statement1\n statement2\n .\nelse\n if [ expression2 ]\n then\n statement3\n .\n fi\nfi" }, { "code": null, "e": 26476, "s": 26102, "text": "switch statementcase statement works as a switch statement if specified value match with the pattern then it will execute a block of that particular patternWhen a match is found all of the associated statements until the double semicolon (;;) is executed.A case will be terminated when the last command is executed.If there is no match, the exit status of the case is zero." }, { "code": null, "e": 26484, "s": 26476, "text": "Syntax:" }, { "code": null, "e": 26554, "s": 26484, "text": "case in\n Pattern 1) Statement 1;;\n Pattern n) Statement n;;\nesac" }, { "code": null, "e": 26571, "s": 26554, "text": "Example Programs" }, { "code": null, "e": 26607, "s": 26571, "text": "Example 1:Implementing if statement" }, { "code": "#Initializing two variablesa=10b=20 #Check whether they are equalif [ $a == $b ]then echo \"a is equal to b\"fi #Check whether they are not equalif [ $a != $b ]then echo \"a is not equal to b\"fi", "e": 26807, "s": 26607, "text": null }, { "code": null, "e": 26814, "s": 26807, "text": "Output" }, { "code": null, "e": 26851, "s": 26814, "text": "$bash -f main.sh\na is not equal to b" }, { "code": null, "e": 26892, "s": 26851, "text": "Example 2:Implementing if.else statement" }, { "code": "#Initializing two variablesa=20b=20 if [ $a == $b ]then #If they are equal then print this echo \"a is equal to b\"else #else print this echo \"a is not equal to b\"fi", "e": 27069, "s": 26892, "text": null }, { "code": null, "e": 27076, "s": 27069, "text": "Output" }, { "code": null, "e": 27109, "s": 27076, "text": "$bash -f main.sh\na is equal to b" }, { "code": null, "e": 27149, "s": 27109, "text": "Example 3:Implementing switch statement" }, { "code": "CARS=\"bmw\" #Pass the variable in stringcase \"$CARS\" in #case 1 \"mercedes\") echo \"Headquarters - Affalterbach, Germany\" ;; #case 2 \"audi\") echo \"Headquarters - Ingolstadt, Germany\" ;; #case 3 \"bmw\") echo \"Headquarters - Chennai, Tamil Nadu, India\" ;;esac", "e": 27434, "s": 27149, "text": null }, { "code": null, "e": 27441, "s": 27434, "text": "Output" }, { "code": null, "e": 27501, "s": 27441, "text": "$bash -f main.sh\nHeadquarters - Chennai, Tamil Nadu, India." }, { "code": null, "e": 27625, "s": 27501, "text": "Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts." }, { "code": null, "e": 27634, "s": 27625, "text": "sahuaman" }, { "code": null, "e": 27640, "s": 27634, "text": "Shell" }, { "code": null, "e": 27653, "s": 27640, "text": "Shell Script" }, { "code": null, "e": 27664, "s": 27653, "text": "Linux-Unix" }, { "code": null, "e": 27762, "s": 27664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27771, "s": 27762, "text": "Comments" }, { "code": null, "e": 27784, "s": 27771, "text": "Old Comments" }, { "code": null, "e": 27819, "s": 27784, "text": "tar command in Linux with examples" }, { "code": null, "e": 27857, "s": 27819, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27890, "s": 27857, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 27925, "s": 27890, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27961, "s": 27925, "text": "echo command in Linux with Examples" }, { "code": null, "e": 27998, "s": 27961, "text": "touch command in Linux with Examples" }, { "code": null, "e": 28033, "s": 27998, "text": "tee command in Linux with examples" }, { "code": null, "e": 28069, "s": 28033, "text": "Tail command in Linux with examples" }, { "code": null, "e": 28113, "s": 28069, "text": "Mutex lock for Linux Thread Synchronization" } ]
Getting the last 30 rows in MySQL
To get the last 30 rows in MySQL, you need to use ORDER BY DESC and then LIMIT 30. The syntax is as follows − select * from yourTableName order by yourColumnName DESC LIMIT 30; Let us first create a table − mysql> create table DemoTable1567 -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY -> ); Query OK, 0 rows affected (0.82 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1567 values(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(); Query OK, 37 rows affected (0.37 sec) Records: 37 Duplicates: 0 Warnings: 0 Display all records from the table using select statement − mysql> select * from DemoTable1567; This will produce the following output − +----+ | Id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 8 | | 9 | | 10 | | 11 | | 12 | | 13 | | 14 | | 15 | | 16 | | 17 | | 18 | | 19 | | 20 | | 21 | | 22 | | 23 | | 24 | | 25 | | 26 | | 27 | | 28 | | 29 | | 30 | | 31 | | 32 | | 33 | | 34 | | 35 | | 36 | | 37 | +----+ 37 rows in set (0.00 sec) Following is the query to get last 30 rows − mysql> select * from DemoTable1567 order by Id DESC LIMIT 30; This will produce the following output − +----+ | Id | +----+ | 37 | | 36 | | 35 | | 34 | | 33 | | 32 | | 31 | | 30 | | 29 | | 28 | | 27 | | 26 | | 25 | | 24 | | 23 | | 22 | | 21 | | 20 | | 19 | | 18 | | 17 | | 16 | | 15 | | 14 | | 13 | | 12 | | 11 | | 10 | | 9 | | 8 | +----+ 30 rows in set (0.00 sec)
[ { "code": null, "e": 1172, "s": 1062, "text": "To get the last 30 rows in MySQL, you need to use ORDER BY DESC and then LIMIT 30. The syntax is as follows −" }, { "code": null, "e": 1239, "s": 1172, "text": "select * from yourTableName order by yourColumnName DESC LIMIT 30;" }, { "code": null, "e": 1269, "s": 1239, "text": "Let us first create a table −" }, { "code": null, "e": 1406, "s": 1269, "text": "mysql> create table DemoTable1567\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY\n -> );\nQuery OK, 0 rows affected (0.82 sec)" }, { "code": null, "e": 1462, "s": 1406, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1691, "s": 1462, "text": "mysql> insert into DemoTable1567 values(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),();\nQuery OK, 37 rows affected (0.37 sec)\nRecords: 37 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1751, "s": 1691, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1787, "s": 1751, "text": "mysql> select * from DemoTable1567;" }, { "code": null, "e": 1828, "s": 1787, "text": "This will produce the following output −" }, { "code": null, "e": 2141, "s": 1828, "text": "+----+\n| Id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n| 7 |\n| 8 |\n| 9 |\n| 10 |\n| 11 |\n| 12 |\n| 13 |\n| 14 |\n| 15 |\n| 16 |\n| 17 |\n| 18 |\n| 19 |\n| 20 |\n| 21 |\n| 22 |\n| 23 |\n| 24 |\n| 25 |\n| 26 |\n| 27 |\n| 28 |\n| 29 |\n| 30 |\n| 31 |\n| 32 |\n| 33 |\n| 34 |\n| 35 |\n| 36 |\n| 37 |\n+----+\n37 rows in set (0.00 sec)" }, { "code": null, "e": 2186, "s": 2141, "text": "Following is the query to get last 30 rows −" }, { "code": null, "e": 2248, "s": 2186, "text": "mysql> select * from DemoTable1567 order by Id DESC LIMIT 30;" }, { "code": null, "e": 2289, "s": 2248, "text": "This will produce the following output −" }, { "code": null, "e": 2553, "s": 2289, "text": "+----+\n| Id |\n+----+\n| 37 |\n| 36 |\n| 35 |\n| 34 |\n| 33 |\n| 32 |\n| 31 |\n| 30 |\n| 29 |\n| 28 |\n| 27 |\n| 26 |\n| 25 |\n| 24 |\n| 23 |\n| 22 |\n| 21 |\n| 20 |\n| 19 |\n| 18 |\n| 17 |\n| 16 |\n| 15 |\n| 14 |\n| 13 |\n| 12 |\n| 11 |\n| 10 |\n| 9 |\n| 8 |\n+----+\n30 rows in set (0.00 sec)" } ]
Difference between peek(), poll() and remove() method of Queue interface in java?
This represents a collection that is indented to hold data before processing. It is an arrangement of the type First-In-First-Out (FIFO). The first element put in the queue is the first element taken out from it. This method returns the object at the top of the current queue, without removing it. If the queue is empty this method returns null. Live Demo import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String args[]) { Queue<String> queue = new LinkedList<String>(); queue.add("Java"); queue.add("JavaFX"); queue.add("OpenCV"); queue.add("Coffee Script"); queue.add("HBase"); System.out.println("Element at the top of the queue: "+queue.peek()); Iterator<String> it = queue.iterator(); System.out.println("Contents of the queue: "); while(it.hasNext()) { System.out.println(it.next()); } } } Element at the top of the queue: Java Contents of the queue: Java JavaFX OpenCV Coffee Script Hbase The peek() method of the Queue interface returns the object at the top of the current queue and removes it. If the queue is empty this method returns null. Live Demo import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String args[]) { Queue<String> queue = new LinkedList<String>(); queue.add("Java"); queue.add("JavaFX"); queue.add("OpenCV"); queue.add("Coffee Script"); queue.add("HBase"); System.out.println("Element at the top of the queue: "+queue.poll()); Iterator<String> it = queue.iterator(); System.out.println("Contents of the queue: "); while(it.hasNext()) { System.out.println(it.next()); } } } Element at the top of the queue: Java Contents of the queue: JavaFX OpenCV Coffee Script HBase
[ { "code": null, "e": 1275, "s": 1062, "text": "This represents a collection that is indented to hold data before processing. It is an arrangement of the type First-In-First-Out (FIFO). The first element put in the queue is the first element taken out from it." }, { "code": null, "e": 1408, "s": 1275, "text": "This method returns the object at the top of the current queue, without removing it. If the queue is empty this method returns null." }, { "code": null, "e": 1419, "s": 1408, "text": " Live Demo" }, { "code": null, "e": 2022, "s": 1419, "text": "import java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.Queue;\npublic class QueueExample {\n public static void main(String args[]) {\n Queue<String> queue = new LinkedList<String>();\n queue.add(\"Java\");\n queue.add(\"JavaFX\");\n queue.add(\"OpenCV\");\n queue.add(\"Coffee Script\");\n queue.add(\"HBase\");\n System.out.println(\"Element at the top of the queue: \"+queue.peek());\n Iterator<String> it = queue.iterator();\n System.out.println(\"Contents of the queue: \");\n while(it.hasNext()) {\n System.out.println(it.next());\n }\n }\n}" }, { "code": null, "e": 2122, "s": 2022, "text": "Element at the top of the queue: Java\nContents of the queue:\nJava\nJavaFX\nOpenCV\nCoffee Script\nHbase" }, { "code": null, "e": 2278, "s": 2122, "text": "The peek() method of the Queue interface returns the object at the top of the current queue and removes it. If the queue is empty this method returns null." }, { "code": null, "e": 2289, "s": 2278, "text": " Live Demo" }, { "code": null, "e": 2892, "s": 2289, "text": "import java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.Queue;\npublic class QueueExample {\n public static void main(String args[]) {\n Queue<String> queue = new LinkedList<String>();\n queue.add(\"Java\");\n queue.add(\"JavaFX\");\n queue.add(\"OpenCV\");\n queue.add(\"Coffee Script\");\n queue.add(\"HBase\");\n System.out.println(\"Element at the top of the queue: \"+queue.poll());\n Iterator<String> it = queue.iterator();\n System.out.println(\"Contents of the queue: \");\n while(it.hasNext()) {\n System.out.println(it.next());\n }\n }\n}" }, { "code": null, "e": 2987, "s": 2892, "text": "Element at the top of the queue: Java\nContents of the queue:\nJavaFX\nOpenCV\nCoffee Script\nHBase" } ]
Python Number log10() Method
Python number method log10() returns base-10 logarithm of x for x > 0. Following is the syntax for log10() method − import math math.log10( x ) Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object. x − This is a numeric expression. x − This is a numeric expression. This method returns base-10 logarithm of x for x > 0. The following example shows the usage of log10() method. #!/usr/bin/python import math # This will import math module print "math.log10(100.12) : ", math.log10(100.12) print "math.log10(100.72) : ", math.log10(100.72) print "math.log10(119L) : ", math.log10(119L) print "math.log10(math.pi) : ", math.log10(math.pi) When we run above program, it produces following result − math.log10(100.12) : 2.00052084094 math.log10(100.72) : 2.0031157171 math.log10(119L) : 2.07554696139 math.log10(math.pi) : 0.497149872694 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2316, "s": 2244, "text": "Python number method log10() returns base-10 logarithm of x for x > 0." }, { "code": null, "e": 2361, "s": 2316, "text": "Following is the syntax for log10() method −" }, { "code": null, "e": 2390, "s": 2361, "text": "import math\n\nmath.log10( x )" }, { "code": null, "e": 2537, "s": 2390, "text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object." }, { "code": null, "e": 2571, "s": 2537, "text": "x − This is a numeric expression." }, { "code": null, "e": 2605, "s": 2571, "text": "x − This is a numeric expression." }, { "code": null, "e": 2659, "s": 2605, "text": "This method returns base-10 logarithm of x for x > 0." }, { "code": null, "e": 2716, "s": 2659, "text": "The following example shows the usage of log10() method." }, { "code": null, "e": 2978, "s": 2716, "text": "#!/usr/bin/python\nimport math # This will import math module\n\nprint \"math.log10(100.12) : \", math.log10(100.12)\nprint \"math.log10(100.72) : \", math.log10(100.72)\nprint \"math.log10(119L) : \", math.log10(119L)\nprint \"math.log10(math.pi) : \", math.log10(math.pi)" }, { "code": null, "e": 3036, "s": 2978, "text": "When we run above program, it produces following result −" }, { "code": null, "e": 3180, "s": 3036, "text": "math.log10(100.12) : 2.00052084094\nmath.log10(100.72) : 2.0031157171\nmath.log10(119L) : 2.07554696139\nmath.log10(math.pi) : 0.497149872694\n" }, { "code": null, "e": 3217, "s": 3180, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3233, "s": 3217, "text": " Malhar Lathkar" }, { "code": null, "e": 3266, "s": 3233, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3285, "s": 3266, "text": " Arnab Chakraborty" }, { "code": null, "e": 3320, "s": 3285, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3342, "s": 3320, "text": " In28Minutes Official" }, { "code": null, "e": 3376, "s": 3342, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3404, "s": 3376, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3439, "s": 3404, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3453, "s": 3439, "text": " Lets Kode It" }, { "code": null, "e": 3486, "s": 3453, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3503, "s": 3486, "text": " Abhilash Nelson" }, { "code": null, "e": 3510, "s": 3503, "text": " Print" }, { "code": null, "e": 3521, "s": 3510, "text": " Add Notes" } ]
JavaScript - Array every() Method
JavaScript array every method tests whether all the elements in an array passes the test implemented by the provided function. Its syntax is as follows − array.every(callback[, thisObject]); callback − Function to test for each element. callback − Function to test for each element. thisObject − Object to use as this when executing callback. thisObject − Object to use as this when executing callback. Returns true if every element in this array satisfies the provided testing function. This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script. if (!Array.prototype.every) { Array.prototype.every = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this && !fun.call(thisp, this[i], i, this)) return false; } return true; }; } Try the following example. <html> <head> <title>JavaScript Array every Method</title> </head> <body> <script type = "text/javascript"> if (!Array.prototype.every) { Array.prototype.every = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this && !fun.call(thisp, this[i], i, this)) return false; } return true; }; } function isBigEnough(element, index, array) { return (element >= 10); } var passed = [12, 5, 8, 130, 44].every(isBigEnough); document.write("First Test Value : " + passed ); passed = [12, 54, 18, 130, 44].every(isBigEnough); document.write("Second Test Value : " + passed ); </script> </body> </html> First Test Value : falseSecond Test Value : true 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2593, "s": 2466, "text": "JavaScript array every method tests whether all the elements in an array passes the test implemented by the provided function." }, { "code": null, "e": 2620, "s": 2593, "text": "Its syntax is as follows −" }, { "code": null, "e": 2658, "s": 2620, "text": "array.every(callback[, thisObject]);\n" }, { "code": null, "e": 2704, "s": 2658, "text": "callback − Function to test for each element." }, { "code": null, "e": 2750, "s": 2704, "text": "callback − Function to test for each element." }, { "code": null, "e": 2810, "s": 2750, "text": "thisObject − Object to use as this when executing callback." }, { "code": null, "e": 2870, "s": 2810, "text": "thisObject − Object to use as this when executing callback." }, { "code": null, "e": 2955, "s": 2870, "text": "Returns true if every element in this array satisfies the provided testing function." }, { "code": null, "e": 3170, "s": 2955, "text": "This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script." }, { "code": null, "e": 3546, "s": 3170, "text": "if (!Array.prototype.every) {\n Array.prototype.every = function(fun /*, thisp*/) {\n var len = this.length;\n if (typeof fun != \"function\")\n throw new TypeError();\n \n var thisp = arguments[1];\n for (var i = 0; i < len; i++) {\n if (i in this && !fun.call(thisp, this[i], i, this))\n return false;\n }\n return true;\n };\n}" }, { "code": null, "e": 3573, "s": 3546, "text": "Try the following example." }, { "code": null, "e": 4605, "s": 3573, "text": "<html>\n <head>\n <title>JavaScript Array every Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n if (!Array.prototype.every) {\n Array.prototype.every = function(fun /*, thisp*/) {\n var len = this.length;\n if (typeof fun != \"function\")\n throw new TypeError();\n \n var thisp = arguments[1];\n for (var i = 0; i < len; i++) {\n if (i in this && !fun.call(thisp, this[i], i, this))\n return false;\n }\n return true;\n };\n }\n function isBigEnough(element, index, array) {\n return (element >= 10);\n }\n var passed = [12, 5, 8, 130, 44].every(isBigEnough);\n document.write(\"First Test Value : \" + passed ); \n \n passed = [12, 54, 18, 130, 44].every(isBigEnough);\n document.write(\"Second Test Value : \" + passed ); \n </script> \n </body>\n</html>" }, { "code": null, "e": 4655, "s": 4605, "text": "First Test Value : falseSecond Test Value : true\n" }, { "code": null, "e": 4690, "s": 4655, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4704, "s": 4690, "text": " Anadi Sharma" }, { "code": null, "e": 4738, "s": 4704, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 4752, "s": 4738, "text": " Lets Kode It" }, { "code": null, "e": 4787, "s": 4752, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4804, "s": 4787, "text": " Frahaan Hussain" }, { "code": null, "e": 4839, "s": 4804, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4856, "s": 4839, "text": " Frahaan Hussain" }, { "code": null, "e": 4889, "s": 4856, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 4917, "s": 4889, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4951, "s": 4917, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 4979, "s": 4951, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4986, "s": 4979, "text": " Print" }, { "code": null, "e": 4997, "s": 4986, "text": " Add Notes" } ]
Binary Gap in Python
Suppose we have a positive integer N, we have to find the longest distance between two consecutive 1's in the binary representation of N. If there are no two-consecutive 1's, then return 0. So, if the input is like 22, then the output will be 2, as 22 in binary is 10110. There are three ones In the binary representation of 22, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2, then the second consecutive pair of 1's have distance 1. Answer will be the largest of these two distances, which is 2. To solve this, we will follow these steps − K := make a list of bits of binary representation of N Max := 0, C := 0, S := 0 Flag := False for i in range 0 to size of K, doif K[i] is '1' and C is 0 and Flag is False, thenC:= iFlag := Trueotherwise when K[i] is '1' and Flag, thenS:= iif Max<abs(S-C), thenMax := |S-C|C:= S if K[i] is '1' and C is 0 and Flag is False, thenC:= iFlag := True C:= i Flag := True otherwise when K[i] is '1' and Flag, thenS:= iif Max<abs(S-C), thenMax := |S-C|C:= S S:= i if Max<abs(S-C), thenMax := |S-C| Max := |S-C| C:= S return Max Let us see the following implementation to get better understanding − Live Demo class Solution: def binaryGap(self, N): B = bin(N).replace('0b','') K = str(B) K = list(K) Max = 0 C = 0 S =0 Flag =False for i in range(len(K)): if K[i] is '1' and C is 0 and Flag is False: C=i Flag = True elif K[i] is '1' and Flag: S=i if Max<abs(S-C): Max = abs(S-C) C=S return Max ob = Solution() print(ob.binaryGap(22)) 22 2
[ { "code": null, "e": 1252, "s": 1062, "text": "Suppose we have a positive integer N, we have to find the longest distance between two\nconsecutive 1's in the binary representation of N. If there are no two-consecutive 1's, then return 0." }, { "code": null, "e": 1596, "s": 1252, "text": "So, if the input is like 22, then the output will be 2, as 22 in binary is 10110. There are three ones In the binary representation of 22, and two consecutive pairs of 1's. The first consecutive pair of 1's have distance 2, then the second consecutive pair of 1's have distance 1. Answer will be the largest of these two distances, which is 2." }, { "code": null, "e": 1640, "s": 1596, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1695, "s": 1640, "text": "K := make a list of bits of binary representation of N" }, { "code": null, "e": 1720, "s": 1695, "text": "Max := 0, C := 0, S := 0" }, { "code": null, "e": 1734, "s": 1720, "text": "Flag := False" }, { "code": null, "e": 1918, "s": 1734, "text": "for i in range 0 to size of K, doif K[i] is '1' and C is 0 and Flag is False, thenC:= iFlag := Trueotherwise when K[i] is '1' and Flag, thenS:= iif Max<abs(S-C), thenMax := |S-C|C:= S" }, { "code": null, "e": 1985, "s": 1918, "text": "if K[i] is '1' and C is 0 and Flag is False, thenC:= iFlag := True" }, { "code": null, "e": 1991, "s": 1985, "text": "C:= i" }, { "code": null, "e": 2004, "s": 1991, "text": "Flag := True" }, { "code": null, "e": 2089, "s": 2004, "text": "otherwise when K[i] is '1' and Flag, thenS:= iif Max<abs(S-C), thenMax := |S-C|C:= S" }, { "code": null, "e": 2095, "s": 2089, "text": "S:= i" }, { "code": null, "e": 2129, "s": 2095, "text": "if Max<abs(S-C), thenMax := |S-C|" }, { "code": null, "e": 2142, "s": 2129, "text": "Max := |S-C|" }, { "code": null, "e": 2148, "s": 2142, "text": "C:= S" }, { "code": null, "e": 2159, "s": 2148, "text": "return Max" }, { "code": null, "e": 2229, "s": 2159, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2240, "s": 2229, "text": " Live Demo" }, { "code": null, "e": 2715, "s": 2240, "text": "class Solution:\n def binaryGap(self, N):\n B = bin(N).replace('0b','')\n K = str(B)\n K = list(K)\n Max = 0\n C = 0\n S =0\n Flag =False\n for i in range(len(K)):\n if K[i] is '1' and C is 0 and Flag is False:\n C=i\n Flag = True\n elif K[i] is '1' and Flag:\n S=i\n if Max<abs(S-C):\n Max = abs(S-C)\n C=S\n return Max\nob = Solution()\nprint(ob.binaryGap(22))" }, { "code": null, "e": 2718, "s": 2715, "text": "22" }, { "code": null, "e": 2720, "s": 2718, "text": "2" } ]
Retrieve time from MySQL as HH:MM format?
To retrieve time as HH:MM format, use the DATE_FORMAT() function. To understand the function and retrieve time, let us create a table. The query to create a table is as follows mysql> create table retrieveTimeDemo -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserArrivalTime datetime -> ); Query OK, 0 rows affected (0.57 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2013-01-21 13:45:34'); Query OK, 1 row affected (0.16 sec) mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2014-11-25 11:40:56'); Query OK, 1 row affected (0.11 sec) mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2016-10-27 17:30:40'); Query OK, 1 row affected (0.12 sec) mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2017-02-21 18:03:06'); Query OK, 1 row affected (0.19 sec) mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2018-04-24 22:30:32'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement. The query is as follows mysql> select *from retrieveTimeDemo; The following is the output +--------+---------------------+ | UserId | UserArrivalTime | +--------+---------------------+ | 1 | 2013-01-21 13:45:34 | | 2 | 2014-11-25 11:40:56 | | 3 | 2016-10-27 17:30:40 | | 4 | 2017-02-21 18:03:06 | | 5 | 2018-04-24 22:30:32 | +--------+---------------------+ 5 rows in set (0.00 sec) Here is the query to retrieve time from MySQL as HH:MM format mysql> select date_format(UserArrivalTime,'%H:%i') from retrieveTimeDemo; The following is the output +--------------------------------------+ | date_format(UserArrivalTime,'%H:%i') | +--------------------------------------+ | 13:45 | | 11:40 | | 17:30 | | 18:03 | | 22:30 | +--------------------------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1197, "s": 1062, "text": "To retrieve time as HH:MM format, use the DATE_FORMAT() function. To understand the function and retrieve time, let us create a table." }, { "code": null, "e": 1239, "s": 1197, "text": "The query to create a table is as follows" }, { "code": null, "e": 1415, "s": 1239, "text": "mysql> create table retrieveTimeDemo\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> UserArrivalTime datetime\n -> );\nQuery OK, 0 rows affected (0.57 sec)" }, { "code": null, "e": 1470, "s": 1415, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1494, "s": 1470, "text": "The query is as follows" }, { "code": null, "e": 2094, "s": 1494, "text": "mysql> insert into retrieveTimeDemo(UserArrivalTime) values('2013-01-21 13:45:34');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into retrieveTimeDemo(UserArrivalTime) values('2014-11-25 11:40:56');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into retrieveTimeDemo(UserArrivalTime) values('2016-10-27 17:30:40');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into retrieveTimeDemo(UserArrivalTime) values('2017-02-21 18:03:06');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into retrieveTimeDemo(UserArrivalTime) values('2018-04-24 22:30:32');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2153, "s": 2094, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2177, "s": 2153, "text": "The query is as follows" }, { "code": null, "e": 2215, "s": 2177, "text": "mysql> select *from retrieveTimeDemo;" }, { "code": null, "e": 2243, "s": 2215, "text": "The following is the output" }, { "code": null, "e": 2565, "s": 2243, "text": "+--------+---------------------+\n| UserId | UserArrivalTime |\n+--------+---------------------+\n| 1 | 2013-01-21 13:45:34 |\n| 2 | 2014-11-25 11:40:56 |\n| 3 | 2016-10-27 17:30:40 |\n| 4 | 2017-02-21 18:03:06 |\n| 5 | 2018-04-24 22:30:32 |\n+--------+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2627, "s": 2565, "text": "Here is the query to retrieve time from MySQL as HH:MM format" }, { "code": null, "e": 2701, "s": 2627, "text": "mysql> select date_format(UserArrivalTime,'%H:%i') from retrieveTimeDemo;" }, { "code": null, "e": 2729, "s": 2701, "text": "The following is the output" }, { "code": null, "e": 3123, "s": 2729, "text": "+--------------------------------------+\n| date_format(UserArrivalTime,'%H:%i') |\n+--------------------------------------+\n| 13:45 |\n| 11:40 |\n| 17:30 |\n| 18:03 |\n| 22:30 |\n+--------------------------------------+\n5 rows in set (0.00 sec)" } ]
JDBC - Update Records Example
This chapter provides an example on how to update records in a table using JDBC application. Before executing the following example, make sure you have the following in place − To execute the following example you can replace the username and password with your actual user name and password. To execute the following example you can replace the username and password with your actual user name and password. Your MySQL or whatever database you are using is up and running. Your MySQL or whatever database you are using is up and running. The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records. Clean up the environment − try with resources automatically closes the resources. Clean up the environment − try with resources automatically closes the resources. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCExample { static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT"; static final String USER = "guest"; static final String PASS = "guest123"; static final String QUERY = "SELECT id, first, last, age FROM Registration"; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { String sql = "UPDATE Registration " + "SET age = 30 WHERE id in (100, 101)"; stmt.executeUpdate(sql); ResultSet rs = stmt.executeQuery(QUERY); while(rs.next()){ //Display values System.out.print("ID: " + rs.getInt("id")); System.out.print(", Age: " + rs.getInt("age")); System.out.print(", First: " + rs.getString("first")); System.out.println(", Last: " + rs.getString("last")); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac JDBCExample.java C:\> When you run JDBCExample, it produces the following result − C:\>java JDBCExample ID: 100, Age: 30, First: Zara, Last: Ali ID: 101, Age: 30, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:\> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2339, "s": 2162, "text": "This chapter provides an example on how to update records in a table using JDBC application. Before executing the following example, make sure you have the following in place −" }, { "code": null, "e": 2455, "s": 2339, "text": "To execute the following example you can replace the username and password with your actual user name and password." }, { "code": null, "e": 2571, "s": 2455, "text": "To execute the following example you can replace the username and password with your actual user name and password." }, { "code": null, "e": 2636, "s": 2571, "text": "Your MySQL or whatever database you are using is up and running." }, { "code": null, "e": 2701, "s": 2636, "text": "Your MySQL or whatever database you are using is up and running." }, { "code": null, "e": 2784, "s": 2701, "text": "The following steps are required to create a new Database using JDBC application −" }, { "code": null, "e": 2956, "s": 2784, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3128, "s": 2956, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3298, "s": 3128, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server." }, { "code": null, "e": 3468, "s": 3298, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server." }, { "code": null, "e": 3679, "s": 3468, "text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records." }, { "code": null, "e": 3890, "s": 3679, "text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to update records in a table. This Query makes use of IN and WHERE clause to update conditional records." }, { "code": null, "e": 3973, "s": 3890, "text": "Clean up the environment − try with resources automatically closes the resources.\n" }, { "code": null, "e": 4055, "s": 3973, "text": "Clean up the environment − try with resources automatically closes the resources." }, { "code": null, "e": 4142, "s": 4055, "text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −" }, { "code": null, "e": 5363, "s": 4142, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/TUTORIALSPOINT\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n static final String QUERY = \"SELECT id, first, last, age FROM Registration\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"UPDATE Registration \" +\n \"SET age = 30 WHERE id in (100, 101)\";\n stmt.executeUpdate(sql);\n ResultSet rs = stmt.executeQuery(QUERY);\n while(rs.next()){\n //Display values\n System.out.print(\"ID: \" + rs.getInt(\"id\"));\n System.out.print(\", Age: \" + rs.getInt(\"age\"));\n System.out.print(\", First: \" + rs.getString(\"first\"));\n System.out.println(\", Last: \" + rs.getString(\"last\"));\n }\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 5413, "s": 5363, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 5445, "s": 5413, "text": "C:\\>javac JDBCExample.java\nC:\\>" }, { "code": null, "e": 5506, "s": 5445, "text": "When you run JDBCExample, it produces the following result −" }, { "code": null, "e": 5706, "s": 5506, "text": "C:\\>java JDBCExample\nID: 100, Age: 30, First: Zara, Last: Ali\nID: 101, Age: 30, First: Mahnaz, Last: Fatma\nID: 102, Age: 30, First: Zaid, Last: Khan\nID: 103, Age: 28, First: Sumit, Last: Mittal\nC:\\>\n" }, { "code": null, "e": 5739, "s": 5706, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5755, "s": 5739, "text": " Malhar Lathkar" }, { "code": null, "e": 5788, "s": 5755, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5804, "s": 5788, "text": " Malhar Lathkar" }, { "code": null, "e": 5839, "s": 5804, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5853, "s": 5839, "text": " Anadi Sharma" }, { "code": null, "e": 5887, "s": 5853, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5901, "s": 5887, "text": " Tushar Kale" }, { "code": null, "e": 5938, "s": 5901, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5953, "s": 5938, "text": " Monica Mittal" }, { "code": null, "e": 5986, "s": 5953, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6005, "s": 5986, "text": " Arnab Chakraborty" }, { "code": null, "e": 6012, "s": 6005, "text": " Print" }, { "code": null, "e": 6023, "s": 6012, "text": " Add Notes" } ]
All you want to know about preprocessing: Data preparation | by Maksym Balatsko | Towards Data Science
Nowadays, almost all ML/data mining projects workflow run on a standard CRISP-DM (Cross-industry standard process for data mining) or its IBM enhance ASUM-DM (Analytics Solutions Unified Method for Data Mining/Predictive Analytics). The longest and the most important step in this workflow is Data preparation/preprocessing, which approximately takes 70% of the time. This step is important because in most situations data provided by the customer has a bad quality or just cannot be directly fed to some kind of ML model. My favorite byword, that I'll mention in all my posts, concerning data preprocessing, says: Garbage in, garbage out (GIGO). In other words, if you feed your model with miserable data, don't expect it to perform well. In this post we are going to discuss: Data typesData validationHandling datesHandling nominal and ordinal categorical values Data types Data validation Handling dates Handling nominal and ordinal categorical values In the next posts we are going to talk about more advanced preprocessing techniques: Data cleaning and standardization: Normalization and standartization, Handling missing data, Handling outliersFeature selection and dataset balancing: Dataset balancing, Feature extraction, Feature selection. Data cleaning and standardization: Normalization and standartization, Handling missing data, Handling outliers Feature selection and dataset balancing: Dataset balancing, Feature extraction, Feature selection. This post series represents the usual preprocessing flow order, but, in fact, all these parts are divided in such a way to be independent and not to require the knowledge of the previous parts. This is an introduction part, where we are going to discuss how to check and prepare your data for further preprocessing. To start, let’s define what data types exist and what measurement scales they have: Discrete - integer values. Example: number of products bought in the shopContinuos - any value in some admissable range (float, double). Example: average length of words in text Discrete - integer values. Example: number of products bought in the shop Continuos - any value in some admissable range (float, double). Example: average length of words in text The variable value selected from a predefined number of categories Ordinal - categories could be meaningfully ordered. Example: grade (A, B, C, D, E, F)Nominal - categories don't have any order. Example: religion (Christian, Muslim, Hindu, etc.)Dichotomous/Binary - the special case of nominal, with only 2 possible categories. Example: gender (male, female) Ordinal - categories could be meaningfully ordered. Example: grade (A, B, C, D, E, F) Nominal - categories don't have any order. Example: religion (Christian, Muslim, Hindu, etc.) Dichotomous/Binary - the special case of nominal, with only 2 possible categories. Example: gender (male, female) String, python datetime, timestamp. Example: 12.12.2012 Multidimensional data, more about text preprocessing see in my previous post Multidimensional data, more about image preprocessing see in my next posts Data points indexed in the time order, more about time series preprocessing see in my next posts. The first step is the simplest and the most obvious: you have to investigate and validate your data. To be able to validate the data you have to have a deep understanding of your data. Easy rule: Don't dismiss the description of the dataset. Validation step consists of: Same things have to be represented in the same way and in the same format. Examples: Dates have the same format. Several times in my practice I’ve got data where a part of dates was in American format, the other part in European.Integers are really integers, not strings or floatsCategorical data doesn’t have duplicates because of whitespaces, lower/upper casesOther data representations don’t contain an error Dates have the same format. Several times in my practice I’ve got data where a part of dates was in American format, the other part in European. Integers are really integers, not strings or floats Categorical data doesn’t have duplicates because of whitespaces, lower/upper cases Other data representations don’t contain an error Data is in range of permissible values. Example: numerical variables are in admissable (min, max) range. Check permitted relationships and fulfillment of the constraints. Examples: Check name titles with sex, age of birth with ageHistorical data have the right chronology. Delivery after purchase, Bank account opening before the first payment, etc.The actions are made by allowed entities. The mortgage could be approved only for people older than 18 years old, etc. Check name titles with sex, age of birth with age Historical data have the right chronology. Delivery after purchase, Bank account opening before the first payment, etc. The actions are made by allowed entities. The mortgage could be approved only for people older than 18 years old, etc. Correct them, if you are sure, what the problem is, or consult with the specialist or data provider if possible.Discard samples with errors, in many cases it is a good choice because you aren't able to fulfill 1.Do nothing, this, of course, could cause undesired effects in future steps. Correct them, if you are sure, what the problem is, or consult with the specialist or data provider if possible. Discard samples with errors, in many cases it is a good choice because you aren't able to fulfill 1. Do nothing, this, of course, could cause undesired effects in future steps. Different systems stores dates in different formats: 11.12.2019, 2016-02-12, Sep 24, 2003 etc. But for building models on dates data, we need to somehow convert it to a numeric format. To start, I'll show you an example of how to convert a date string into python datetime type, which is much more convenient for further steps. The example is demonstrated on pandas dataframe. Let's assume that date_string column contains dates in strings: # Converts date string column to python datetime type# `infer_datetime_format=True` says method to guess date format from stringdf['datetime'] = pd.to_datetime(df['date_string'], infer_datetime_format=True)# Converts date string column to python datetime type# `format` argument specifies the format of date to parse, fails on errorsdf['datetime'] = pd.to_datetime(df['date_string'], format='%Y.%m.%d') Frequently, just the year (YYYY) is sufficient. But if we want to store months, days or even more detailed data, our numeric format has to fulfill 1 sufficient constraint, it has to save intervals, it means that for example, Monday — Friday in one week has to have the same difference as 1. — 5. of any month. So YYYYMMDD format will be not an option, because the last day of the month and the first day of the next month have a bigger distance than the first and the second day of the month. Actually, there are 4 most common methods to transform date to numeric format: Number of seconds since 1970 Pros: perfectly preserve intervalsgood if hours, minutes and seconds matters perfectly preserve intervals good if hours, minutes and seconds matters Cons: values are non-obviousdon’t help intuition and knowledge discoveryharder to verify, easier to make an error values are non-obvious don’t help intuition and knowledge discovery harder to verify, easier to make an error Converting datetime column to timestamp in pandas: # Coverts column in python datetime type to timestampdf['timestamp'] = df['datetime'].values.astype(np.int64) // 10 ** 9 Pros: the year and quarter are obviouseasy intuition and knowledge discoverycan be extended to include time the year and quarter are obvious easy intuition and knowledge discovery can be extended to include time Cons: preserves intervals (almost) preserves intervals (almost) Converting python datetime column to KSP format in pandas: import datetime as dtimport calendardef to_ksp_format(datetime): year = datetime.year day_from_jan_1 = (datetime - dt.datetime(year, 1, 1)).days is_leap_year = int(calendar.isleap(year)) return year + (day_from_jan_1 - 0.5) / (365 + is_leap_year)df['ksp_date'] = df['datetime'].apply(to_ksp_format) Year, month, days, etc. Cons: perfectly preserve intervalseasy intuition and knowledge discovery perfectly preserve intervals easy intuition and knowledge discovery Pros: more dimensions you add, more complex your model could get, but it is not always bad. more dimensions you add, more complex your model could get, but it is not always bad. Construct a new feature based on date features. For example: date of birth -> age date order created and date order delivered -> time to delivery. Cons: easy intuition and knowledge discovery easy intuition and knowledge discovery Pros: manual feature construction might lead to important information loss manual feature construction might lead to important information loss Flashback: Categorical - the variable value selected from a predefined number of categories. Categorical values, like any other non-numeric types, has also to be converted into numeric values. How to do it right? Categories could be meaningfully ordered. Can be converted into numeric values saving its natural order. Grades: A+ - 4.0, A- - 3.7, B+ - 3.3, B - 3.0, etc. Demonstration in pandas: grades = { 'A+': 4.0, 'A-': 3.7, 'B+': 3.3, 'B' : 3.0}df['grade_numeric'] = df['grade'].apply(lambda x: grades[x]) Only one of two possible categories. In this case, you can convert values into indicator values 1/0. For example: Male - 1 or Female - 0, or you can do it oppositely. Demonstration in pandas: df['gender_indicator'] = df['gender'].apply(lambda x: int(x.lower() == 'Male')) One or more of all possible categories. In this case, One hot encoding have to be used. This method assumes creating an indicator value for every category(1- the sample is in the category, 0 - if not). This method is applicable also for Dichotomous/Binary categorical values. NEVER USE ORDINAL REPRESENTATION FOR NOMINAL VALUES, it would cause terrible side effects and your model will not be able to handle the categorical feature in the right way. Demonstration in pandas: # Pandas `.get_dummies()` methoddf = pd.concat([df, pd.get_dummies(df['category'], prefix='category')],axis=1)# now drop the original 'category' column (you don't need it anymore)df.drop(['category'],axis=1, inplace=True) Demonstration in sklearn and pandas: from sklearn.preprocessing import LabelEncoder, OneHotEncoderprefix = 'category'ohe = OneHotEncoder(sparse=False)ohe = ohe.fit(df[['category']])onehot_encoded = ohe.transform(df[['category']])features_names_prefixed = [ f"{prefix}_{category}" for category in onehot_encoder.categories_[0]]df = pd.concat([df, pd.DataFrame(onehot_encoded, columns=features_names_prefixed)], axis=1)# now drop the original 'category' column (you don't need it anymore)df.drop(['category'],axis=1, inplace=True) I hope you’ll like my post. Feel free to ask questions in comments. P.S. These are very and very basic and simple things, but they are very important in practice. Much more interesting stuff is coming in the next posts!
[ { "code": null, "e": 950, "s": 172, "text": "Nowadays, almost all ML/data mining projects workflow run on a standard CRISP-DM (Cross-industry standard process for data mining) or its IBM enhance ASUM-DM (Analytics Solutions Unified Method for Data Mining/Predictive Analytics). The longest and the most important step in this workflow is Data preparation/preprocessing, which approximately takes 70% of the time. This step is important because in most situations data provided by the customer has a bad quality or just cannot be directly fed to some kind of ML model. My favorite byword, that I'll mention in all my posts, concerning data preprocessing, says: Garbage in, garbage out (GIGO). In other words, if you feed your model with miserable data, don't expect it to perform well. In this post we are going to discuss:" }, { "code": null, "e": 1037, "s": 950, "text": "Data typesData validationHandling datesHandling nominal and ordinal categorical values" }, { "code": null, "e": 1048, "s": 1037, "text": "Data types" }, { "code": null, "e": 1064, "s": 1048, "text": "Data validation" }, { "code": null, "e": 1079, "s": 1064, "text": "Handling dates" }, { "code": null, "e": 1127, "s": 1079, "text": "Handling nominal and ordinal categorical values" }, { "code": null, "e": 1212, "s": 1127, "text": "In the next posts we are going to talk about more advanced preprocessing techniques:" }, { "code": null, "e": 1421, "s": 1212, "text": "Data cleaning and standardization: Normalization and standartization, Handling missing data, Handling outliersFeature selection and dataset balancing: Dataset balancing, Feature extraction, Feature selection." }, { "code": null, "e": 1532, "s": 1421, "text": "Data cleaning and standardization: Normalization and standartization, Handling missing data, Handling outliers" }, { "code": null, "e": 1631, "s": 1532, "text": "Feature selection and dataset balancing: Dataset balancing, Feature extraction, Feature selection." }, { "code": null, "e": 1825, "s": 1631, "text": "This post series represents the usual preprocessing flow order, but, in fact, all these parts are divided in such a way to be independent and not to require the knowledge of the previous parts." }, { "code": null, "e": 1947, "s": 1825, "text": "This is an introduction part, where we are going to discuss how to check and prepare your data for further preprocessing." }, { "code": null, "e": 2031, "s": 1947, "text": "To start, let’s define what data types exist and what measurement scales they have:" }, { "code": null, "e": 2209, "s": 2031, "text": "Discrete - integer values. Example: number of products bought in the shopContinuos - any value in some admissable range (float, double). Example: average length of words in text" }, { "code": null, "e": 2283, "s": 2209, "text": "Discrete - integer values. Example: number of products bought in the shop" }, { "code": null, "e": 2388, "s": 2283, "text": "Continuos - any value in some admissable range (float, double). Example: average length of words in text" }, { "code": null, "e": 2455, "s": 2388, "text": "The variable value selected from a predefined number of categories" }, { "code": null, "e": 2747, "s": 2455, "text": "Ordinal - categories could be meaningfully ordered. Example: grade (A, B, C, D, E, F)Nominal - categories don't have any order. Example: religion (Christian, Muslim, Hindu, etc.)Dichotomous/Binary - the special case of nominal, with only 2 possible categories. Example: gender (male, female)" }, { "code": null, "e": 2833, "s": 2747, "text": "Ordinal - categories could be meaningfully ordered. Example: grade (A, B, C, D, E, F)" }, { "code": null, "e": 2927, "s": 2833, "text": "Nominal - categories don't have any order. Example: religion (Christian, Muslim, Hindu, etc.)" }, { "code": null, "e": 3041, "s": 2927, "text": "Dichotomous/Binary - the special case of nominal, with only 2 possible categories. Example: gender (male, female)" }, { "code": null, "e": 3097, "s": 3041, "text": "String, python datetime, timestamp. Example: 12.12.2012" }, { "code": null, "e": 3174, "s": 3097, "text": "Multidimensional data, more about text preprocessing see in my previous post" }, { "code": null, "e": 3249, "s": 3174, "text": "Multidimensional data, more about image preprocessing see in my next posts" }, { "code": null, "e": 3347, "s": 3249, "text": "Data points indexed in the time order, more about time series preprocessing see in my next posts." }, { "code": null, "e": 3618, "s": 3347, "text": "The first step is the simplest and the most obvious: you have to investigate and validate your data. To be able to validate the data you have to have a deep understanding of your data. Easy rule: Don't dismiss the description of the dataset. Validation step consists of:" }, { "code": null, "e": 3703, "s": 3618, "text": "Same things have to be represented in the same way and in the same format. Examples:" }, { "code": null, "e": 4030, "s": 3703, "text": "Dates have the same format. Several times in my practice I’ve got data where a part of dates was in American format, the other part in European.Integers are really integers, not strings or floatsCategorical data doesn’t have duplicates because of whitespaces, lower/upper casesOther data representations don’t contain an error" }, { "code": null, "e": 4175, "s": 4030, "text": "Dates have the same format. Several times in my practice I’ve got data where a part of dates was in American format, the other part in European." }, { "code": null, "e": 4227, "s": 4175, "text": "Integers are really integers, not strings or floats" }, { "code": null, "e": 4310, "s": 4227, "text": "Categorical data doesn’t have duplicates because of whitespaces, lower/upper cases" }, { "code": null, "e": 4360, "s": 4310, "text": "Other data representations don’t contain an error" }, { "code": null, "e": 4465, "s": 4360, "text": "Data is in range of permissible values. Example: numerical variables are in admissable (min, max) range." }, { "code": null, "e": 4541, "s": 4465, "text": "Check permitted relationships and fulfillment of the constraints. Examples:" }, { "code": null, "e": 4828, "s": 4541, "text": "Check name titles with sex, age of birth with ageHistorical data have the right chronology. Delivery after purchase, Bank account opening before the first payment, etc.The actions are made by allowed entities. The mortgage could be approved only for people older than 18 years old, etc." }, { "code": null, "e": 4878, "s": 4828, "text": "Check name titles with sex, age of birth with age" }, { "code": null, "e": 4998, "s": 4878, "text": "Historical data have the right chronology. Delivery after purchase, Bank account opening before the first payment, etc." }, { "code": null, "e": 5117, "s": 4998, "text": "The actions are made by allowed entities. The mortgage could be approved only for people older than 18 years old, etc." }, { "code": null, "e": 5405, "s": 5117, "text": "Correct them, if you are sure, what the problem is, or consult with the specialist or data provider if possible.Discard samples with errors, in many cases it is a good choice because you aren't able to fulfill 1.Do nothing, this, of course, could cause undesired effects in future steps." }, { "code": null, "e": 5518, "s": 5405, "text": "Correct them, if you are sure, what the problem is, or consult with the specialist or data provider if possible." }, { "code": null, "e": 5619, "s": 5518, "text": "Discard samples with errors, in many cases it is a good choice because you aren't able to fulfill 1." }, { "code": null, "e": 5695, "s": 5619, "text": "Do nothing, this, of course, could cause undesired effects in future steps." }, { "code": null, "e": 5880, "s": 5695, "text": "Different systems stores dates in different formats: 11.12.2019, 2016-02-12, Sep 24, 2003 etc. But for building models on dates data, we need to somehow convert it to a numeric format." }, { "code": null, "e": 6136, "s": 5880, "text": "To start, I'll show you an example of how to convert a date string into python datetime type, which is much more convenient for further steps. The example is demonstrated on pandas dataframe. Let's assume that date_string column contains dates in strings:" }, { "code": null, "e": 6539, "s": 6136, "text": "# Converts date string column to python datetime type# `infer_datetime_format=True` says method to guess date format from stringdf['datetime'] = pd.to_datetime(df['date_string'], infer_datetime_format=True)# Converts date string column to python datetime type# `format` argument specifies the format of date to parse, fails on errorsdf['datetime'] = pd.to_datetime(df['date_string'], format='%Y.%m.%d')" }, { "code": null, "e": 7111, "s": 6539, "text": "Frequently, just the year (YYYY) is sufficient. But if we want to store months, days or even more detailed data, our numeric format has to fulfill 1 sufficient constraint, it has to save intervals, it means that for example, Monday — Friday in one week has to have the same difference as 1. — 5. of any month. So YYYYMMDD format will be not an option, because the last day of the month and the first day of the next month have a bigger distance than the first and the second day of the month. Actually, there are 4 most common methods to transform date to numeric format:" }, { "code": null, "e": 7140, "s": 7111, "text": "Number of seconds since 1970" }, { "code": null, "e": 7146, "s": 7140, "text": "Pros:" }, { "code": null, "e": 7217, "s": 7146, "text": "perfectly preserve intervalsgood if hours, minutes and seconds matters" }, { "code": null, "e": 7246, "s": 7217, "text": "perfectly preserve intervals" }, { "code": null, "e": 7289, "s": 7246, "text": "good if hours, minutes and seconds matters" }, { "code": null, "e": 7295, "s": 7289, "text": "Cons:" }, { "code": null, "e": 7403, "s": 7295, "text": "values are non-obviousdon’t help intuition and knowledge discoveryharder to verify, easier to make an error" }, { "code": null, "e": 7426, "s": 7403, "text": "values are non-obvious" }, { "code": null, "e": 7471, "s": 7426, "text": "don’t help intuition and knowledge discovery" }, { "code": null, "e": 7513, "s": 7471, "text": "harder to verify, easier to make an error" }, { "code": null, "e": 7564, "s": 7513, "text": "Converting datetime column to timestamp in pandas:" }, { "code": null, "e": 7685, "s": 7564, "text": "# Coverts column in python datetime type to timestampdf['timestamp'] = df['datetime'].values.astype(np.int64) // 10 ** 9" }, { "code": null, "e": 7691, "s": 7685, "text": "Pros:" }, { "code": null, "e": 7793, "s": 7691, "text": "the year and quarter are obviouseasy intuition and knowledge discoverycan be extended to include time" }, { "code": null, "e": 7826, "s": 7793, "text": "the year and quarter are obvious" }, { "code": null, "e": 7865, "s": 7826, "text": "easy intuition and knowledge discovery" }, { "code": null, "e": 7897, "s": 7865, "text": "can be extended to include time" }, { "code": null, "e": 7903, "s": 7897, "text": "Cons:" }, { "code": null, "e": 7932, "s": 7903, "text": "preserves intervals (almost)" }, { "code": null, "e": 7961, "s": 7932, "text": "preserves intervals (almost)" }, { "code": null, "e": 8020, "s": 7961, "text": "Converting python datetime column to KSP format in pandas:" }, { "code": null, "e": 8331, "s": 8020, "text": "import datetime as dtimport calendardef to_ksp_format(datetime): year = datetime.year day_from_jan_1 = (datetime - dt.datetime(year, 1, 1)).days is_leap_year = int(calendar.isleap(year)) return year + (day_from_jan_1 - 0.5) / (365 + is_leap_year)df['ksp_date'] = df['datetime'].apply(to_ksp_format)" }, { "code": null, "e": 8355, "s": 8331, "text": "Year, month, days, etc." }, { "code": null, "e": 8361, "s": 8355, "text": "Cons:" }, { "code": null, "e": 8428, "s": 8361, "text": "perfectly preserve intervalseasy intuition and knowledge discovery" }, { "code": null, "e": 8457, "s": 8428, "text": "perfectly preserve intervals" }, { "code": null, "e": 8496, "s": 8457, "text": "easy intuition and knowledge discovery" }, { "code": null, "e": 8502, "s": 8496, "text": "Pros:" }, { "code": null, "e": 8588, "s": 8502, "text": "more dimensions you add, more complex your model could get, but it is not always bad." }, { "code": null, "e": 8674, "s": 8588, "text": "more dimensions you add, more complex your model could get, but it is not always bad." }, { "code": null, "e": 8735, "s": 8674, "text": "Construct a new feature based on date features. For example:" }, { "code": null, "e": 8756, "s": 8735, "text": "date of birth -> age" }, { "code": null, "e": 8821, "s": 8756, "text": "date order created and date order delivered -> time to delivery." }, { "code": null, "e": 8827, "s": 8821, "text": "Cons:" }, { "code": null, "e": 8866, "s": 8827, "text": "easy intuition and knowledge discovery" }, { "code": null, "e": 8905, "s": 8866, "text": "easy intuition and knowledge discovery" }, { "code": null, "e": 8911, "s": 8905, "text": "Pros:" }, { "code": null, "e": 8980, "s": 8911, "text": "manual feature construction might lead to important information loss" }, { "code": null, "e": 9049, "s": 8980, "text": "manual feature construction might lead to important information loss" }, { "code": null, "e": 9262, "s": 9049, "text": "Flashback: Categorical - the variable value selected from a predefined number of categories. Categorical values, like any other non-numeric types, has also to be converted into numeric values. How to do it right?" }, { "code": null, "e": 9419, "s": 9262, "text": "Categories could be meaningfully ordered. Can be converted into numeric values saving its natural order. Grades: A+ - 4.0, A- - 3.7, B+ - 3.3, B - 3.0, etc." }, { "code": null, "e": 9444, "s": 9419, "text": "Demonstration in pandas:" }, { "code": null, "e": 9571, "s": 9444, "text": "grades = { 'A+': 4.0, 'A-': 3.7, 'B+': 3.3, 'B' : 3.0}df['grade_numeric'] = df['grade'].apply(lambda x: grades[x])" }, { "code": null, "e": 9738, "s": 9571, "text": "Only one of two possible categories. In this case, you can convert values into indicator values 1/0. For example: Male - 1 or Female - 0, or you can do it oppositely." }, { "code": null, "e": 9763, "s": 9738, "text": "Demonstration in pandas:" }, { "code": null, "e": 9843, "s": 9763, "text": "df['gender_indicator'] = df['gender'].apply(lambda x: int(x.lower() == 'Male'))" }, { "code": null, "e": 10293, "s": 9843, "text": "One or more of all possible categories. In this case, One hot encoding have to be used. This method assumes creating an indicator value for every category(1- the sample is in the category, 0 - if not). This method is applicable also for Dichotomous/Binary categorical values. NEVER USE ORDINAL REPRESENTATION FOR NOMINAL VALUES, it would cause terrible side effects and your model will not be able to handle the categorical feature in the right way." }, { "code": null, "e": 10318, "s": 10293, "text": "Demonstration in pandas:" }, { "code": null, "e": 10540, "s": 10318, "text": "# Pandas `.get_dummies()` methoddf = pd.concat([df, pd.get_dummies(df['category'], prefix='category')],axis=1)# now drop the original 'category' column (you don't need it anymore)df.drop(['category'],axis=1, inplace=True)" }, { "code": null, "e": 10577, "s": 10540, "text": "Demonstration in sklearn and pandas:" }, { "code": null, "e": 11069, "s": 10577, "text": "from sklearn.preprocessing import LabelEncoder, OneHotEncoderprefix = 'category'ohe = OneHotEncoder(sparse=False)ohe = ohe.fit(df[['category']])onehot_encoded = ohe.transform(df[['category']])features_names_prefixed = [ f\"{prefix}_{category}\" for category in onehot_encoder.categories_[0]]df = pd.concat([df, pd.DataFrame(onehot_encoded, columns=features_names_prefixed)], axis=1)# now drop the original 'category' column (you don't need it anymore)df.drop(['category'],axis=1, inplace=True)" }, { "code": null, "e": 11137, "s": 11069, "text": "I hope you’ll like my post. Feel free to ask questions in comments." } ]
Function Pointer in C - GeeksforGeeks
05 Sep, 2018 In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer. #include <stdio.h>// A normal function with an int parameter// and void return typevoid fun(int a){ printf("Value of a is %d\n", a);} int main(){ // fun_ptr is a pointer to function fun() void (*fun_ptr)(int) = &fun; /* The above line is equivalent of following two void (*fun_ptr)(int); fun_ptr = &fun; */ // Invoking fun() using fun_ptr (*fun_ptr)(10); return 0;} Output: Value of a is 10 Why do we need an extra bracket around function pointers like fun_ptr in above example?If we remove bracket, then the expression “void (*fun_ptr)(int)” becomes “void *fun_ptr(int)” which is declaration of a function that returns void pointer. See following post for details.How to declare a pointer to a function? Following are some interesting facts about function pointers. 1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. 2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers. 3) A function’s name can also be used to get functions’ address. For example, in the below program, we have removed address operator ‘&’ in assignment. We have also changed function call by removing *, the program still works. #include <stdio.h>// A normal function with an int parameter// and void return typevoid fun(int a){ printf("Value of a is %d\n", a);} int main(){ void (*fun_ptr)(int) = fun; // & removed fun_ptr(10); // * removed return 0;} Output: Value of a is 10 4) Like normal pointers, we can have an array of function pointers. Below example in point 5 shows syntax for array of pointers. 5) Function pointer can be used in place of switch case. For example, in below program, user is asked for a choice between 0 and 2 to do different tasks. #include <stdio.h>void add(int a, int b){ printf("Addition is %d\n", a+b);}void subtract(int a, int b){ printf("Subtraction is %d\n", a-b);}void multiply(int a, int b){ printf("Multiplication is %d\n", a*b);} int main(){ // fun_ptr_arr is an array of function pointers void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply}; unsigned int ch, a = 15, b = 10; printf("Enter Choice: 0 for add, 1 for subtract and 2 " "for multiply\n"); scanf("%d", &ch); if (ch > 2) return 0; (*fun_ptr_arr[ch])(a, b); return 0;} Enter Choice: 0 for add, 1 for subtract and 2 for multiply 2 Multiplication is 150 6) Like normal data pointers, a function pointer can be passed as an argument and can also be returned from a function.For example, consider the following C program where wrapper() receives a void fun() as parameter and calls the passed function. // A simple C program to show function pointers as parameter#include <stdio.h> // Two simple functionsvoid fun1() { printf("Fun1\n"); }void fun2() { printf("Fun2\n"); } // A function that receives a simple function// as parameter and calls the functionvoid wrapper(void (*fun)()){ fun();} int main(){ wrapper(fun1); wrapper(fun2); return 0;} This point in particular is very useful in C. In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type. // An example for qsort and comparator#include <stdio.h>#include <stdlib.h> // A sample comparator function that is used// for sorting an integer array in ascending order.// To sort any array for any other data type and/or// criteria, all we need to do is write more compare// functions. And we can use the same qsort()int compare (const void * a, const void * b){ return ( *(int*)a - *(int*)b );} int main (){ int arr[] = {10, 5, 15, 12, 90, 80}; int n = sizeof(arr)/sizeof(arr[0]), i; qsort (arr, n, sizeof(int), compare); for (i=0; i<n; i++) printf ("%d ", arr[i]); return 0;} Output: 5 10 12 15 80 90 Similar to qsort(), we can write our own functions that can be used for any data type and can do different tasks without code redundancy. Below is an example search function that can be used for any data type. In fact we can use this search function to find close elements (below a threshold) by writing a customized compare function. #include <stdio.h>#include <stdbool.h> // A compare function that is used for searching an integer// arraybool compare (const void * a, const void * b){ return ( *(int*)a == *(int*)b );} // General purpose search() function that can be used// for searching an element *x in an array arr[] of// arr_size. Note that void pointers are used so that// the function can be called by passing a pointer of// any type. ele_size is size of an array elementint search(void *arr, int arr_size, int ele_size, void *x, bool compare (const void * , const void *)){ // Since char takes one byte, we can use char pointer // for any type/ To get pointer arithmetic correct, // we need to multiply index with size of an array // element ele_size char *ptr = (char *)arr; int i; for (i=0; i<arr_size; i++) if (compare(ptr + i*ele_size, x)) return i; // If element not found return -1;} int main(){ int arr[] = {2, 5, 7, 90, 70}; int n = sizeof(arr)/sizeof(arr[0]); int x = 7; printf ("Returned index is %d ", search(arr, n, sizeof(int), &x, compare)); return 0;} Output: Returned index is 2 The above search function can be used for any data type by writing a separate customized compare(). 7) Many object oriented features in C++ are implemented using function pointers in C. For example virtual functions. Class methods are another example implemented using function pointers. Refer this book for more details. Related Article:Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array) References:http://www.cs.cmu.edu/~ab/15-123S11/AnnotatedNotes/Lecture14.pdf http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-087-practical-programming-in-c-january-iap-2010/lecture-notes/MIT6_087IAP10_lec08.pdf http://www.cs.cmu.edu/~guna/15-123S11/Lectures/Lecture14.pdf This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. C-Pointers CPP-Functions cpp-pointer C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments fork() in C TCP Server-Client implementation in C Enumeration (or enum) in C std::string class in C++ Structures in C 'this' pointer in C++ Exception Handling in C++ C Language Introduction Memory Layout of C Programs Multithreading in C
[ { "code": null, "e": 24426, "s": 24398, "text": "\n05 Sep, 2018" }, { "code": null, "e": 24610, "s": 24426, "text": "In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer." }, { "code": "#include <stdio.h>// A normal function with an int parameter// and void return typevoid fun(int a){ printf(\"Value of a is %d\\n\", a);} int main(){ // fun_ptr is a pointer to function fun() void (*fun_ptr)(int) = &fun; /* The above line is equivalent of following two void (*fun_ptr)(int); fun_ptr = &fun; */ // Invoking fun() using fun_ptr (*fun_ptr)(10); return 0;}", "e": 25021, "s": 24610, "text": null }, { "code": null, "e": 25029, "s": 25021, "text": "Output:" }, { "code": null, "e": 25046, "s": 25029, "text": "Value of a is 10" }, { "code": null, "e": 25360, "s": 25046, "text": "Why do we need an extra bracket around function pointers like fun_ptr in above example?If we remove bracket, then the expression “void (*fun_ptr)(int)” becomes “void *fun_ptr(int)” which is declaration of a function that returns void pointer. See following post for details.How to declare a pointer to a function?" }, { "code": null, "e": 25422, "s": 25360, "text": "Following are some interesting facts about function pointers." }, { "code": null, "e": 25561, "s": 25422, "text": " 1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code." }, { "code": null, "e": 25651, "s": 25561, "text": "2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers." }, { "code": null, "e": 25879, "s": 25651, "text": " 3) A function’s name can also be used to get functions’ address. For example, in the below program, we have removed address operator ‘&’ in assignment. We have also changed function call by removing *, the program still works." }, { "code": "#include <stdio.h>// A normal function with an int parameter// and void return typevoid fun(int a){ printf(\"Value of a is %d\\n\", a);} int main(){ void (*fun_ptr)(int) = fun; // & removed fun_ptr(10); // * removed return 0;}", "e": 26123, "s": 25879, "text": null }, { "code": null, "e": 26131, "s": 26123, "text": "Output:" }, { "code": null, "e": 26148, "s": 26131, "text": "Value of a is 10" }, { "code": null, "e": 26278, "s": 26148, "text": " 4) Like normal pointers, we can have an array of function pointers. Below example in point 5 shows syntax for array of pointers." }, { "code": null, "e": 26433, "s": 26278, "text": " 5) Function pointer can be used in place of switch case. For example, in below program, user is asked for a choice between 0 and 2 to do different tasks." }, { "code": "#include <stdio.h>void add(int a, int b){ printf(\"Addition is %d\\n\", a+b);}void subtract(int a, int b){ printf(\"Subtraction is %d\\n\", a-b);}void multiply(int a, int b){ printf(\"Multiplication is %d\\n\", a*b);} int main(){ // fun_ptr_arr is an array of function pointers void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply}; unsigned int ch, a = 15, b = 10; printf(\"Enter Choice: 0 for add, 1 for subtract and 2 \" \"for multiply\\n\"); scanf(\"%d\", &ch); if (ch > 2) return 0; (*fun_ptr_arr[ch])(a, b); return 0;}", "e": 27001, "s": 26433, "text": null }, { "code": null, "e": 27085, "s": 27001, "text": "Enter Choice: 0 for add, 1 for subtract and 2 for multiply\n2\nMultiplication is 150 " }, { "code": null, "e": 27333, "s": 27085, "text": " 6) Like normal data pointers, a function pointer can be passed as an argument and can also be returned from a function.For example, consider the following C program where wrapper() receives a void fun() as parameter and calls the passed function." }, { "code": "// A simple C program to show function pointers as parameter#include <stdio.h> // Two simple functionsvoid fun1() { printf(\"Fun1\\n\"); }void fun2() { printf(\"Fun2\\n\"); } // A function that receives a simple function// as parameter and calls the functionvoid wrapper(void (*fun)()){ fun();} int main(){ wrapper(fun1); wrapper(fun2); return 0;}", "e": 27690, "s": 27333, "text": null }, { "code": null, "e": 28053, "s": 27690, "text": "This point in particular is very useful in C. In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type." }, { "code": "// An example for qsort and comparator#include <stdio.h>#include <stdlib.h> // A sample comparator function that is used// for sorting an integer array in ascending order.// To sort any array for any other data type and/or// criteria, all we need to do is write more compare// functions. And we can use the same qsort()int compare (const void * a, const void * b){ return ( *(int*)a - *(int*)b );} int main (){ int arr[] = {10, 5, 15, 12, 90, 80}; int n = sizeof(arr)/sizeof(arr[0]), i; qsort (arr, n, sizeof(int), compare); for (i=0; i<n; i++) printf (\"%d \", arr[i]); return 0;}", "e": 28650, "s": 28053, "text": null }, { "code": null, "e": 28658, "s": 28650, "text": "Output:" }, { "code": null, "e": 28675, "s": 28658, "text": "5 10 12 15 80 90" }, { "code": null, "e": 29010, "s": 28675, "text": "Similar to qsort(), we can write our own functions that can be used for any data type and can do different tasks without code redundancy. Below is an example search function that can be used for any data type. In fact we can use this search function to find close elements (below a threshold) by writing a customized compare function." }, { "code": "#include <stdio.h>#include <stdbool.h> // A compare function that is used for searching an integer// arraybool compare (const void * a, const void * b){ return ( *(int*)a == *(int*)b );} // General purpose search() function that can be used// for searching an element *x in an array arr[] of// arr_size. Note that void pointers are used so that// the function can be called by passing a pointer of// any type. ele_size is size of an array elementint search(void *arr, int arr_size, int ele_size, void *x, bool compare (const void * , const void *)){ // Since char takes one byte, we can use char pointer // for any type/ To get pointer arithmetic correct, // we need to multiply index with size of an array // element ele_size char *ptr = (char *)arr; int i; for (i=0; i<arr_size; i++) if (compare(ptr + i*ele_size, x)) return i; // If element not found return -1;} int main(){ int arr[] = {2, 5, 7, 90, 70}; int n = sizeof(arr)/sizeof(arr[0]); int x = 7; printf (\"Returned index is %d \", search(arr, n, sizeof(int), &x, compare)); return 0;}", "e": 30161, "s": 29010, "text": null }, { "code": null, "e": 30169, "s": 30161, "text": "Output:" }, { "code": null, "e": 30189, "s": 30169, "text": "Returned index is 2" }, { "code": null, "e": 30289, "s": 30189, "text": "The above search function can be used for any data type by writing a separate customized compare()." }, { "code": null, "e": 30512, "s": 30289, "text": " 7) Many object oriented features in C++ are implemented using function pointers in C. For example virtual functions. Class methods are another example implemented using function pointers. Refer this book for more details." }, { "code": null, "e": 30595, "s": 30512, "text": "Related Article:Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)" }, { "code": null, "e": 30671, "s": 30595, "text": "References:http://www.cs.cmu.edu/~ab/15-123S11/AnnotatedNotes/Lecture14.pdf" }, { "code": null, "e": 30830, "s": 30671, "text": "http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-087-practical-programming-in-c-january-iap-2010/lecture-notes/MIT6_087IAP10_lec08.pdf" }, { "code": null, "e": 30891, "s": 30830, "text": "http://www.cs.cmu.edu/~guna/15-123S11/Lectures/Lecture14.pdf" }, { "code": null, "e": 31060, "s": 30891, "text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31071, "s": 31060, "text": "C-Pointers" }, { "code": null, "e": 31085, "s": 31071, "text": "CPP-Functions" }, { "code": null, "e": 31097, "s": 31085, "text": "cpp-pointer" }, { "code": null, "e": 31108, "s": 31097, "text": "C Language" }, { "code": null, "e": 31206, "s": 31108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31215, "s": 31206, "text": "Comments" }, { "code": null, "e": 31228, "s": 31215, "text": "Old Comments" }, { "code": null, "e": 31240, "s": 31228, "text": "fork() in C" }, { "code": null, "e": 31278, "s": 31240, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 31305, "s": 31278, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 31330, "s": 31305, "text": "std::string class in C++" }, { "code": null, "e": 31346, "s": 31330, "text": "Structures in C" }, { "code": null, "e": 31368, "s": 31346, "text": "'this' pointer in C++" }, { "code": null, "e": 31394, "s": 31368, "text": "Exception Handling in C++" }, { "code": null, "e": 31418, "s": 31394, "text": "C Language Introduction" }, { "code": null, "e": 31446, "s": 31418, "text": "Memory Layout of C Programs" } ]
C Program to convert a number to a string
In this section we will see how to convert a number (integer or float or any other numeric type data) to a string. The logic is very simple. Here we will use the sprintf() function. This function is used to print some value or line into a string, but not in the console. This is the only difference between printf() and sprintf(). Here the first argument is the string buffer. where we want to save our data. Input: User will put some numeric value say 42.26 Output: This program will return the string equivalent result of that number like "42.26" Step 1: Take a number from the user Step 2: Create an empty string buffer to store result Step 3: Use sprintf() to convert number to string Step 4: End Live Demo #include<stdio.h> main() { char str[20]; //create an empty string to store number float number; printf("Enter a number: "); scanf("%f", &number); sprintf(str, "%f", number); //make the number into string using sprintf function printf("\nYou have entered: %s", str); } Enter a number: 46.3258 You have entered: 46.325802
[ { "code": null, "e": 1177, "s": 1062, "text": "In this section we will see how to convert a number (integer or float or any other numeric type data) to a string." }, { "code": null, "e": 1471, "s": 1177, "text": "The logic is very simple. Here we will use the sprintf() function. This function is used to print some value or line into a string, but not in the console. This is the only difference between printf() and sprintf(). Here the first argument is the string buffer. where we want to save our data." }, { "code": null, "e": 1611, "s": 1471, "text": "Input: User will put some numeric value say 42.26\nOutput: This program will return the string equivalent result of that number like \"42.26\"" }, { "code": null, "e": 1763, "s": 1611, "text": "Step 1: Take a number from the user\nStep 2: Create an empty string buffer to store result\nStep 3: Use sprintf() to convert number to string\nStep 4: End" }, { "code": null, "e": 1774, "s": 1763, "text": " Live Demo" }, { "code": null, "e": 2065, "s": 1774, "text": "#include<stdio.h>\nmain() {\n char str[20]; //create an empty string to store number\n float number;\n printf(\"Enter a number: \");\n scanf(\"%f\", &number);\n sprintf(str, \"%f\", number); //make the number into string using sprintf function\n printf(\"\\nYou have entered: %s\", str);\n}" }, { "code": null, "e": 2117, "s": 2065, "text": "Enter a number: 46.3258\nYou have entered: 46.325802" } ]
HTTP headers | Set-Cookie
31 Oct, 2019 The HTTP header Set-Cookie is a response header and used to send cookies from the server to the user agent. So the user agent can send them back to the server later so the server can detect the user. Syntax: Set-Cookie: <cookie-name>=<cookie-value> | Expires=<date> | Max-Age=<non-zero-digit> | Domain=<domain-value> | Path=<path-value> | SameSite=Strict|Lax|none Note: Using multiple directives are also possible. Directives: <cookie-name>=<cookie-value>: The cookie name have to avoid this character ( ) @, ; : \ ” / [ ] ? = { } plus control characters, spaces, and tabs. It can be any US-ASCII characters. Expires=<date>: It is an optional directive that contains the expiry date of the cookie. Max-Age=<non-zero-digit>: It contains the life span in a digit of seconds format, zero or negative value will make the cookie expired immediately. Domain=<domain-value>: This directive defines the host where the cookie will be sent. It is an optional directive. Path=<path-value>: This directive define a path that must exist in the requested URL, else the browser can’t send the cookie header. SameSite=Strict|Lax|none: This directives providing some protection against cross-site request forgery attacks. Example: This types cookies were removed when the user shut down the system this types of cookies known as a session cookie.Set-Cookie: sessionId=38afes7a8 Set-Cookie: sessionId=38afes7a8 Permanent cookies expire on some specific dateset-cookie: 1P_JAR=2019-10-24-18; expires=...in=.google.com; SameSite=none set-cookie: 1P_JAR=2019-10-24-18; expires=...in=.google.com; SameSite=none To check this Set-Cookie in action go to Inspect Element -> Network check the response header for Set-Cookie. Supported Browsers: The browsers compatible with HTTP header Set-Cookie are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTTP-headers Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Oct, 2019" }, { "code": null, "e": 254, "s": 54, "text": "The HTTP header Set-Cookie is a response header and used to send cookies from the server to the user agent. So the user agent can send them back to the server later so the server can detect the user." }, { "code": null, "e": 262, "s": 254, "text": "Syntax:" }, { "code": null, "e": 449, "s": 262, "text": "Set-Cookie: <cookie-name>=<cookie-value> | Expires=<date> \n | Max-Age=<non-zero-digit> | Domain=<domain-value>\n | Path=<path-value> | SameSite=Strict|Lax|none" }, { "code": null, "e": 500, "s": 449, "text": "Note: Using multiple directives are also possible." }, { "code": null, "e": 512, "s": 500, "text": "Directives:" }, { "code": null, "e": 694, "s": 512, "text": "<cookie-name>=<cookie-value>: The cookie name have to avoid this character ( ) @, ; : \\ ” / [ ] ? = { } plus control characters, spaces, and tabs. It can be any US-ASCII characters." }, { "code": null, "e": 783, "s": 694, "text": "Expires=<date>: It is an optional directive that contains the expiry date of the cookie." }, { "code": null, "e": 930, "s": 783, "text": "Max-Age=<non-zero-digit>: It contains the life span in a digit of seconds format, zero or negative value will make the cookie expired immediately." }, { "code": null, "e": 1045, "s": 930, "text": "Domain=<domain-value>: This directive defines the host where the cookie will be sent. It is an optional directive." }, { "code": null, "e": 1178, "s": 1045, "text": "Path=<path-value>: This directive define a path that must exist in the requested URL, else the browser can’t send the cookie header." }, { "code": null, "e": 1290, "s": 1178, "text": "SameSite=Strict|Lax|none: This directives providing some protection against cross-site request forgery attacks." }, { "code": null, "e": 1299, "s": 1290, "text": "Example:" }, { "code": null, "e": 1446, "s": 1299, "text": "This types cookies were removed when the user shut down the system this types of cookies known as a session cookie.Set-Cookie: sessionId=38afes7a8" }, { "code": null, "e": 1478, "s": 1446, "text": "Set-Cookie: sessionId=38afes7a8" }, { "code": null, "e": 1599, "s": 1478, "text": "Permanent cookies expire on some specific dateset-cookie: 1P_JAR=2019-10-24-18; expires=...in=.google.com; SameSite=none" }, { "code": null, "e": 1674, "s": 1599, "text": "set-cookie: 1P_JAR=2019-10-24-18; expires=...in=.google.com; SameSite=none" }, { "code": null, "e": 1784, "s": 1674, "text": "To check this Set-Cookie in action go to Inspect Element -> Network check the response header for Set-Cookie." }, { "code": null, "e": 1874, "s": 1784, "text": "Supported Browsers: The browsers compatible with HTTP header Set-Cookie are listed below:" }, { "code": null, "e": 1888, "s": 1874, "text": "Google Chrome" }, { "code": null, "e": 1906, "s": 1888, "text": "Internet Explorer" }, { "code": null, "e": 1914, "s": 1906, "text": "Firefox" }, { "code": null, "e": 1921, "s": 1914, "text": "Safari" }, { "code": null, "e": 1927, "s": 1921, "text": "Opera" }, { "code": null, "e": 1940, "s": 1927, "text": "HTTP-headers" }, { "code": null, "e": 1947, "s": 1940, "text": "Picked" }, { "code": null, "e": 1964, "s": 1947, "text": "Web Technologies" } ]
How To Automate Google Chrome Using Foxtrot and Python
14 Sep, 2021 In this article, we are going to see how to automate google chrome using Foxtrot & Python. Robotic process automation (RPA) cuts down employees’ workloads by automating repetitive, high-volume steps in processes. Software robots, such as Foxtrot RPA emulate the actions of human workers to execute tasks within applications via their UI. Install the latest version of Foxtrot RPA. Install python selenium package by running the following command in terminal. Install the latest Google Chrome and its Chrome webdriver. We need to create a simple python script that automates a work in Google Chrome using selenium and chrome webdriver. And here, we will automate an authorization at “https://auth.geeksforgeeks.org” and extract the Name, Email, Institute name from the logged-in profile. First, we test it by running the python file and then we will add this python script in Foxtrot Python Actions Botflow and run the Botflow. First, we need to initiate the webdriver using selenium and send a get request to the url, and then identify the HTML document and find the input tags and button tags which accept username/email, password, and sign in button. To Send the user given email and password to the input tags respectively: driver.find_element_by_name('user').send_keys(email) driver.find_element_by_name('pass').send_keys(password) To Identify the button tag and click on it using the CSS selector via selenium webdriver: driver.find_element_by_css_selector(‘button.btn.btn-green.signin-button’).click() After clicking on Sign in, a new page should be loaded containing the Name, Institute Name, and Email id. Identify the tags containing the above data’s and select them: container = driver.find_elements_by_css_selector(‘div.mdl-cell.mdl-cell–9-col.mdl-cell–12-col-phone.textBold’) Get the text from each of these tags from the returned list of selected CSS selectors: name = container[0].text try: institution = container[1].find_element_by_css_selector('a').text except: institution = container[1].text email_id = container[2].text Finally, print the output: print({“Name”: name, “Institution”: institution, “Email ID”: email}) Python3 # Import the required modulesfrom selenium import webdriverimport time # Main Functionif __name__ == '__main__': # Provide the email and password email = '' password = '' options = webdriver.ChromeOptions() options.add_argument("--start-maximized") # Provide the path of chromedriver # present on your system. driver = webdriver.Chrome( executable_path="C:/chromedriver/chromedriver.exe", chrome_options=options) driver.set_window_size(1920, 1080) # Send a get request to the url driver.get('https://auth.geeksforgeeks.org/') time.sleep(5) # Finds the input box by name # in DOM tree to send both # the provided email and password in it. driver.find_element_by_name('user').send_keys(email) driver.find_element_by_name('pass').send_keys(password) # Find the signin button and click on it. driver.find_element_by_css_selector( 'button.btn.btn-green.signin-button').click() time.sleep(5) # Returns the list of elements # having the following css selector. container = driver.find_elements_by_css_selector( 'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold') # Extracts the text from name, # institution, email_id css selector. name = container[0].text try: institution = container[1].find_element_by_css_selector('a').text except: institution = container[1].text email_id = container[2].text # Output print({"Name": name, "Institution": institution, "Email ID": email}) # Quits the driver driver.quit() Output: Here we are going to automate the script using foxtrot. Step 1: Open Foxtrot App and make sure to select the Level as Expert in Account setting: Step 2: Create a New Botflow and click on the Advanced tab in Actions Panel and select Python. Step 3: A new window should appear where you can select the method as Code and copy-paste the previous script in the Code Box provided. Or, you can select the method the python file containing the script: Step 4: To show the output of the above script in Foxtrot, we need to create a variable. Click on the checkbox beside Save to and select the magic button on the right side. Creating Variable Step 5: A new window should appear called Expression, Select Variables in the Items and click on “+” button top right of the window. Step 6: Provide a Name and select Type as Text and click OK. Click OK again and then type the name of the variable in Save To Box. The below Image represents the final state after following the above-mentioned steps. Click on OK to Run the BOT: Step 7: To view the Output, Select Variables in the BotFlow and click on the pencil button of the previously selected variable. The output is the same as we saw before while running the script on Terminal: This is how we can automate Google Chrome by using Selenium, Python and Foxtrot. Blogathon-2021 Picked Python Selenium-Exercises Python-selenium python-utility Blogathon 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 Sep, 2021" }, { "code": null, "e": 119, "s": 28, "text": "In this article, we are going to see how to automate google chrome using Foxtrot & Python." }, { "code": null, "e": 366, "s": 119, "text": "Robotic process automation (RPA) cuts down employees’ workloads by automating repetitive, high-volume steps in processes. Software robots, such as Foxtrot RPA emulate the actions of human workers to execute tasks within applications via their UI." }, { "code": null, "e": 409, "s": 366, "text": "Install the latest version of Foxtrot RPA." }, { "code": null, "e": 487, "s": 409, "text": "Install python selenium package by running the following command in terminal." }, { "code": null, "e": 546, "s": 487, "text": "Install the latest Google Chrome and its Chrome webdriver." }, { "code": null, "e": 815, "s": 546, "text": "We need to create a simple python script that automates a work in Google Chrome using selenium and chrome webdriver. And here, we will automate an authorization at “https://auth.geeksforgeeks.org” and extract the Name, Email, Institute name from the logged-in profile." }, { "code": null, "e": 955, "s": 815, "text": "First, we test it by running the python file and then we will add this python script in Foxtrot Python Actions Botflow and run the Botflow." }, { "code": null, "e": 1181, "s": 955, "text": "First, we need to initiate the webdriver using selenium and send a get request to the url, and then identify the HTML document and find the input tags and button tags which accept username/email, password, and sign in button." }, { "code": null, "e": 1255, "s": 1181, "text": "To Send the user given email and password to the input tags respectively:" }, { "code": null, "e": 1364, "s": 1255, "text": "driver.find_element_by_name('user').send_keys(email)\ndriver.find_element_by_name('pass').send_keys(password)" }, { "code": null, "e": 1454, "s": 1364, "text": "To Identify the button tag and click on it using the CSS selector via selenium webdriver:" }, { "code": null, "e": 1536, "s": 1454, "text": "driver.find_element_by_css_selector(‘button.btn.btn-green.signin-button’).click()" }, { "code": null, "e": 1642, "s": 1536, "text": "After clicking on Sign in, a new page should be loaded containing the Name, Institute Name, and Email id." }, { "code": null, "e": 1705, "s": 1642, "text": "Identify the tags containing the above data’s and select them:" }, { "code": null, "e": 1816, "s": 1705, "text": "container = driver.find_elements_by_css_selector(‘div.mdl-cell.mdl-cell–9-col.mdl-cell–12-col-phone.textBold’)" }, { "code": null, "e": 1903, "s": 1816, "text": "Get the text from each of these tags from the returned list of selected CSS selectors:" }, { "code": null, "e": 2076, "s": 1903, "text": "name = container[0].text\ntry:\n institution = container[1].find_element_by_css_selector('a').text\nexcept:\n institution = container[1].text\nemail_id = container[2].text" }, { "code": null, "e": 2103, "s": 2076, "text": "Finally, print the output:" }, { "code": null, "e": 2172, "s": 2103, "text": "print({“Name”: name, “Institution”: institution, “Email ID”: email})" }, { "code": null, "e": 2180, "s": 2172, "text": "Python3" }, { "code": "# Import the required modulesfrom selenium import webdriverimport time # Main Functionif __name__ == '__main__': # Provide the email and password email = '' password = '' options = webdriver.ChromeOptions() options.add_argument(\"--start-maximized\") # Provide the path of chromedriver # present on your system. driver = webdriver.Chrome( executable_path=\"C:/chromedriver/chromedriver.exe\", chrome_options=options) driver.set_window_size(1920, 1080) # Send a get request to the url driver.get('https://auth.geeksforgeeks.org/') time.sleep(5) # Finds the input box by name # in DOM tree to send both # the provided email and password in it. driver.find_element_by_name('user').send_keys(email) driver.find_element_by_name('pass').send_keys(password) # Find the signin button and click on it. driver.find_element_by_css_selector( 'button.btn.btn-green.signin-button').click() time.sleep(5) # Returns the list of elements # having the following css selector. container = driver.find_elements_by_css_selector( 'div.mdl-cell.mdl-cell--9-col.mdl-cell--12-col-phone.textBold') # Extracts the text from name, # institution, email_id css selector. name = container[0].text try: institution = container[1].find_element_by_css_selector('a').text except: institution = container[1].text email_id = container[2].text # Output print({\"Name\": name, \"Institution\": institution, \"Email ID\": email}) # Quits the driver driver.quit()", "e": 3764, "s": 2180, "text": null }, { "code": null, "e": 3772, "s": 3764, "text": "Output:" }, { "code": null, "e": 3828, "s": 3772, "text": "Here we are going to automate the script using foxtrot." }, { "code": null, "e": 3917, "s": 3828, "text": "Step 1: Open Foxtrot App and make sure to select the Level as Expert in Account setting:" }, { "code": null, "e": 4012, "s": 3917, "text": "Step 2: Create a New Botflow and click on the Advanced tab in Actions Panel and select Python." }, { "code": null, "e": 4148, "s": 4012, "text": "Step 3: A new window should appear where you can select the method as Code and copy-paste the previous script in the Code Box provided." }, { "code": null, "e": 4217, "s": 4148, "text": "Or, you can select the method the python file containing the script:" }, { "code": null, "e": 4390, "s": 4217, "text": "Step 4: To show the output of the above script in Foxtrot, we need to create a variable. Click on the checkbox beside Save to and select the magic button on the right side." }, { "code": null, "e": 4408, "s": 4390, "text": "Creating Variable" }, { "code": null, "e": 4541, "s": 4408, "text": "Step 5: A new window should appear called Expression, Select Variables in the Items and click on “+” button top right of the window." }, { "code": null, "e": 4602, "s": 4541, "text": "Step 6: Provide a Name and select Type as Text and click OK." }, { "code": null, "e": 4758, "s": 4602, "text": "Click OK again and then type the name of the variable in Save To Box. The below Image represents the final state after following the above-mentioned steps." }, { "code": null, "e": 4786, "s": 4758, "text": "Click on OK to Run the BOT:" }, { "code": null, "e": 4914, "s": 4786, "text": "Step 7: To view the Output, Select Variables in the BotFlow and click on the pencil button of the previously selected variable." }, { "code": null, "e": 4992, "s": 4914, "text": "The output is the same as we saw before while running the script on Terminal:" }, { "code": null, "e": 5073, "s": 4992, "text": "This is how we can automate Google Chrome by using Selenium, Python and Foxtrot." }, { "code": null, "e": 5088, "s": 5073, "text": "Blogathon-2021" }, { "code": null, "e": 5095, "s": 5088, "text": "Picked" }, { "code": null, "e": 5121, "s": 5095, "text": "Python Selenium-Exercises" }, { "code": null, "e": 5137, "s": 5121, "text": "Python-selenium" }, { "code": null, "e": 5152, "s": 5137, "text": "python-utility" }, { "code": null, "e": 5162, "s": 5152, "text": "Blogathon" }, { "code": null, "e": 5169, "s": 5162, "text": "Python" } ]
How to detect escape key press using jQuery?
12 Apr, 2019 To detect escape key press, keyup or keydown event handler will be used in jquery. It will trigger over the document when the escape key will be pressed from the keyboard. keyup event: This event is fired when key is released from the keyboard. keydown event: This event is fired when key is pressed from the keyboard. Syntax: $(document).on('keydown', function(event) { if (event.key == "Escape") { alert('Esc key pressed.'); } }); Explanation:Over whole document we are calling the on method and we are passing the keydown or keyup event as first parameter. As second parameter a function is attached which invokes when keydown or keyup event occurs and it will show an alert on pressing the escape key from the keyboard. Example-1: This example detects the escape key press(using keydown event handler) <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title> escape-jquery-detection </title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script></head> <body> <h1> Escape jquery detection using keydown event handler </h1></body> <script> $(document).on( 'keydown', function(event) { if (event.key == "Escape") { alert('Esc key pressed.'); } });</script> </html> Output before pressing escape: Output after pressing escape: Example-2: This example detects the escape key press (using keyup event handler) <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <title> escape-jquery-detection </title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script></head> <body> <h1>Escape jquery detection using keyup event handler </h1></body> <script> $(document).on('keyup', function(event) { if (event.key == "Escape") { alert('Esc key pressed.'); } });</script> </html> Output before pressing escape: Output after pressing escape: Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2019" }, { "code": null, "e": 200, "s": 28, "text": "To detect escape key press, keyup or keydown event handler will be used in jquery. It will trigger over the document when the escape key will be pressed from the keyboard." }, { "code": null, "e": 273, "s": 200, "text": "keyup event: This event is fired when key is released from the keyboard." }, { "code": null, "e": 347, "s": 273, "text": "keydown event: This event is fired when key is pressed from the keyboard." }, { "code": null, "e": 355, "s": 347, "text": "Syntax:" }, { "code": null, "e": 490, "s": 355, "text": "$(document).on('keydown', function(event) {\n if (event.key == \"Escape\") {\n alert('Esc key pressed.');\n }\n });\n" }, { "code": null, "e": 781, "s": 490, "text": "Explanation:Over whole document we are calling the on method and we are passing the keydown or keyup event as first parameter. As second parameter a function is attached which invokes when keydown or keyup event occurs and it will show an alert on pressing the escape key from the keyboard." }, { "code": null, "e": 863, "s": 781, "text": "Example-1: This example detects the escape key press(using keydown event handler)" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title> escape-jquery-detection </title> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script></head> <body> <h1> Escape jquery detection using keydown event handler </h1></body> <script> $(document).on( 'keydown', function(event) { if (event.key == \"Escape\") { alert('Esc key pressed.'); } });</script> </html>", "e": 1322, "s": 863, "text": null }, { "code": null, "e": 1353, "s": 1322, "text": "Output before pressing escape:" }, { "code": null, "e": 1383, "s": 1353, "text": "Output after pressing escape:" }, { "code": null, "e": 1464, "s": 1383, "text": "Example-2: This example detects the escape key press (using keyup event handler)" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <title> escape-jquery-detection </title> <script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"> </script></head> <body> <h1>Escape jquery detection using keyup event handler </h1></body> <script> $(document).on('keyup', function(event) { if (event.key == \"Escape\") { alert('Esc key pressed.'); } });</script> </html>", "e": 1902, "s": 1464, "text": null }, { "code": null, "e": 1933, "s": 1902, "text": "Output before pressing escape:" }, { "code": null, "e": 1963, "s": 1933, "text": "Output after pressing escape:" }, { "code": null, "e": 1970, "s": 1963, "text": "Picked" }, { "code": null, "e": 1977, "s": 1970, "text": "JQuery" }, { "code": null, "e": 1994, "s": 1977, "text": "Web Technologies" } ]
Difference between queue.queue vs collections.deque in Python
22 Oct, 2020 Both queue.queue and collections.deque commands give an idea about queues in general to the reader but, both have a very different application hence shouldn’t be confused as one. Although they are different and used for very different purposes they are in a way linked to each other in terms of complete functionality. Before we jump into what they actually do and how they are linked to each other, there is one concept that has to be revisited, the basics of processing in computer software. We know, that any program becomes a process in active state and each process can be broken down to threads to reap the benefits of the advantage this possesses. We also know, that two threads may have to communicate with each other and this is where queue.queue comes into the picture. Collections.deque on the other hand is used as a data structure within a thread to perform certain functionality. The link between them is that queue.queue uses collections.deque internally. Both deal with thread-safe operations. Queue.Queue: This class as stated above is used to facilitate communication between two threads originating from the same process. It works like a typical queue though, the only difference being the purpose it serves. It has all the functions of multirocessing.queue to do so, along with two more functions- task_done() and join(). As the name suggests, task_done() is used to inform task completion Join() is used to ask all the tasks to wait until all processes are done processing. Python3 # import modulesimport threading, queue # setting up a queue for threadsq = queue.Queue() def execute_thread(): while True: th=q.get() print(f'task {th} started') print(f'task {th} finished') q.task_done() # set up for threads to workthreading.Thread(target = execute_thread, daemon = True).start() # sending task requests for i in range(5): q.put(i)print("all tasks sent") # making threads wait until all tasks are doneq.join()print("all tasks completed") Output: all tasks sent task 0 started task 0 finished task 1 started task 1 finished task 2 started task 2 finished task 3 started task 3 finished task 4 started task 4 finished all tasks completed Collections.Deque: A general data structure, which behaves like a regular FIFO Queue. This is employed within a thread to get some functionality done. Its basic implementation is shown below: Python3 # import modulefrom collections import deque # initialisedq = deque(['first','second','third'])print(dq)deque(['first', 'second', 'third']) # adding more valuesdq.append('fourth')dq.appendleft('zeroth')print(dq)deque(['zeroth', 'first', 'second', 'third', 'fourth']) # adding value to a specified indexdq.insert(0,'fifth')print(dq)deque(['fifth', 'zeroth', 'first', 'second', 'third', 'fourth']) # removing valuesdq.pop()'fourth'print(dq)deque(['fifth', 'zeroth', 'first', 'second', 'third'])dq.remove('zeroth')print(dq)deque(['fifth', 'first', 'second', 'third']) Output: deque([‘first’, ‘second’, ‘third’])deque([‘zeroth’, ‘first’, ‘second’, ‘third’, ‘fourth’])deque([‘fifth’, ‘zeroth’, ‘first’, ‘second’, ‘third’, ‘fourth’])deque([‘fifth’, ‘zeroth’, ‘first’, ‘second’, ‘third’])deque([‘fifth’, ‘first’, ‘second’, ‘third’]) Python collections-module Difference Between Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Oct, 2020" }, { "code": null, "e": 547, "s": 52, "text": "Both queue.queue and collections.deque commands give an idea about queues in general to the reader but, both have a very different application hence shouldn’t be confused as one. Although they are different and used for very different purposes they are in a way linked to each other in terms of complete functionality. Before we jump into what they actually do and how they are linked to each other, there is one concept that has to be revisited, the basics of processing in computer software. " }, { "code": null, "e": 1063, "s": 547, "text": "We know, that any program becomes a process in active state and each process can be broken down to threads to reap the benefits of the advantage this possesses. We also know, that two threads may have to communicate with each other and this is where queue.queue comes into the picture. Collections.deque on the other hand is used as a data structure within a thread to perform certain functionality. The link between them is that queue.queue uses collections.deque internally. Both deal with thread-safe operations." }, { "code": null, "e": 1395, "s": 1063, "text": "Queue.Queue: This class as stated above is used to facilitate communication between two threads originating from the same process. It works like a typical queue though, the only difference being the purpose it serves. It has all the functions of multirocessing.queue to do so, along with two more functions- task_done() and join()." }, { "code": null, "e": 1463, "s": 1395, "text": "As the name suggests, task_done() is used to inform task completion" }, { "code": null, "e": 1548, "s": 1463, "text": "Join() is used to ask all the tasks to wait until all processes are done processing." }, { "code": null, "e": 1556, "s": 1548, "text": "Python3" }, { "code": "# import modulesimport threading, queue # setting up a queue for threadsq = queue.Queue() def execute_thread(): while True: th=q.get() print(f'task {th} started') print(f'task {th} finished') q.task_done() # set up for threads to workthreading.Thread(target = execute_thread, daemon = True).start() # sending task requests for i in range(5): q.put(i)print(\"all tasks sent\") # making threads wait until all tasks are doneq.join()print(\"all tasks completed\")", "e": 2070, "s": 1556, "text": null }, { "code": null, "e": 2078, "s": 2070, "text": "Output:" }, { "code": null, "e": 2269, "s": 2078, "text": "all tasks sent\ntask 0 started\ntask 0 finished\ntask 1 started\ntask 1 finished\ntask 2 started\ntask 2 finished\ntask 3 started\ntask 3 finished\ntask 4 started\ntask 4 finished\nall tasks completed\n" }, { "code": null, "e": 2461, "s": 2269, "text": "Collections.Deque: A general data structure, which behaves like a regular FIFO Queue. This is employed within a thread to get some functionality done. Its basic implementation is shown below:" }, { "code": null, "e": 2469, "s": 2461, "text": "Python3" }, { "code": "# import modulefrom collections import deque # initialisedq = deque(['first','second','third'])print(dq)deque(['first', 'second', 'third']) # adding more valuesdq.append('fourth')dq.appendleft('zeroth')print(dq)deque(['zeroth', 'first', 'second', 'third', 'fourth']) # adding value to a specified indexdq.insert(0,'fifth')print(dq)deque(['fifth', 'zeroth', 'first', 'second', 'third', 'fourth']) # removing valuesdq.pop()'fourth'print(dq)deque(['fifth', 'zeroth', 'first', 'second', 'third'])dq.remove('zeroth')print(dq)deque(['fifth', 'first', 'second', 'third'])", "e": 3038, "s": 2469, "text": null }, { "code": null, "e": 3046, "s": 3038, "text": "Output:" }, { "code": null, "e": 3299, "s": 3046, "text": "deque([‘first’, ‘second’, ‘third’])deque([‘zeroth’, ‘first’, ‘second’, ‘third’, ‘fourth’])deque([‘fifth’, ‘zeroth’, ‘first’, ‘second’, ‘third’, ‘fourth’])deque([‘fifth’, ‘zeroth’, ‘first’, ‘second’, ‘third’])deque([‘fifth’, ‘first’, ‘second’, ‘third’])" }, { "code": null, "e": 3325, "s": 3299, "text": "Python collections-module" }, { "code": null, "e": 3344, "s": 3325, "text": "Difference Between" }, { "code": null, "e": 3351, "s": 3344, "text": "Python" } ]
Python | Pandas Index.summary()
18 Dec, 2018 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 Index.summary() function return a summarized representation of the Index. This function is similar to what we have for the dataframes. Syntax: Index.summary(name=None) Returns : Summary Example #1: Use Index.summary() function to find the summary of the Index. # importing pandas as pdimport pandas as pd # Creating the index idx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Sephard', 'Mastiff', 'Husky']) # Print the indexidx Output : Now we will find the summary of the Index. # find the summary of the Index.idx.summary() Output : As we can see in the output, the function has returned an overall summary of the Index. Example #2: Use Index.summary() function to summarize the Index. # importing pandas as pdimport pandas as pd # Creating the index idx = pd.Index([22, 14, 8, 56, 27, 21, 51, 23]) # Print the indexidx Output : Now we will find the summary of the index. # the function returns the summary of the Indexidx.summary() Output : As we can see in the output, the function has returned the summary for the Index. Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Dec, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 384, "s": 242, "text": "Pandas Index.summary() function return a summarized representation of the Index. This function is similar to what we have for the dataframes." }, { "code": null, "e": 417, "s": 384, "text": "Syntax: Index.summary(name=None)" }, { "code": null, "e": 435, "s": 417, "text": "Returns : Summary" }, { "code": null, "e": 510, "s": 435, "text": "Example #1: Use Index.summary() function to find the summary of the Index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the index idx = pd.Index(['Beagle', 'Pug', 'Labrador', 'Sephard', 'Mastiff', 'Husky']) # Print the indexidx", "e": 690, "s": 510, "text": null }, { "code": null, "e": 699, "s": 690, "text": "Output :" }, { "code": null, "e": 742, "s": 699, "text": "Now we will find the summary of the Index." }, { "code": "# find the summary of the Index.idx.summary()", "e": 788, "s": 742, "text": null }, { "code": null, "e": 797, "s": 788, "text": "Output :" }, { "code": null, "e": 950, "s": 797, "text": "As we can see in the output, the function has returned an overall summary of the Index. Example #2: Use Index.summary() function to summarize the Index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the index idx = pd.Index([22, 14, 8, 56, 27, 21, 51, 23]) # Print the indexidx", "e": 1086, "s": 950, "text": null }, { "code": null, "e": 1095, "s": 1086, "text": "Output :" }, { "code": null, "e": 1138, "s": 1095, "text": "Now we will find the summary of the index." }, { "code": "# the function returns the summary of the Indexidx.summary()", "e": 1199, "s": 1138, "text": null }, { "code": null, "e": 1208, "s": 1199, "text": "Output :" }, { "code": null, "e": 1290, "s": 1208, "text": "As we can see in the output, the function has returned the summary for the Index." }, { "code": null, "e": 1313, "s": 1290, "text": "Python pandas-indexing" }, { "code": null, "e": 1327, "s": 1313, "text": "Python-pandas" }, { "code": null, "e": 1334, "s": 1327, "text": "Python" } ]
Seaborn Heatmap – A comprehensive guide
12 Nov, 2020 Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. In this, to represent more common values or higher activities brighter colors basically reddish colors are used and to represent less common or activity values, darker colors are preferred. Heatmap is also defined by the name of the shading matrix. Heatmaps in Seaborn can be plotted by using the seaborn.heatmap() function. Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs) Important Parameters: data: 2D dataset that can be coerced into an ndarray. vmin, vmax: Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments. cmap: The mapping from data values to color space. center: The value at which to center the colormap when plotting divergent data. annot: If True, write the data value in each cell. fmt: String formatting code to use when adding annotations. linewidths: Width of the lines that will divide each cell. linecolor: Color of the lines that will divide each cell. cbar: Whether to draw a colorbar. All the parameters except data are optional. Returns: An object of type matplotlib.axes._subplots.AxesSubplot Let us understand the heatmap with examples. Making a heatmap with the default parameters. We will be creating a 10×10 2-D data using the randint() function of the NumPy module. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low = 1, high = 100, size = (10, 10))print("The data to be plotted:\n")print(data) # plotting the heatmaphm = sn.heatmap(data = data) # displaying the plotted heatmapplt.show() Output: The data to be plotted: [[46 30 55 86 42 94 31 56 21 7] [68 42 95 28 93 13 90 27 14 65] [73 84 92 66 16 15 57 36 46 84] [ 7 11 41 37 8 41 96 53 51 72] [52 64 1 80 33 30 91 80 28 88] [19 93 64 23 72 15 39 35 62 3] [51 45 51 17 83 37 81 31 62 10] [ 9 28 30 47 73 96 10 43 30 2] [74 28 34 26 2 70 82 53 97 96] [86 13 60 51 95 26 22 29 14 29]] We’ll be using this same data in all the examples. If we set the vmin value to 30 and the vmax value to 70, then only the cells with values between 30 and 70 will be displayed. This is called anchoring the colormap. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuesvmin = 30vmax = 70 # plotting the heatmaphm = sn.heatmap(data=data, vmin=vmin, vmax=vmax) # displaying the plotted heatmapplt.show() Output: In this, we will be looking at the cmap parameter. Matplotlib provides us with multiple colormaps, you can look at all of them here. In our example, we’ll be using tab20. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuescmap = "tab20" # plotting the heatmaphm = sn.heatmap(data=data, cmap=cmap) # displaying the plotted heatmapplt.show() Output: Centering the cmap to 0 by passing the center parameter as 0. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuescmap = "tab20"center = 0 # plotting the heatmaphm = sn.heatmap(data=data, cmap=cmap, center=center) # displaying the plotted heatmapplt.show() Output: If we want to display the value of the cells, then we pass the parameter annot as True. fmt is used to select the datatype of the contents of the cells displayed. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuesannot = True # plotting the heatmaphm = sn.heatmap(data=data, annot=annot) # displaying the plotted heatmapplt.show() Output: We can change the thickness and the color of the lines separating the cells using the linewidths and linecolor parameters respectively. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valueslinewidths = 2linecolor = "yellow" # plotting the heatmaphm = sn.heatmap(data=data, linewidths=linewidths, linecolor=linecolor) # displaying the plotted heatmapplt.show() Output: We can disable the colorbar by setting the cbar parameter to False. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuescbar = False # plotting the heatmaphm = sn.heatmap(data=data, cbar=cbar) # displaying the plotted heatmapplt.show() Output: We can disable the x-label and the y-label by passing False in the xticklabels and yticklabels parameters respectively. Python3 # importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuesxticklabels = Falseyticklabels = False # plotting the heatmaphm = sn.heatmap(data=data, xticklabels=xticklabels, yticklabels=yticklabels) # displaying the plotted heatmapplt.show() Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2020" }, { "code": null, "e": 461, "s": 28, "text": "Heatmap is defined as a graphical representation of data using colors to visualize the value of the matrix. In this, to represent more common values or higher activities brighter colors basically reddish colors are used and to represent less common or activity values, darker colors are preferred. Heatmap is also defined by the name of the shading matrix. Heatmaps in Seaborn can be plotted by using the seaborn.heatmap() function." }, { "code": null, "e": 610, "s": 461, "text": "Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs)" }, { "code": null, "e": 632, "s": 610, "text": "Important Parameters:" }, { "code": null, "e": 686, "s": 632, "text": "data: 2D dataset that can be coerced into an ndarray." }, { "code": null, "e": 800, "s": 686, "text": "vmin, vmax: Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments." }, { "code": null, "e": 851, "s": 800, "text": "cmap: The mapping from data values to color space." }, { "code": null, "e": 931, "s": 851, "text": "center: The value at which to center the colormap when plotting divergent data." }, { "code": null, "e": 982, "s": 931, "text": "annot: If True, write the data value in each cell." }, { "code": null, "e": 1042, "s": 982, "text": "fmt: String formatting code to use when adding annotations." }, { "code": null, "e": 1101, "s": 1042, "text": "linewidths: Width of the lines that will divide each cell." }, { "code": null, "e": 1159, "s": 1101, "text": "linecolor: Color of the lines that will divide each cell." }, { "code": null, "e": 1193, "s": 1159, "text": "cbar: Whether to draw a colorbar." }, { "code": null, "e": 1238, "s": 1193, "text": "All the parameters except data are optional." }, { "code": null, "e": 1304, "s": 1238, "text": "Returns: An object of type matplotlib.axes._subplots.AxesSubplot " }, { "code": null, "e": 1349, "s": 1304, "text": "Let us understand the heatmap with examples." }, { "code": null, "e": 1482, "s": 1349, "text": "Making a heatmap with the default parameters. We will be creating a 10×10 2-D data using the randint() function of the NumPy module." }, { "code": null, "e": 1490, "s": 1482, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low = 1, high = 100, size = (10, 10))print(\"The data to be plotted:\\n\")print(data) # plotting the heatmaphm = sn.heatmap(data = data) # displaying the plotted heatmapplt.show()", "e": 1898, "s": 1490, "text": null }, { "code": null, "e": 1906, "s": 1898, "text": "Output:" }, { "code": null, "e": 2254, "s": 1906, "text": "The data to be plotted:\n\n[[46 30 55 86 42 94 31 56 21 7]\n[68 42 95 28 93 13 90 27 14 65]\n[73 84 92 66 16 15 57 36 46 84]\n[ 7 11 41 37 8 41 96 53 51 72]\n[52 64 1 80 33 30 91 80 28 88]\n[19 93 64 23 72 15 39 35 62 3]\n[51 45 51 17 83 37 81 31 62 10]\n[ 9 28 30 47 73 96 10 43 30 2]\n[74 28 34 26 2 70 82 53 97 96]\n[86 13 60 51 95 26 22 29 14 29]]\n" }, { "code": null, "e": 2305, "s": 2254, "text": "We’ll be using this same data in all the examples." }, { "code": null, "e": 2470, "s": 2305, "text": "If we set the vmin value to 30 and the vmax value to 70, then only the cells with values between 30 and 70 will be displayed. This is called anchoring the colormap." }, { "code": null, "e": 2478, "s": 2470, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuesvmin = 30vmax = 70 # plotting the heatmaphm = sn.heatmap(data=data, vmin=vmin, vmax=vmax) # displaying the plotted heatmapplt.show()", "e": 2935, "s": 2478, "text": null }, { "code": null, "e": 2943, "s": 2935, "text": "Output:" }, { "code": null, "e": 3114, "s": 2943, "text": "In this, we will be looking at the cmap parameter. Matplotlib provides us with multiple colormaps, you can look at all of them here. In our example, we’ll be using tab20." }, { "code": null, "e": 3122, "s": 3114, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuescmap = \"tab20\" # plotting the heatmaphm = sn.heatmap(data=data, cmap=cmap) # displaying the plotted heatmapplt.show()", "e": 3549, "s": 3122, "text": null }, { "code": null, "e": 3557, "s": 3549, "text": "Output:" }, { "code": null, "e": 3619, "s": 3557, "text": "Centering the cmap to 0 by passing the center parameter as 0." }, { "code": null, "e": 3627, "s": 3619, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuescmap = \"tab20\"center = 0 # plotting the heatmaphm = sn.heatmap(data=data, cmap=cmap, center=center) # displaying the plotted heatmapplt.show()", "e": 4094, "s": 3627, "text": null }, { "code": null, "e": 4102, "s": 4094, "text": "Output:" }, { "code": null, "e": 4266, "s": 4102, "text": "If we want to display the value of the cells, then we pass the parameter annot as True. fmt is used to select the datatype of the contents of the cells displayed. " }, { "code": null, "e": 4274, "s": 4266, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuesannot = True # plotting the heatmaphm = sn.heatmap(data=data, annot=annot) # displaying the plotted heatmapplt.show()", "e": 4701, "s": 4274, "text": null }, { "code": null, "e": 4709, "s": 4701, "text": "Output:" }, { "code": null, "e": 4845, "s": 4709, "text": "We can change the thickness and the color of the lines separating the cells using the linewidths and linecolor parameters respectively." }, { "code": null, "e": 4853, "s": 4845, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valueslinewidths = 2linecolor = \"yellow\" # plotting the heatmaphm = sn.heatmap(data=data, linewidths=linewidths, linecolor=linecolor) # displaying the plotted heatmapplt.show()", "e": 5348, "s": 4853, "text": null }, { "code": null, "e": 5356, "s": 5348, "text": "Output:" }, { "code": null, "e": 5424, "s": 5356, "text": "We can disable the colorbar by setting the cbar parameter to False." }, { "code": null, "e": 5432, "s": 5424, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuescbar = False # plotting the heatmaphm = sn.heatmap(data=data, cbar=cbar) # displaying the plotted heatmapplt.show()", "e": 5857, "s": 5432, "text": null }, { "code": null, "e": 5865, "s": 5857, "text": "Output:" }, { "code": null, "e": 5985, "s": 5865, "text": "We can disable the x-label and the y-label by passing False in the xticklabels and yticklabels parameters respectively." }, { "code": null, "e": 5993, "s": 5985, "text": "Python3" }, { "code": "# importing the modulesimport numpy as npimport seaborn as snimport matplotlib.pyplot as plt # generating 2-D 10x10 matrix of random numbers# from 1 to 100data = np.random.randint(low=1, high=100, size=(10, 10)) # setting the parameter valuesxticklabels = Falseyticklabels = False # plotting the heatmaphm = sn.heatmap(data=data, xticklabels=xticklabels, yticklabels=yticklabels) # displaying the plotted heatmapplt.show()", "e": 6498, "s": 5993, "text": null }, { "code": null, "e": 6506, "s": 6498, "text": "Output:" }, { "code": null, "e": 6521, "s": 6506, "text": "Python-Seaborn" }, { "code": null, "e": 6528, "s": 6521, "text": "Python" } ]
How to add a title to a Matplotlib legend?
24 Jan, 2021 Prerequisites: Matplotlib In this article, we will see how can we can add a title to a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph. Approach: Import required module. Create data. Add a title to a legend. Normally plot the data. Display plot. Below is the Implementation: Example 1: In this example, we will draw different lines with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title. Python3 # importing packageimport matplotlib.pyplot as pltimport numpy as np # create dataX = [1, 2, 3, 4, 5] # plot linesplt.plot(X, np.sin(X), label = "Curve-1")plt.plot(X, np.cos(X), label = "Curve-2") # Add a title to a legendplt.legend(title = "Legend Title")plt.title("Line Graph - Geeksforgeeks") plt.show() Output: Example 2: In this example, we will draw a Bar Graph with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title. Python3 # importing packageimport matplotlib.pyplot as plt # sample code plt.bar([1, 2, 3], [16, 4, 1], color ='yellow', label = 'Label 2') plt.bar([4, 5], [2, 4], label = 'Label 1') # Add a title to a legendplt.legend(title = "Variation Rate") plt.title("Line Graph - Geeksforgeeks") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 54, "s": 28, "text": "Prerequisites: Matplotlib" }, { "code": null, "e": 217, "s": 54, "text": "In this article, we will see how can we can add a title to a legend in our graph using matplotlib, Here we will take two different examples to showcase our graph." }, { "code": null, "e": 227, "s": 217, "text": "Approach:" }, { "code": null, "e": 251, "s": 227, "text": "Import required module." }, { "code": null, "e": 264, "s": 251, "text": "Create data." }, { "code": null, "e": 289, "s": 264, "text": "Add a title to a legend." }, { "code": null, "e": 313, "s": 289, "text": "Normally plot the data." }, { "code": null, "e": 327, "s": 313, "text": "Display plot." }, { "code": null, "e": 356, "s": 327, "text": "Below is the Implementation:" }, { "code": null, "e": 367, "s": 356, "text": "Example 1:" }, { "code": null, "e": 513, "s": 367, "text": "In this example, we will draw different lines with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title." }, { "code": null, "e": 521, "s": 513, "text": "Python3" }, { "code": "# importing packageimport matplotlib.pyplot as pltimport numpy as np # create dataX = [1, 2, 3, 4, 5] # plot linesplt.plot(X, np.sin(X), label = \"Curve-1\")plt.plot(X, np.cos(X), label = \"Curve-2\") # Add a title to a legendplt.legend(title = \"Legend Title\")plt.title(\"Line Graph - Geeksforgeeks\") plt.show()", "e": 832, "s": 521, "text": null }, { "code": null, "e": 840, "s": 832, "text": "Output:" }, { "code": null, "e": 851, "s": 840, "text": "Example 2:" }, { "code": null, "e": 993, "s": 851, "text": "In this example, we will draw a Bar Graph with the help of matplotlib and Use the title argument to plt.legend() to specify the legend title." }, { "code": null, "e": 1001, "s": 993, "text": "Python3" }, { "code": "# importing packageimport matplotlib.pyplot as plt # sample code plt.bar([1, 2, 3], [16, 4, 1], color ='yellow', label = 'Label 2') plt.bar([4, 5], [2, 4], label = 'Label 1') # Add a title to a legendplt.legend(title = \"Variation Rate\") plt.title(\"Line Graph - Geeksforgeeks\") plt.show()", "e": 1318, "s": 1001, "text": null }, { "code": null, "e": 1326, "s": 1318, "text": "Output:" }, { "code": null, "e": 1344, "s": 1326, "text": "Python-matplotlib" }, { "code": null, "e": 1351, "s": 1344, "text": "Python" } ]
filepath.Base() Function in Golang With Examples
10 May, 2020 In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Base() function in Go language used to return the last element of the specified path. Here the trailing path separators are removed before extracting the last element. If the path is empty, Base returns “.”. If the path consists entirely of separators, Base returns a single separator. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions. Syntax: func Base(path string) string Here, ‘path’ is the specified path. Return Value: It return the last element of the specified path. If the path is empty, this function returns “.”. If the path consists entirely of separators, this function returns a single separator. Example 1: // Golang program to illustrate the usage of// filepath.Base() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Base() function to // get the last element of path fmt.Println(filepath.Base("/home/gfg")) fmt.Println(filepath.Base(".gfg")) fmt.Println(filepath.Base("/gfg")) fmt.Println(filepath.Base(":gfg/GFG"))} Output: gfg .gfg gfg GFG Example 2: // Golang program to illustrate the usage of// filepath.Base() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( "fmt" "path/filepath") // Calling mainfunc main() { // Calling the Base() function which // returns "." if the path is empty // and returns a single separator if // the path consists entirely of separators fmt.Println(filepath.Base("")) fmt.Println(filepath.Base(".")) fmt.Println(filepath.Base("/")) fmt.Println(filepath.Base("/.")) fmt.Println(filepath.Base("//")) fmt.Println(filepath.Base(":/")) } Output: . . / . / : Golang-filepath Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? Constants- Go Language Go Variables Loops in Go Language Time Durations in Golang Structures in Golang Strings in Golang How to iterate over an Array using for loop in Golang? time.Parse() Function in Golang With Examples Class and Object in Golang
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 576, "s": 28, "text": "In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Base() function in Go language used to return the last element of the specified path. Here the trailing path separators are removed before extracting the last element. If the path is empty, Base returns “.”. If the path consists entirely of separators, Base returns a single separator. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions." }, { "code": null, "e": 584, "s": 576, "text": "Syntax:" }, { "code": null, "e": 615, "s": 584, "text": "func Base(path string) string\n" }, { "code": null, "e": 651, "s": 615, "text": "Here, ‘path’ is the specified path." }, { "code": null, "e": 851, "s": 651, "text": "Return Value: It return the last element of the specified path. If the path is empty, this function returns “.”. If the path consists entirely of separators, this function returns a single separator." }, { "code": null, "e": 862, "s": 851, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// filepath.Base() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Base() function to // get the last element of path fmt.Println(filepath.Base(\"/home/gfg\")) fmt.Println(filepath.Base(\".gfg\")) fmt.Println(filepath.Base(\"/gfg\")) fmt.Println(filepath.Base(\":gfg/GFG\"))}", "e": 1316, "s": 862, "text": null }, { "code": null, "e": 1324, "s": 1316, "text": "Output:" }, { "code": null, "e": 1342, "s": 1324, "text": "gfg\n.gfg\ngfg\nGFG\n" }, { "code": null, "e": 1353, "s": 1342, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// filepath.Base() function // Including the main packagepackage main // Importing fmt and path/filepathimport ( \"fmt\" \"path/filepath\") // Calling mainfunc main() { // Calling the Base() function which // returns \".\" if the path is empty // and returns a single separator if // the path consists entirely of separators fmt.Println(filepath.Base(\"\")) fmt.Println(filepath.Base(\".\")) fmt.Println(filepath.Base(\"/\")) fmt.Println(filepath.Base(\"/.\")) fmt.Println(filepath.Base(\"//\")) fmt.Println(filepath.Base(\":/\")) }", "e": 1958, "s": 1353, "text": null }, { "code": null, "e": 1966, "s": 1958, "text": "Output:" }, { "code": null, "e": 1979, "s": 1966, "text": ".\n.\n/\n.\n/\n:\n" }, { "code": null, "e": 1995, "s": 1979, "text": "Golang-filepath" }, { "code": null, "e": 2007, "s": 1995, "text": "Go Language" }, { "code": null, "e": 2105, "s": 2007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2134, "s": 2105, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 2157, "s": 2134, "text": "Constants- Go Language" }, { "code": null, "e": 2170, "s": 2157, "text": "Go Variables" }, { "code": null, "e": 2191, "s": 2170, "text": "Loops in Go Language" }, { "code": null, "e": 2216, "s": 2191, "text": "Time Durations in Golang" }, { "code": null, "e": 2237, "s": 2216, "text": "Structures in Golang" }, { "code": null, "e": 2255, "s": 2237, "text": "Strings in Golang" }, { "code": null, "e": 2310, "s": 2255, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 2356, "s": 2310, "text": "time.Parse() Function in Golang With Examples" } ]
How to Create a Facebook Phishing Page ?
29 Jun, 2022 Phishing is the technique to create a similar type of web page to the existing web page. Phishing is a type of attack where the intruders disguising as trustworthy agents attempt to gain your personal information such as passwords, credit card numbers, or any other information. Steps to Create Facebook Phishing Page: Open the Facebook login page in your browser. Press ctrl+U to find the source code. Copy whole source code and create a PHP file (index.php) and paste it. Now, search for string methode=”POST”, it will give you two results first for login and second for register. Next, replace the action file name as “xyz.php” in the login form. Now create a file “xyz.php” and “log.txt” and paste below code in “xyz.php”. File name: xyz.php php <?php // Set the location to redirect the pageheader ('Location: http://www.facebook.com'); // Open the text file in writing mode $file = fopen("log.txt", "a"); foreach($_POST as $variable => $value) { fwrite($file, $variable); fwrite($file, "="); fwrite($file, $value); fwrite($file, "\r\n");} fwrite($file, "\r\n");fclose($file);exit;?> Now you are done, share the page and if anyone will enter username and password then it will save into the log.txt file. pkanu8744 PHP-Misc PHP Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jun, 2022" }, { "code": null, "e": 333, "s": 54, "text": "Phishing is the technique to create a similar type of web page to the existing web page. Phishing is a type of attack where the intruders disguising as trustworthy agents attempt to gain your personal information such as passwords, credit card numbers, or any other information." }, { "code": null, "e": 374, "s": 333, "text": "Steps to Create Facebook Phishing Page: " }, { "code": null, "e": 420, "s": 374, "text": "Open the Facebook login page in your browser." }, { "code": null, "e": 458, "s": 420, "text": "Press ctrl+U to find the source code." }, { "code": null, "e": 529, "s": 458, "text": "Copy whole source code and create a PHP file (index.php) and paste it." }, { "code": null, "e": 638, "s": 529, "text": "Now, search for string methode=”POST”, it will give you two results first for login and second for register." }, { "code": null, "e": 705, "s": 638, "text": "Next, replace the action file name as “xyz.php” in the login form." }, { "code": null, "e": 784, "s": 705, "text": "Now create a file “xyz.php” and “log.txt” and paste below code in “xyz.php”. " }, { "code": null, "e": 804, "s": 784, "text": "File name: xyz.php " }, { "code": null, "e": 808, "s": 804, "text": "php" }, { "code": "<?php // Set the location to redirect the pageheader ('Location: http://www.facebook.com'); // Open the text file in writing mode $file = fopen(\"log.txt\", \"a\"); foreach($_POST as $variable => $value) { fwrite($file, $variable); fwrite($file, \"=\"); fwrite($file, $value); fwrite($file, \"\\r\\n\");} fwrite($file, \"\\r\\n\");fclose($file);exit;?>", "e": 1163, "s": 808, "text": null }, { "code": null, "e": 1284, "s": 1163, "text": "Now you are done, share the page and if anyone will enter username and password then it will save into the log.txt file." }, { "code": null, "e": 1294, "s": 1284, "text": "pkanu8744" }, { "code": null, "e": 1303, "s": 1294, "text": "PHP-Misc" }, { "code": null, "e": 1307, "s": 1303, "text": "PHP" }, { "code": null, "e": 1324, "s": 1307, "text": "Web Technologies" }, { "code": null, "e": 1351, "s": 1324, "text": "Web technologies Questions" }, { "code": null, "e": 1355, "s": 1351, "text": "PHP" }, { "code": null, "e": 1453, "s": 1355, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1503, "s": 1453, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1543, "s": 1503, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 1604, "s": 1543, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 1654, "s": 1604, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 1699, "s": 1654, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 1732, "s": 1699, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1794, "s": 1732, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1855, "s": 1794, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1905, "s": 1855, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Run Python Script using PythonShell from Node.js
19 Nov, 2021 Nowadays Node.js is the most attractive technology in the field of backend development for developers around the globe. And if someone wishes to use something like Web Scraping using python modules or run some python scripts having some machine learning algorithms, then one need to know how to integrate these two. We are going to get some data of a user through web scraping of leetcode . So, let’s get started. Now, setup the Node.js server code first. Javascript //Import express.js module and create its variable.const express=require('express');const app=express(); //Import PythonShell module.const {PythonShell} =require('python-shell'); //Router to handle the incoming request.app.get("/", (req, res, next)=>{ //Here are the option object in which arguments can be passed for the python_test.js. let options = { mode: 'text', pythonOptions: ['-u'], // get print results in real-time scriptPath: 'path/to/my/scripts', //If you are having python_test.py script in same folder, then it's optional. args: ['shubhamk314'] //An argument which can be accessed in the script using sys.argv[1] }; PythonShell.run('python_test.py', options, function (err, result){ if (err) throw err; // result is an array consisting of messages collected //during execution of script. console.log('result: ', result.toString()); res.send(result.toString()) });}); //Creates the server on default port 8000 and can be accessed through localhost:8000const port=8000;app.listen(port, ()=>console.log(`Server connected to ${port}`)); Now, Python Script. (Make sure you have installed the bs4 module and csv module.) Python3 # codeimport sysimport requestsfrom bs4 import BeautifulSoupfrom csv import writer# bs4 module for web scraping and requests for making HTTPS requests using Python.response = requests.get('https://leetcode.com / shubhamk314')soup = BeautifulSoup(response.text, 'html.parser')main_content = soup.select( '# base_content>div>div>div.col-sm-5.col-md-4>div:nth-child(3)>ul')list_items = main_content[0].select('li')items = ['Solved Question', 'Accepted Submission', 'Acceptance Rate']n = 0 # It will create csv files named progress.csv in root folder once this is script is called.with open('progress.csv', 'w') as csv_file: csv_writer = writer(csv_file) headers = ['Name', 'Score'] csv_writer.writerow(headers) while(n < 3): name = items[n] score = list_items[n].find('span').get_text().strip() csv_writer.writerow([name, score]) n = n + 1print("csv file created for leetcode") After saving both the files, run the following command from its root folder : node test.js Now, send request through localhost:8000 in the browser. If everything goes right, then the output will be : Message: csv file created for leetcode. This is the simple implementation of a how-to run python script with Node.js which can be useful in situations where you have a stack of Node.js application and you want to run a simple python script. If you want to know more about PythonShell module, then go through the given link. Link : https://github.com/extrabacon/python-shell saurabh1990aror prachisoda1234 Node.js Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2021" }, { "code": null, "e": 345, "s": 28, "text": "Nowadays Node.js is the most attractive technology in the field of backend development for developers around the globe. And if someone wishes to use something like Web Scraping using python modules or run some python scripts having some machine learning algorithms, then one need to know how to integrate these two. " }, { "code": null, "e": 443, "s": 345, "text": "We are going to get some data of a user through web scraping of leetcode . So, let’s get started." }, { "code": null, "e": 485, "s": 443, "text": "Now, setup the Node.js server code first." }, { "code": null, "e": 496, "s": 485, "text": "Javascript" }, { "code": "//Import express.js module and create its variable.const express=require('express');const app=express(); //Import PythonShell module.const {PythonShell} =require('python-shell'); //Router to handle the incoming request.app.get(\"/\", (req, res, next)=>{ //Here are the option object in which arguments can be passed for the python_test.js. let options = { mode: 'text', pythonOptions: ['-u'], // get print results in real-time scriptPath: 'path/to/my/scripts', //If you are having python_test.py script in same folder, then it's optional. args: ['shubhamk314'] //An argument which can be accessed in the script using sys.argv[1] }; PythonShell.run('python_test.py', options, function (err, result){ if (err) throw err; // result is an array consisting of messages collected //during execution of script. console.log('result: ', result.toString()); res.send(result.toString()) });}); //Creates the server on default port 8000 and can be accessed through localhost:8000const port=8000;app.listen(port, ()=>console.log(`Server connected to ${port}`));", "e": 1639, "s": 496, "text": null }, { "code": null, "e": 1721, "s": 1639, "text": "Now, Python Script. (Make sure you have installed the bs4 module and csv module.)" }, { "code": null, "e": 1729, "s": 1721, "text": "Python3" }, { "code": "# codeimport sysimport requestsfrom bs4 import BeautifulSoupfrom csv import writer# bs4 module for web scraping and requests for making HTTPS requests using Python.response = requests.get('https://leetcode.com / shubhamk314')soup = BeautifulSoup(response.text, 'html.parser')main_content = soup.select( '# base_content>div>div>div.col-sm-5.col-md-4>div:nth-child(3)>ul')list_items = main_content[0].select('li')items = ['Solved Question', 'Accepted Submission', 'Acceptance Rate']n = 0 # It will create csv files named progress.csv in root folder once this is script is called.with open('progress.csv', 'w') as csv_file: csv_writer = writer(csv_file) headers = ['Name', 'Score'] csv_writer.writerow(headers) while(n < 3): name = items[n] score = list_items[n].find('span').get_text().strip() csv_writer.writerow([name, score]) n = n + 1print(\"csv file created for leetcode\")", "e": 2623, "s": 1729, "text": null }, { "code": null, "e": 2702, "s": 2623, "text": "After saving both the files, run the following command from its root folder : " }, { "code": null, "e": 2715, "s": 2702, "text": "node test.js" }, { "code": null, "e": 2772, "s": 2715, "text": "Now, send request through localhost:8000 in the browser." }, { "code": null, "e": 2824, "s": 2772, "text": "If everything goes right, then the output will be :" }, { "code": null, "e": 2864, "s": 2824, "text": "Message: csv file created for leetcode." }, { "code": null, "e": 3148, "s": 2864, "text": "This is the simple implementation of a how-to run python script with Node.js which can be useful in situations where you have a stack of Node.js application and you want to run a simple python script. If you want to know more about PythonShell module, then go through the given link." }, { "code": null, "e": 3199, "s": 3148, "text": "Link : https://github.com/extrabacon/python-shell" }, { "code": null, "e": 3215, "s": 3199, "text": "saurabh1990aror" }, { "code": null, "e": 3230, "s": 3215, "text": "prachisoda1234" }, { "code": null, "e": 3238, "s": 3230, "text": "Node.js" }, { "code": null, "e": 3245, "s": 3238, "text": "Python" }, { "code": null, "e": 3262, "s": 3245, "text": "Web Technologies" } ]
Get a List of all the Attached Packages in R Programming – search() Function
12 Jun, 2020 search() function in R Language is used to get the list of all the attached packages in the R search path. Syntax: search() Parameters:This function takes no parameters. Example 1: # R program to list the packages# attached to R search path # Calling search() functionsearch() Output: [1] ".GlobalEnv" "package:stats" "package:graphics" [4] "package:grDevices" "package:utils" "package:datasets" [7] "package:methods" "Autoloads" "package:base" Example 2: # R program to list the packages# attached to R search path # Attaching datasets to pathattach(airquality)attach(BOD) # Calling search() functionsearch() Output: [1] ".GlobalEnv" "BOD" "airquality" [4] "package:stats" "package:graphics" "package:grDevices" [7] "package:utils" "package:datasets" "package:methods" [10] "Autoloads" "package:base" R-Functions R-Packages R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2020" }, { "code": null, "e": 135, "s": 28, "text": "search() function in R Language is used to get the list of all the attached packages in the R search path." }, { "code": null, "e": 152, "s": 135, "text": "Syntax: search()" }, { "code": null, "e": 198, "s": 152, "text": "Parameters:This function takes no parameters." }, { "code": null, "e": 209, "s": 198, "text": "Example 1:" }, { "code": "# R program to list the packages# attached to R search path # Calling search() functionsearch()", "e": 306, "s": 209, "text": null }, { "code": null, "e": 314, "s": 306, "text": "Output:" }, { "code": null, "e": 507, "s": 314, "text": "[1] \".GlobalEnv\" \"package:stats\" \"package:graphics\" \n[4] \"package:grDevices\" \"package:utils\" \"package:datasets\" \n[7] \"package:methods\" \"Autoloads\" \"package:base\" \n" }, { "code": null, "e": 518, "s": 507, "text": "Example 2:" }, { "code": "# R program to list the packages# attached to R search path # Attaching datasets to pathattach(airquality)attach(BOD) # Calling search() functionsearch()", "e": 674, "s": 518, "text": null }, { "code": null, "e": 682, "s": 674, "text": "Output:" }, { "code": null, "e": 923, "s": 682, "text": " [1] \".GlobalEnv\" \"BOD\" \"airquality\" \n [4] \"package:stats\" \"package:graphics\" \"package:grDevices\"\n [7] \"package:utils\" \"package:datasets\" \"package:methods\" \n[10] \"Autoloads\" \"package:base\" \n" }, { "code": null, "e": 935, "s": 923, "text": "R-Functions" }, { "code": null, "e": 946, "s": 935, "text": "R-Packages" }, { "code": null, "e": 957, "s": 946, "text": "R Language" } ]
Python | os.path.isdir() method
26 Aug, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation. os.path.isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True. Syntax: os.path.isdir(path) Parameter:path: A path-like object representing a file system path. Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing directory, otherwise returns False. Code #1: Use of os.path.isdir() method # Python program to explain os.path.isdir() method # importing os.path module import os.path # Pathpath = '/home/User/Documents/file.txt' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) # Pathpath = '/home/User/Documents/' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) False True Code #2: If the specified path is a symbolic link # Python program to explain os.path.isdir() method # importing os.path module import os.path # Create a directory# (in current working directory)dirname = "GeeksForGeeks"os.mkdir(dirname) # Create a symbolic link# pointing to above directorysymlink_path = "/home/User/Desktop/gfg"os.symlink(dirname, symlink_path) path = dirname # Now, Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) path = symlink_path # Check whether the # specified path (which is a# symbolic link ) is an# existing directory or notisdir = os.path.isdir(path)print(isdir) True True Reference: https://docs.python.org/3/library/os.path.html Python OS-path-module python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Aug, 2019" }, { "code": null, "e": 339, "s": 28, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation." }, { "code": null, "e": 594, "s": 339, "text": "os.path.isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows symbolic link, that means if the specified path is a symbolic link pointing to a directory then the method will return True." }, { "code": null, "e": 622, "s": 594, "text": "Syntax: os.path.isdir(path)" }, { "code": null, "e": 690, "s": 622, "text": "Parameter:path: A path-like object representing a file system path." }, { "code": null, "e": 848, "s": 690, "text": "Return Type: This method returns a Boolean value of class bool. This method returns True if specified path is an existing directory, otherwise returns False." }, { "code": null, "e": 887, "s": 848, "text": "Code #1: Use of os.path.isdir() method" }, { "code": "# Python program to explain os.path.isdir() method # importing os.path module import os.path # Pathpath = '/home/User/Documents/file.txt' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) # Pathpath = '/home/User/Documents/' # Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir)", "e": 1290, "s": 887, "text": null }, { "code": null, "e": 1302, "s": 1290, "text": "False\nTrue\n" }, { "code": null, "e": 1352, "s": 1302, "text": "Code #2: If the specified path is a symbolic link" }, { "code": "# Python program to explain os.path.isdir() method # importing os.path module import os.path # Create a directory# (in current working directory)dirname = \"GeeksForGeeks\"os.mkdir(dirname) # Create a symbolic link# pointing to above directorysymlink_path = \"/home/User/Desktop/gfg\"os.symlink(dirname, symlink_path) path = dirname # Now, Check whether the # specified path is an# existing directory or notisdir = os.path.isdir(path)print(isdir) path = symlink_path # Check whether the # specified path (which is a# symbolic link ) is an# existing directory or notisdir = os.path.isdir(path)print(isdir)", "e": 1967, "s": 1352, "text": null }, { "code": null, "e": 1978, "s": 1967, "text": "True\nTrue\n" }, { "code": null, "e": 2036, "s": 1978, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 2058, "s": 2036, "text": "Python OS-path-module" }, { "code": null, "e": 2075, "s": 2058, "text": "python-os-module" }, { "code": null, "e": 2082, "s": 2075, "text": "Python" } ]
Create a Hover effect in Vue.js
22 Feb, 2021 Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries. To create the hover effect to get more information upon hovering, we have to bind the ‘title’ attribute and assign a proper title that we want to show upon hovering in the vue element. If it makes no sense let’s jump into the example to get a more clear view. Example: Filename: index.html HTML <!DOCTYPE html><html lang="en"> <head> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"> </script></head> <body> <div id='parent'> <h3> Different Frameworks and Libraries in JavaScript </h3> <button v-bind:title='reactMsg'>React</button> <button v-bind:title='vueMsg'>Vue</button> <button v-bind:title='angularMsg'>Angular</button> <script src='app.js'></script> </div></body></html> Filename: app.js Javascript const parent = new Vue({ el : '#parent', data : { // Data that interpolate in DOM reactMsg: "React with Redux works awesome", vueMsg: "Vue is a progressive framework for building user interfaces", angularMsg: "Angular is awesome for single page application development" }}) Output: Vue.JS JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2021" }, { "code": null, "e": 341, "s": 28, "text": "Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries." }, { "code": null, "e": 601, "s": 341, "text": "To create the hover effect to get more information upon hovering, we have to bind the ‘title’ attribute and assign a proper title that we want to show upon hovering in the vue element. If it makes no sense let’s jump into the example to get a more clear view." }, { "code": null, "e": 610, "s": 601, "text": "Example:" }, { "code": null, "e": 631, "s": 610, "text": "Filename: index.html" }, { "code": null, "e": 636, "s": 631, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <script src=\"https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js\"> </script></head> <body> <div id='parent'> <h3> Different Frameworks and Libraries in JavaScript </h3> <button v-bind:title='reactMsg'>React</button> <button v-bind:title='vueMsg'>Vue</button> <button v-bind:title='angularMsg'>Angular</button> <script src='app.js'></script> </div></body></html>", "e": 1111, "s": 636, "text": null }, { "code": null, "e": 1128, "s": 1111, "text": "Filename: app.js" }, { "code": null, "e": 1139, "s": 1128, "text": "Javascript" }, { "code": "const parent = new Vue({ el : '#parent', data : { // Data that interpolate in DOM reactMsg: \"React with Redux works awesome\", vueMsg: \"Vue is a progressive framework for building user interfaces\", angularMsg: \"Angular is awesome for single page application development\" }})", "e": 1489, "s": 1139, "text": null }, { "code": null, "e": 1497, "s": 1489, "text": "Output:" }, { "code": null, "e": 1504, "s": 1497, "text": "Vue.JS" }, { "code": null, "e": 1515, "s": 1504, "text": "JavaScript" }, { "code": null, "e": 1532, "s": 1515, "text": "Web Technologies" } ]
Flutter - Designing Email Authentication System using Firebase - GeeksforGeeks
08 Dec, 2020 Flutter is an amazing tool for developing cross-platform applications using a single code base. While Flutter is useful, it gets even better when you add Firebase. In this article we’ll discuss, how to implement the Email/Password Authentication process in Flutter, using Firebase. In this article we’ll cover the following flutter development aspects: Improved widget tree. TextFormField Validation logic. Toggle password text visibility. Handling Authentication errors in UI. Custom submit button with loading state. UI logic and Firebase authentication logic, separated. Note: Configure Firebase in your Flutter application, before diving into Firebase Authentication. Check this link for the initial firebase setup with flutter. Now, Let’s look into the implementation. Before any Firebase services can be used, you must first install the firebase_core plugin, which is responsible for connecting your application to Firebase. Add the plugin to your pubspec.yaml file. Also, add few supporting plugins which is used to deal with the authentication flow. project/lib/pubspec.yaml dependencies: flutter: sdk: flutter firebase_core: "0.5.2" firebase_auth: "^0.18.3" provider: ^4.3.2+2 cloud_firestore: ^0.14.3 font_awesome_flutter: ^8.10.0 Install the plugin by running the following command from the project root: $ flutter pub get To initialize Firebase, call the .initializeApp() method on the Firebase class, as described in the below code. This method is asynchronous and returns a Future, so we need to ensure it has completed before displaying our main application. Updating the main( ) method of main.dart project/lib/main.dart Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } /libservices/authentication_service.dart Create a new folder as services, and inside it a new dart file as authentication_service.dart, it will contain all the authentication logic, which in case help us to separate the UI logic. authentication_service.dart Dart import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter_auth_example/models/user_model.dart'; class AuthenticationService { final FirebaseAuth _firebaseAuth; UserModel userModel = UserModel(); final userRef = Firestore.instance.collection("users"); AuthenticationService(this._firebaseAuth); // managing the user state via stream. // stream provides an immediate event of // the user's current authentication state, // and then provides subsequent events whenever // the authentication state changes. Stream<User> get authStateChanges => _firebaseAuth.authStateChanges(); //1 Future<String> signIn({String email, String password}) async { try { await _firebaseAuth.signInWithEmailAndPassword( email: email, password: password); return "Signed In"; } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { return "No user found for that email."; } else if (e.code == 'wrong-password') { return "Wrong password provided for that user."; } else { return "Something Went Wrong."; } } } //2 Future<String> signUp({String email, String password}) async { try { await _firebaseAuth.createUserWithEmailAndPassword( email: email, password: password); return "Signed Up"; } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { return "The password provided is too weak."; } else if (e.code == 'email-already-in-use') { return "The account already exists for that email."; } else { return "Something Went Wrong."; } } catch (e) { print(e); } } //3 Future<void> addUserToDB( {String uid, String username, String email, DateTime timestamp}) async { userModel = UserModel( uid: uid, username: username, email: email, timestamp: timestamp); await userRef.document(uid).setData(userModel.toMap(userModel)); } //4 Future<UserModel> getUserFromDB({String uid}) async { final DocumentSnapshot doc = await userRef.document(uid).get(); //print(doc.data()); return UserModel.fromMap(doc.data()); } //5 Future<void> signOut() async { await _firebaseAuth.signOut(); }} /libmodels/user_model.dart Dart import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_auth/firebase_auth.dart'; class UserModel { String email; String uid; String username; DateTime timestamp; UserModel({this.email, this.uid, this.username, this.timestamp}); Map toMap(UserModel user) { var data = Map<String, dynamic>(); data["uid"] = user.uid; data["username"] = user.username; data["email"] = user.email; data["timestamp"] = user.timestamp; return data; } UserModel.fromMap(Map<String, dynamic> mapData) { this.uid = mapData["uid"]; this.username = mapData["username"]; this.email = mapData["email"]; }} The user_model.dart is just a Plain Old Dart Object Strategy, which is used to convert the user model into a Map and also to retrieve it as a Map like it’s a JSON object basically. Below are the methods used in the authentication_service.dart file: This method accepts email and password as a parameter. Email and Password are used to Sign-In the user. It returns an appropriate message when the user “Signed In“. It returns an appropriate message when FirebaseAuthException catches an error. This method accepts email and password as a parameter. Email and Password are used to Register the user. It returns an appropriate message when the user “Signed Up” . It returns an appropriate message when FirebaseAuthException catches an error. This method accepts user uid, username, email, and the current timestamp( DateTime.now( ) ) of the user as a parameter. Creating a new document of the current user in the Cloud Firestore Database. (Do enable cloud firestore from your firebase project console). The document name should be the uid of the user. This method can only be triggered, when the current user is a new user, i.e the user registered in our application at the initial point. This method accepts the current user uid as a parameter. It will help us to get the current user, stored data from the cloud firestore database. This method is simply used to signing out the user from the application. Registering the AuthenticationService methods as Provider, in our main.dart file. Project/lib/main.dart Dart import 'package:firebase_auth/firebase_auth.dart';import 'package:firebase_core/firebase_core.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/pages/auth_screen_view.dart';import 'package:flutter_auth_example/pages/home_page.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MultiProvider( providers: [ Provider<AuthenticationService>( create: (_) => AuthenticationService(FirebaseAuth.instance), ), StreamProvider( create: (context) => context.read<AuthenticationService>().authStateChanges), ], child: MaterialApp( theme: ThemeData( brightness: Brightness.dark, primaryColor: Colors.green[400], accentColor: Colors.deepOrange[200]), home: AuthenticationWrapper(), ), ); }} class AuthenticationWrapper extends StatelessWidget { @override Widget build(BuildContext context) { final firebaseUser = context.watch<User>(); if (firebaseUser != null) { //If the user is successfully Logged-In. return HomePage(); } else { //If the user is not Logged-In. return AuthScreenView(); } }} The AuthenticationWrapper class of main.dart, checks the state of the user. If the user is not Logged-In it will display the AuthScreenView( ), If the user is Logged-In it will display the HomePage( ). /lib/pages/auth_screen_view.dart AuthScreenView is just a pageview, which deals with switching between the LoginPage() and RegisterPage() . auth_screen_view.dart Dart import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/pages/login_page.dart';import 'package:flutter_auth_example/pages/register_page.dart';import 'package:font_awesome_flutter/font_awesome_flutter.dart'; class AuthScreenView extends StatefulWidget { @override _AuthScreenViewState createState() => _AuthScreenViewState();} class _AuthScreenViewState extends State<AuthScreenView> { PageController pageController; int pageIndex = 0; @override void initState() { // TODO: implement initState super.initState(); pageController = PageController(); } @override void dispose() { // TODO: implement dispose super.dispose(); pageController.dispose(); } onPageChanged(int pageIndex) { setState(() { this.pageIndex = pageIndex; }); } onTap(int pageIndex) { //pageController.jumpToPage(pageIndex); pageController.animateToPage(pageIndex, duration: Duration(milliseconds: 300), curve: Curves.easeInOut); } @override Widget build(BuildContext context) { return Scaffold( body: PageView( children: [ //when pageIndex == 0 LoginPage(), //when pageIndex == 1 RegisterPage() ], controller: pageController, onPageChanged: onPageChanged, ), bottomNavigationBar: CupertinoTabBar( currentIndex: pageIndex, onTap: onTap, activeColor: Theme.of(context).primaryColor, items: [ BottomNavigationBarItem( title: Text("Log-In"), icon: Icon( FontAwesomeIcons.signInAlt, )), BottomNavigationBarItem( title: Text("Register"), icon: Icon( FontAwesomeIcons.userPlus, )), ], ), ); }} /lib/pages/register_page.dart Dart import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; class RegisterPage extends StatefulWidget { @override _RegisterPageState createState() => _RegisterPageState();} class _RegisterPageState extends State<RegisterPage> { //To Toggle Password Text Visibility. bool _obscureText = true; String _username, _email, _password; //For the loading state. bool _isSubmitting; final _formKey = GlobalKey<FormState>(); final _scaffoldKey = GlobalKey<ScaffoldState>(); FirebaseAuth auth = FirebaseAuth.instance; final DateTime timestamp = DateTime.now(); @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar(title: Text("GeeksForGeeks"), centerTitle: true), body: Container( padding: EdgeInsets.symmetric(horizontal: 20), child: Center( child: SingleChildScrollView( child: Form( key: _formKey, child: Column( children: [ _showTitle(), _showUsernameInput(), _showEmailInput(), _showPasswordInput(), _showFormActions() ], ), ), ), ), ), ); } //1 _showTitle() { return Text( "Register", style: TextStyle(fontSize: 72, fontWeight: FontWeight.bold), ); } //2 _showUsernameInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _username = val, validator: (val) => val.length < 6 ? "Username is too short." : null, decoration: InputDecoration( border: OutlineInputBorder(), labelText: "Username", hintText: "Enter Valid Username", icon: Icon( Icons.face, color: Colors.grey, )), ), ); } //3 _showEmailInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _email = val, validator: (val) => !val.contains("@") ? "Invalid Email" : null, decoration: InputDecoration( border: OutlineInputBorder(), labelText: "Email", hintText: "Enter Valid Email", icon: Icon( Icons.mail, color: Colors.grey, )), ), ); } //4 _showPasswordInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _password = val, validator: (val) => val.length < 6 ? "Password Is Too Short" : null, obscureText: _obscureText, decoration: InputDecoration( suffixIcon: GestureDetector( onTap: () { setState(() { _obscureText = !_obscureText; }); }, child: Icon(_obscureText ? Icons.visibility_off : Icons.visibility), ), border: OutlineInputBorder(), labelText: "Password", hintText: "Enter Valid Password", icon: Icon( Icons.lock, color: Colors.grey, )), ), ); } //5 _showFormActions() { return Padding( padding: EdgeInsets.only(top: 20), child: Column( children: [ _isSubmitting == true ? CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Theme.of(context).primaryColor), ) : RaisedButton( child: Text( "Submit", style: TextStyle(color: Colors.black, fontSize: 18), ), elevation: 8.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), color: Colors.orange, onPressed: _submit), ], ), ); } //6 _submit() { final _form = _formKey.currentState; if (_form.validate()) { _form.save(); //print("Email $_email, Password $_password, Username $_username"); _registerUser(); } else { print("Form is Invalid"); } } //7 _registerUser() async { setState(() { _isSubmitting = true; }); final logMessage = await context .read<AuthenticationService>() .signUp(email: _email, password: _password); logMessage == "Signed Up" ? _showSuccessSnack(logMessage) : _showErrorSnack(logMessage); print(logMessage); if (logMessage == "Signed Up") { createUserInFirestore(); } else { setState(() { _isSubmitting = false; }); } } //When User "Signed Up", success snack will display. _showSuccessSnack(String message) { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( "$message", style: TextStyle(color: Colors.green), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); _formKey.currentState.reset(); } //When FirebaseAuth Catches error, error snack will display. _showErrorSnack(String message) { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( "$message", style: TextStyle(color: Colors.red), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); } createUserInFirestore() async { context.read<AuthenticationService>().addUserToDB( uid: auth.currentUser.uid, username: _username, email: auth.currentUser.email, timestamp: timestamp); }} Output: Registration Page Authentication Logic Workflow. The LoginPage is exactly similar to the RegisterPage, the only difference is, the LoginPage is having only two TextFormField (For email and password) and while submitting it triggers signIn() method of authentication_service.dart /lib /pages/login_page.dart Dart import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState();} class _LoginPageState extends State<LoginPage> { bool _obscureText = true; String _email, _password; bool _isSubmitting; final _formKey = GlobalKey<FormState>(); final _scaffoldKey = GlobalKey<ScaffoldState>(); FirebaseAuth auth = FirebaseAuth.instance; final DateTime timestamp = DateTime.now(); @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar( centerTitle: true, title: Text("GeeksForGeeks"), ), body: Container( padding: EdgeInsets.symmetric(horizontal: 20), child: Center( child: SingleChildScrollView( child: Form( key: _formKey, child: Column( children: [ _showTitle(), _showEmailInput(), _showPasswordInput(), _showFormActions() ], ), ), ), ), ), ); } _showTitle() { return Text( "Login", style: TextStyle(fontSize: 72, fontWeight: FontWeight.bold), ); } _showEmailInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _email = val, validator: (val) => !val.contains("@") ? "Invalid Email" : null, decoration: InputDecoration( border: OutlineInputBorder(), labelText: "Email", hintText: "Enter Valid Email", icon: Icon( Icons.mail, color: Colors.grey, )), ), ); } _showPasswordInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _password = val, validator: (val) => val.length < 6 ? "Password Is Too Short" : null, obscureText: _obscureText, decoration: InputDecoration( suffixIcon: GestureDetector( onTap: () { setState(() { _obscureText = !_obscureText; }); }, child: Icon(_obscureText ? Icons.visibility_off : Icons.visibility), ), border: OutlineInputBorder(), labelText: "Password", hintText: "Enter Valid Password", icon: Icon( Icons.lock, color: Colors.grey, )), ), ); } _showFormActions() { return Padding( padding: EdgeInsets.only(top: 20), child: Column( children: [ _isSubmitting == true ? CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Theme.of(context).primaryColor), ) : RaisedButton( child: Text( "Submit", style: TextStyle(color: Colors.black, fontSize: 18), ), elevation: 8.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), color: Colors.orange, onPressed: _submit), ], ), ); } _submit() { final _form = _formKey.currentState; if (_form.validate()) { _form.save(); //print("Email $_email, Password $_password"); _LoginUser(); } else { print("Form is Invalid"); } } _LoginUser() async { setState(() { _isSubmitting = true; }); final logMessage = await context .read<AuthenticationService>() .signIn(email: _email, password: _password); logMessage == "Signed In" ? _showSuccessSnack(logMessage) : _showErrorSnack(logMessage); //print("I am logMessage $logMessage"); if (logMessage == "Signed In") { return; } else { setState(() { _isSubmitting = false; }); } } _showSuccessSnack(String message) async { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( "$message", style: TextStyle(color: Colors.green), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); _formKey.currentState.reset(); } _showErrorSnack(String message) { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( "$message", style: TextStyle(color: Colors.red), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); setState(() { _isSubmitting = false; }); }} Output: Login Page Authentication Logic Workflow. The HomePage will be displayed when the firebaseUser != null, checking from main.dart lib/pages/home_page.dart Dart import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/models/user_model.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { FirebaseAuth auth = FirebaseAuth.instance; final userRef = Firestore.instance.collection("users"); UserModel _currentUser; String _uid; String _username; String _email; @override void initState() { // TODO: implement initState super.initState(); getCurrentUser(); } getCurrentUser() async { UserModel currentUser = await context .read<AuthenticationService>() .getUserFromDB(uid: auth.currentUser.uid); _currentUser = currentUser; print("${_currentUser.username}"); setState(() { _uid = _currentUser.uid; _username = _currentUser.username; _email = _currentUser.email; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("HomePage"), centerTitle: true, ), body: _currentUser == null ? Center(child: CircularProgressIndicator()) : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "uid is ${_uid} , email is ${_email}, name is ${_username}", textAlign: TextAlign.center, ), Center( child: RaisedButton( child: Text( "Logout", style: TextStyle(color: Colors.black, fontSize: 18), ), elevation: 8.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), color: Colors.orange, onPressed: () { context.read<AuthenticationService>().signOut(); }, ), ), ], ), ); }} Output: Home Page android Firebase Technical Scripter 2020 Dart Flutter Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Flutter - Flexible Widget ListView Class in Flutter Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Format Dates in Flutter
[ { "code": null, "e": 23645, "s": 23617, "text": "\n08 Dec, 2020" }, { "code": null, "e": 23928, "s": 23645, "text": "Flutter is an amazing tool for developing cross-platform applications using a single code base. While Flutter is useful, it gets even better when you add Firebase. In this article we’ll discuss, how to implement the Email/Password Authentication process in Flutter, using Firebase." }, { "code": null, "e": 23999, "s": 23928, "text": "In this article we’ll cover the following flutter development aspects:" }, { "code": null, "e": 24021, "s": 23999, "text": "Improved widget tree." }, { "code": null, "e": 24053, "s": 24021, "text": "TextFormField Validation logic." }, { "code": null, "e": 24086, "s": 24053, "text": "Toggle password text visibility." }, { "code": null, "e": 24124, "s": 24086, "text": "Handling Authentication errors in UI." }, { "code": null, "e": 24165, "s": 24124, "text": "Custom submit button with loading state." }, { "code": null, "e": 24220, "s": 24165, "text": "UI logic and Firebase authentication logic, separated." }, { "code": null, "e": 24379, "s": 24220, "text": "Note: Configure Firebase in your Flutter application, before diving into Firebase Authentication. Check this link for the initial firebase setup with flutter." }, { "code": null, "e": 24420, "s": 24379, "text": "Now, Let’s look into the implementation." }, { "code": null, "e": 24704, "s": 24420, "text": "Before any Firebase services can be used, you must first install the firebase_core plugin, which is responsible for connecting your application to Firebase. Add the plugin to your pubspec.yaml file. Also, add few supporting plugins which is used to deal with the authentication flow." }, { "code": null, "e": 24729, "s": 24704, "text": "project/lib/pubspec.yaml" }, { "code": null, "e": 24894, "s": 24729, "text": "dependencies:\n flutter:\n sdk: flutter\n\nfirebase_core: \"0.5.2\"\nfirebase_auth: \"^0.18.3\"\nprovider: ^4.3.2+2\ncloud_firestore: ^0.14.3\nfont_awesome_flutter: ^8.10.0" }, { "code": null, "e": 24969, "s": 24894, "text": "Install the plugin by running the following command from the project root:" }, { "code": null, "e": 24987, "s": 24969, "text": "$ flutter pub get" }, { "code": null, "e": 25268, "s": 24987, "text": "To initialize Firebase, call the .initializeApp() method on the Firebase class, as described in the below code. This method is asynchronous and returns a Future, so we need to ensure it has completed before displaying our main application. Updating the main( ) method of main.dart" }, { "code": null, "e": 25290, "s": 25268, "text": "project/lib/main.dart" }, { "code": null, "e": 25418, "s": 25290, "text": "Future<void> main() async {\n WidgetsFlutterBinding.ensureInitialized();\n await Firebase.initializeApp();\n runApp(MyApp());\n}" }, { "code": null, "e": 25459, "s": 25418, "text": "/libservices/authentication_service.dart" }, { "code": null, "e": 25648, "s": 25459, "text": "Create a new folder as services, and inside it a new dart file as authentication_service.dart, it will contain all the authentication logic, which in case help us to separate the UI logic." }, { "code": null, "e": 25676, "s": 25648, "text": "authentication_service.dart" }, { "code": null, "e": 25681, "s": 25676, "text": "Dart" }, { "code": "import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter_auth_example/models/user_model.dart'; class AuthenticationService { final FirebaseAuth _firebaseAuth; UserModel userModel = UserModel(); final userRef = Firestore.instance.collection(\"users\"); AuthenticationService(this._firebaseAuth); // managing the user state via stream. // stream provides an immediate event of // the user's current authentication state, // and then provides subsequent events whenever // the authentication state changes. Stream<User> get authStateChanges => _firebaseAuth.authStateChanges(); //1 Future<String> signIn({String email, String password}) async { try { await _firebaseAuth.signInWithEmailAndPassword( email: email, password: password); return \"Signed In\"; } on FirebaseAuthException catch (e) { if (e.code == 'user-not-found') { return \"No user found for that email.\"; } else if (e.code == 'wrong-password') { return \"Wrong password provided for that user.\"; } else { return \"Something Went Wrong.\"; } } } //2 Future<String> signUp({String email, String password}) async { try { await _firebaseAuth.createUserWithEmailAndPassword( email: email, password: password); return \"Signed Up\"; } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { return \"The password provided is too weak.\"; } else if (e.code == 'email-already-in-use') { return \"The account already exists for that email.\"; } else { return \"Something Went Wrong.\"; } } catch (e) { print(e); } } //3 Future<void> addUserToDB( {String uid, String username, String email, DateTime timestamp}) async { userModel = UserModel( uid: uid, username: username, email: email, timestamp: timestamp); await userRef.document(uid).setData(userModel.toMap(userModel)); } //4 Future<UserModel> getUserFromDB({String uid}) async { final DocumentSnapshot doc = await userRef.document(uid).get(); //print(doc.data()); return UserModel.fromMap(doc.data()); } //5 Future<void> signOut() async { await _firebaseAuth.signOut(); }}", "e": 27959, "s": 25681, "text": null }, { "code": null, "e": 27986, "s": 27959, "text": "/libmodels/user_model.dart" }, { "code": null, "e": 27991, "s": 27986, "text": "Dart" }, { "code": "import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_auth/firebase_auth.dart'; class UserModel { String email; String uid; String username; DateTime timestamp; UserModel({this.email, this.uid, this.username, this.timestamp}); Map toMap(UserModel user) { var data = Map<String, dynamic>(); data[\"uid\"] = user.uid; data[\"username\"] = user.username; data[\"email\"] = user.email; data[\"timestamp\"] = user.timestamp; return data; } UserModel.fromMap(Map<String, dynamic> mapData) { this.uid = mapData[\"uid\"]; this.username = mapData[\"username\"]; this.email = mapData[\"email\"]; }}", "e": 28638, "s": 27991, "text": null }, { "code": null, "e": 28819, "s": 28638, "text": "The user_model.dart is just a Plain Old Dart Object Strategy, which is used to convert the user model into a Map and also to retrieve it as a Map like it’s a JSON object basically." }, { "code": null, "e": 28887, "s": 28819, "text": "Below are the methods used in the authentication_service.dart file:" }, { "code": null, "e": 28942, "s": 28887, "text": "This method accepts email and password as a parameter." }, { "code": null, "e": 28991, "s": 28942, "text": "Email and Password are used to Sign-In the user." }, { "code": null, "e": 29052, "s": 28991, "text": "It returns an appropriate message when the user “Signed In“." }, { "code": null, "e": 29131, "s": 29052, "text": "It returns an appropriate message when FirebaseAuthException catches an error." }, { "code": null, "e": 29186, "s": 29131, "text": "This method accepts email and password as a parameter." }, { "code": null, "e": 29236, "s": 29186, "text": "Email and Password are used to Register the user." }, { "code": null, "e": 29298, "s": 29236, "text": "It returns an appropriate message when the user “Signed Up” ." }, { "code": null, "e": 29377, "s": 29298, "text": "It returns an appropriate message when FirebaseAuthException catches an error." }, { "code": null, "e": 29497, "s": 29377, "text": "This method accepts user uid, username, email, and the current timestamp( DateTime.now( ) ) of the user as a parameter." }, { "code": null, "e": 29687, "s": 29497, "text": "Creating a new document of the current user in the Cloud Firestore Database. (Do enable cloud firestore from your firebase project console). The document name should be the uid of the user." }, { "code": null, "e": 29824, "s": 29687, "text": "This method can only be triggered, when the current user is a new user, i.e the user registered in our application at the initial point." }, { "code": null, "e": 29881, "s": 29824, "text": "This method accepts the current user uid as a parameter." }, { "code": null, "e": 29969, "s": 29881, "text": "It will help us to get the current user, stored data from the cloud firestore database." }, { "code": null, "e": 30042, "s": 29969, "text": "This method is simply used to signing out the user from the application." }, { "code": null, "e": 30124, "s": 30042, "text": "Registering the AuthenticationService methods as Provider, in our main.dart file." }, { "code": null, "e": 30146, "s": 30124, "text": "Project/lib/main.dart" }, { "code": null, "e": 30151, "s": 30146, "text": "Dart" }, { "code": "import 'package:firebase_auth/firebase_auth.dart';import 'package:firebase_core/firebase_core.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/pages/auth_screen_view.dart';import 'package:flutter_auth_example/pages/home_page.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MultiProvider( providers: [ Provider<AuthenticationService>( create: (_) => AuthenticationService(FirebaseAuth.instance), ), StreamProvider( create: (context) => context.read<AuthenticationService>().authStateChanges), ], child: MaterialApp( theme: ThemeData( brightness: Brightness.dark, primaryColor: Colors.green[400], accentColor: Colors.deepOrange[200]), home: AuthenticationWrapper(), ), ); }} class AuthenticationWrapper extends StatelessWidget { @override Widget build(BuildContext context) { final firebaseUser = context.watch<User>(); if (firebaseUser != null) { //If the user is successfully Logged-In. return HomePage(); } else { //If the user is not Logged-In. return AuthScreenView(); } }}", "e": 31672, "s": 30151, "text": null }, { "code": null, "e": 31874, "s": 31672, "text": "The AuthenticationWrapper class of main.dart, checks the state of the user. If the user is not Logged-In it will display the AuthScreenView( ), If the user is Logged-In it will display the HomePage( )." }, { "code": null, "e": 31907, "s": 31874, "text": "/lib/pages/auth_screen_view.dart" }, { "code": null, "e": 32015, "s": 31907, "text": " AuthScreenView is just a pageview, which deals with switching between the LoginPage() and RegisterPage() ." }, { "code": null, "e": 32037, "s": 32015, "text": "auth_screen_view.dart" }, { "code": null, "e": 32042, "s": 32037, "text": "Dart" }, { "code": "import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/pages/login_page.dart';import 'package:flutter_auth_example/pages/register_page.dart';import 'package:font_awesome_flutter/font_awesome_flutter.dart'; class AuthScreenView extends StatefulWidget { @override _AuthScreenViewState createState() => _AuthScreenViewState();} class _AuthScreenViewState extends State<AuthScreenView> { PageController pageController; int pageIndex = 0; @override void initState() { // TODO: implement initState super.initState(); pageController = PageController(); } @override void dispose() { // TODO: implement dispose super.dispose(); pageController.dispose(); } onPageChanged(int pageIndex) { setState(() { this.pageIndex = pageIndex; }); } onTap(int pageIndex) { //pageController.jumpToPage(pageIndex); pageController.animateToPage(pageIndex, duration: Duration(milliseconds: 300), curve: Curves.easeInOut); } @override Widget build(BuildContext context) { return Scaffold( body: PageView( children: [ //when pageIndex == 0 LoginPage(), //when pageIndex == 1 RegisterPage() ], controller: pageController, onPageChanged: onPageChanged, ), bottomNavigationBar: CupertinoTabBar( currentIndex: pageIndex, onTap: onTap, activeColor: Theme.of(context).primaryColor, items: [ BottomNavigationBarItem( title: Text(\"Log-In\"), icon: Icon( FontAwesomeIcons.signInAlt, )), BottomNavigationBarItem( title: Text(\"Register\"), icon: Icon( FontAwesomeIcons.userPlus, )), ], ), ); }}", "e": 33912, "s": 32042, "text": null }, { "code": null, "e": 33942, "s": 33912, "text": "/lib/pages/register_page.dart" }, { "code": null, "e": 33947, "s": 33942, "text": "Dart" }, { "code": "import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; class RegisterPage extends StatefulWidget { @override _RegisterPageState createState() => _RegisterPageState();} class _RegisterPageState extends State<RegisterPage> { //To Toggle Password Text Visibility. bool _obscureText = true; String _username, _email, _password; //For the loading state. bool _isSubmitting; final _formKey = GlobalKey<FormState>(); final _scaffoldKey = GlobalKey<ScaffoldState>(); FirebaseAuth auth = FirebaseAuth.instance; final DateTime timestamp = DateTime.now(); @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar(title: Text(\"GeeksForGeeks\"), centerTitle: true), body: Container( padding: EdgeInsets.symmetric(horizontal: 20), child: Center( child: SingleChildScrollView( child: Form( key: _formKey, child: Column( children: [ _showTitle(), _showUsernameInput(), _showEmailInput(), _showPasswordInput(), _showFormActions() ], ), ), ), ), ), ); } //1 _showTitle() { return Text( \"Register\", style: TextStyle(fontSize: 72, fontWeight: FontWeight.bold), ); } //2 _showUsernameInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _username = val, validator: (val) => val.length < 6 ? \"Username is too short.\" : null, decoration: InputDecoration( border: OutlineInputBorder(), labelText: \"Username\", hintText: \"Enter Valid Username\", icon: Icon( Icons.face, color: Colors.grey, )), ), ); } //3 _showEmailInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _email = val, validator: (val) => !val.contains(\"@\") ? \"Invalid Email\" : null, decoration: InputDecoration( border: OutlineInputBorder(), labelText: \"Email\", hintText: \"Enter Valid Email\", icon: Icon( Icons.mail, color: Colors.grey, )), ), ); } //4 _showPasswordInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _password = val, validator: (val) => val.length < 6 ? \"Password Is Too Short\" : null, obscureText: _obscureText, decoration: InputDecoration( suffixIcon: GestureDetector( onTap: () { setState(() { _obscureText = !_obscureText; }); }, child: Icon(_obscureText ? Icons.visibility_off : Icons.visibility), ), border: OutlineInputBorder(), labelText: \"Password\", hintText: \"Enter Valid Password\", icon: Icon( Icons.lock, color: Colors.grey, )), ), ); } //5 _showFormActions() { return Padding( padding: EdgeInsets.only(top: 20), child: Column( children: [ _isSubmitting == true ? CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Theme.of(context).primaryColor), ) : RaisedButton( child: Text( \"Submit\", style: TextStyle(color: Colors.black, fontSize: 18), ), elevation: 8.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), color: Colors.orange, onPressed: _submit), ], ), ); } //6 _submit() { final _form = _formKey.currentState; if (_form.validate()) { _form.save(); //print(\"Email $_email, Password $_password, Username $_username\"); _registerUser(); } else { print(\"Form is Invalid\"); } } //7 _registerUser() async { setState(() { _isSubmitting = true; }); final logMessage = await context .read<AuthenticationService>() .signUp(email: _email, password: _password); logMessage == \"Signed Up\" ? _showSuccessSnack(logMessage) : _showErrorSnack(logMessage); print(logMessage); if (logMessage == \"Signed Up\") { createUserInFirestore(); } else { setState(() { _isSubmitting = false; }); } } //When User \"Signed Up\", success snack will display. _showSuccessSnack(String message) { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( \"$message\", style: TextStyle(color: Colors.green), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); _formKey.currentState.reset(); } //When FirebaseAuth Catches error, error snack will display. _showErrorSnack(String message) { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( \"$message\", style: TextStyle(color: Colors.red), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); } createUserInFirestore() async { context.read<AuthenticationService>().addUserToDB( uid: auth.currentUser.uid, username: _username, email: auth.currentUser.email, timestamp: timestamp); }}", "e": 39692, "s": 33947, "text": null }, { "code": null, "e": 39700, "s": 39692, "text": "Output:" }, { "code": null, "e": 39749, "s": 39700, "text": "Registration Page Authentication Logic Workflow." }, { "code": null, "e": 39979, "s": 39749, "text": "The LoginPage is exactly similar to the RegisterPage, the only difference is, the LoginPage is having only two TextFormField (For email and password) and while submitting it triggers signIn() method of authentication_service.dart" }, { "code": null, "e": 40007, "s": 39979, "text": "/lib /pages/login_page.dart" }, { "code": null, "e": 40012, "s": 40007, "text": "Dart" }, { "code": "import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState();} class _LoginPageState extends State<LoginPage> { bool _obscureText = true; String _email, _password; bool _isSubmitting; final _formKey = GlobalKey<FormState>(); final _scaffoldKey = GlobalKey<ScaffoldState>(); FirebaseAuth auth = FirebaseAuth.instance; final DateTime timestamp = DateTime.now(); @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar( centerTitle: true, title: Text(\"GeeksForGeeks\"), ), body: Container( padding: EdgeInsets.symmetric(horizontal: 20), child: Center( child: SingleChildScrollView( child: Form( key: _formKey, child: Column( children: [ _showTitle(), _showEmailInput(), _showPasswordInput(), _showFormActions() ], ), ), ), ), ), ); } _showTitle() { return Text( \"Login\", style: TextStyle(fontSize: 72, fontWeight: FontWeight.bold), ); } _showEmailInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _email = val, validator: (val) => !val.contains(\"@\") ? \"Invalid Email\" : null, decoration: InputDecoration( border: OutlineInputBorder(), labelText: \"Email\", hintText: \"Enter Valid Email\", icon: Icon( Icons.mail, color: Colors.grey, )), ), ); } _showPasswordInput() { return Padding( padding: EdgeInsets.only(top: 20), child: TextFormField( onSaved: (val) => _password = val, validator: (val) => val.length < 6 ? \"Password Is Too Short\" : null, obscureText: _obscureText, decoration: InputDecoration( suffixIcon: GestureDetector( onTap: () { setState(() { _obscureText = !_obscureText; }); }, child: Icon(_obscureText ? Icons.visibility_off : Icons.visibility), ), border: OutlineInputBorder(), labelText: \"Password\", hintText: \"Enter Valid Password\", icon: Icon( Icons.lock, color: Colors.grey, )), ), ); } _showFormActions() { return Padding( padding: EdgeInsets.only(top: 20), child: Column( children: [ _isSubmitting == true ? CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Theme.of(context).primaryColor), ) : RaisedButton( child: Text( \"Submit\", style: TextStyle(color: Colors.black, fontSize: 18), ), elevation: 8.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), color: Colors.orange, onPressed: _submit), ], ), ); } _submit() { final _form = _formKey.currentState; if (_form.validate()) { _form.save(); //print(\"Email $_email, Password $_password\"); _LoginUser(); } else { print(\"Form is Invalid\"); } } _LoginUser() async { setState(() { _isSubmitting = true; }); final logMessage = await context .read<AuthenticationService>() .signIn(email: _email, password: _password); logMessage == \"Signed In\" ? _showSuccessSnack(logMessage) : _showErrorSnack(logMessage); //print(\"I am logMessage $logMessage\"); if (logMessage == \"Signed In\") { return; } else { setState(() { _isSubmitting = false; }); } } _showSuccessSnack(String message) async { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( \"$message\", style: TextStyle(color: Colors.green), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); _formKey.currentState.reset(); } _showErrorSnack(String message) { final snackbar = SnackBar( backgroundColor: Colors.black, content: Text( \"$message\", style: TextStyle(color: Colors.red), ), ); _scaffoldKey.currentState.showSnackBar(snackbar); setState(() { _isSubmitting = false; }); }}", "e": 44796, "s": 40012, "text": null }, { "code": null, "e": 44804, "s": 44796, "text": "Output:" }, { "code": null, "e": 44846, "s": 44804, "text": "Login Page Authentication Logic Workflow." }, { "code": null, "e": 44932, "s": 44846, "text": "The HomePage will be displayed when the firebaseUser != null, checking from main.dart" }, { "code": null, "e": 44957, "s": 44932, "text": "lib/pages/home_page.dart" }, { "code": null, "e": 44962, "s": 44957, "text": "Dart" }, { "code": "import 'package:cloud_firestore/cloud_firestore.dart';import 'package:firebase_auth/firebase_auth.dart';import 'package:flutter/material.dart';import 'package:flutter_auth_example/models/user_model.dart';import 'package:flutter_auth_example/services/authentication_service.dart';import 'package:provider/provider.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { FirebaseAuth auth = FirebaseAuth.instance; final userRef = Firestore.instance.collection(\"users\"); UserModel _currentUser; String _uid; String _username; String _email; @override void initState() { // TODO: implement initState super.initState(); getCurrentUser(); } getCurrentUser() async { UserModel currentUser = await context .read<AuthenticationService>() .getUserFromDB(uid: auth.currentUser.uid); _currentUser = currentUser; print(\"${_currentUser.username}\"); setState(() { _uid = _currentUser.uid; _username = _currentUser.username; _email = _currentUser.email; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"HomePage\"), centerTitle: true, ), body: _currentUser == null ? Center(child: CircularProgressIndicator()) : Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( \"uid is ${_uid} , email is ${_email}, name is ${_username}\", textAlign: TextAlign.center, ), Center( child: RaisedButton( child: Text( \"Logout\", style: TextStyle(color: Colors.black, fontSize: 18), ), elevation: 8.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10))), color: Colors.orange, onPressed: () { context.read<AuthenticationService>().signOut(); }, ), ), ], ), ); }}", "e": 47222, "s": 44962, "text": null }, { "code": null, "e": 47230, "s": 47222, "text": "Output:" }, { "code": null, "e": 47240, "s": 47230, "text": "Home Page" }, { "code": null, "e": 47248, "s": 47240, "text": "android" }, { "code": null, "e": 47257, "s": 47248, "text": "Firebase" }, { "code": null, "e": 47281, "s": 47257, "text": "Technical Scripter 2020" }, { "code": null, "e": 47286, "s": 47281, "text": "Dart" }, { "code": null, "e": 47294, "s": 47286, "text": "Flutter" }, { "code": null, "e": 47313, "s": 47294, "text": "Technical Scripter" }, { "code": null, "e": 47411, "s": 47313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47420, "s": 47411, "text": "Comments" }, { "code": null, "e": 47433, "s": 47420, "text": "Old Comments" }, { "code": null, "e": 47472, "s": 47433, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 47498, "s": 47472, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 47524, "s": 47498, "text": "ListView Class in Flutter" }, { "code": null, "e": 47547, "s": 47524, "text": "Flutter - Stack Widget" }, { "code": null, "e": 47592, "s": 47547, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 47631, "s": 47592, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 47648, "s": 47631, "text": "Flutter Tutorial" }, { "code": null, "e": 47674, "s": 47648, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 47697, "s": 47674, "text": "Flutter - Stack Widget" } ]
Python | Pandas Series.cumsum() to find cumulative sum of a Series - GeeksforGeeks
31 Oct, 2018 Pandas Series.cumsum() is used to find Cumulative sum of a series. In cumulative sum, the length of returned series is same as input and every element is equal to sum of all previous elements. Syntax: Series.cumsum(axis=None, skipna=True) Parameters:axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operationskipna: Skips NaN addition for elements after the very next one if True. Result type: Series Example #1:In this example, a series is created from a Python list using Pandas .Series() method. The list also contains a Null value and the skipna parameter is kept default, that is True. # importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # making list of valuesvalues = [3, 4, np.nan, 7, 2, 0] # making series from listseries = pd.Series(values) # calling methodcumsum = series.cumsum() # displaycumsum Output: 3 7 NaN 14 16 16 dtype: float64 ExplanationCumulative sum is sum of current and all previous values. As shown in above output, the addition was done as follows 3 3+4 = 7 7+NaN = NaN 7+7 = 14 14+2 = 16 16+0 = 16 Example #2: skipna=FalseIn this example, a series is created just like in the above example. But the skipna parameter is kept False. Hence NULL values won’t be ignored and it would be added every time after it’s occurrence. # importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # making list of valuesvalues = [1, 20, 13, np.nan, 0, 1, 5, 23] # making series from listseries = pd.Series(values) # calling methodcumsum = series.cumsum(skipna = False) # displaycumsum Output: 0 1.0 1 21.0 2 34.0 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN dtype: float64 Explanation: As it can be seen in output, all the values after first occurrence of NaN are also NaN since any number + NaN is also NaN. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python
[ { "code": null, "e": 24671, "s": 24643, "text": "\n31 Oct, 2018" }, { "code": null, "e": 24864, "s": 24671, "text": "Pandas Series.cumsum() is used to find Cumulative sum of a series. In cumulative sum, the length of returned series is same as input and every element is equal to sum of all previous elements." }, { "code": null, "e": 24910, "s": 24864, "text": "Syntax: Series.cumsum(axis=None, skipna=True)" }, { "code": null, "e": 25080, "s": 24910, "text": "Parameters:axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operationskipna: Skips NaN addition for elements after the very next one if True." }, { "code": null, "e": 25100, "s": 25080, "text": "Result type: Series" }, { "code": null, "e": 25290, "s": 25100, "text": "Example #1:In this example, a series is created from a Python list using Pandas .Series() method. The list also contains a Null value and the skipna parameter is kept default, that is True." }, { "code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # making list of valuesvalues = [3, 4, np.nan, 7, 2, 0] # making series from listseries = pd.Series(values) # calling methodcumsum = series.cumsum() # displaycumsum", "e": 25548, "s": 25290, "text": null }, { "code": null, "e": 25556, "s": 25548, "text": "Output:" }, { "code": null, "e": 25588, "s": 25556, "text": "3\n7\nNaN\n14\n16\n16\ndtype: float64" }, { "code": null, "e": 25716, "s": 25588, "text": "ExplanationCumulative sum is sum of current and all previous values. As shown in above output, the addition was done as follows" }, { "code": null, "e": 25767, "s": 25716, "text": "3\n3+4 = 7\n7+NaN = NaN\n7+7 = 14\n14+2 = 16\n16+0 = 16" }, { "code": null, "e": 25992, "s": 25767, "text": " Example #2: skipna=FalseIn this example, a series is created just like in the above example. But the skipna parameter is kept False. Hence NULL values won’t be ignored and it would be added every time after it’s occurrence." }, { "code": "# importing pandas moduleimport pandas as pd # importing numpy moduleimport numpy as np # making list of valuesvalues = [1, 20, 13, np.nan, 0, 1, 5, 23] # making series from listseries = pd.Series(values) # calling methodcumsum = series.cumsum(skipna = False) # displaycumsum", "e": 26273, "s": 25992, "text": null }, { "code": null, "e": 26281, "s": 26273, "text": "Output:" }, { "code": null, "e": 26376, "s": 26281, "text": "0 1.0\n1 21.0\n2 34.0\n3 NaN\n4 NaN\n5 NaN\n6 NaN\n7 NaN\ndtype: float64" }, { "code": null, "e": 26512, "s": 26376, "text": "Explanation: As it can be seen in output, all the values after first occurrence of NaN are also NaN since any number + NaN is also NaN." }, { "code": null, "e": 26533, "s": 26512, "text": "Python pandas-series" }, { "code": null, "e": 26562, "s": 26533, "text": "Python pandas-series-methods" }, { "code": null, "e": 26576, "s": 26562, "text": "Python-pandas" }, { "code": null, "e": 26583, "s": 26576, "text": "Python" }, { "code": null, "e": 26681, "s": 26583, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26690, "s": 26681, "text": "Comments" }, { "code": null, "e": 26703, "s": 26690, "text": "Old Comments" }, { "code": null, "e": 26721, "s": 26703, "text": "Python Dictionary" }, { "code": null, "e": 26743, "s": 26721, "text": "Enumerate() in Python" }, { "code": null, "e": 26775, "s": 26743, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26817, "s": 26775, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26843, "s": 26817, "text": "Python String | replace()" }, { "code": null, "e": 26887, "s": 26843, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 26912, "s": 26887, "text": "sum() function in Python" }, { "code": null, "e": 26949, "s": 26912, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27005, "s": 26949, "text": "How to drop one or multiple columns in Pandas Dataframe" } ]
C library function - exit()
The C library function void exit(int status) terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal. Following is the declaration for exit() function. void exit(int status) status − This is the status value returned to the parent process. status − This is the status value returned to the parent process. This function does not return any value. The following example shows the usage of exit() function. #include <stdio.h> #include <stdlib.h> int main () { printf("Start of the program....\n"); printf("Exiting the program....\n"); exit(0); printf("End of the program....\n"); return(0); } Let us compile and run the above program that will produce the following result − Start of the program.... Exiting the program.... 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": 2273, "s": 2007, "text": "The C library function void exit(int status) terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal." }, { "code": null, "e": 2323, "s": 2273, "text": "Following is the declaration for exit() function." }, { "code": null, "e": 2345, "s": 2323, "text": "void exit(int status)" }, { "code": null, "e": 2411, "s": 2345, "text": "status − This is the status value returned to the parent process." }, { "code": null, "e": 2477, "s": 2411, "text": "status − This is the status value returned to the parent process." }, { "code": null, "e": 2518, "s": 2477, "text": "This function does not return any value." }, { "code": null, "e": 2576, "s": 2518, "text": "The following example shows the usage of exit() function." }, { "code": null, "e": 2784, "s": 2576, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main () {\n printf(\"Start of the program....\\n\");\n \n printf(\"Exiting the program....\\n\");\n exit(0);\n\n printf(\"End of the program....\\n\");\n\n return(0);\n}" }, { "code": null, "e": 2866, "s": 2784, "text": "Let us compile and run the above program that will produce the following result −" }, { "code": null, "e": 2916, "s": 2866, "text": "Start of the program....\nExiting the program....\n" }, { "code": null, "e": 2949, "s": 2916, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2964, "s": 2949, "text": " Nishant Malik" }, { "code": null, "e": 2999, "s": 2964, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3014, "s": 2999, "text": " Nishant Malik" }, { "code": null, "e": 3049, "s": 3014, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3063, "s": 3049, "text": " Asif Hussain" }, { "code": null, "e": 3096, "s": 3063, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3114, "s": 3096, "text": " Richa Maheshwari" }, { "code": null, "e": 3149, "s": 3114, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3168, "s": 3149, "text": " Vandana Annavaram" }, { "code": null, "e": 3201, "s": 3168, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3213, "s": 3201, "text": " Amit Diwan" }, { "code": null, "e": 3220, "s": 3213, "text": " Print" }, { "code": null, "e": 3231, "s": 3220, "text": " Add Notes" } ]
Rexx - If else statement
The next decision-making statement is the if-else statement. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. The general form of this statement in Rexx is as follows. − if (condition) then do #statement1 #statement2 end else do #statement3 #statement4 end In Rexx, the condition is an expression which evaluates to either true or false. If the condition is true, then the subsequent statements are executed. Else if the condition is evaluated to false, then the statements in the else condition are evaluated. The flow diagram of the if-else statement is as follows − From the above diagram, it can be noted that we have two code blocks. One gets executed if the condition is evaluated to true and the other if the code is evaluated to false. The following program is an example of the simple if-else expression in Rexx. /* Main program */ i = 50 if (i < 10) then do say "i is less than 10" end else do say "i is greater than 10" end The output of the above code will be − i is greater than 10 Print Add Notes Bookmark this page
[ { "code": null, "e": 2516, "s": 2339, "text": "The next decision-making statement is the if-else statement. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false." }, { "code": null, "e": 2576, "s": 2516, "text": "The general form of this statement in Rexx is as follows. −" }, { "code": null, "e": 2710, "s": 2576, "text": "if (condition) then \n do \n #statement1 \n #statement2 \n end \nelse \n do \n #statement3 \n #statement4 \n end \n" }, { "code": null, "e": 2964, "s": 2710, "text": "In Rexx, the condition is an expression which evaluates to either true or false. If the condition is true, then the subsequent statements are executed. Else if the condition is evaluated to false, then the statements in the else condition are evaluated." }, { "code": null, "e": 3022, "s": 2964, "text": "The flow diagram of the if-else statement is as follows −" }, { "code": null, "e": 3197, "s": 3022, "text": "From the above diagram, it can be noted that we have two code blocks. One gets executed if the condition is evaluated to true and the other if the code is evaluated to false." }, { "code": null, "e": 3275, "s": 3197, "text": "The following program is an example of the simple if-else expression in Rexx." }, { "code": null, "e": 3423, "s": 3275, "text": "/* Main program */ \ni = 50 \nif (i < 10) then \n do \n say \"i is less than 10\" \n end \nelse \n do \n say \"i is greater than 10\" \n end " }, { "code": null, "e": 3462, "s": 3423, "text": "The output of the above code will be −" }, { "code": null, "e": 3485, "s": 3462, "text": "i is greater than 10 \n" }, { "code": null, "e": 3492, "s": 3485, "text": " Print" }, { "code": null, "e": 3503, "s": 3492, "text": " Add Notes" } ]
Count of numbers in given range [L, R] that is perfect square and digits are in wave form - GeeksforGeeks
12 Jan, 2022 Given two integers L and R, the task is to count the integers in the range [L, R] such that they satisfy the following two properties: The number must be a perfect square of any integer. In digits of the integer must be in the wave form i.e, let d1, d2, d3, d4, d5 be the digits in the current integer, then d1 < d2 > d3 < d4... must hold true. Examples: Input: L = 1, R = 64Output: 7 Explanation:The special numbers in the range [1, 64] are 1, 4, 9, 16, 25, 36 and 49. Input: L = 80, R = 82Output: 0 Naive Approach: The simplest approach to solve the problem is to traverse in the range [L, R], and for each number in the range check for the above two conditions.Time Complexity: O(N)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach iterate over only perfect squares and check for the second condition. Follow the steps below for the approach: Initialize a variable say, count = 0, to count all the special numbers in the range [L, R]. Iterate over all the perfect squares that are less than R. Define a function, say check(N), to check whether the number N satisfies the second condition by iterating over even and odd digits. Increase the count, if the number is greater than L and function check returns true for the given number. Finally, return the count. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Utility function to check if// the digits of the current// integer forms a wave patternbool check(int N){ // Convert the number to a string string S = to_string(N); // Loop to iterate over digits for (int i = 0; i < S.size(); i++) { if (i == 0) { // Next character of // the number int next = i + 1; // Current character is // not a local minimum if (next < S.size()) { if (S[i] >= S[next]) { return false; } } } else if (i == S.size() - 1) { // Previous character of // the number int prev = i - 1; if (prev >= 0) { // Character is a // local maximum if (i & 1) { // Character is not // a local maximum if (S[i] <= S[prev]) { return false; } } else { // Character is a // local minimum if (S[i] >= S[prev]) { return false; } } } } else { int prev = i - 1; int next = i + 1; if (i & 1) { // Character is a // local maximum if ((S[i] > S[prev]) && (S[i] > S[next])) { } else { return false; } } else { // Character is a // local minimum if ((S[i] < S[prev]) && (S[i] < S[next])) { } else { return false; } } } } return true;} // Function to calculate total// integer in the given rangeint totalUniqueNumber(int L, int R){ // Base case if (R <= 0) { return 0; } // Current number int cur = 1; // Variable to store // total unique numbers int count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { int num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count;} // Driver Codeint main(){ int L = 1, R = 64; cout << totalUniqueNumber(L, R);} // Java program for the above approachimport java.util.*;public class GFG{ // Utility function to check if // the digits of the current // integer forms a wave pattern static boolean check(int N) { // Convert the number to a string String S = Integer.toString(N); // Loop to iterate over digits for (int i = 0; i < S.length(); i++) { if (i == 0) { // Next character of // the number int next = i + 1; // Current character is // not a local minimum if (next < S.length()) { if (S.charAt(i) >= S.charAt(next)) { return false; } } } else if (i == S.length() - 1) { // Previous character of // the number int prev = i - 1; if (prev >= 0) { // Character is a // local maximum if ((i & 1) == 1) { // Character is not // a local maximum if (S.charAt(i) <= S.charAt(prev)) { return false; } } else { // Character is a // local minimum if (S.charAt(i) >= S.charAt(prev)) { return false; } } } } else { int prev = i - 1; int next = i + 1; if ((i & 1) == 1) { // Character is a // local maximum if ((S.charAt(i) > S.charAt(prev)) && (S.charAt(i) > S.charAt(next))) { } else { return false; } } else { // Character is a // local minimum if ((S.charAt(i) < S.charAt(prev)) && (S.charAt(i) < S.charAt(next))) { } else { return false; } } } } return true; } // Function to calculate total // integer in the given range static int totalUniqueNumber(int L, int R) { // Base case if (R <= 0) { return 0; } // Current number int cur = 1; // Variable to store // total unique numbers int count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { int num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count; } // Driver Code public static void main(String args[]) { int L = 1, R = 64; // Function call System.out.println(totalUniqueNumber(L, R)); }}// This code is contributed by Samim Hossain Mondal. # Python program for the above approach # Utility function to check if# the digits of the current# integer forms a wave patterndef check(N): # Convert the number to a string S = str(N); # Loop to iterate over digits for i in range(len(S)): if (i == 0): # Next character of # the number next = i + 1; # Current character is # not a local minimum if (next < len(S)): if (S[i] >= S[next]): return False; elif(i == len(S) - 1): # Previous character of # the number prev = i - 1; if (prev >= 0): # Character is a # local maximum if ((i & 1) == 1): # Character is not # a local maximum if (S[i] <= S[prev]): return False; else: # Character is a # local minimum if (S[i] >= S[prev]): return False; else: prev = i - 1; next = i + 1; if ((i & 1) == 1): # Character is a # local maximum if ((S[i] > S[prev]) and (S[i] > S[next])): return True; else: return False; else: # Character is a # local minimum if ((S[i] < S[prev]) and (S[i] < S[next])): return True; else: return False; return True; # Function to calculate total# integer in the given rangedef totalUniqueNumber(L, R): # Base case if (R <= 0): return 0; # Current number cur = 1; # Variable to store # total unique numbers count = 0; # Iterating over perfect # squares while ((cur * cur) <= R): num = cur * cur; # If number is greater # than L and satisfies # required conditions if (num >= L and check(num)): count += 1; # Moving to the # next number cur += 1; # Return Answer return count; # Driver Codeif __name__ == '__main__': L = 1; R = 64; # Function call print(totalUniqueNumber(L, R)); # This code is contributed by gauravrajput1 // C# program for the above approachusing System;using System.Collections; class GFG{ // Utility function to check if // the digits of the current // integer forms a wave pattern static bool check(int N) { // Convert the number to a string string S = N.ToString(); // Loop to iterate over digits for (int i = 0; i < S.Length; i++) { if (i == 0) { // Next character of // the number int next = i + 1; // Current character is // not a local minimum if (next < S.Length) { if (S[i] >= S[next]) { return false; } } } else if (i == S.Length - 1) { // Previous character of // the number int prev = i - 1; if (prev >= 0) { // Character is a // local maximum if ((i & 1) == 1) { // Character is not // a local maximum if (S[i] <= S[prev]) { return false; } } else { // Character is a // local minimum if (S[i] >= S[prev]) { return false; } } } } else { int prev = i - 1; int next = i + 1; if ((i & 1) == 1) { // Character is a // local maximum if ((S[i] > S[prev]) && (S[i] > S[next])) { } else { return false; } } else { // Character is a // local minimum if ((S[i] < S[prev]) && (S[i] < S[next])) { } else { return false; } } } } return true; } // Function to calculate total // integer in the given range static int totalUniqueNumber(int L, int R) { // Base case if (R <= 0) { return 0; } // Current number int cur = 1; // Variable to store // total unique numbers int count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { int num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count; } // Driver Code public static void Main() { int L = 1, R = 64; // Function call Console.Write(totalUniqueNumber(L, R)); }}// This code is contributed by Samim Hossain Mondal. <script> // JavaScript code for the above approach // Utility function to check if // the digits of the current // integer forms a wave pattern function check(N) { // Convert the number to a string let S = N.toString(); // Loop to iterate over digits for (let i = 0; i < S.length; i++) { if (i == 0) { // Next character of // the number let next = i + 1; // Current character is // not a local minimum if (next < S.length) { if (S[i] >= S[next]) { return false; } } } else if (i == S.length - 1) { // Previous character of // the number let prev = i - 1; if (prev >= 0) { // Character is a // local maximum if (i & 1) { // Character is not // a local maximum if (S[i] <= S[prev]) { return false; } } else { // Character is a // local minimum if (S[i] >= S[prev]) { return false; } } } } else { let prev = i - 1; let next = i + 1; if (i & 1) { // Character is a // local maximum if ((S[i] > S[prev]) && (S[i] > S[next])) { } else { return false; } } else { // Character is a // local minimum if ((S[i] < S[prev]) && (S[i] < S[next])) { } else { return false; } } } } return true; } // Function to calculate total // integer in the given range function totalUniqueNumber(L, R) { // Base case if (R <= 0) { return 0; } // Current number let cur = 1; // Variable to store // total unique numbers let count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { let num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count; } // Driver Code let L = 1, R = 64; document.write(totalUniqueNumber(L, R)); // This code is contributed by Potta Lokesh </script> 7 Time Complexity: O(sqrt(N))Auxiliary Space: O(1) lokeshpotta20 samim2000 GauravRajput1 array-range-queries Maths number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to convert a given number to words Modular multiplicative inverse Algorithm to solve Rubik's Cube Program to multiply two matrices Count ways to reach the n'th stair Program to print prime numbers from 1 to N. Check if a number is Palindrome Singular Value Decomposition (SVD) Fizz Buzz Implementation Program for Armstrong Numbers
[ { "code": null, "e": 24637, "s": 24609, "text": "\n12 Jan, 2022" }, { "code": null, "e": 24772, "s": 24637, "text": "Given two integers L and R, the task is to count the integers in the range [L, R] such that they satisfy the following two properties:" }, { "code": null, "e": 24824, "s": 24772, "text": "The number must be a perfect square of any integer." }, { "code": null, "e": 24982, "s": 24824, "text": "In digits of the integer must be in the wave form i.e, let d1, d2, d3, d4, d5 be the digits in the current integer, then d1 < d2 > d3 < d4... must hold true." }, { "code": null, "e": 24992, "s": 24982, "text": "Examples:" }, { "code": null, "e": 25107, "s": 24992, "text": "Input: L = 1, R = 64Output: 7 Explanation:The special numbers in the range [1, 64] are 1, 4, 9, 16, 25, 36 and 49." }, { "code": null, "e": 25138, "s": 25107, "text": "Input: L = 80, R = 82Output: 0" }, { "code": null, "e": 25344, "s": 25138, "text": "Naive Approach: The simplest approach to solve the problem is to traverse in the range [L, R], and for each number in the range check for the above two conditions.Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 25506, "s": 25344, "text": "Efficient Approach: To optimize the above approach iterate over only perfect squares and check for the second condition. Follow the steps below for the approach:" }, { "code": null, "e": 25598, "s": 25506, "text": "Initialize a variable say, count = 0, to count all the special numbers in the range [L, R]." }, { "code": null, "e": 25657, "s": 25598, "text": "Iterate over all the perfect squares that are less than R." }, { "code": null, "e": 25790, "s": 25657, "text": "Define a function, say check(N), to check whether the number N satisfies the second condition by iterating over even and odd digits." }, { "code": null, "e": 25896, "s": 25790, "text": "Increase the count, if the number is greater than L and function check returns true for the given number." }, { "code": null, "e": 25923, "s": 25896, "text": "Finally, return the count." }, { "code": null, "e": 25974, "s": 25923, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 25978, "s": 25974, "text": "C++" }, { "code": null, "e": 25983, "s": 25978, "text": "Java" }, { "code": null, "e": 25991, "s": 25983, "text": "Python3" }, { "code": null, "e": 25994, "s": 25991, "text": "C#" }, { "code": null, "e": 26005, "s": 25994, "text": "Javascript" }, { "code": "// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // Utility function to check if// the digits of the current// integer forms a wave patternbool check(int N){ // Convert the number to a string string S = to_string(N); // Loop to iterate over digits for (int i = 0; i < S.size(); i++) { if (i == 0) { // Next character of // the number int next = i + 1; // Current character is // not a local minimum if (next < S.size()) { if (S[i] >= S[next]) { return false; } } } else if (i == S.size() - 1) { // Previous character of // the number int prev = i - 1; if (prev >= 0) { // Character is a // local maximum if (i & 1) { // Character is not // a local maximum if (S[i] <= S[prev]) { return false; } } else { // Character is a // local minimum if (S[i] >= S[prev]) { return false; } } } } else { int prev = i - 1; int next = i + 1; if (i & 1) { // Character is a // local maximum if ((S[i] > S[prev]) && (S[i] > S[next])) { } else { return false; } } else { // Character is a // local minimum if ((S[i] < S[prev]) && (S[i] < S[next])) { } else { return false; } } } } return true;} // Function to calculate total// integer in the given rangeint totalUniqueNumber(int L, int R){ // Base case if (R <= 0) { return 0; } // Current number int cur = 1; // Variable to store // total unique numbers int count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { int num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count;} // Driver Codeint main(){ int L = 1, R = 64; cout << totalUniqueNumber(L, R);}", "e": 28692, "s": 26005, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class GFG{ // Utility function to check if // the digits of the current // integer forms a wave pattern static boolean check(int N) { // Convert the number to a string String S = Integer.toString(N); // Loop to iterate over digits for (int i = 0; i < S.length(); i++) { if (i == 0) { // Next character of // the number int next = i + 1; // Current character is // not a local minimum if (next < S.length()) { if (S.charAt(i) >= S.charAt(next)) { return false; } } } else if (i == S.length() - 1) { // Previous character of // the number int prev = i - 1; if (prev >= 0) { // Character is a // local maximum if ((i & 1) == 1) { // Character is not // a local maximum if (S.charAt(i) <= S.charAt(prev)) { return false; } } else { // Character is a // local minimum if (S.charAt(i) >= S.charAt(prev)) { return false; } } } } else { int prev = i - 1; int next = i + 1; if ((i & 1) == 1) { // Character is a // local maximum if ((S.charAt(i) > S.charAt(prev)) && (S.charAt(i) > S.charAt(next))) { } else { return false; } } else { // Character is a // local minimum if ((S.charAt(i) < S.charAt(prev)) && (S.charAt(i) < S.charAt(next))) { } else { return false; } } } } return true; } // Function to calculate total // integer in the given range static int totalUniqueNumber(int L, int R) { // Base case if (R <= 0) { return 0; } // Current number int cur = 1; // Variable to store // total unique numbers int count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { int num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count; } // Driver Code public static void main(String args[]) { int L = 1, R = 64; // Function call System.out.println(totalUniqueNumber(L, R)); }}// This code is contributed by Samim Hossain Mondal.", "e": 31364, "s": 28692, "text": null }, { "code": "# Python program for the above approach # Utility function to check if# the digits of the current# integer forms a wave patterndef check(N): # Convert the number to a string S = str(N); # Loop to iterate over digits for i in range(len(S)): if (i == 0): # Next character of # the number next = i + 1; # Current character is # not a local minimum if (next < len(S)): if (S[i] >= S[next]): return False; elif(i == len(S) - 1): # Previous character of # the number prev = i - 1; if (prev >= 0): # Character is a # local maximum if ((i & 1) == 1): # Character is not # a local maximum if (S[i] <= S[prev]): return False; else: # Character is a # local minimum if (S[i] >= S[prev]): return False; else: prev = i - 1; next = i + 1; if ((i & 1) == 1): # Character is a # local maximum if ((S[i] > S[prev]) and (S[i] > S[next])): return True; else: return False; else: # Character is a # local minimum if ((S[i] < S[prev]) and (S[i] < S[next])): return True; else: return False; return True; # Function to calculate total# integer in the given rangedef totalUniqueNumber(L, R): # Base case if (R <= 0): return 0; # Current number cur = 1; # Variable to store # total unique numbers count = 0; # Iterating over perfect # squares while ((cur * cur) <= R): num = cur * cur; # If number is greater # than L and satisfies # required conditions if (num >= L and check(num)): count += 1; # Moving to the # next number cur += 1; # Return Answer return count; # Driver Codeif __name__ == '__main__': L = 1; R = 64; # Function call print(totalUniqueNumber(L, R)); # This code is contributed by gauravrajput1", "e": 33819, "s": 31364, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections; class GFG{ // Utility function to check if // the digits of the current // integer forms a wave pattern static bool check(int N) { // Convert the number to a string string S = N.ToString(); // Loop to iterate over digits for (int i = 0; i < S.Length; i++) { if (i == 0) { // Next character of // the number int next = i + 1; // Current character is // not a local minimum if (next < S.Length) { if (S[i] >= S[next]) { return false; } } } else if (i == S.Length - 1) { // Previous character of // the number int prev = i - 1; if (prev >= 0) { // Character is a // local maximum if ((i & 1) == 1) { // Character is not // a local maximum if (S[i] <= S[prev]) { return false; } } else { // Character is a // local minimum if (S[i] >= S[prev]) { return false; } } } } else { int prev = i - 1; int next = i + 1; if ((i & 1) == 1) { // Character is a // local maximum if ((S[i] > S[prev]) && (S[i] > S[next])) { } else { return false; } } else { // Character is a // local minimum if ((S[i] < S[prev]) && (S[i] < S[next])) { } else { return false; } } } } return true; } // Function to calculate total // integer in the given range static int totalUniqueNumber(int L, int R) { // Base case if (R <= 0) { return 0; } // Current number int cur = 1; // Variable to store // total unique numbers int count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { int num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count; } // Driver Code public static void Main() { int L = 1, R = 64; // Function call Console.Write(totalUniqueNumber(L, R)); }}// This code is contributed by Samim Hossain Mondal.", "e": 36311, "s": 33819, "text": null }, { "code": "<script> // JavaScript code for the above approach // Utility function to check if // the digits of the current // integer forms a wave pattern function check(N) { // Convert the number to a string let S = N.toString(); // Loop to iterate over digits for (let i = 0; i < S.length; i++) { if (i == 0) { // Next character of // the number let next = i + 1; // Current character is // not a local minimum if (next < S.length) { if (S[i] >= S[next]) { return false; } } } else if (i == S.length - 1) { // Previous character of // the number let prev = i - 1; if (prev >= 0) { // Character is a // local maximum if (i & 1) { // Character is not // a local maximum if (S[i] <= S[prev]) { return false; } } else { // Character is a // local minimum if (S[i] >= S[prev]) { return false; } } } } else { let prev = i - 1; let next = i + 1; if (i & 1) { // Character is a // local maximum if ((S[i] > S[prev]) && (S[i] > S[next])) { } else { return false; } } else { // Character is a // local minimum if ((S[i] < S[prev]) && (S[i] < S[next])) { } else { return false; } } } } return true; } // Function to calculate total // integer in the given range function totalUniqueNumber(L, R) { // Base case if (R <= 0) { return 0; } // Current number let cur = 1; // Variable to store // total unique numbers let count = 0; // Iterating over perfect // squares while ((cur * cur) <= R) { let num = cur * cur; // If number is greater // than L and satisfies // required conditions if (num >= L && check(num)) { count++; } // Moving to the // next number cur++; } // Return Answer return count; } // Driver Code let L = 1, R = 64; document.write(totalUniqueNumber(L, R)); // This code is contributed by Potta Lokesh </script>", "e": 39735, "s": 36311, "text": null }, { "code": null, "e": 39740, "s": 39738, "text": "7" }, { "code": null, "e": 39790, "s": 39740, "text": "Time Complexity: O(sqrt(N))Auxiliary Space: O(1) " }, { "code": null, "e": 39804, "s": 39790, "text": "lokeshpotta20" }, { "code": null, "e": 39814, "s": 39804, "text": "samim2000" }, { "code": null, "e": 39828, "s": 39814, "text": "GauravRajput1" }, { "code": null, "e": 39848, "s": 39828, "text": "array-range-queries" }, { "code": null, "e": 39854, "s": 39848, "text": "Maths" }, { "code": null, "e": 39868, "s": 39854, "text": "number-digits" }, { "code": null, "e": 39881, "s": 39868, "text": "Mathematical" }, { "code": null, "e": 39894, "s": 39881, "text": "Mathematical" }, { "code": null, "e": 39992, "s": 39894, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40001, "s": 39992, "text": "Comments" }, { "code": null, "e": 40014, "s": 40001, "text": "Old Comments" }, { "code": null, "e": 40057, "s": 40014, "text": "Program to convert a given number to words" }, { "code": null, "e": 40088, "s": 40057, "text": "Modular multiplicative inverse" }, { "code": null, "e": 40120, "s": 40088, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 40153, "s": 40120, "text": "Program to multiply two matrices" }, { "code": null, "e": 40188, "s": 40153, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 40232, "s": 40188, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 40264, "s": 40232, "text": "Check if a number is Palindrome" }, { "code": null, "e": 40299, "s": 40264, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 40324, "s": 40299, "text": "Fizz Buzz Implementation" } ]
3D Cone Plots using Plotly in Python - GeeksforGeeks
10 Jul, 2020 Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. In plotly, a cone plot is a plot that has 3d equivalent of a 2D quiver plot. A 3d vector represents the direction and norm of the vectors. 3d coordinates are X, Y, and Z which define the coordinates for a vector. 3d coordinates of a vector field are U, V, and W which is defined as the vector field. Syntax: plotly.graph_objects.Cone(arg=None, anchor=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, sizemode=None, sizeref=None, stream=None, text=None, textsrc=None, u=None, uid=None, uirevision=None, usrc=None, v=None, visible=None, vsrc=None, w=None, wsrc=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, **kwargs) Parameters: u – Sets the x components of the vector field. v – Sets the y components of the vector field. w – Sets the z components of the vector field. x – Sets the x coordinates of the vector field and of the displayed cones. y – Sets the y coordinates of the vector field and of the displayed cones. z – Sets the z coordinates of the vector field and of the displayed cones. Example: Python3 import plotly.graph_objects as go fig = go.Figure(data=go.Cone(x=[3], y=[1], z=[4], u=[1], v=[7], w=[2])) fig.show() Output: In plotly, the multiple 3d cones use the parameter scene, in this the graph show many cones in a single graph that help to differentiate between each other. It can be created by passing multiple values in the x, y, z, u, v, w parameters. Example 1: Python3 import plotly.graph_objects as go fig = go.Figure(data=go.Cone(x=[1,3], y=[1,3], z=[1,4], u=[1,6], v=[1,7], w=[0,2])) fig.show() Output: Example 2: Python3 import plotly.graph_objects as go fig = go.Figure(data=go.Cone(x=[11,31, 12], y=[12,32, 21], z=[13,41, 15], u=[14,16, 17], v=[15,27, 10], w=[10,29, 21])) fig.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Enumerate() in Python Read a file line by line in Python Python OOPs Concepts Different ways to create Pandas Dataframe sum() function in Python How to Install PIP on Windows ? Stack in Python Bar Plot in Matplotlib Reading and Writing to text files in Python
[ { "code": null, "e": 24345, "s": 24317, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24647, "s": 24345, "text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library." }, { "code": null, "e": 24786, "s": 24647, "text": "In plotly, a cone plot is a plot that has 3d equivalent of a 2D quiver plot. A 3d vector represents the direction and norm of the vectors." }, { "code": null, "e": 24860, "s": 24786, "text": "3d coordinates are X, Y, and Z which define the coordinates for a vector." }, { "code": null, "e": 24948, "s": 24860, "text": "3d coordinates of a vector field are U, V, and W which is defined as the vector field." }, { "code": null, "e": 25708, "s": 24948, "text": "Syntax: plotly.graph_objects.Cone(arg=None, anchor=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, sizemode=None, sizeref=None, stream=None, text=None, textsrc=None, u=None, uid=None, uirevision=None, usrc=None, v=None, visible=None, vsrc=None, w=None, wsrc=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, **kwargs)" }, { "code": null, "e": 25720, "s": 25708, "text": "Parameters:" }, { "code": null, "e": 25767, "s": 25720, "text": "u – Sets the x components of the vector field." }, { "code": null, "e": 25814, "s": 25767, "text": "v – Sets the y components of the vector field." }, { "code": null, "e": 25861, "s": 25814, "text": "w – Sets the z components of the vector field." }, { "code": null, "e": 25936, "s": 25861, "text": "x – Sets the x coordinates of the vector field and of the displayed cones." }, { "code": null, "e": 26011, "s": 25936, "text": "y – Sets the y coordinates of the vector field and of the displayed cones." }, { "code": null, "e": 26086, "s": 26011, "text": "z – Sets the z coordinates of the vector field and of the displayed cones." }, { "code": null, "e": 26095, "s": 26086, "text": "Example:" }, { "code": null, "e": 26103, "s": 26095, "text": "Python3" }, { "code": "import plotly.graph_objects as go fig = go.Figure(data=go.Cone(x=[3], y=[1], z=[4], u=[1], v=[7], w=[2])) fig.show()", "e": 26362, "s": 26103, "text": null }, { "code": null, "e": 26370, "s": 26362, "text": "Output:" }, { "code": null, "e": 26608, "s": 26370, "text": "In plotly, the multiple 3d cones use the parameter scene, in this the graph show many cones in a single graph that help to differentiate between each other. It can be created by passing multiple values in the x, y, z, u, v, w parameters." }, { "code": null, "e": 26619, "s": 26608, "text": "Example 1:" }, { "code": null, "e": 26627, "s": 26619, "text": "Python3" }, { "code": "import plotly.graph_objects as go fig = go.Figure(data=go.Cone(x=[1,3], y=[1,3], z=[1,4], u=[1,6], v=[1,7], w=[0,2])) fig.show()", "e": 26899, "s": 26627, "text": null }, { "code": null, "e": 26907, "s": 26899, "text": "Output:" }, { "code": null, "e": 26918, "s": 26907, "text": "Example 2:" }, { "code": null, "e": 26926, "s": 26918, "text": "Python3" }, { "code": "import plotly.graph_objects as go fig = go.Figure(data=go.Cone(x=[11,31, 12], y=[12,32, 21], z=[13,41, 15], u=[14,16, 17], v=[15,27, 10], w=[10,29, 21])) fig.show()", "e": 27234, "s": 26926, "text": null }, { "code": null, "e": 27242, "s": 27234, "text": "Output:" }, { "code": null, "e": 27256, "s": 27242, "text": "Python-Plotly" }, { "code": null, "e": 27263, "s": 27256, "text": "Python" }, { "code": null, "e": 27361, "s": 27263, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27370, "s": 27361, "text": "Comments" }, { "code": null, "e": 27383, "s": 27370, "text": "Old Comments" }, { "code": null, "e": 27401, "s": 27383, "text": "Python Dictionary" }, { "code": null, "e": 27423, "s": 27401, "text": "Enumerate() in Python" }, { "code": null, "e": 27458, "s": 27423, "text": "Read a file line by line in Python" }, { "code": null, "e": 27479, "s": 27458, "text": "Python OOPs Concepts" }, { "code": null, "e": 27521, "s": 27479, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27546, "s": 27521, "text": "sum() function in Python" }, { "code": null, "e": 27578, "s": 27546, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27594, "s": 27578, "text": "Stack in Python" }, { "code": null, "e": 27617, "s": 27594, "text": "Bar Plot in Matplotlib" } ]
Gerrit - Add Your SSH Key
You can add SSH key to the ssh-agent on different platforms discussed further. Use the following command on Linux system to add SSH key cat /home/<local-user>/.ssh/id_rsa.pub Open the GIT GUI and go to Help → Show SSH Key as shown in the following image. Then, click the Copy To Clipboard button, to copy the key to the clipboard. In Mac OS X, you can copy id_rsa.pub contents to the clipboard using the following command. $ pbcopy < ~/.ssh/id_rsa.pub Print Add Notes Bookmark this page
[ { "code": null, "e": 2317, "s": 2238, "text": "You can add SSH key to the ssh-agent on different platforms discussed further." }, { "code": null, "e": 2374, "s": 2317, "text": "Use the following command on Linux system to add SSH key" }, { "code": null, "e": 2414, "s": 2374, "text": "cat /home/<local-user>/.ssh/id_rsa.pub\n" }, { "code": null, "e": 2494, "s": 2414, "text": "Open the GIT GUI and go to Help → Show SSH Key as shown in the following image." }, { "code": null, "e": 2570, "s": 2494, "text": "Then, click the Copy To Clipboard button, to copy the key to the clipboard." }, { "code": null, "e": 2662, "s": 2570, "text": "In Mac OS X, you can copy id_rsa.pub contents to the clipboard using the following command." }, { "code": null, "e": 2692, "s": 2662, "text": "$ pbcopy < ~/.ssh/id_rsa.pub\n" }, { "code": null, "e": 2699, "s": 2692, "text": " Print" }, { "code": null, "e": 2710, "s": 2699, "text": " Add Notes" } ]
Algorithm for matrix multiplication in JavaScript
We are required to write a JavaScript function that takes in two 2-D arrays of numbers and returns their matrix multiplication result. Let’s write the code for this function − The code for this will be − const multiplyMatrices = (a, b) => { if (!Array.isArray(a) || !Array.isArray(b) || !a.length || !b.length) { throw new Error('arguments should be in 2-dimensional array format'); } let x = a.length, z = a[0].length, y = b[0].length; if (b.length !== z) { // XxZ & ZxY => XxY throw new Error('number of columns in the first matrix should be the same as the number of rows in the second'); } let productRow = Array.apply(null, new Array(y)).map(Number.prototype.valueOf, 0); let product = new Array(x); for (let p = 0; p < x; p++) { product[p] = productRow.slice(); } for (let i = 0; i < x; i++) { for (let j = 0; j < y; j++) { for (let k = 0; k < z; k++) { product[i][j] += a[i][k] * b[k][j]; } } } return product; } // 5 x 4 let a = [ [1, 2, 3, 1], [4, 5, 6, 1], [7, 8, 9, 1], [1, 1, 1, 1], [5, 7, 2, 6] ]; // 4 x 6 let b = [ [1, 4, 7, 3, 4, 6], [2, 5, 8, 7, 3, 2], [3, 6, 9, 6, 7, 8], [1, 1, 1, 2, 3, 6] ]; // should result in a 5 x 6 matrix console.log(multiplyMatrices(a, b)); The output in the console − [ [ 15, 33, 51, 37, 34, 40 ], [ 33, 78, 123, 85, 76, 88 ], [ 51, 123, 195, 133, 118, 136 ], [ 7, 16, 25, 18, 17, 22 ], [ 31, 73, 115, 88, 73, 96 ] ]
[ { "code": null, "e": 1197, "s": 1062, "text": "We are required to write a JavaScript function that takes in two 2-D arrays of numbers and\nreturns their matrix multiplication result." }, { "code": null, "e": 1238, "s": 1197, "text": "Let’s write the code for this function −" }, { "code": null, "e": 1266, "s": 1238, "text": "The code for this will be −" }, { "code": null, "e": 2387, "s": 1266, "text": "const multiplyMatrices = (a, b) => {\n if (!Array.isArray(a) || !Array.isArray(b) || !a.length || !b.length) {\n throw new Error('arguments should be in 2-dimensional array format');\n }\n let x = a.length,\n z = a[0].length,\n y = b[0].length;\n if (b.length !== z) {\n // XxZ & ZxY => XxY\n throw new Error('number of columns in the first matrix should be\n the same as the number of rows in the second');\n }\n let productRow = Array.apply(null, new Array(y)).map(Number.prototype.valueOf, 0);\n let product = new Array(x);\n for (let p = 0; p < x; p++) {\n product[p] = productRow.slice();\n }\n for (let i = 0; i < x; i++) {\n for (let j = 0; j < y; j++) {\n for (let k = 0; k < z; k++) {\n product[i][j] += a[i][k] * b[k][j];\n }\n }\n }\n return product;\n}\n// 5 x 4\nlet a = [\n [1, 2, 3, 1],\n [4, 5, 6, 1],\n [7, 8, 9, 1],\n [1, 1, 1, 1],\n [5, 7, 2, 6]\n];\n// 4 x 6\nlet b = [\n [1, 4, 7, 3, 4, 6],\n [2, 5, 8, 7, 3, 2],\n [3, 6, 9, 6, 7, 8],\n [1, 1, 1, 2, 3, 6]\n];\n// should result in a 5 x 6 matrix\nconsole.log(multiplyMatrices(a, b));" }, { "code": null, "e": 2415, "s": 2387, "text": "The output in the console −" }, { "code": null, "e": 2579, "s": 2415, "text": "[\n [ 15, 33, 51, 37, 34, 40 ],\n [ 33, 78, 123, 85, 76, 88 ],\n [ 51, 123, 195, 133, 118, 136 ],\n [ 7, 16, 25, 18, 17, 22 ],\n [ 31, 73, 115, 88, 73, 96 ]\n]" } ]
Check if product of first N natural numbers is divisible by their sum in Python
Suppose we have a number n. We have to check whether the product of (1*2*...*n) is divisible by (1+2+...+n) or not So, if the input is like num = 5, then the output will be True as (1*2*3*4*5) = 120 and (1+2+3+4+5) = 15, and 120 is divisible by 15. To solve this, we will follow these steps − if num + 1 is prime, thenreturn false return false return true Let us see the following implementation to get better understanding − Live Demo def isPrime(num): if num > 1: for i in range(2, num): if num % i == 0: return False return True return False def solve(num): if isPrime(num + 1): return False return True num = 3 print(solve(num)) 5 True
[ { "code": null, "e": 1177, "s": 1062, "text": "Suppose we have a number n. We have to check whether the product of (1*2*...*n) is divisible by (1+2+...+n) or not" }, { "code": null, "e": 1311, "s": 1177, "text": "So, if the input is like num = 5, then the output will be True as (1*2*3*4*5) = 120 and (1+2+3+4+5) = 15, and 120 is divisible by 15." }, { "code": null, "e": 1355, "s": 1311, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1393, "s": 1355, "text": "if num + 1 is prime, thenreturn false" }, { "code": null, "e": 1406, "s": 1393, "text": "return false" }, { "code": null, "e": 1418, "s": 1406, "text": "return true" }, { "code": null, "e": 1488, "s": 1418, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1499, "s": 1488, "text": " Live Demo" }, { "code": null, "e": 1747, "s": 1499, "text": "def isPrime(num):\n if num > 1:\n for i in range(2, num):\n if num % i == 0:\n return False\n return True\n return False\ndef solve(num):\n if isPrime(num + 1):\n return False\n return True\nnum = 3\nprint(solve(num))" }, { "code": null, "e": 1749, "s": 1747, "text": "5" }, { "code": null, "e": 1754, "s": 1749, "text": "True" } ]
Math operations for BigDecimal in Java
Let us apply the following operations on BigDecimal using the in-built methods in Java − Addition: add() method Subtraction: subtract() method Multiplication: multiply() method Division: divide() method Let us create three BigInteger objects − BigDecimal val1 = new BigDecimal("37578975587.876876989"); BigDecimal val2 = new BigDecimal("62567875598.976876569"); BigDecimal val3 = new BigDecimal("72567875598.376876569"); Apply mathematical operations on them − val1 = val1.add(val2); System.out.println("Addition Operation = " + val1); val1 = val1.multiply(val2); System.out.println("Multiplication Operation = " + val1); val2 = val3.subtract(val2); System.out.println("Subtract Operation = " + val2); The following is an example − Live Demo import java.math.BigDecimal; public class Demo { public static void main(String[] argv) throws Exception { BigDecimal val1 = new BigDecimal("37578975587.876876989"); BigDecimal val2 = new BigDecimal("62567875598.976876569"); BigDecimal val3 = new BigDecimal("72567875598.376876569"); System.out.println("Value 1 : "+val1); System.out.println("Value 2 : "+val2); val1 = val1.add(val2); System.out.println("Addition Operation = " + val1); val1 = val1.multiply(val2); System.out.println("Multiplication Operation = " + val1); val2 = val3.subtract(val2); System.out.println("Subtract Operation = " + val2); val2 = val3.divide(val2,BigDecimal.ROUND_UP); System.out.println("Division Operation = " + val2); } } Value 1 : 37578975587.876876989 Value 2 : 62567875598.976876569 Addition Operation = 100146851186.853753558 Multiplication Operation = 6265975726688315418019.861150364510582502 Subtract Operation = 9999999999.400000000 Division Operation = 7.256787561
[ { "code": null, "e": 1151, "s": 1062, "text": "Let us apply the following operations on BigDecimal using the in-built methods in Java −" }, { "code": null, "e": 1265, "s": 1151, "text": "Addition: add() method\nSubtraction: subtract() method\nMultiplication: multiply() method\nDivision: divide() method" }, { "code": null, "e": 1306, "s": 1265, "text": "Let us create three BigInteger objects −" }, { "code": null, "e": 1483, "s": 1306, "text": "BigDecimal val1 = new BigDecimal(\"37578975587.876876989\");\nBigDecimal val2 = new BigDecimal(\"62567875598.976876569\");\nBigDecimal val3 = new BigDecimal(\"72567875598.376876569\");" }, { "code": null, "e": 1523, "s": 1483, "text": "Apply mathematical operations on them −" }, { "code": null, "e": 1764, "s": 1523, "text": "val1 = val1.add(val2);\nSystem.out.println(\"Addition Operation = \" + val1);\nval1 = val1.multiply(val2);\nSystem.out.println(\"Multiplication Operation = \" + val1);\nval2 = val3.subtract(val2);\nSystem.out.println(\"Subtract Operation = \" + val2);" }, { "code": null, "e": 1794, "s": 1764, "text": "The following is an example −" }, { "code": null, "e": 1805, "s": 1794, "text": " Live Demo" }, { "code": null, "e": 2594, "s": 1805, "text": "import java.math.BigDecimal;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n BigDecimal val1 = new BigDecimal(\"37578975587.876876989\");\n BigDecimal val2 = new BigDecimal(\"62567875598.976876569\");\n BigDecimal val3 = new BigDecimal(\"72567875598.376876569\");\n System.out.println(\"Value 1 : \"+val1);\n System.out.println(\"Value 2 : \"+val2);\n val1 = val1.add(val2);\n System.out.println(\"Addition Operation = \" + val1);\n val1 = val1.multiply(val2);\n System.out.println(\"Multiplication Operation = \" + val1);\n val2 = val3.subtract(val2);\n System.out.println(\"Subtract Operation = \" + val2);\n val2 = val3.divide(val2,BigDecimal.ROUND_UP);\n System.out.println(\"Division Operation = \" + val2);\n }\n}" }, { "code": null, "e": 2846, "s": 2594, "text": "Value 1 : 37578975587.876876989\nValue 2 : 62567875598.976876569\nAddition Operation = 100146851186.853753558\nMultiplication Operation = 6265975726688315418019.861150364510582502\nSubtract Operation = 9999999999.400000000\nDivision Operation = 7.256787561" } ]
React State
React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders. The state object is initialized in the constructor: Specify the state object in the constructor method: class Car extends React.Component { constructor(props) { super(props); this.state = {brand: "Ford"}; } render() { return ( <div> <h1>My Car</h1> </div> ); } } The state object can contain as many properties as you like: Specify all the properties your component need: class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } render() { return ( <div> <h1>My Car</h1> </div> ); } } Refer to the state object anywhere in the component by using the this.state.propertyname syntax: Refer to the state object in the render() method: class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } render() { return ( <div> <h1>My {this.state.brand}</h1> <p> It is a {this.state.color} {this.state.model} from {this.state.year}. </p> </div> ); } } Run Example » To change a value in the state object, use the this.setState() method. When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s). Add a button with an onClick event that will change the color property: class Car extends React.Component { constructor(props) { super(props); this.state = { brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } changeColor = () => { this.setState({color: "blue"}); } render() { return ( <div> <h1>My {this.state.brand}</h1> <p> It is a {this.state.color} {this.state.model} from {this.state.year}. </p> <button type="button" onClick={this.changeColor} >Change color</button> </div> ); } } Run Example » Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods). We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 48, "s": 0, "text": "React components has a built-in state \nobject. " }, { "code": null, "e": 132, "s": 48, "text": "The state object is where you \nstore property values that belongs to the component." }, { "code": null, "e": 190, "s": 132, "text": "When the state object changes, \nthe component re-renders." }, { "code": null, "e": 242, "s": 190, "text": "The state object is initialized in the constructor:" }, { "code": null, "e": 294, "s": 242, "text": "Specify the state object in the constructor method:" }, { "code": null, "e": 500, "s": 294, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {brand: \"Ford\"};\n }\n render() {\n return (\n <div>\n <h1>My Car</h1>\n </div>\n );\n }\n}\n \n" }, { "code": null, "e": 561, "s": 500, "text": "The state object can contain as many properties as you like:" }, { "code": null, "e": 609, "s": 561, "text": "Specify all the properties your component need:" }, { "code": null, "e": 899, "s": 609, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n brand: \"Ford\",\n model: \"Mustang\",\n color: \"red\",\n year: 1964\n };\n }\n render() {\n return (\n <div>\n <h1>My Car</h1>\n </div>\n );\n }\n}\n \n \n \n \n \n \n" }, { "code": null, "e": 996, "s": 899, "text": "Refer to the state object anywhere in the component by using the\nthis.state.propertyname syntax:" }, { "code": null, "e": 1049, "s": 996, "text": "Refer to the state object in the \n render() method:" }, { "code": null, "e": 1479, "s": 1049, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n brand: \"Ford\",\n model: \"Mustang\",\n color: \"red\",\n year: 1964\n };\n }\n render() {\n return (\n <div>\n <h1>My {this.state.brand}</h1>\n <p>\n It is a {this.state.color}\n {this.state.model}\n from {this.state.year}.\n </p>\n </div>\n );\n }\n}\n \n \n \n \n \n \n" }, { "code": null, "e": 1496, "s": 1479, "text": "\nRun \nExample »\n" }, { "code": null, "e": 1567, "s": 1496, "text": "To change a value in the state object, use the this.setState() method." }, { "code": null, "e": 1708, "s": 1567, "text": "When a value in the state object changes, \nthe component will re-render, meaning that the output will change according to \nthe new value(s)." }, { "code": null, "e": 1783, "s": 1708, "text": "Add a button with an onClick event that \n will change the color property:" }, { "code": null, "e": 2387, "s": 1783, "text": "class Car extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n brand: \"Ford\",\n model: \"Mustang\",\n color: \"red\",\n year: 1964\n };\n }\n changeColor = () => {\n this.setState({color: \"blue\"});\n }\n render() {\n return (\n <div>\n <h1>My {this.state.brand}</h1>\n <p>\n It is a {this.state.color}\n {this.state.model}\n from {this.state.year}.\n </p>\n <button\n type=\"button\"\n onClick={this.changeColor}\n >Change color</button>\n </div>\n );\n }\n}\n \n \n \n \n \n \n \n" }, { "code": null, "e": 2404, "s": 2387, "text": "\nRun \nExample »\n" }, { "code": null, "e": 2591, "s": 2404, "text": "Always use the setState() method to change the state object,\nit will ensure that the component knows its been updated and calls the render() method\n(and all the other lifecycle methods)." }, { "code": null, "e": 2624, "s": 2591, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 2666, "s": 2624, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 2773, "s": 2666, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 2792, "s": 2773, "text": "help@w3schools.com" } ]
What is Common Locale Data Repository (CLDR) in Java 9?
Internationalization enhancements for Java 9 include enabling of CLDR Locale Data by Default. There are four distinct sources for locale data identified by using the below keywords: CLDR: The locale data provided by a Unicode Common Locale Data Repository (CLDR) project. HOST: The current user’s customization of an underlying operating system’s settings. Depending on the operating system, formats like date, time, number, and currency can be supported. SPI: The locale-sensitive services implemented in installed SPI providers. COMPAT (JRE): The locale data that is compatible with releases prior to Java 9. The JRE can still be used as a value but deprecated, and removed in the future. In Java 8 and previous versions, JRE is default locale data. Java 9 sets CLDR as the highest priority by default. We select a locale data source in preferred order by using java.locale.providers system property. If a provider has failed to request locale data, the next provider can be processed. java.locale.providers=COMPAT,CLDR,HOST,SPI If we don’t set the property, the default behavior is: java.locale.providers=CLDR,COMPAT,SPI To make compatible with Java 8, keep COMPAT ahead of CLDR. java.locale.providers=COMPAT,CLDR
[ { "code": null, "e": 1156, "s": 1062, "text": "Internationalization enhancements for Java 9 include enabling of CLDR Locale Data by Default." }, { "code": null, "e": 1244, "s": 1156, "text": "There are four distinct sources for locale data identified by using the below keywords:" }, { "code": null, "e": 1334, "s": 1244, "text": "CLDR: The locale data provided by a Unicode Common Locale Data Repository (CLDR) project." }, { "code": null, "e": 1518, "s": 1334, "text": "HOST: The current user’s customization of an underlying operating system’s settings. Depending on the operating system, formats like date, time, number, and currency can be supported." }, { "code": null, "e": 1593, "s": 1518, "text": "SPI: The locale-sensitive services implemented in installed SPI providers." }, { "code": null, "e": 1753, "s": 1593, "text": "COMPAT (JRE): The locale data that is compatible with releases prior to Java 9. The JRE can still be used as a value but deprecated, and removed in the future." }, { "code": null, "e": 2050, "s": 1753, "text": "In Java 8 and previous versions, JRE is default locale data. Java 9 sets CLDR as the highest priority by default. We select a locale data source in preferred order by using java.locale.providers system property. If a provider has failed to request locale data, the next provider can be processed." }, { "code": null, "e": 2093, "s": 2050, "text": "java.locale.providers=COMPAT,CLDR,HOST,SPI" }, { "code": null, "e": 2148, "s": 2093, "text": "If we don’t set the property, the default behavior is:" }, { "code": null, "e": 2186, "s": 2148, "text": "java.locale.providers=CLDR,COMPAT,SPI" }, { "code": null, "e": 2245, "s": 2186, "text": "To make compatible with Java 8, keep COMPAT ahead of CLDR." }, { "code": null, "e": 2279, "s": 2245, "text": "java.locale.providers=COMPAT,CLDR" } ]
C Program for Activity Selection Problem
The activity selection problem is a problem in which we are given a set of activities with their starting and finishing times. And we need to find all those activities that a person can do performing the single activity at a time. The greedy algorithm is appointed in this problem to select the next activity that is to be performed. Let’s first understand the greedy algorithm. Greedy Algorithm is an algorithm that tries to find the solution to a problem by finding the solution step by step. For selecting the next step, the algorithm also selected the step that seems to be the most promising i.e. can lead to the optimised solution immediately as compared to rest. The greedy algorithm is used to solve optimization problems as it tries to find the most optimized solution for the next intermediate step that leads to an optimal solution to the whole problem. Though the greedy algorithm is a good solution but there are some problems with which it cannot be applied. For example, 0-1 knapsack cannot be solved using the greedy algorithm. Some standard greedy algorithm is − 1) Dijkstrata’s Shortest Path 2) Minimum Spanning Tree (MST) {prim’s and kruskal’s} 3) Huffman coding Inactivity selection problem, we are given n problems with starting and finishing time. And we need to select the maximum number of activities that can be performed by an individual is given that he can do a single activity at a point of time. There are 3 activities which are sorted in order of their finishing time, Start = [1 , 5 , 12 ] End = [10, 13, 23] Here, the person will be able to perform two activities at most. Activities that can be executed are [0, 2]. Live Demo #include<stdio.h> int main(){ int start[] = {1 , 5 , 12}; int finish[] = {10, 13, 23}; int activities = sizeof(start)/sizeof(start[0]); int i, j; printf ("Following activities are selected \t"); i = 0; printf("%d\t", i); for (j = 1; j < activities; j++){ if (start[j] >= finish[i]){ printf ("%d ", j); i = j; } } return 0; } Following activities are selected 0 2
[ { "code": null, "e": 1293, "s": 1062, "text": "The activity selection problem is a problem in which we are given a set of activities with their starting and finishing times. And we need to find all those activities that a person can do performing the single activity at a time." }, { "code": null, "e": 1441, "s": 1293, "text": "The greedy algorithm is appointed in this problem to select the next activity that is to be performed. Let’s first understand the greedy algorithm." }, { "code": null, "e": 1927, "s": 1441, "text": "Greedy Algorithm is an algorithm that tries to find the solution to a problem by finding the solution step by step. For selecting the next step, the algorithm also selected the step that seems to be the most promising i.e. can lead to the optimised solution immediately as compared to rest. The greedy algorithm is used to solve optimization problems as it tries to find the most optimized solution for the next intermediate step that leads to an optimal solution to the whole problem." }, { "code": null, "e": 2106, "s": 1927, "text": "Though the greedy algorithm is a good solution but there are some problems with which it cannot be applied. For example, 0-1 knapsack cannot be solved using the greedy algorithm." }, { "code": null, "e": 2142, "s": 2106, "text": "Some standard greedy algorithm is −" }, { "code": null, "e": 2244, "s": 2142, "text": "1) Dijkstrata’s Shortest Path\n2) Minimum Spanning Tree (MST) {prim’s and kruskal’s}\n3) Huffman coding" }, { "code": null, "e": 2488, "s": 2244, "text": "Inactivity selection problem, we are given n problems with starting and finishing time. And we need to select the maximum number of activities that can be performed by an individual is given that he can do a single activity at a point of time." }, { "code": null, "e": 2562, "s": 2488, "text": "There are 3 activities which are sorted in order of their finishing time," }, { "code": null, "e": 2603, "s": 2562, "text": "Start = [1 , 5 , 12 ]\nEnd = [10, 13, 23]" }, { "code": null, "e": 2712, "s": 2603, "text": "Here, the person will be able to perform two activities at most. Activities that can be executed are [0, 2]." }, { "code": null, "e": 2723, "s": 2712, "text": " Live Demo" }, { "code": null, "e": 3108, "s": 2723, "text": "#include<stdio.h>\nint main(){\n int start[] = {1 , 5 , 12};\n int finish[] = {10, 13, 23};\n int activities = sizeof(start)/sizeof(start[0]);\n int i, j;\n printf (\"Following activities are selected \\t\");\n i = 0;\n printf(\"%d\\t\", i);\n for (j = 1; j < activities; j++){\n if (start[j] >= finish[i]){\n printf (\"%d \", j);\n i = j;\n }\n }\n return 0;\n}" }, { "code": null, "e": 3146, "s": 3108, "text": "Following activities are selected 0 2" } ]
Gson - Tree Model
Tree Model prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML. JsonParser provides a pointer to the root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String. //Create an JsonParser instance JsonParser parser = new JsonParser(); String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}"; //create tree from JSON JsonElement rootNode = parser.parse(jsonString); Get each node using relative path to the root node while traversing the tree and process the data. The following code snippet shows how you can traverse a tree. JsonObject details = rootNode.getAsJsonObject(); JsonElement nameNode = details.get("name"); System.out.println("Name: " +nameNode.getAsString()); JsonElement ageNode = details.get("age"); System.out.println("Age: " + ageNode.getAsInt()); Create a Java class file named GsonTester in C:\>GSON_WORKSPACE. File − GsonTester.java import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; public class GsonTester { public static void main(String args[]) { String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}"; JsonParser parser = new JsonParser(); JsonElement rootNode = parser.parse(jsonString); if (rootNode.isJsonObject()) { JsonObject details = rootNode.getAsJsonObject(); JsonElement nameNode = details.get("name"); System.out.println("Name: " +nameNode.getAsString()); JsonElement ageNode = details.get("age"); System.out.println("Age: " + ageNode.getAsInt()); JsonElement verifiedNode = details.get("verified"); System.out.println("Verified: " + (verifiedNode.getAsBoolean() ? "Yes":"No")); JsonArray marks = details.getAsJsonArray("marks"); for (int i = 0; i < marks.size(); i++) { JsonPrimitive value = marks.get(i).getAsJsonPrimitive(); System.out.print(value.getAsInt() + " "); } } } } Compile the classes using javac compiler as follows − C:\GSON_WORKSPACE>javac GsonTester.java Now run the GsonTester to see the result − C:\GSON_WORKSPACE>java GsonTester Verify the output. Name: Mahesh Kumar Age: 21 Verified: No 100 90 85 Print Add Notes Bookmark this page
[ { "code": null, "e": 2111, "s": 1932, "text": "Tree Model prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML." }, { "code": null, "e": 2331, "s": 2111, "text": "JsonParser provides a pointer to the root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String." }, { "code": null, "e": 2587, "s": 2331, "text": "//Create an JsonParser instance \nJsonParser parser = new JsonParser(); \n\nString jsonString = \n\"{\\\"name\\\":\\\"Mahesh Kumar\\\", \\\"age\\\":21,\\\"verified\\\":false,\\\"marks\\\": [100,90,85]}\"; \n\n//create tree from JSON \nJsonElement rootNode = parser.parse(jsonString);\n" }, { "code": null, "e": 2748, "s": 2587, "text": "Get each node using relative path to the root node while traversing the tree and process the data. The following code snippet shows how you can traverse a tree." }, { "code": null, "e": 2995, "s": 2748, "text": "JsonObject details = rootNode.getAsJsonObject(); \n\nJsonElement nameNode = details.get(\"name\"); \nSystem.out.println(\"Name: \" +nameNode.getAsString()); \n\nJsonElement ageNode = details.get(\"age\"); \nSystem.out.println(\"Age: \" + ageNode.getAsInt()); \n" }, { "code": null, "e": 3060, "s": 2995, "text": "Create a Java class file named GsonTester in C:\\>GSON_WORKSPACE." }, { "code": null, "e": 3083, "s": 3060, "text": "File − GsonTester.java" }, { "code": null, "e": 4355, "s": 3083, "text": "import com.google.gson.JsonArray; \nimport com.google.gson.JsonElement; \nimport com.google.gson.JsonObject; \nimport com.google.gson.JsonParser;\nimport com.google.gson.JsonPrimitive; \n\npublic class GsonTester { \n public static void main(String args[]) { \n \n String jsonString = \n \"{\\\"name\\\":\\\"Mahesh Kumar\\\", \\\"age\\\":21,\\\"verified\\\":false,\\\"marks\\\": [100,90,85]}\";\n JsonParser parser = new JsonParser(); \n JsonElement rootNode = parser.parse(jsonString); \n \n if (rootNode.isJsonObject()) { \n JsonObject details = rootNode.getAsJsonObject(); \n JsonElement nameNode = details.get(\"name\"); \n System.out.println(\"Name: \" +nameNode.getAsString()); \n \n JsonElement ageNode = details.get(\"age\"); \n System.out.println(\"Age: \" + ageNode.getAsInt()); \n \n JsonElement verifiedNode = details.get(\"verified\"); \n System.out.println(\"Verified: \" + (verifiedNode.getAsBoolean() ? \"Yes\":\"No\")); \n JsonArray marks = details.getAsJsonArray(\"marks\"); \n \n for (int i = 0; i < marks.size(); i++) { \n JsonPrimitive value = marks.get(i).getAsJsonPrimitive(); \n System.out.print(value.getAsInt() + \" \"); \n } \n } \n } \n}" }, { "code": null, "e": 4409, "s": 4355, "text": "Compile the classes using javac compiler as follows −" }, { "code": null, "e": 4451, "s": 4409, "text": "C:\\GSON_WORKSPACE>javac GsonTester.java \n" }, { "code": null, "e": 4494, "s": 4451, "text": "Now run the GsonTester to see the result −" }, { "code": null, "e": 4530, "s": 4494, "text": "C:\\GSON_WORKSPACE>java GsonTester \n" }, { "code": null, "e": 4549, "s": 4530, "text": "Verify the output." }, { "code": null, "e": 4603, "s": 4549, "text": "Name: Mahesh Kumar \nAge: 21 \nVerified: No \n100 90 85\n" }, { "code": null, "e": 4610, "s": 4603, "text": " Print" }, { "code": null, "e": 4621, "s": 4610, "text": " Add Notes" } ]
React-Bootstrap Tabs Component - GeeksforGeeks
24 Sep, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. Tabs Component provides a way to make form dynamic tabbed interfaces. With the help of tabs, the user can switch between components present in given different tabs. We can use the following approach in ReactJS to use the react-bootstrap tabs Component. Tabs Props: activeKey: It is used to mark the tab as active based on the matching event key. defaultActiveKey: It is used to indicate the default active key that is selected on start. id: It is the HTML id attribute required when no generateChildId prop is specified. mountOnEnter: It is used to mount tabs. onSelect: It is a callback function that is triggered when a tab is selected. transition: For all children <TabPane>, it is used to set a default animation strategy. unmountOnExit: It is used to unmount the tabs. variant: It is used to define the navigation style. Tab Props: disabled: It is used to disable the component. eventKey: It is basically a unique identifier for the component. tabClassName: It is used to add the class name for the tab styling. title: It is used to indicate the title for the tab component. TabContainer Props: activeKey: It is used for the eventKey of the current tab which is active. defaultActiveKey: It is used for the default eventKey for the tab. generateChildId: It is a function that is used to generate the unique id for child tab <TabPane>s and <NavItem>s on the basis of eventKey and type which is passed as a parameter to this function. id: It is the normal HTML id attribute for identification. mountOnEnter: It is used to wait until first “enter” transition to mount the tab. onSelect: It is a callback that is triggered when a tab is selected. transition: For all children, it is used to set a default animation strategy. unmountOnExit: It is used to unmount the tab. TabContent Props: as: It can be used as a custom element type for this component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. TabPane Props: active: It is used to toggle the active state of the TabPane. aria-labelledby: It is used to pass the aria labeled attribute to TabPane. as: It can be used as a custom element type for this component. eventKey: It is used a key that associates TabPane with help of its controlling NavLink id: It is the normal HTML id attribute for identification. mountOnEnter: It is used to wait until first “enter” transition to mount the tab. onEnter: When animation is not false, it is used to transition the OnEnter callback. onEntered: When animation is not false, it is used to transition the OnEntered callback. onEntering: When animation is not false, it is used to transition the OnEntering callback. onExit: When animation is not false, it is used to transition the OnExit callback. onExited: When animation is not false, it is used to transition the OnExited callback. onExiting: When animation is not false, it is used to transition the OnExiting callback. transition: It is used to show the animation when hiding or showing the <TabPane>s unmountOnExit: It is used to unmount the tab. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import Tabs from 'react-bootstrap/Tabs'; import Tab from 'react-bootstrap/Tab'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Tab Component</h4> <Tabs defaultActiveKey="second"> <Tab eventKey="first" title="Dashboard"> Hii, I am 1st tab content </Tab> <Tab eventKey="second" title="Setting"> Hii, I am 2nd tab content </Tab> <Tab eventKey="third" title="Aboutus"> Hii, I am 3rd tab content </Tab> </Tabs> </div> ); } Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/components/tabs/ anikakapoor React-Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to pass data from one component to other component in ReactJS ? ReactJS useNavigate() Hook Re-rendering Components in ReactJS How to set background images in ReactJS ? Axios in React: A Guide for Beginners Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25591, "s": 25560, "text": " \n24 Sep, 2021\n" }, { "code": null, "e": 25926, "s": 25591, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Tabs Component provides a way to make form dynamic tabbed interfaces. With the help of tabs, the user can switch between components present in given different tabs. We can use the following approach in ReactJS to use the react-bootstrap tabs Component." }, { "code": null, "e": 25938, "s": 25926, "text": "Tabs Props:" }, { "code": null, "e": 26019, "s": 25938, "text": "activeKey: It is used to mark the tab as active based on the matching event key." }, { "code": null, "e": 26110, "s": 26019, "text": "defaultActiveKey: It is used to indicate the default active key that is selected on start." }, { "code": null, "e": 26194, "s": 26110, "text": "id: It is the HTML id attribute required when no generateChildId prop is specified." }, { "code": null, "e": 26234, "s": 26194, "text": "mountOnEnter: It is used to mount tabs." }, { "code": null, "e": 26312, "s": 26234, "text": "onSelect: It is a callback function that is triggered when a tab is selected." }, { "code": null, "e": 26400, "s": 26312, "text": "transition: For all children <TabPane>, it is used to set a default animation strategy." }, { "code": null, "e": 26447, "s": 26400, "text": "unmountOnExit: It is used to unmount the tabs." }, { "code": null, "e": 26499, "s": 26447, "text": "variant: It is used to define the navigation style." }, { "code": null, "e": 26510, "s": 26499, "text": "Tab Props:" }, { "code": null, "e": 26557, "s": 26510, "text": "disabled: It is used to disable the component." }, { "code": null, "e": 26622, "s": 26557, "text": "eventKey: It is basically a unique identifier for the component." }, { "code": null, "e": 26690, "s": 26622, "text": "tabClassName: It is used to add the class name for the tab styling." }, { "code": null, "e": 26753, "s": 26690, "text": "title: It is used to indicate the title for the tab component." }, { "code": null, "e": 26773, "s": 26753, "text": "TabContainer Props:" }, { "code": null, "e": 26848, "s": 26773, "text": "activeKey: It is used for the eventKey of the current tab which is active." }, { "code": null, "e": 26915, "s": 26848, "text": "defaultActiveKey: It is used for the default eventKey for the tab." }, { "code": null, "e": 27112, "s": 26915, "text": "generateChildId: It is a function that is used to generate the unique id for child tab <TabPane>s and <NavItem>s on the basis of eventKey and type which is passed as a parameter to this function." }, { "code": null, "e": 27171, "s": 27112, "text": "id: It is the normal HTML id attribute for identification." }, { "code": null, "e": 27253, "s": 27171, "text": "mountOnEnter: It is used to wait until first “enter” transition to mount the tab." }, { "code": null, "e": 27322, "s": 27253, "text": "onSelect: It is a callback that is triggered when a tab is selected." }, { "code": null, "e": 27400, "s": 27322, "text": "transition: For all children, it is used to set a default animation strategy." }, { "code": null, "e": 27446, "s": 27400, "text": "unmountOnExit: It is used to unmount the tab." }, { "code": null, "e": 27464, "s": 27446, "text": "TabContent Props:" }, { "code": null, "e": 27528, "s": 27464, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 27612, "s": 27528, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 27627, "s": 27612, "text": "TabPane Props:" }, { "code": null, "e": 27689, "s": 27627, "text": "active: It is used to toggle the active state of the TabPane." }, { "code": null, "e": 27764, "s": 27689, "text": "aria-labelledby: It is used to pass the aria labeled attribute to TabPane." }, { "code": null, "e": 27828, "s": 27764, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 27916, "s": 27828, "text": "eventKey: It is used a key that associates TabPane with help of its controlling NavLink" }, { "code": null, "e": 27975, "s": 27916, "text": "id: It is the normal HTML id attribute for identification." }, { "code": null, "e": 28057, "s": 27975, "text": "mountOnEnter: It is used to wait until first “enter” transition to mount the tab." }, { "code": null, "e": 28142, "s": 28057, "text": "onEnter: When animation is not false, it is used to transition the OnEnter callback." }, { "code": null, "e": 28231, "s": 28142, "text": "onEntered: When animation is not false, it is used to transition the OnEntered callback." }, { "code": null, "e": 28322, "s": 28231, "text": "onEntering: When animation is not false, it is used to transition the OnEntering callback." }, { "code": null, "e": 28405, "s": 28322, "text": "onExit: When animation is not false, it is used to transition the OnExit callback." }, { "code": null, "e": 28492, "s": 28405, "text": "onExited: When animation is not false, it is used to transition the OnExited callback." }, { "code": null, "e": 28581, "s": 28492, "text": "onExiting: When animation is not false, it is used to transition the OnExiting callback." }, { "code": null, "e": 28664, "s": 28581, "text": "transition: It is used to show the animation when hiding or showing the <TabPane>s" }, { "code": null, "e": 28710, "s": 28664, "text": "unmountOnExit: It is used to unmount the tab." }, { "code": null, "e": 28794, "s": 28710, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 28844, "s": 28794, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 28942, "s": 28844, "text": "\nStep 1: Create a React application using the following command:\nnpx create-react-app foldername\n" }, { "code": null, "e": 29006, "s": 28942, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 29038, "s": 29006, "text": "npx create-react-app foldername" }, { "code": null, "e": 29154, "s": 29038, "text": "\nStep 2: After creating your project folder i.e. foldername, move to it using the following command:\ncd foldername\n" }, { "code": null, "e": 29254, "s": 29154, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 29268, "s": 29254, "text": "cd foldername" }, { "code": null, "e": 29426, "s": 29268, "text": "\nStep 3: After creating the ReactJS application, Install the required module using the following command:\nnpm install react-bootstrap \nnpm install bootstrap\n" }, { "code": null, "e": 29531, "s": 29426, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 29582, "s": 29531, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 29634, "s": 29582, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 29652, "s": 29634, "text": "Project Structure" }, { "code": null, "e": 29782, "s": 29652, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 29789, "s": 29782, "text": "App.js" }, { "code": "\n\n\n\n\n\n\nimport React from 'react'; \nimport 'bootstrap/dist/css/bootstrap.css'; \nimport Tabs from 'react-bootstrap/Tabs'; \nimport Tab from 'react-bootstrap/Tab'; \n \nexport default function App() { \n return ( \n <div style={{ display: 'block', width: 700, padding: 30 }}> \n <h4>React-Bootstrap Tab Component</h4> \n <Tabs defaultActiveKey=\"second\"> \n <Tab eventKey=\"first\" title=\"Dashboard\"> \n Hii, I am 1st tab content \n </Tab> \n <Tab eventKey=\"second\" title=\"Setting\"> \n Hii, I am 2nd tab content \n </Tab> \n <Tab eventKey=\"third\" title=\"Aboutus\"> \n Hii, I am 3rd tab content \n </Tab> \n </Tabs> \n </div> \n ); \n}\n\n\n\n\n\n", "e": 30506, "s": 29799, "text": null }, { "code": null, "e": 30619, "s": 30506, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 30629, "s": 30619, "text": "npm start" }, { "code": null, "e": 30728, "s": 30629, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 30790, "s": 30728, "text": "Reference: https://react-bootstrap.github.io/components/tabs/" }, { "code": null, "e": 30802, "s": 30790, "text": "anikakapoor" }, { "code": null, "e": 30820, "s": 30802, "text": "\nReact-Bootstrap\n" }, { "code": null, "e": 30830, "s": 30820, "text": "\nReactJS\n" }, { "code": null, "e": 30849, "s": 30830, "text": "\nWeb Technologies\n" }, { "code": null, "e": 31054, "s": 30849, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 31122, "s": 31054, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 31149, "s": 31122, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 31184, "s": 31149, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 31226, "s": 31184, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 31264, "s": 31226, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 31304, "s": 31264, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31337, "s": 31304, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31382, "s": 31337, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31432, "s": 31382, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Can Two IP Addresses Be Same? - GeeksforGeeks
09 Sep, 2021 Overview :A simple definition of Computer Network is an interconnection of two or more computers(includes personal computers, mobiles, laptops, etc, network devices like a router, switch, bridge, etc) for the purpose of transferring data. Now one obvious question arises how does one computer in the network identify another? Here, is the answer. By MAC address and IP address MAC (Media Access Control) is 6 bytes =48 bits =12 nibbles (1 nibble=4bits) long . Note –It is a hardware address given to each NIC(Network Interface Card). Can two devices have the same MAC address?No.Can two devices have the same IP address? Yes Can two devices have the same MAC address?No. Can two devices have the same IP address? Yes Why and How :Now comes the interesting part, WHY and HOW? Let me first explain WHY and then HOW ingeniously we do that as follows. Why : Today the two most widely used version of IP is IPv4 and IPv6. IPv4 is 32 bit and IPv6 is 128 bit if we talk about IPv4 it has only 32 bits means 2^32 addresses possible (max) which is roughly equal to 4 billion(10^9) addresses. but to have more than billions of devices in the world is possible as now we have lots of IoT devices, smartphones, even smart fridges which are connected to the internet. so we have to find out some solution that how can we reuse the already used IP address. otherwise we will run out of IP How :To solve this problem we introduce two terminologies Public IP address and Private IP address are as follows. Public IP address and Private IP address :Any IP address in this range is the private IP address and the remaining are public IP addresses. Private IPs are free of cost Public IPs are costly (ISPs like Jio, Airtel purchase public IPs) 10.0.0.0 - 10.255.255.255/8 172.16.0.0 - 172.31.255.255/12 192.168.0.0 - 192.168.255.255/16 Diagram Representation –Here we have two routers Jio and Airtel both are connecting private networks and public networks. Remember we do not talk directly to Google or Amazon server or any public device directly, we talk via our ISP . we talk to ISP router and ISP router talk to the Internet. All ISP or public routers have public IP addresses that they purchase and all have different public IP addresses, they can’t be the same, as in fig. Airtel public IP is 43.5.6.1 and Jio public IP is 53.9.7.1. Now under each public IP address, any private IP address range can be used (private IP range listed above). That’s why host A and host B in fig. can have the same private IP address. so within one network for ex-Airtel, all private IPs must be different but for hosts, on two different networks ex-Airtel and Jio hosts may have the same private IP address this way we reuse the private IPs. Public and private network Conclusion :All public IPs assigned to Routers of ISPs or Routers connecting to Internet are unique. but private IPs of two hosts can be the same if both are connected to different public networks. So the combination of public and private IP identifies your device uniquely. One interesting activity you can do, take two or more phones to connect all the phones with the hotspot of anyone’s phone. now on all the phones type on Google “what is my IP address” it will give you the public IP to which your phone is connected, (not the private IP), you will see all of your phones have the same public IP (because all of you are connected to the same public router) and to see your private IP go to setting and then Wi-Fi and then Wi-Fi setting. You will see your private IP address ( for your mobile model please search on google how to find private IP). One more thing you will note here is that all of your private IPs will differ in a uniform manner. Because all of you have the same public network your private IP can’t be the same. mohammadaquib372 Picked Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Advanced Encryption Standard (AES) Intrusion Detection System (IDS) GSM in Wireless Communication Multiple Access Protocols in Computer Network Stop and Wait ARQ Cryptography and its Types Secure Socket Layer (SSL) Introduction and IPv4 Datagram Header TCP Congestion Control Block Cipher modes of Operation
[ { "code": null, "e": 24534, "s": 24506, "text": "\n09 Sep, 2021" }, { "code": null, "e": 24912, "s": 24534, "text": "Overview :A simple definition of Computer Network is an interconnection of two or more computers(includes personal computers, mobiles, laptops, etc, network devices like a router, switch, bridge, etc) for the purpose of transferring data. Now one obvious question arises how does one computer in the network identify another? Here, is the answer. By MAC address and IP address" }, { "code": null, "e": 24997, "s": 24912, "text": "MAC (Media Access Control) is 6 bytes \n=48 bits =12 nibbles\n(1 nibble=4bits) long . " }, { "code": null, "e": 25072, "s": 24997, "text": "Note –It is a hardware address given to each NIC(Network Interface Card). " }, { "code": null, "e": 25164, "s": 25072, "text": "Can two devices have the same MAC address?No.Can two devices have the same IP address? Yes" }, { "code": null, "e": 25210, "s": 25164, "text": "Can two devices have the same MAC address?No." }, { "code": null, "e": 25257, "s": 25210, "text": "Can two devices have the same IP address? Yes" }, { "code": null, "e": 25388, "s": 25257, "text": "Why and How :Now comes the interesting part, WHY and HOW? Let me first explain WHY and then HOW ingeniously we do that as follows." }, { "code": null, "e": 25394, "s": 25388, "text": "Why :" }, { "code": null, "e": 25457, "s": 25394, "text": "Today the two most widely used version of IP is IPv4 and IPv6." }, { "code": null, "e": 25492, "s": 25457, "text": "IPv4 is 32 bit and IPv6 is 128 bit" }, { "code": null, "e": 25555, "s": 25492, "text": "if we talk about IPv4 it has only 32 bits means 2^32 addresses" }, { "code": null, "e": 25623, "s": 25555, "text": "possible (max) which is roughly equal to 4 billion(10^9) addresses." }, { "code": null, "e": 25690, "s": 25623, "text": "but to have more than billions of devices in the world is possible" }, { "code": null, "e": 25750, "s": 25690, "text": "as now we have lots of IoT devices, smartphones, even smart" }, { "code": null, "e": 25795, "s": 25750, "text": "fridges which are connected to the internet." }, { "code": null, "e": 25915, "s": 25795, "text": "so we have to find out some solution that how can we reuse the already used IP address. otherwise we will run out of IP" }, { "code": null, "e": 26030, "s": 25915, "text": "How :To solve this problem we introduce two terminologies Public IP address and Private IP address are as follows." }, { "code": null, "e": 26170, "s": 26030, "text": "Public IP address and Private IP address :Any IP address in this range is the private IP address and the remaining are public IP addresses." }, { "code": null, "e": 26199, "s": 26170, "text": "Private IPs are free of cost" }, { "code": null, "e": 26265, "s": 26199, "text": "Public IPs are costly (ISPs like Jio, Airtel purchase public IPs)" }, { "code": null, "e": 26382, "s": 26265, "text": "10.0.0.0 - 10.255.255.255/8\n172.16.0.0 - 172.31.255.255/12\n192.168.0.0 - 192.168.255.255/16" }, { "code": null, "e": 27277, "s": 26382, "text": "Diagram Representation –Here we have two routers Jio and Airtel both are connecting private networks and public networks. Remember we do not talk directly to Google or Amazon server or any public device directly, we talk via our ISP . we talk to ISP router and ISP router talk to the Internet. All ISP or public routers have public IP addresses that they purchase and all have different public IP addresses, they can’t be the same, as in fig. Airtel public IP is 43.5.6.1 and Jio public IP is 53.9.7.1. Now under each public IP address, any private IP address range can be used (private IP range listed above). That’s why host A and host B in fig. can have the same private IP address. so within one network for ex-Airtel, all private IPs must be different but for hosts, on two different networks ex-Airtel and Jio hosts may have the same private IP address this way we reuse the private IPs." }, { "code": null, "e": 27304, "s": 27277, "text": "Public and private network" }, { "code": null, "e": 28341, "s": 27304, "text": "Conclusion :All public IPs assigned to Routers of ISPs or Routers connecting to Internet are unique. but private IPs of two hosts can be the same if both are connected to different public networks. So the combination of public and private IP identifies your device uniquely. One interesting activity you can do, take two or more phones to connect all the phones with the hotspot of anyone’s phone. now on all the phones type on Google “what is my IP address” it will give you the public IP to which your phone is connected, (not the private IP), you will see all of your phones have the same public IP (because all of you are connected to the same public router) and to see your private IP go to setting and then Wi-Fi and then Wi-Fi setting. You will see your private IP address ( for your mobile model please search on google how to find private IP). One more thing you will note here is that all of your private IPs will differ in a uniform manner. Because all of you have the same public network your private IP can’t be the same. " }, { "code": null, "e": 28358, "s": 28341, "text": "mohammadaquib372" }, { "code": null, "e": 28365, "s": 28358, "text": "Picked" }, { "code": null, "e": 28383, "s": 28365, "text": "Computer Networks" }, { "code": null, "e": 28401, "s": 28383, "text": "Computer Networks" }, { "code": null, "e": 28499, "s": 28401, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28508, "s": 28499, "text": "Comments" }, { "code": null, "e": 28521, "s": 28508, "text": "Old Comments" }, { "code": null, "e": 28556, "s": 28521, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 28589, "s": 28556, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 28619, "s": 28589, "text": "GSM in Wireless Communication" }, { "code": null, "e": 28665, "s": 28619, "text": "Multiple Access Protocols in Computer Network" }, { "code": null, "e": 28683, "s": 28665, "text": "Stop and Wait ARQ" }, { "code": null, "e": 28710, "s": 28683, "text": "Cryptography and its Types" }, { "code": null, "e": 28736, "s": 28710, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 28774, "s": 28736, "text": "Introduction and IPv4 Datagram Header" }, { "code": null, "e": 28797, "s": 28774, "text": "TCP Congestion Control" } ]
jQuery | Move an element into another element - GeeksforGeeks
28 Mar, 2019 There are two methods to move an element inside another element are listed below: Method 1: Using append() method: This append() Method in jQuery is used to insert some content at the end of the selected elements. Syntax: $(selector).append( content, function(index, html) ) Parameters: This method accepts two parameters as mentioned above and described below: content: It is required parameter and used to specify the content which is to be inserted at the end of selected elements. The possible value of contents are HTML elements, jQuery objects and DOM elements. function(index, html): It is optional parameter and used to specify the function that will return the content to be inserted.index: It is used to return the index position of the element.html: It is used to return the current HTML of the selected element. index: It is used to return the index position of the element. html: It is used to return the current HTML of the selected element. Example: <!DOCTYPE html> <html> <head> <title> JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #child { height: 40px; width: 100px; margin: 0 auto; color: yellow } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <div id= "parent"></div> <br> <h4 id= "child"> A Computer Science Portal for geeks </h4> <br> <button onclick="myGeeks()"> move </button> <!-- Script to move element --> <script> function myGeeks() { $("#parent").append($("#child")); } </script> </body> </html> Output: Before clicking the button: After clicking the button: Method 2: Using prepend() Method: The prepend() method is an inbuilt method in jQuery which is used to insert a specified content at the beginning of the selected element. Syntax: $(selector).prepend(content, function) Parameters: This method accept two parameters as mentioned above and described below: content: It is required parameter which is used to specify the content need to be inserted. function: It is optional parameter which is used to specify the function to perform after call. Example: <!DOCTYPE html> <html> <head> <title> JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #child { height: 40px; width: 100px; margin: 0 auto; color: yellow } </style></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <div id= "parent"></div> <br> <h4 id= "child"> A Computer Science Portal for geeks </h4> <br> <button onclick="myGeeks()"> move </button> <!-- Script to move element --> <script> function myGeeks() { $("#parent").prepend($("#child")); } </script> </body> </html> Output: Before clicking the button: After clicking the button: jQuery-Misc JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? Scroll to the top of the page using JavaScript/jQuery jQuery | children() with Examples How to prevent Body from scrolling when a modal is opened using jQuery ? How to redirect to a particular section of a page using HTML or jQuery? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26654, "s": 26626, "text": "\n28 Mar, 2019" }, { "code": null, "e": 26736, "s": 26654, "text": "There are two methods to move an element inside another element are listed below:" }, { "code": null, "e": 26868, "s": 26736, "text": "Method 1: Using append() method: This append() Method in jQuery is used to insert some content at the end of the selected elements." }, { "code": null, "e": 26876, "s": 26868, "text": "Syntax:" }, { "code": null, "e": 26929, "s": 26876, "text": "$(selector).append( content, function(index, html) )" }, { "code": null, "e": 27016, "s": 26929, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 27222, "s": 27016, "text": "content: It is required parameter and used to specify the content which is to be inserted at the end of selected elements. The possible value of contents are HTML elements, jQuery objects and DOM elements." }, { "code": null, "e": 27478, "s": 27222, "text": "function(index, html): It is optional parameter and used to specify the function that will return the content to be inserted.index: It is used to return the index position of the element.html: It is used to return the current HTML of the selected element." }, { "code": null, "e": 27541, "s": 27478, "text": "index: It is used to return the index position of the element." }, { "code": null, "e": 27610, "s": 27541, "text": "html: It is used to return the current HTML of the selected element." }, { "code": null, "e": 27619, "s": 27610, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #child { height: 40px; width: 100px; margin: 0 auto; color: yellow } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <div id= \"parent\"></div> <br> <h4 id= \"child\"> A Computer Science Portal for geeks </h4> <br> <button onclick=\"myGeeks()\"> move </button> <!-- Script to move element --> <script> function myGeeks() { $(\"#parent\").append($(\"#child\")); } </script> </body> </html>", "e": 28594, "s": 27619, "text": null }, { "code": null, "e": 28602, "s": 28594, "text": "Output:" }, { "code": null, "e": 28630, "s": 28602, "text": "Before clicking the button:" }, { "code": null, "e": 28657, "s": 28630, "text": "After clicking the button:" }, { "code": null, "e": 28829, "s": 28657, "text": "Method 2: Using prepend() Method: The prepend() method is an inbuilt method in jQuery which is used to insert a specified content at the beginning of the selected element." }, { "code": null, "e": 28837, "s": 28829, "text": "Syntax:" }, { "code": null, "e": 28876, "s": 28837, "text": "$(selector).prepend(content, function)" }, { "code": null, "e": 28962, "s": 28876, "text": "Parameters: This method accept two parameters as mentioned above and described below:" }, { "code": null, "e": 29054, "s": 28962, "text": "content: It is required parameter which is used to specify the content need to be inserted." }, { "code": null, "e": 29150, "s": 29054, "text": "function: It is optional parameter which is used to specify the function to perform after call." }, { "code": null, "e": 29159, "s": 29150, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <style> #parent { height: 100px; width: 300px; background: green; margin: 0 auto; } #child { height: 40px; width: 100px; margin: 0 auto; color: yellow } </style></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <div id= \"parent\"></div> <br> <h4 id= \"child\"> A Computer Science Portal for geeks </h4> <br> <button onclick=\"myGeeks()\"> move </button> <!-- Script to move element --> <script> function myGeeks() { $(\"#parent\").prepend($(\"#child\")); } </script> </body> </html>", "e": 30136, "s": 29159, "text": null }, { "code": null, "e": 30144, "s": 30136, "text": "Output:" }, { "code": null, "e": 30172, "s": 30144, "text": "Before clicking the button:" }, { "code": null, "e": 30199, "s": 30172, "text": "After clicking the button:" }, { "code": null, "e": 30211, "s": 30199, "text": "jQuery-Misc" }, { "code": null, "e": 30218, "s": 30211, "text": "JQuery" }, { "code": null, "e": 30235, "s": 30218, "text": "Web Technologies" }, { "code": null, "e": 30262, "s": 30235, "text": "Web technologies Questions" }, { "code": null, "e": 30360, "s": 30262, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30415, "s": 30360, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 30469, "s": 30415, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 30503, "s": 30469, "text": "jQuery | children() with Examples" }, { "code": null, "e": 30576, "s": 30503, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30648, "s": 30576, "text": "How to redirect to a particular section of a page using HTML or jQuery?" }, { "code": null, "e": 30688, "s": 30648, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30721, "s": 30688, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30766, "s": 30721, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30809, "s": 30766, "text": "How to fetch data from an API in ReactJS ?" } ]
Flutter - Internationalization - GeeksforGeeks
15 Jan, 2021 Internationalization refers to the term that an app is available in different regional languages for better reach to people. For this, we have to make an app available in different languages and suitable layouts for them. Flutter provides methods to internationalize the app. We will be discussing how to localize a MaterialApp. Flutter supports 78 different languages. By default, English (US) is the localized language. First, we have to add the below lines of code in the pubspec.yaml dependencies file as shown below: dependencies: flutter: sdk: flutter flutter_localizations: # ADD sdk: flutter # ADD intl: ^0.17.0-nullsafety.2 # ADD And in the flutter section in pubspec.yaml add the code : generate: true Click on the pub get to get all the dependencies. Now create a new yaml file (as l10n.yaml) in the root directory of the project with the following content: arb-dir: lib/l10n template-arb-file: app_en.arb output-localization-file: app_localizations.dart Add a directory named l10n in the lib directory and then add the files for the languages. Here we will be adding data for two languages i.e. English and Hindi. Name: app_en.arb Content: { "helloWorld": "GeeksforGeeks", "displayText":"This is a sample App", "@helloWorld": { "description": "SampleApp for GeeksforGeeks" } } And for the second file Name: app_hi.arb Content: { "helloWorld": "गीक्स फॉर गीक्स ", "displayText":"यह एक सैंपल ऐप है" } Now restart the app so that app_localizations.dart file is generated in the following directory: <project_dir>.dart_tools/flutter_get/genl10n Now we have to write below lines of codes to make the app internationalize – First, we have to import app_localizations then we have to add the following two properties to the MaterialApp as import 'package:flutter_gen/gen_l10n/app_localizations.dart'; localizationsDelegates property: It defines all the localized resources for the application. supportedLocales property: It provides a list of languages supported by the app. onGeneratedTitle property: It is called after the widget is set up which means localization is available. Example: Dart import 'package:flutter/material.dart';import 'package:flutter_gen/gen_l10n/app_localizations.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( onGenerateTitle: (context) => AppLocalizations.of(context).helloWorld, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, theme: ThemeData(primarySwatch: Colors.green), home: MyHomePage(), ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(AppLocalizations.of(context).helloWorld), ), body: Center( child: Text( AppLocalizations.of(context).displayText, style: TextStyle(fontSize: 30), ), ), ); }} Output: We can switch Languages by changing the Language of the device in the settings. android Flutter Picked Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget Android Studio Setup for Flutter Development Flutter - Custom Bottom Navigation Bar Flutter Tutorial Flutter - Flexible Widget Flutter - Stack Widget Flutter - Positioned Widget
[ { "code": null, "e": 25261, "s": 25233, "text": "\n15 Jan, 2021" }, { "code": null, "e": 25590, "s": 25261, "text": "Internationalization refers to the term that an app is available in different regional languages for better reach to people. For this, we have to make an app available in different languages and suitable layouts for them. Flutter provides methods to internationalize the app. We will be discussing how to localize a MaterialApp." }, { "code": null, "e": 25683, "s": 25590, "text": "Flutter supports 78 different languages. By default, English (US) is the localized language." }, { "code": null, "e": 25783, "s": 25683, "text": "First, we have to add the below lines of code in the pubspec.yaml dependencies file as shown below:" }, { "code": null, "e": 25919, "s": 25783, "text": "dependencies:\n flutter:\n sdk: flutter\n flutter_localizations: # ADD\n sdk: flutter # ADD\n intl: ^0.17.0-nullsafety.2 # ADD" }, { "code": null, "e": 25977, "s": 25919, "text": "And in the flutter section in pubspec.yaml add the code :" }, { "code": null, "e": 25993, "s": 25977, "text": " generate: true" }, { "code": null, "e": 26043, "s": 25993, "text": "Click on the pub get to get all the dependencies." }, { "code": null, "e": 26150, "s": 26043, "text": "Now create a new yaml file (as l10n.yaml) in the root directory of the project with the following content:" }, { "code": null, "e": 26247, "s": 26150, "text": "arb-dir: lib/l10n\ntemplate-arb-file: app_en.arb\noutput-localization-file: app_localizations.dart" }, { "code": null, "e": 26407, "s": 26247, "text": "Add a directory named l10n in the lib directory and then add the files for the languages. Here we will be adding data for two languages i.e. English and Hindi." }, { "code": null, "e": 26582, "s": 26407, "text": "Name: app_en.arb\nContent:\n{\n \"helloWorld\": \"GeeksforGeeks\",\n \"displayText\":\"This is a sample App\",\n \"@helloWorld\": {\n \"description\": \"SampleApp for GeeksforGeeks\"\n }\n}" }, { "code": null, "e": 26606, "s": 26582, "text": "And for the second file" }, { "code": null, "e": 26708, "s": 26606, "text": "Name: app_hi.arb\nContent:\n{\n \"helloWorld\": \"गीक्स फॉर गीक्स \",\n \"displayText\":\"यह एक सैंपल ऐप है\"\n}" }, { "code": null, "e": 26806, "s": 26708, "text": "Now restart the app so that app_localizations.dart file is generated in the following directory:" }, { "code": null, "e": 26851, "s": 26806, "text": "<project_dir>.dart_tools/flutter_get/genl10n" }, { "code": null, "e": 26928, "s": 26851, "text": "Now we have to write below lines of codes to make the app internationalize –" }, { "code": null, "e": 27042, "s": 26928, "text": "First, we have to import app_localizations then we have to add the following two properties to the MaterialApp as" }, { "code": null, "e": 27104, "s": 27042, "text": "import 'package:flutter_gen/gen_l10n/app_localizations.dart';" }, { "code": null, "e": 27197, "s": 27104, "text": "localizationsDelegates property: It defines all the localized resources for the application." }, { "code": null, "e": 27278, "s": 27197, "text": "supportedLocales property: It provides a list of languages supported by the app." }, { "code": null, "e": 27384, "s": 27278, "text": "onGeneratedTitle property: It is called after the widget is set up which means localization is available." }, { "code": null, "e": 27393, "s": 27384, "text": "Example:" }, { "code": null, "e": 27398, "s": 27393, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:flutter_gen/gen_l10n/app_localizations.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( onGenerateTitle: (context) => AppLocalizations.of(context).helloWorld, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, theme: ThemeData(primarySwatch: Colors.green), home: MyHomePage(), ); }} class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(AppLocalizations.of(context).helloWorld), ), body: Center( child: Text( AppLocalizations.of(context).displayText, style: TextStyle(fontSize: 30), ), ), ); }}", "e": 28464, "s": 27398, "text": null }, { "code": null, "e": 28472, "s": 28464, "text": "Output:" }, { "code": null, "e": 28552, "s": 28472, "text": "We can switch Languages by changing the Language of the device in the settings." }, { "code": null, "e": 28560, "s": 28552, "text": "android" }, { "code": null, "e": 28568, "s": 28560, "text": "Flutter" }, { "code": null, "e": 28575, "s": 28568, "text": "Picked" }, { "code": null, "e": 28580, "s": 28575, "text": "Dart" }, { "code": null, "e": 28588, "s": 28580, "text": "Flutter" }, { "code": null, "e": 28686, "s": 28588, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28725, "s": 28686, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28751, "s": 28725, "text": "ListView Class in Flutter" }, { "code": null, "e": 28777, "s": 28751, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 28800, "s": 28777, "text": "Flutter - Stack Widget" }, { "code": null, "e": 28845, "s": 28800, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 28884, "s": 28845, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 28901, "s": 28884, "text": "Flutter Tutorial" }, { "code": null, "e": 28927, "s": 28901, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 28950, "s": 28927, "text": "Flutter - Stack Widget" } ]
Java Program to convert from decimal to binary
To convert decimal to binary, Java has a method “Integer.toBinaryString()”. The method returns a string representation of the integer argument as an unsigned integer in base 2. Let us first declare and initialize an integer variable. int dec = 25; Convert it to binary. String bin = Integer.toBinaryString(dec); Now display the “bin” string, which consists of the Binary value. Here is the complete example. Live Demo public class Demo { public static void main( String args[] ) { int dec = 25; // converting to binary and representing it in a string String bin = Integer.toBinaryString(dec); System.out.println(bin); } } 11001
[ { "code": null, "e": 1239, "s": 1062, "text": "To convert decimal to binary, Java has a method “Integer.toBinaryString()”. The method returns a string representation of the integer argument as an unsigned integer in base 2." }, { "code": null, "e": 1296, "s": 1239, "text": "Let us first declare and initialize an integer variable." }, { "code": null, "e": 1310, "s": 1296, "text": "int dec = 25;" }, { "code": null, "e": 1332, "s": 1310, "text": "Convert it to binary." }, { "code": null, "e": 1374, "s": 1332, "text": "String bin = Integer.toBinaryString(dec);" }, { "code": null, "e": 1470, "s": 1374, "text": "Now display the “bin” string, which consists of the Binary value. Here is the complete example." }, { "code": null, "e": 1481, "s": 1470, "text": " Live Demo" }, { "code": null, "e": 1715, "s": 1481, "text": "public class Demo {\n public static void main( String args[] ) {\n int dec = 25;\n // converting to binary and representing it in a string\n String bin = Integer.toBinaryString(dec);\n System.out.println(bin);\n }\n}" }, { "code": null, "e": 1721, "s": 1715, "text": "11001" } ]
Java 8 | BiConsumer Interface in Java with Examples - GeeksforGeeks
14 Sep, 2021 The BiConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function that takes in two arguments and produces a result. However, these kinds of functions doesn’t return any value. This functional interface takes in two generics, namely:- T: denotes the type of the first input argument to the operation U: denotes the type of the second input argument to the operation The lambda expression assigned to an object of BiConsumer type is used to define its accept() which eventually applies the given operation to its arguments. BiConsumers are useful when it is not required to return any value as they are expected to operate via side-effects. The BiConsumer interface consists of the following two functions: 1. accept() This method accepts two values and performs the operation on the given arguments Syntax: void accept(T t, U u) Parameters: This method takes in two parameters: t– the first input argument u– the second input argument Returns: This method does not return any value. Below is the code to illustrate accept() method: Program 1: Program to compare 2 list of integers using BiConsumer’s accept() method: Java // Java Program to demonstrate// BiConsumer's accept() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class GFG { public static void main(String args[]) { // Create the first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create the second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); listb.add(2); // BiConsumer to compare both lists BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { if (list1.size() != list2.size()) { System.out.println("False"); } else { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println("False"); return; } System.out.println("True"); } }; equals.accept(lista, listb); }} False 2. andThen() It returns a composed BiConsumer wherein the parameterized BiConsumer will be executed after the first one. If the evaluation of either operation throws an error, it is relayed to the caller of the composed operation. Note: The operation being passed as the argument should be of type BiConsumer. Syntax: default BiConsumer <T, U> andThen(BiConsumer<? super T, ? super U> after) Parameters: This method accepts a parameter after which is the BiConsumer to be applied after the current one.Return Value: This method returns a composed BiConsumer that first applies the current operation first and then the after operation. Exception: This method throws NullPointerException if the after operation is null. Below is the code to illustrate andThen() method: Program 1: Java // Java Program to demonstrate// BiConsumer's andThen() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class Main { public static void main(String args[]) { // Create first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); listb.add(2); // BiConsumer to compare 2 lists of integers BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { if (list1.size() != list2.size()) { System.out.println("False"); } else { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println("False"); return; } System.out.println("True"); } }; // BiConsumer to print 2 lists BiConsumer<List<Integer>, List<Integer> > disp = (list1, list2) -> { list1.stream().forEach(a -> System.out.print(a + " ")); System.out.println(); list2.stream().forEach(a -> System.out.print(a + " ")); System.out.println(); }; // Using addThen() method equals.andThen(disp).accept(lista, listb); }} False 2 1 3 2 1 2 Program 2: To demonstrate when NullPointerException is returned. Java // Java Program to demonstrate// BiConsumer's andThen() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class Main { public static void main(String args[]) { // Create first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); listb.add(2); // BiConsumer to compare 2 lists of integers BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { if (list1.size() != list2.size()) { System.out.println("False"); } else { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println("False"); return; } System.out.println("True"); } }; // BiConsumer to print 2 lists BiConsumer<List<Integer>, List<Integer> > disp = (list1, list2) -> { list1.stream().forEach(a -> System.out.print(a + " ")); System.out.println(); list2.stream().forEach(a -> System.out.print(a + " ")); System.out.println(); }; try { equals.andThen(null).accept(lista, listb); } catch (Exception e) { System.out.println("Exception : " + e); } }} Exception : java.lang.NullPointerException Program 3: To demonstrate how an Exception in after the function is returned and handled. Java // Java Program to demonstrate// BiConsumer's andThen() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class Main { public static void main(String args[]) { // Create first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); // BiConsumer to compare 2 lists of integers BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println("False"); return; } System.out.println("True"); }; // BiConsumer to print 2 lists BiConsumer<List<Integer>, List<Integer> > disp = (list1, list2) -> { list1.stream().forEach(a -> System.out.print(a + " ")); System.out.println(); list2.stream().forEach(a -> System.out.print(a + " ")); System.out.println(); }; try { disp.andThen(equals).accept(lista, listb); } catch (Exception e) { System.out.println("Exception : " + e); } }} 2 1 3 2 1 Exception : java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2 simmytarika5 Java - util package Java 8 java-basics Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25645, "s": 25617, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25935, "s": 25645, "text": "The BiConsumer Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function that takes in two arguments and produces a result. However, these kinds of functions doesn’t return any value." }, { "code": null, "e": 25994, "s": 25935, "text": "This functional interface takes in two generics, namely:- " }, { "code": null, "e": 26059, "s": 25994, "text": "T: denotes the type of the first input argument to the operation" }, { "code": null, "e": 26125, "s": 26059, "text": "U: denotes the type of the second input argument to the operation" }, { "code": null, "e": 26283, "s": 26125, "text": "The lambda expression assigned to an object of BiConsumer type is used to define its accept() which eventually applies the given operation to its arguments. " }, { "code": null, "e": 26401, "s": 26283, "text": "BiConsumers are useful when it is not required to return any value as they are expected to operate via side-effects. " }, { "code": null, "e": 26467, "s": 26401, "text": "The BiConsumer interface consists of the following two functions:" }, { "code": null, "e": 26479, "s": 26467, "text": "1. accept()" }, { "code": null, "e": 26560, "s": 26479, "text": "This method accepts two values and performs the operation on the given arguments" }, { "code": null, "e": 26570, "s": 26560, "text": "Syntax: " }, { "code": null, "e": 26592, "s": 26570, "text": "void accept(T t, U u)" }, { "code": null, "e": 26643, "s": 26592, "text": "Parameters: This method takes in two parameters: " }, { "code": null, "e": 26671, "s": 26643, "text": "t– the first input argument" }, { "code": null, "e": 26700, "s": 26671, "text": "u– the second input argument" }, { "code": null, "e": 26748, "s": 26700, "text": "Returns: This method does not return any value." }, { "code": null, "e": 26797, "s": 26748, "text": "Below is the code to illustrate accept() method:" }, { "code": null, "e": 26883, "s": 26797, "text": "Program 1: Program to compare 2 list of integers using BiConsumer’s accept() method: " }, { "code": null, "e": 26888, "s": 26883, "text": "Java" }, { "code": "// Java Program to demonstrate// BiConsumer's accept() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class GFG { public static void main(String args[]) { // Create the first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create the second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); listb.add(2); // BiConsumer to compare both lists BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { if (list1.size() != list2.size()) { System.out.println(\"False\"); } else { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println(\"False\"); return; } System.out.println(\"True\"); } }; equals.accept(lista, listb); }}", "e": 27989, "s": 26888, "text": null }, { "code": null, "e": 27995, "s": 27989, "text": "False" }, { "code": null, "e": 28010, "s": 27997, "text": "2. andThen()" }, { "code": null, "e": 28228, "s": 28010, "text": "It returns a composed BiConsumer wherein the parameterized BiConsumer will be executed after the first one. If the evaluation of either operation throws an error, it is relayed to the caller of the composed operation." }, { "code": null, "e": 28307, "s": 28228, "text": "Note: The operation being passed as the argument should be of type BiConsumer." }, { "code": null, "e": 28317, "s": 28307, "text": "Syntax: " }, { "code": null, "e": 28400, "s": 28317, "text": "default BiConsumer <T, U> \n andThen(BiConsumer<? super T, ? super U> after)" }, { "code": null, "e": 28643, "s": 28400, "text": "Parameters: This method accepts a parameter after which is the BiConsumer to be applied after the current one.Return Value: This method returns a composed BiConsumer that first applies the current operation first and then the after operation." }, { "code": null, "e": 28726, "s": 28643, "text": "Exception: This method throws NullPointerException if the after operation is null." }, { "code": null, "e": 28776, "s": 28726, "text": "Below is the code to illustrate andThen() method:" }, { "code": null, "e": 28788, "s": 28776, "text": "Program 1: " }, { "code": null, "e": 28793, "s": 28788, "text": "Java" }, { "code": "// Java Program to demonstrate// BiConsumer's andThen() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class Main { public static void main(String args[]) { // Create first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); listb.add(2); // BiConsumer to compare 2 lists of integers BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { if (list1.size() != list2.size()) { System.out.println(\"False\"); } else { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println(\"False\"); return; } System.out.println(\"True\"); } }; // BiConsumer to print 2 lists BiConsumer<List<Integer>, List<Integer> > disp = (list1, list2) -> { list1.stream().forEach(a -> System.out.print(a + \" \")); System.out.println(); list2.stream().forEach(a -> System.out.print(a + \" \")); System.out.println(); }; // Using addThen() method equals.andThen(disp).accept(lista, listb); }}", "e": 30266, "s": 28793, "text": null }, { "code": null, "e": 30285, "s": 30266, "text": "False\n2 1 3 \n2 1 2" }, { "code": null, "e": 30352, "s": 30287, "text": "Program 2: To demonstrate when NullPointerException is returned." }, { "code": null, "e": 30357, "s": 30352, "text": "Java" }, { "code": "// Java Program to demonstrate// BiConsumer's andThen() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class Main { public static void main(String args[]) { // Create first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); listb.add(2); // BiConsumer to compare 2 lists of integers BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { if (list1.size() != list2.size()) { System.out.println(\"False\"); } else { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println(\"False\"); return; } System.out.println(\"True\"); } }; // BiConsumer to print 2 lists BiConsumer<List<Integer>, List<Integer> > disp = (list1, list2) -> { list1.stream().forEach(a -> System.out.print(a + \" \")); System.out.println(); list2.stream().forEach(a -> System.out.print(a + \" \")); System.out.println(); }; try { equals.andThen(null).accept(lista, listb); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 31912, "s": 30357, "text": null }, { "code": null, "e": 31955, "s": 31912, "text": "Exception : java.lang.NullPointerException" }, { "code": null, "e": 32045, "s": 31955, "text": "Program 3: To demonstrate how an Exception in after the function is returned and handled." }, { "code": null, "e": 32050, "s": 32045, "text": "Java" }, { "code": "// Java Program to demonstrate// BiConsumer's andThen() method import java.util.ArrayList;import java.util.List;import java.util.function.BiConsumer; public class Main { public static void main(String args[]) { // Create first list List<Integer> lista = new ArrayList<Integer>(); lista.add(2); lista.add(1); lista.add(3); // Create second list List<Integer> listb = new ArrayList<Integer>(); listb.add(2); listb.add(1); // BiConsumer to compare 2 lists of integers BiConsumer<List<Integer>, List<Integer> > equals = (list1, list2) -> { for (int i = 0; i < list1.size(); i++) if (list1.get(i) != list2.get(i)) { System.out.println(\"False\"); return; } System.out.println(\"True\"); }; // BiConsumer to print 2 lists BiConsumer<List<Integer>, List<Integer> > disp = (list1, list2) -> { list1.stream().forEach(a -> System.out.print(a + \" \")); System.out.println(); list2.stream().forEach(a -> System.out.print(a + \" \")); System.out.println(); }; try { disp.andThen(equals).accept(lista, listb); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 33425, "s": 32050, "text": null }, { "code": null, "e": 33521, "s": 33425, "text": "2 1 3 \n2 1 \nException : java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2" }, { "code": null, "e": 33534, "s": 33521, "text": "simmytarika5" }, { "code": null, "e": 33554, "s": 33534, "text": "Java - util package" }, { "code": null, "e": 33561, "s": 33554, "text": "Java 8" }, { "code": null, "e": 33573, "s": 33561, "text": "java-basics" }, { "code": null, "e": 33578, "s": 33573, "text": "Java" }, { "code": null, "e": 33592, "s": 33578, "text": "Java Programs" }, { "code": null, "e": 33597, "s": 33592, "text": "Java" }, { "code": null, "e": 33695, "s": 33597, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33746, "s": 33695, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 33776, "s": 33746, "text": "HashMap in Java with Examples" }, { "code": null, "e": 33795, "s": 33776, "text": "Interfaces in Java" }, { "code": null, "e": 33826, "s": 33795, "text": "How to iterate any Map in Java" }, { "code": null, "e": 33844, "s": 33826, "text": "ArrayList in Java" }, { "code": null, "e": 33872, "s": 33844, "text": "Initializing a List in Java" }, { "code": null, "e": 33916, "s": 33872, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 33942, "s": 33916, "text": "Java Programming Examples" }, { "code": null, "e": 33976, "s": 33942, "text": "Convert Double to Integer in Java" } ]
Series GP | Practice | GeeksforGeeks
Given the A and R i,e first term and common ratio of a GP series. Find the Nth term of the series. Note: As the answer can be rather large print its modulo 1000000007 (109 + 7). Example 1: Input: A = 2, R = 2, N = 4 Output: 16 Explanation: The GP series is 2, 4, 8, 16, 32,... in which 16 is th 4th term. Example 2: Input: A = 4, R = 3, N = 3 Output: 36 Explanation: The GP series is 4, 12, 36, 108,.. in which 36 is the 3rd term. Your Task: You don't need to read or print anything. Your task is to complete the function Nth_term() which takes A, R and N as input parameter ans returns Nth term of the GP series modulo 109 + 7. Expected Time Complexity: O(log2(N)) Expected Space Complexity: O(1) Constraints: 1 <= A, R, N <= 1000000 +6 jaideepnagillscsebtech1 month ago This question is total dog shit -4 parsaniyayash71 month ago class Solution{ public int Nth_term(int a, int r, int n) { // code here int mod= 1000000007; int S = a * ((int)Math.pow(r,n-1))%mod; return S; } } 0 bhaskor882 months ago Can anyone please help me out with the issue in the below code block ? class Solution { public int Nth_term(int a, int r, int n) { // code here int modulo = 1000000007; return (a*power(r, n-1))%modulo; } // Find power of a number in O(log n) time complesity private int power(int base, int exponent){ if(exponent == 0){ return 1; } int temp = power(base, exponent/2); if(exponent%2 == 0) return temp * temp; else return base * temp * temp; } } 0 hrshuva92 months ago concept:let (a, r, n) = (2, 3, 4)res = a * r^n-1n = 0, 1, 2, 3, 42 X 3^0 = 22 X 3^1 = 62 X 3^2 = 182 X 3^3 = 54 ------- result is for n-12 X 3^4 = 162 0 2017bcs0982 months ago // c++ code // also refer: https://cp-algorithms.com/algebra/binary-exp.html long long binpow(long long a, long long b, long long m) { a %= m; long long res = 1; while (b > 0) { if (b & 1) res = res * a % m; a = a * a % m; b >>= 1; } return res; } int Nth_term(int a, int r, int n){ const int mod = 1e9 + 7; return a * binpow(r, n-1, mod) % mod; } 0 nidhikumaridbg14 months ago //it is giving compilation error //what is wrong //if anybody understands please tell me public: int Nth_term(int a, int r, int n){ //gp nth term=a*pow(r,n-1) //modular arithmetics //(a*pow(r,n-1))%(pow(10,9)+7) int p=pow(10,9)+7; int gp=(a*pow(r,n-1))%p; return gp; } 0 naharnikhil6 This comment was deleted. 0 naharnikhil6 This comment was deleted. +3 ashutoshkumarsme188 months ago class Solution:def Nth_term(self, a, r, n): value = a*pow(r,i) return value # Code here #{ # Driver Code Starts#Initial Template for Python 3 if __name__ == '__main__':T=int(input())for i in range(T): a, r, n = input().split() a = int(a) r = int(r) n = int(n) ob = Solution() ans = ob.Nth_term(a, r, n) print(ans)# } Driver Code Ends This is the write code and it shows one test case does not pass that is because the test case answer is wrong 0 Siddhartha Gupta8 months ago Siddhartha Gupta This is my solution in Javascript, doesn't work with a large number. class Solution { Nth_term(a,r,n){ //code herevalue = a*pow(r,n-1)// # for i in range(0,n):// # value = var something = Math.pow(r,n-1) // console.log("something ", something) var result = a*something; var limited = Math.pow(10,9)+7 // console.log("limited ", limited) // console.log("result ", result) if(result!= Infinity) { return result % limited } }} 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": 325, "s": 226, "text": "Given the A and R i,e first term and common ratio of a GP series. Find the Nth term of the series." }, { "code": null, "e": 404, "s": 325, "text": "Note: As the answer can be rather large print its modulo 1000000007 (109 + 7)." }, { "code": null, "e": 415, "s": 404, "text": "Example 1:" }, { "code": null, "e": 534, "s": 415, "text": "Input: A = 2, R = 2, N = 4\nOutput: 16\nExplanation: The GP series is \n2, 4, 8, 16, 32,... in which 16 \nis th 4th term.\n" }, { "code": null, "e": 545, "s": 534, "text": "Example 2:" }, { "code": null, "e": 661, "s": 545, "text": "Input: A = 4, R = 3, N = 3\nOutput: 36\nExplanation: The GP series is\n4, 12, 36, 108,.. in which 36 is\nthe 3rd term.\n" }, { "code": null, "e": 863, "s": 663, "text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function Nth_term() which takes A, R and N as input parameter ans returns Nth term of the GP series modulo 109 + 7.\n " }, { "code": null, "e": 970, "s": 863, "text": "Expected Time Complexity: O(log2(N))\nExpected Space Complexity: O(1)\n\nConstraints:\n1 <= A, R, N <= 1000000" }, { "code": null, "e": 973, "s": 970, "text": "+6" }, { "code": null, "e": 1007, "s": 973, "text": "jaideepnagillscsebtech1 month ago" }, { "code": null, "e": 1039, "s": 1007, "text": "This question is total dog shit" }, { "code": null, "e": 1044, "s": 1041, "text": "-4" }, { "code": null, "e": 1070, "s": 1044, "text": "parsaniyayash71 month ago" }, { "code": null, "e": 1252, "s": 1070, "text": "class Solution{ public int Nth_term(int a, int r, int n) { // code here int mod= 1000000007; int S = a * ((int)Math.pow(r,n-1))%mod; return S; } } " }, { "code": null, "e": 1254, "s": 1252, "text": "0" }, { "code": null, "e": 1276, "s": 1254, "text": "bhaskor882 months ago" }, { "code": null, "e": 1347, "s": 1276, "text": "Can anyone please help me out with the issue in the below code block ?" }, { "code": null, "e": 1870, "s": 1347, "text": "class Solution\n{\n public int Nth_term(int a, int r, int n)\n {\n // code here\n int modulo = 1000000007;\n return (a*power(r, n-1))%modulo;\n }\n \n // Find power of a number in O(log n) time complesity\n private int power(int base, int exponent){\n if(exponent == 0){\n return 1; \n }\n \n int temp = power(base, exponent/2);\n \n if(exponent%2 == 0)\n return temp * temp;\n else\n return base * temp * temp;\n }\n}" }, { "code": null, "e": 1872, "s": 1870, "text": "0" }, { "code": null, "e": 1893, "s": 1872, "text": "hrshuva92 months ago" }, { "code": null, "e": 2048, "s": 1893, "text": "concept:let (a, r, n) = (2, 3, 4)res = a * r^n-1n = 0, 1, 2, 3, 42 X 3^0 = 22 X 3^1 = 62 X 3^2 = 182 X 3^3 = 54 ------- result is for n-12 X 3^4 = 162" }, { "code": null, "e": 2050, "s": 2048, "text": "0" }, { "code": null, "e": 2073, "s": 2050, "text": "2017bcs0982 months ago" }, { "code": null, "e": 2542, "s": 2073, "text": "// c++ code\n// also refer: https://cp-algorithms.com/algebra/binary-exp.html\nlong long binpow(long long a, long long b, long long m) {\n a %= m;\n long long res = 1;\n while (b > 0) {\n if (b & 1)\n res = res * a % m;\n a = a * a % m;\n b >>= 1;\n }\n return res;\n }\n\n \tint Nth_term(int a, int r, int n){\n \t const int mod = 1e9 + 7;\n \t return a * binpow(r, n-1, mod) % mod;\n \t}" }, { "code": null, "e": 2544, "s": 2542, "text": "0" }, { "code": null, "e": 2572, "s": 2544, "text": "nidhikumaridbg14 months ago" }, { "code": null, "e": 2605, "s": 2572, "text": "//it is giving compilation error" }, { "code": null, "e": 2622, "s": 2605, "text": "//what is wrong " }, { "code": null, "e": 2662, "s": 2622, "text": "//if anybody understands please tell me" }, { "code": null, "e": 2881, "s": 2662, "text": " public: int Nth_term(int a, int r, int n){ //gp nth term=a*pow(r,n-1) //modular arithmetics //(a*pow(r,n-1))%(pow(10,9)+7) int p=pow(10,9)+7; int gp=(a*pow(r,n-1))%p; return gp; } " }, { "code": null, "e": 2883, "s": 2881, "text": "0" }, { "code": null, "e": 2896, "s": 2883, "text": "naharnikhil6" }, { "code": null, "e": 2922, "s": 2896, "text": "This comment was deleted." }, { "code": null, "e": 2924, "s": 2922, "text": "0" }, { "code": null, "e": 2937, "s": 2924, "text": "naharnikhil6" }, { "code": null, "e": 2963, "s": 2937, "text": "This comment was deleted." }, { "code": null, "e": 2966, "s": 2963, "text": "+3" }, { "code": null, "e": 2997, "s": 2966, "text": "ashutoshkumarsme188 months ago" }, { "code": null, "e": 3094, "s": 2997, "text": "class Solution:def Nth_term(self, a, r, n): value = a*pow(r,i) return value # Code here" }, { "code": null, "e": 3149, "s": 3094, "text": "#{ # Driver Code Starts#Initial Template for Python 3" }, { "code": null, "e": 3341, "s": 3149, "text": "if __name__ == '__main__':T=int(input())for i in range(T): a, r, n = input().split() a = int(a) r = int(r) n = int(n) ob = Solution() ans = ob.Nth_term(a, r, n) print(ans)# } Driver Code Ends" }, { "code": null, "e": 3455, "s": 3345, "text": "This is the write code and it shows one test case does not pass that is because the test case answer is wrong" }, { "code": null, "e": 3457, "s": 3455, "text": "0" }, { "code": null, "e": 3486, "s": 3457, "text": "Siddhartha Gupta8 months ago" }, { "code": null, "e": 3503, "s": 3486, "text": "Siddhartha Gupta" }, { "code": null, "e": 3589, "s": 3503, "text": "This is my solution in Javascript, doesn't work with a large number. class Solution {" }, { "code": null, "e": 4015, "s": 3589, "text": " Nth_term(a,r,n){ //code herevalue = a*pow(r,n-1)// # for i in range(0,n):// # value = var something = Math.pow(r,n-1) // console.log(\"something \", something) var result = a*something; var limited = Math.pow(10,9)+7 // console.log(\"limited \", limited) // console.log(\"result \", result) if(result!= Infinity) { return result % limited }" }, { "code": null, "e": 4018, "s": 4015, "text": "}}" }, { "code": null, "e": 4164, "s": 4018, "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": 4200, "s": 4164, "text": " Login to access your submissions. " }, { "code": null, "e": 4210, "s": 4200, "text": "\nProblem\n" }, { "code": null, "e": 4220, "s": 4210, "text": "\nContest\n" }, { "code": null, "e": 4283, "s": 4220, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4431, "s": 4283, "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": 4639, "s": 4431, "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": 4745, "s": 4639, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find an index of maximum occurring element with equal probability - GeeksforGeeks
06 Jul, 2021 Given an array of integers, find the most occurring element of the array and return any one of its indexes randomly with equal probability.Examples: Input: arr[] = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9] Output: Element with maximum frequency present at index 6 OR Element with maximum frequency present at Index 3 OR Element with maximum frequency present at index 4 OR Element with maximum frequency present at index 12 All outputs above have equal probability. The idea is to iterate through the array once and find out the maximum occurring element and its frequency n. Then we generate a random number r between 1 and n and finally return the r’th occurrence of maximum occurring element in the array.Below are implementation of above idea – C++ Java Python3 Javascript // C++ program to return index of most occurring element// of the array randomly with equal probability#include <iostream>#include <unordered_map>#include <climits>using namespace std; // Function to return index of most occurring element// of the array randomly with equal probabilityvoid findRandomIndexOfMax(int arr[], int n){ // freq store frequency of each element in the array unordered_map<int, int> freq; for (int i = 0; i < n; i++) freq[arr[i]] += 1; int max_element; // stores max occurring element // stores count of max occurring element int max_so_far = INT_MIN; // traverse each pair in map and find maximum // occurring element and its frequency for (pair<int, int> p : freq) { if (p.second > max_so_far) { max_so_far = p.second; max_element = p.first; } } // generate a random number between [1, max_so_far] int r = (rand() % max_so_far) + 1; // traverse array again and return index of rth // occurrence of max element for (int i = 0, count = 0; i < n; i++) { if (arr[i] == max_element) count++; // print index of rth occurrence of max element if (count == r) { cout << "Element with maximum frequency present " "at index " << i << endl; break; } }} // Driver codeint main(){ // input array int arr[] = { -1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); // randomize seed srand(time(NULL)); findRandomIndexOfMax(arr, n); return 0;} // Java program to return index of most occurring element// of the array randomly with equal probabilityimport java.util.*; class GFG{ // Function to return index of most occurring element// of the array randomly with equal probabilitystatic void findRandomIndexOfMax(int arr[], int n){ // freq store frequency of each element in the array HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } int max_element = Integer.MIN_VALUE; // stores max occurring element // stores count of max occurring element int max_so_far = Integer.MIN_VALUE; // traverse each pair in map and find maximum // occurring element and its frequency for (Map.Entry<Integer, Integer> p : mp.entrySet()) { if (p.getValue() > max_so_far) { max_so_far = p.getValue(); max_element = p.getKey(); } } // generate a random number between [1, max_so_far] int r = (int) ((new Random().nextInt(max_so_far) % max_so_far) + 1); // traverse array again and return index of rth // occurrence of max element for (int i = 0, count = 0; i < n; i++) { if (arr[i] == max_element) count++; // print index of rth occurrence of max element if (count == r) { System.out.print("Element with maximum frequency present " +"at index " + i +"\n"); break; } }} // Driver codepublic static void main(String[] args){ // input array int arr[] = { -1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9 }; int n = arr.length; findRandomIndexOfMax(arr, n);}} // This code is contributed by Rajput-Ji # Python3 program to return index of most occurring element# of the array randomly with equal probabilityimport random # Function to return index of most occurring element# of the array randomly with equal probabilitydef findRandomIndexOfMax(arr, n): # freq store frequency of each element in the array mp = dict() for i in range(n) : if(arr[i] in mp): mp[arr[i]] = mp[arr[i]] + 1 else: mp[arr[i]] = 1 max_element = -323567 # stores max occurring element # stores count of max occurring element max_so_far = -323567 # traverse each pair in map and find maximum # occurring element and its frequency for p in mp : if (mp[p] > max_so_far): max_so_far = mp[p] max_element = p # generate a random number between [1, max_so_far] r = int( ((random.randrange(1, max_so_far, 2) % max_so_far) + 1)) i = 0 count = 0 # traverse array again and return index of rth # occurrence of max element while ( i < n ): if (arr[i] == max_element): count = count + 1 # Print index of rth occurrence of max element if (count == r): print("Element with maximum frequency present at index " , i ) break i = i + 1 # Driver code # input arrayarr = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9]n = len(arr)findRandomIndexOfMax(arr, n) # This code is contributed by Arnab Kundu <script>// Javascript program to return index of most occurring element// of the array randomly with equal probability // Function to return index of most occurring element// of the array randomly with equal probabilityfunction findRandomIndexOfMax(arr,n){ // freq store frequency of each element in the array let mp = new Map(); for (let i = 0; i < n; i++) if(mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1); } else { mp.set(arr[i], 1); } let max_element = Number.MIN_VALUE; // stores max occurring element // stores count of max occurring element let max_so_far = Number.MIN_VALUE; // traverse each pair in map and find maximum // occurring element and its frequency for (let [key, value] of mp.entries()) { if (value > max_so_far) { max_so_far = value; max_element = key; } } // generate a random number between [1, max_so_far] let r = Math.floor(((Math.random() * max_so_far)% max_so_far)+ 1) // traverse array again and return index of rth // occurrence of max element for (let i = 0, count = 0; i < n; i++) { if (arr[i] == max_element) count++; // print index of rth occurrence of max element if (count == r) { document.write("Element with maximum frequency present " +"at index " + i +"<br>"); break; } }} // Driver codelet arr=[-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9 ];let n = arr.length;findRandomIndexOfMax(arr, n); // This code is contributed by avanitrachhadiya2155</script> Output: Element with maximum frequency present at index 4 Time complexity of above solution is O(n). Auxiliary space used by the program is O(n).This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Rajput-Ji nidhi_biet andrew1234 avanitrachhadiya2155 Randomized Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Random Walk (Implementation in Python) Generating Random String Using PHP Operations on Sparse Matrices Karger's algorithm for Minimum Cut | Set 1 (Introduction and Implementation) Randomized Algorithms | Set 1 (Introduction and Analysis) Birthday Paradox Primality Test | Set 2 (Fermat Method) Random number generator in arbitrary probability distribution fashion Randomized Algorithms | Set 2 (Classification and Applications)
[ { "code": null, "e": 25178, "s": 25150, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25329, "s": 25178, "text": "Given an array of integers, find the most occurring element of the array and return any one of its indexes randomly with equal probability.Examples: " }, { "code": null, "e": 25656, "s": 25329, "text": "Input: \narr[] = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9]\n\nOutput: \nElement with maximum frequency present at index 6\nOR\nElement with maximum frequency present at Index 3\nOR\nElement with maximum frequency present at index 4\nOR\nElement with maximum frequency present at index 12\n\nAll outputs above have equal probability." }, { "code": null, "e": 25943, "s": 25658, "text": "The idea is to iterate through the array once and find out the maximum occurring element and its frequency n. Then we generate a random number r between 1 and n and finally return the r’th occurrence of maximum occurring element in the array.Below are implementation of above idea – " }, { "code": null, "e": 25947, "s": 25943, "text": "C++" }, { "code": null, "e": 25952, "s": 25947, "text": "Java" }, { "code": null, "e": 25960, "s": 25952, "text": "Python3" }, { "code": null, "e": 25971, "s": 25960, "text": "Javascript" }, { "code": "// C++ program to return index of most occurring element// of the array randomly with equal probability#include <iostream>#include <unordered_map>#include <climits>using namespace std; // Function to return index of most occurring element// of the array randomly with equal probabilityvoid findRandomIndexOfMax(int arr[], int n){ // freq store frequency of each element in the array unordered_map<int, int> freq; for (int i = 0; i < n; i++) freq[arr[i]] += 1; int max_element; // stores max occurring element // stores count of max occurring element int max_so_far = INT_MIN; // traverse each pair in map and find maximum // occurring element and its frequency for (pair<int, int> p : freq) { if (p.second > max_so_far) { max_so_far = p.second; max_element = p.first; } } // generate a random number between [1, max_so_far] int r = (rand() % max_so_far) + 1; // traverse array again and return index of rth // occurrence of max element for (int i = 0, count = 0; i < n; i++) { if (arr[i] == max_element) count++; // print index of rth occurrence of max element if (count == r) { cout << \"Element with maximum frequency present \" \"at index \" << i << endl; break; } }} // Driver codeint main(){ // input array int arr[] = { -1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); // randomize seed srand(time(NULL)); findRandomIndexOfMax(arr, n); return 0;}", "e": 27592, "s": 25971, "text": null }, { "code": "// Java program to return index of most occurring element// of the array randomly with equal probabilityimport java.util.*; class GFG{ // Function to return index of most occurring element// of the array randomly with equal probabilitystatic void findRandomIndexOfMax(int arr[], int n){ // freq store frequency of each element in the array HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) if(mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } int max_element = Integer.MIN_VALUE; // stores max occurring element // stores count of max occurring element int max_so_far = Integer.MIN_VALUE; // traverse each pair in map and find maximum // occurring element and its frequency for (Map.Entry<Integer, Integer> p : mp.entrySet()) { if (p.getValue() > max_so_far) { max_so_far = p.getValue(); max_element = p.getKey(); } } // generate a random number between [1, max_so_far] int r = (int) ((new Random().nextInt(max_so_far) % max_so_far) + 1); // traverse array again and return index of rth // occurrence of max element for (int i = 0, count = 0; i < n; i++) { if (arr[i] == max_element) count++; // print index of rth occurrence of max element if (count == r) { System.out.print(\"Element with maximum frequency present \" +\"at index \" + i +\"\\n\"); break; } }} // Driver codepublic static void main(String[] args){ // input array int arr[] = { -1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9 }; int n = arr.length; findRandomIndexOfMax(arr, n);}} // This code is contributed by Rajput-Ji", "e": 29436, "s": 27592, "text": null }, { "code": "# Python3 program to return index of most occurring element# of the array randomly with equal probabilityimport random # Function to return index of most occurring element# of the array randomly with equal probabilitydef findRandomIndexOfMax(arr, n): # freq store frequency of each element in the array mp = dict() for i in range(n) : if(arr[i] in mp): mp[arr[i]] = mp[arr[i]] + 1 else: mp[arr[i]] = 1 max_element = -323567 # stores max occurring element # stores count of max occurring element max_so_far = -323567 # traverse each pair in map and find maximum # occurring element and its frequency for p in mp : if (mp[p] > max_so_far): max_so_far = mp[p] max_element = p # generate a random number between [1, max_so_far] r = int( ((random.randrange(1, max_so_far, 2) % max_so_far) + 1)) i = 0 count = 0 # traverse array again and return index of rth # occurrence of max element while ( i < n ): if (arr[i] == max_element): count = count + 1 # Print index of rth occurrence of max element if (count == r): print(\"Element with maximum frequency present at index \" , i ) break i = i + 1 # Driver code # input arrayarr = [-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9]n = len(arr)findRandomIndexOfMax(arr, n) # This code is contributed by Arnab Kundu", "e": 30922, "s": 29436, "text": null }, { "code": "<script>// Javascript program to return index of most occurring element// of the array randomly with equal probability // Function to return index of most occurring element// of the array randomly with equal probabilityfunction findRandomIndexOfMax(arr,n){ // freq store frequency of each element in the array let mp = new Map(); for (let i = 0; i < n; i++) if(mp.has(arr[i])) { mp.set(arr[i], mp.get(arr[i]) + 1); } else { mp.set(arr[i], 1); } let max_element = Number.MIN_VALUE; // stores max occurring element // stores count of max occurring element let max_so_far = Number.MIN_VALUE; // traverse each pair in map and find maximum // occurring element and its frequency for (let [key, value] of mp.entries()) { if (value > max_so_far) { max_so_far = value; max_element = key; } } // generate a random number between [1, max_so_far] let r = Math.floor(((Math.random() * max_so_far)% max_so_far)+ 1) // traverse array again and return index of rth // occurrence of max element for (let i = 0, count = 0; i < n; i++) { if (arr[i] == max_element) count++; // print index of rth occurrence of max element if (count == r) { document.write(\"Element with maximum frequency present \" +\"at index \" + i +\"<br>\"); break; } }} // Driver codelet arr=[-1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5, 7, 8, 9 ];let n = arr.length;findRandomIndexOfMax(arr, n); // This code is contributed by avanitrachhadiya2155</script>", "e": 32607, "s": 30922, "text": null }, { "code": null, "e": 32617, "s": 32607, "text": "Output: " }, { "code": null, "e": 32667, "s": 32617, "text": "Element with maximum frequency present at index 4" }, { "code": null, "e": 33174, "s": 32667, "text": "Time complexity of above solution is O(n). Auxiliary space used by the program is O(n).This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33184, "s": 33174, "text": "Rajput-Ji" }, { "code": null, "e": 33195, "s": 33184, "text": "nidhi_biet" }, { "code": null, "e": 33206, "s": 33195, "text": "andrew1234" }, { "code": null, "e": 33227, "s": 33206, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33238, "s": 33227, "text": "Randomized" }, { "code": null, "e": 33336, "s": 33238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33345, "s": 33336, "text": "Comments" }, { "code": null, "e": 33358, "s": 33345, "text": "Old Comments" }, { "code": null, "e": 33397, "s": 33358, "text": "Random Walk (Implementation in Python)" }, { "code": null, "e": 33432, "s": 33397, "text": "Generating Random String Using PHP" }, { "code": null, "e": 33462, "s": 33432, "text": "Operations on Sparse Matrices" }, { "code": null, "e": 33539, "s": 33462, "text": "Karger's algorithm for Minimum Cut | Set 1 (Introduction and Implementation)" }, { "code": null, "e": 33597, "s": 33539, "text": "Randomized Algorithms | Set 1 (Introduction and Analysis)" }, { "code": null, "e": 33614, "s": 33597, "text": "Birthday Paradox" }, { "code": null, "e": 33653, "s": 33614, "text": "Primality Test | Set 2 (Fermat Method)" }, { "code": null, "e": 33723, "s": 33653, "text": "Random number generator in arbitrary probability distribution fashion" } ]
How to add JList to Scroll pane in Java?
To add JList to Scroll pane in Java, use JScrollPane: JList list = new JList(sports); JScrollPane scrollPane = new JScrollPane(list); After that set it to Container: Container contentPane = frame.getContentPane(); contentPane.add(scrollPane, BorderLayout.CENTER); The following is an example to add JList to Scroll pane: package my; import java.awt.event.*; import java.awt.*; import javax.swing.*; class SwingDemo extends JFrame { static JFrame frame; static JList list; public static void main(String[] args) { frame = new JFrame("JList Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String sports[]= {"Tennis","Archery","Football","Fencing","Cricket","Squash","Hockey","Rugby"}; list = new JList(sports); JScrollPane scrollPane = new JScrollPane(list); Container contentPane = frame.getContentPane(); contentPane.add(scrollPane, BorderLayout.CENTER); frame.setSize(400,100); frame.setVisible(true); } } The output is as follows. As you can see ScrollPane is visible for the items:
[ { "code": null, "e": 1116, "s": 1062, "text": "To add JList to Scroll pane in Java, use JScrollPane:" }, { "code": null, "e": 1196, "s": 1116, "text": "JList list = new JList(sports);\nJScrollPane scrollPane = new JScrollPane(list);" }, { "code": null, "e": 1228, "s": 1196, "text": "After that set it to Container:" }, { "code": null, "e": 1326, "s": 1228, "text": "Container contentPane = frame.getContentPane();\ncontentPane.add(scrollPane, BorderLayout.CENTER);" }, { "code": null, "e": 1383, "s": 1326, "text": "The following is an example to add JList to Scroll pane:" }, { "code": null, "e": 2049, "s": 1383, "text": "package my;\nimport java.awt.event.*;\nimport java.awt.*;\nimport javax.swing.*;\nclass SwingDemo extends JFrame {\n static JFrame frame;\n static JList list;\n public static void main(String[] args) {\n frame = new JFrame(\"JList Demo\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n String sports[]= {\"Tennis\",\"Archery\",\"Football\",\"Fencing\",\"Cricket\",\"Squash\",\"Hockey\",\"Rugby\"};\n list = new JList(sports);\n JScrollPane scrollPane = new JScrollPane(list);\n Container contentPane = frame.getContentPane();\n contentPane.add(scrollPane, BorderLayout.CENTER);\n frame.setSize(400,100);\n frame.setVisible(true);\n }\n}" }, { "code": null, "e": 2127, "s": 2049, "text": "The output is as follows. As you can see ScrollPane is visible for the items:" } ]
XML - Overview
XML stands for Extensible Markup Language. It is a text-based markup language derived from Standard Generalized Markup Language (SGML). XML tags identify the data and are used to store and organize the data, rather than specifying how to display it like HTML tags, which are used to display the data. XML is not going to replace HTML in the near future, but it introduces new possibilities by adopting many successful features of HTML. There are three important characteristics of XML that make it useful in a variety of systems and solutions − XML is extensible − XML allows you to create your own self-descriptive tags, or language, that suits your application. XML is extensible − XML allows you to create your own self-descriptive tags, or language, that suits your application. XML carries the data, does not present it − XML allows you to store the data irrespective of how it will be presented. XML carries the data, does not present it − XML allows you to store the data irrespective of how it will be presented. XML is a public standard − XML was developed by an organization called the World Wide Web Consortium (W3C) and is available as an open standard. XML is a public standard − XML was developed by an organization called the World Wide Web Consortium (W3C) and is available as an open standard. A short list of XML usage says it all − XML can work behind the scene to simplify the creation of HTML documents for large web sites. XML can work behind the scene to simplify the creation of HTML documents for large web sites. XML can be used to exchange the information between organizations and systems. XML can be used to exchange the information between organizations and systems. XML can be used for offloading and reloading of databases. XML can be used for offloading and reloading of databases. XML can be used to store and arrange the data, which can customize your data handling needs. XML can be used to store and arrange the data, which can customize your data handling needs. XML can easily be merged with style sheets to create almost any desired output. XML can easily be merged with style sheets to create almost any desired output. Virtually, any type of data can be expressed as an XML document. Virtually, any type of data can be expressed as an XML document. XML is a markup language that defines set of rules for encoding documents in a format that is both human-readable and machine-readable. So what exactly is a markup language? Markup is information added to a document that enhances its meaning in certain ways, in that it identifies the parts and how they relate to each other. More specifically, a markup language is a set of symbols that can be placed in the text of a document to demarcate and label the parts of that document. Following example shows how XML markup looks, when embedded in a piece of text − <message> <text>Hello, world!</text> </message> This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>... </text>. The tags <message> and </message> mark the start and the end of the XML code fragment. The tags <text> and </text> surround the text Hello, world!. A programming language consists of grammar rules and its own vocabulary which is used to create computer programs. These programs instruct the computer to perform specific tasks. XML does not qualify to be a programming language as it does not perform any computation or algorithms. It is usually stored in a simple text file and is processed by special software that is capable of interpreting XML. 84 Lectures 6 hours Frahaan Hussain 29 Lectures 2 hours YouAccel 27 Lectures 1 hours Jordan Stanchev 16 Lectures 2 hours Simon Sez IT Print Add Notes Bookmark this page
[ { "code": null, "e": 2097, "s": 1961, "text": "XML stands for Extensible Markup Language. It is a text-based markup language derived from Standard Generalized Markup Language (SGML)." }, { "code": null, "e": 2397, "s": 2097, "text": "XML tags identify the data and are used to store and organize the data, rather than specifying how to display it like HTML tags, which are used to display the data. XML is not going to replace HTML in the near future, but it introduces new possibilities by adopting many successful features of HTML." }, { "code": null, "e": 2506, "s": 2397, "text": "There are three important characteristics of XML that make it useful in a variety of systems and solutions −" }, { "code": null, "e": 2625, "s": 2506, "text": "XML is extensible − XML allows you to create your own self-descriptive tags, or language, that suits your application." }, { "code": null, "e": 2744, "s": 2625, "text": "XML is extensible − XML allows you to create your own self-descriptive tags, or language, that suits your application." }, { "code": null, "e": 2863, "s": 2744, "text": "XML carries the data, does not present it − XML allows you to store the data irrespective of how it will be presented." }, { "code": null, "e": 2982, "s": 2863, "text": "XML carries the data, does not present it − XML allows you to store the data irrespective of how it will be presented." }, { "code": null, "e": 3127, "s": 2982, "text": "XML is a public standard − XML was developed by an organization called the World Wide Web Consortium (W3C) and is available as an open standard." }, { "code": null, "e": 3272, "s": 3127, "text": "XML is a public standard − XML was developed by an organization called the World Wide Web Consortium (W3C) and is available as an open standard." }, { "code": null, "e": 3312, "s": 3272, "text": "A short list of XML usage says it all −" }, { "code": null, "e": 3406, "s": 3312, "text": "XML can work behind the scene to simplify the creation of HTML documents for large web sites." }, { "code": null, "e": 3500, "s": 3406, "text": "XML can work behind the scene to simplify the creation of HTML documents for large web sites." }, { "code": null, "e": 3579, "s": 3500, "text": "XML can be used to exchange the information between organizations and systems." }, { "code": null, "e": 3658, "s": 3579, "text": "XML can be used to exchange the information between organizations and systems." }, { "code": null, "e": 3717, "s": 3658, "text": "XML can be used for offloading and reloading of databases." }, { "code": null, "e": 3776, "s": 3717, "text": "XML can be used for offloading and reloading of databases." }, { "code": null, "e": 3869, "s": 3776, "text": "XML can be used to store and arrange the data, which can customize your data handling needs." }, { "code": null, "e": 3962, "s": 3869, "text": "XML can be used to store and arrange the data, which can customize your data handling needs." }, { "code": null, "e": 4042, "s": 3962, "text": "XML can easily be merged with style sheets to create almost any desired output." }, { "code": null, "e": 4122, "s": 4042, "text": "XML can easily be merged with style sheets to create almost any desired output." }, { "code": null, "e": 4187, "s": 4122, "text": "Virtually, any type of data can be expressed as an XML document." }, { "code": null, "e": 4252, "s": 4187, "text": "Virtually, any type of data can be expressed as an XML document." }, { "code": null, "e": 4732, "s": 4252, "text": "XML is a markup language that defines set of rules for encoding documents in a format that is both human-readable and machine-readable. So what exactly is a markup language? Markup is information added to a document that enhances its meaning in certain ways, in that it identifies the parts and how they relate to each other. More specifically, a markup language is a set of symbols that can be placed in the text of a document to demarcate and label the parts of that document." }, { "code": null, "e": 4813, "s": 4732, "text": "Following example shows how XML markup looks, when embedded in a piece of text −" }, { "code": null, "e": 4864, "s": 4813, "text": "<message>\n <text>Hello, world!</text>\n</message>" }, { "code": null, "e": 5120, "s": 4864, "text": "This snippet includes the markup symbols, or the tags such as <message>...</message> and <text>... </text>. The tags <message> and </message> mark the start and the end of the XML code fragment. The tags <text> and </text> surround the text Hello, world!." }, { "code": null, "e": 5520, "s": 5120, "text": "A programming language consists of grammar rules and its own vocabulary which is used\nto create computer programs. These programs instruct the computer to perform specific tasks. XML does not qualify to be a programming language as it does not perform any computation or algorithms. It is usually stored in a simple text file and is processed by special software that is capable of interpreting XML." }, { "code": null, "e": 5553, "s": 5520, "text": "\n 84 Lectures \n 6 hours \n" }, { "code": null, "e": 5570, "s": 5553, "text": " Frahaan Hussain" }, { "code": null, "e": 5603, "s": 5570, "text": "\n 29 Lectures \n 2 hours \n" }, { "code": null, "e": 5613, "s": 5603, "text": " YouAccel" }, { "code": null, "e": 5646, "s": 5613, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 5663, "s": 5646, "text": " Jordan Stanchev" }, { "code": null, "e": 5696, "s": 5663, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5710, "s": 5696, "text": " Simon Sez IT" }, { "code": null, "e": 5717, "s": 5710, "text": " Print" }, { "code": null, "e": 5728, "s": 5717, "text": " Add Notes" } ]
Lexicographically largest string formed from the characters in range L and R - GeeksforGeeks
18 Feb, 2022 Given a string S and a range L and R, the task is to print the lexicographically largest string that can be formed from the characters in range L and R. Examples: Input: str = "thgyfh", L = 2, R = 6 Output: yhhgf Input: str = "striver", L = 3, R = 5 Output: vri Approach: Iterate from min(L, R) to max(L, R) and increase the frequencies of characters in a freq[] array. Iterate from 25 to 0 and print the number of times every character occurs to get the lexicographically largest string. The common point of mistake which everyone does is they iterate from L to R instead of min(L, R) to max(L, R). Below is the implementation of the above approach: C++ Java Python 3 C# Javascript // C++ program to print the// lexicographically largest string that// can be formed from the characters// in range L and R #include <bits/stdc++.h>using namespace std; // Function to return the lexicographically largest stringstring printLargestString(string s, int l, int r){ // hash array int freq[26] = { 0 }; // make 0-based indexing l--; r--; // iterate and count frequencies of character for (int i = min(l, r); i <= max(l, r); i++) { freq[s[i] - 'a']++; } // ans string string ans = ""; // iterate in frequency array for (int i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i]) { ans += char('a' + i); freq[i]--; } } return ans;} // Driver Codeint main(){ string s = "striver"; int l = 3, r = 5; cout << printLargestString(s, l, r); return 0;} // Java program to print the// lexicographically largest String that// can be formed from the characters// in range L and R class GFG { // Function to return the lexicographically largest String static String printLargestString(String s, int l, int r) { // hash array int freq[] = new int[26]; // make 0-based indexing l--; r--; // iterate and count frequencies of character for (int i = Math.min(l, r); i <= Math.max(l, r); i++) { freq[s.charAt(i) - 'a']++; } // ans String String ans = ""; // iterate in frequency array for (int i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i] > 0) { ans += (char) ('a' + i); freq[i]--; } } return ans; } // Driver Code public static void main(String[] args) { String s = "striver"; int l = 3, r = 5; System.out.println(printLargestString(s, l, r)); }}/* This JAVA code is contributed by 29AjayKumar*/ # Python 3 program to print the# lexicographically largest string that# can be formed from the characters# in range L and R # Function to return the lexicographically# largest stringdef printLargestString(s, l, r): # hash array freq = [0] * 26 # make 0-based indexing l -= 1 r -= 1 # iterate and count frequencies of character for i in range(min(l, r), max(l, r) + 1) : freq[ord(s[i]) - ord('a')] += 1 # ans string ans = "" # iterate in frequency array for i in range(25, -1, -1): # add till all characters are added while (freq[i]): ans += chr(ord('a') + i) freq[i] -= 1 return ans # Driver Codeif __name__ == "__main__": s = "striver" l = 3 r = 5 print(printLargestString(s, l, r)) # This code is contributed by ita_c // C# program to print the lexicographically// largest String that can be formed from the// characters in range L and Rusing System; class GFG{ // Function to return the lexicographically// largest Stringstatic String printLargestString(String s, int l, int r){ // hash array int []freq = new int[26]; // make 0-based indexing l--; r--; // iterate and count frequencies // of character for (int i = Math.Min(l, r); i <= Math.Max(l, r); i++) { freq[s[i] - 'a']++; } // ans String String ans = ""; // iterate in frequency array for (int i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i] > 0) { ans += (char) ('a' + i); freq[i]--; } } return ans;} // Driver Codepublic static void Main(){ String s = "striver"; int l = 3, r = 5; Console.Write(printLargestString(s, l, r));}} // This code is contributed by 29AjayKumar <script>// javascript program to print the// lexicographically largest String that// can be formed from the characters// in range L and R // Function to return the lexicographically largest String function printLargestString( s , l , r) { // hash array var freq = Array(26).fill(0); // make 0-based indexing l--; r--; // iterate and count frequencies of character for (i = Math.min(l, r); i <= Math.max(l, r); i++) { freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; } // ans String var ans = ""; // iterate in frequency array for (var i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i] > 0) { ans += String.fromCharCode('a'.charCodeAt(0) + i); freq[i]--; } } return ans; } // Driver Code var s = "striver"; var l = 3, r = 5; document.write(printLargestString(s, l, r)); // This code is contributed by todaysgaurav</script> vri Time Complexity – O(N) Each element gets added to the frequency table only once which takes O(1) and is appended to string which also takes O(1). imdhruvgupta 29AjayKumar ukasp todaysgaurav ankita_saini kk9826225 frequency-counting Technical Scripter 2018 Competitive Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Bits manipulation (Important tactics) Formatted output in Java Algorithm Library | C++ Magicians STL Algorithm How to begin with Competitive Programming? Use of FLAG in programming Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25403, "s": 25375, "text": "\n18 Feb, 2022" }, { "code": null, "e": 25567, "s": 25403, "text": "Given a string S and a range L and R, the task is to print the lexicographically largest string that can be formed from the characters in range L and R. Examples: " }, { "code": null, "e": 25669, "s": 25567, "text": "Input: str = \"thgyfh\", L = 2, R = 6 \nOutput: yhhgf\n\nInput: str = \"striver\", L = 3, R = 5\nOutput: vri" }, { "code": null, "e": 25680, "s": 25669, "text": "Approach: " }, { "code": null, "e": 25778, "s": 25680, "text": "Iterate from min(L, R) to max(L, R) and increase the frequencies of characters in a freq[] array." }, { "code": null, "e": 25897, "s": 25778, "text": "Iterate from 25 to 0 and print the number of times every character occurs to get the lexicographically largest string." }, { "code": null, "e": 26061, "s": 25897, "text": "The common point of mistake which everyone does is they iterate from L to R instead of min(L, R) to max(L, R). Below is the implementation of the above approach: " }, { "code": null, "e": 26065, "s": 26061, "text": "C++" }, { "code": null, "e": 26070, "s": 26065, "text": "Java" }, { "code": null, "e": 26079, "s": 26070, "text": "Python 3" }, { "code": null, "e": 26082, "s": 26079, "text": "C#" }, { "code": null, "e": 26093, "s": 26082, "text": "Javascript" }, { "code": "// C++ program to print the// lexicographically largest string that// can be formed from the characters// in range L and R #include <bits/stdc++.h>using namespace std; // Function to return the lexicographically largest stringstring printLargestString(string s, int l, int r){ // hash array int freq[26] = { 0 }; // make 0-based indexing l--; r--; // iterate and count frequencies of character for (int i = min(l, r); i <= max(l, r); i++) { freq[s[i] - 'a']++; } // ans string string ans = \"\"; // iterate in frequency array for (int i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i]) { ans += char('a' + i); freq[i]--; } } return ans;} // Driver Codeint main(){ string s = \"striver\"; int l = 3, r = 5; cout << printLargestString(s, l, r); return 0;}", "e": 26988, "s": 26093, "text": null }, { "code": "// Java program to print the// lexicographically largest String that// can be formed from the characters// in range L and R class GFG { // Function to return the lexicographically largest String static String printLargestString(String s, int l, int r) { // hash array int freq[] = new int[26]; // make 0-based indexing l--; r--; // iterate and count frequencies of character for (int i = Math.min(l, r); i <= Math.max(l, r); i++) { freq[s.charAt(i) - 'a']++; } // ans String String ans = \"\"; // iterate in frequency array for (int i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i] > 0) { ans += (char) ('a' + i); freq[i]--; } } return ans; } // Driver Code public static void main(String[] args) { String s = \"striver\"; int l = 3, r = 5; System.out.println(printLargestString(s, l, r)); }}/* This JAVA code is contributed by 29AjayKumar*/", "e": 28080, "s": 26988, "text": null }, { "code": "# Python 3 program to print the# lexicographically largest string that# can be formed from the characters# in range L and R # Function to return the lexicographically# largest stringdef printLargestString(s, l, r): # hash array freq = [0] * 26 # make 0-based indexing l -= 1 r -= 1 # iterate and count frequencies of character for i in range(min(l, r), max(l, r) + 1) : freq[ord(s[i]) - ord('a')] += 1 # ans string ans = \"\" # iterate in frequency array for i in range(25, -1, -1): # add till all characters are added while (freq[i]): ans += chr(ord('a') + i) freq[i] -= 1 return ans # Driver Codeif __name__ == \"__main__\": s = \"striver\" l = 3 r = 5 print(printLargestString(s, l, r)) # This code is contributed by ita_c", "e": 28903, "s": 28080, "text": null }, { "code": "// C# program to print the lexicographically// largest String that can be formed from the// characters in range L and Rusing System; class GFG{ // Function to return the lexicographically// largest Stringstatic String printLargestString(String s, int l, int r){ // hash array int []freq = new int[26]; // make 0-based indexing l--; r--; // iterate and count frequencies // of character for (int i = Math.Min(l, r); i <= Math.Max(l, r); i++) { freq[s[i] - 'a']++; } // ans String String ans = \"\"; // iterate in frequency array for (int i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i] > 0) { ans += (char) ('a' + i); freq[i]--; } } return ans;} // Driver Codepublic static void Main(){ String s = \"striver\"; int l = 3, r = 5; Console.Write(printLargestString(s, l, r));}} // This code is contributed by 29AjayKumar", "e": 29920, "s": 28903, "text": null }, { "code": "<script>// javascript program to print the// lexicographically largest String that// can be formed from the characters// in range L and R // Function to return the lexicographically largest String function printLargestString( s , l , r) { // hash array var freq = Array(26).fill(0); // make 0-based indexing l--; r--; // iterate and count frequencies of character for (i = Math.min(l, r); i <= Math.max(l, r); i++) { freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; } // ans String var ans = \"\"; // iterate in frequency array for (var i = 25; i >= 0; i--) { // add till all characters // are added while (freq[i] > 0) { ans += String.fromCharCode('a'.charCodeAt(0) + i); freq[i]--; } } return ans; } // Driver Code var s = \"striver\"; var l = 3, r = 5; document.write(printLargestString(s, l, r)); // This code is contributed by todaysgaurav</script>", "e": 30998, "s": 29920, "text": null }, { "code": null, "e": 31002, "s": 30998, "text": "vri" }, { "code": null, "e": 31150, "s": 31004, "text": "Time Complexity – O(N) Each element gets added to the frequency table only once which takes O(1) and is appended to string which also takes O(1)." }, { "code": null, "e": 31163, "s": 31150, "text": "imdhruvgupta" }, { "code": null, "e": 31175, "s": 31163, "text": "29AjayKumar" }, { "code": null, "e": 31181, "s": 31175, "text": "ukasp" }, { "code": null, "e": 31194, "s": 31181, "text": "todaysgaurav" }, { "code": null, "e": 31207, "s": 31194, "text": "ankita_saini" }, { "code": null, "e": 31217, "s": 31207, "text": "kk9826225" }, { "code": null, "e": 31236, "s": 31217, "text": "frequency-counting" }, { "code": null, "e": 31260, "s": 31236, "text": "Technical Scripter 2018" }, { "code": null, "e": 31284, "s": 31260, "text": "Competitive Programming" }, { "code": null, "e": 31292, "s": 31284, "text": "Strings" }, { "code": null, "e": 31300, "s": 31292, "text": "Strings" }, { "code": null, "e": 31398, "s": 31300, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31407, "s": 31398, "text": "Comments" }, { "code": null, "e": 31420, "s": 31407, "text": "Old Comments" }, { "code": null, "e": 31458, "s": 31420, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 31483, "s": 31458, "text": "Formatted output in Java" }, { "code": null, "e": 31531, "s": 31483, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 31574, "s": 31531, "text": "How to begin with Competitive Programming?" }, { "code": null, "e": 31601, "s": 31574, "text": "Use of FLAG in programming" }, { "code": null, "e": 31626, "s": 31601, "text": "Reverse a string in Java" }, { "code": null, "e": 31672, "s": 31626, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31706, "s": 31672, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 31766, "s": 31706, "text": "Write a program to print all permutations of a given string" } ]
How to get device make and model on iOS?
When we talk about the device make, we refer to the Phone manufacturer (e.g. Apple, Samsung, Nokia and so on) and device model is generally the specific product such as iPhone, iPad/TAB etc. Any mobile devices will be categorized using make and model only. Now let’s understand how do I get device make and model in iOS? There are two ways to get make and model the first way is to directly open your iOS device, navigate to setting, tap on general and in the about section you can find the details of your iOS device The second way is getting make and model using Open Xcode → New Project and add the below code in ViewController’s viewDidLoad method. let modelName = UIDevice.current.model let name = UIDevice.current.name print(modelName) // iPhone print(name) // iPhone XR UIDevice.current.model, gives you a model whether you have an iPhone, iPad, UIDevice.current.name gives you a name identifying the device.
[ { "code": null, "e": 1253, "s": 1062, "text": "When we talk about the device make, we refer to the Phone manufacturer (e.g. Apple, Samsung, Nokia and so on) and device model is generally the specific product such as iPhone, iPad/TAB etc." }, { "code": null, "e": 1319, "s": 1253, "text": "Any mobile devices will be categorized using make and model only." }, { "code": null, "e": 1383, "s": 1319, "text": "Now let’s understand how do I get device make and model in iOS?" }, { "code": null, "e": 1580, "s": 1383, "text": "There are two ways to get make and model the first way is to directly open your iOS device, navigate to setting, tap on general and in the about section you can find the details of your iOS device" }, { "code": null, "e": 1627, "s": 1580, "text": "The second way is getting make and model using" }, { "code": null, "e": 1715, "s": 1627, "text": "Open Xcode → New Project and add the below code in ViewController’s viewDidLoad method." }, { "code": null, "e": 1840, "s": 1715, "text": "let modelName = UIDevice.current.model\nlet name = UIDevice.current.name\n\nprint(modelName) // iPhone\nprint(name) // iPhone XR" }, { "code": null, "e": 1979, "s": 1840, "text": "UIDevice.current.model, gives you a model whether you have an iPhone, iPad, UIDevice.current.name gives you a name identifying the device." } ]
NODE_ENV Variables and How to Use Them ? - GeeksforGeeks
22 Jul, 2020 Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicates whether the server is running on development or production mode. The express framework checks the flag value in the runtime and sets value depending on the environment. Setting NODE_ENV Variable: Setting up the NODE_ENV variable depends on the operating system and also on the user’s setup. To set the environment variable globally to some value, we can run the code from the command line. For Linux and Mac Operating System: export NODE_ENV = production For Windows Operating System $env:NODE_ENV = 'production' We can also apply the environment variable in the application initialization command using the code below assuming we are running a script called app.js. NODE_ENV = production node app.js In Windows, the code is different. We use the code below: set NODE_ENV=production&&node app.js Because different operating systems require different command, there is a package available called cross-env which makes the command cross-platform. npx cross-env NODE_ENV=production node app.js The above code will work on any platform where the cross-env package is installed as a developer dependency. If we are using express, we can provide environment-specific settings that are automatically called based on the environment we are working on. Syntax: if(process.env.NODE_ENV == 'development') { // Code for Development Mode} else { // Code for Testing Mode} Suppose our database server is the localhost when we are working on development mode and we’ll be using https://production-server.com for production. The code can be set accordingly. if(process.env.NODE_ENV == 'development') { db.connect('localhost:1234')} else { db.connect('https://production-server.com')} The above code will check the environment and will set it’s server accordingly. Conclusion: Use of the production environment is a good practice because in the production environment, usually logging is kept minimum also more caching levels take place for optimized performance. So, it is always a good practice to set up the environment variable to production mode whenever we are deploying our app to the production server. Node.js-Misc 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 Node.js fs.readFile() Method 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 Roadmap to Become a Web Developer in 2022 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? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24952, "s": 24924, "text": "\n22 Jul, 2020" }, { "code": null, "e": 25423, "s": 24952, "text": "Introduction: NODE_ENV variables are environment variables that are made popularized by the express framework. The value of this type of variable can be set dynamically depending on the environment(i.e., development/production) the program is running on. The NODE_ENV works like a flag which indicates whether the server is running on development or production mode. The express framework checks the flag value in the runtime and sets value depending on the environment." }, { "code": null, "e": 25545, "s": 25423, "text": "Setting NODE_ENV Variable: Setting up the NODE_ENV variable depends on the operating system and also on the user’s setup." }, { "code": null, "e": 25644, "s": 25545, "text": "To set the environment variable globally to some value, we can run the code from the command line." }, { "code": null, "e": 25680, "s": 25644, "text": "For Linux and Mac Operating System:" }, { "code": null, "e": 25709, "s": 25680, "text": "export NODE_ENV = production" }, { "code": null, "e": 25738, "s": 25709, "text": "For Windows Operating System" }, { "code": null, "e": 25767, "s": 25738, "text": "$env:NODE_ENV = 'production'" }, { "code": null, "e": 25921, "s": 25767, "text": "We can also apply the environment variable in the application initialization command using the code below assuming we are running a script called app.js." }, { "code": null, "e": 25955, "s": 25921, "text": "NODE_ENV = production node app.js" }, { "code": null, "e": 26013, "s": 25955, "text": "In Windows, the code is different. We use the code below:" }, { "code": null, "e": 26050, "s": 26013, "text": "set NODE_ENV=production&&node app.js" }, { "code": null, "e": 26200, "s": 26050, "text": "Because different operating systems require different command, there is a package available called cross-env which makes the command cross-platform. " }, { "code": null, "e": 26246, "s": 26200, "text": "npx cross-env NODE_ENV=production node app.js" }, { "code": null, "e": 26355, "s": 26246, "text": "The above code will work on any platform where the cross-env package is installed as a developer dependency." }, { "code": null, "e": 26499, "s": 26355, "text": "If we are using express, we can provide environment-specific settings that are automatically called based on the environment we are working on." }, { "code": null, "e": 26507, "s": 26499, "text": "Syntax:" }, { "code": "if(process.env.NODE_ENV == 'development') { // Code for Development Mode} else { // Code for Testing Mode}", "e": 26618, "s": 26507, "text": null }, { "code": null, "e": 26801, "s": 26618, "text": "Suppose our database server is the localhost when we are working on development mode and we’ll be using https://production-server.com for production. The code can be set accordingly." }, { "code": "if(process.env.NODE_ENV == 'development') { db.connect('localhost:1234')} else { db.connect('https://production-server.com')}", "e": 26933, "s": 26801, "text": null }, { "code": null, "e": 27013, "s": 26933, "text": "The above code will check the environment and will set it’s server accordingly." }, { "code": null, "e": 27359, "s": 27013, "text": "Conclusion: Use of the production environment is a good practice because in the production environment, usually logging is kept minimum also more caching levels take place for optimized performance. So, it is always a good practice to set up the environment variable to production mode whenever we are deploying our app to the production server." }, { "code": null, "e": 27372, "s": 27359, "text": "Node.js-Misc" }, { "code": null, "e": 27380, "s": 27372, "text": "Node.js" }, { "code": null, "e": 27397, "s": 27380, "text": "Web Technologies" }, { "code": null, "e": 27495, "s": 27397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27504, "s": 27495, "text": "Comments" }, { "code": null, "e": 27517, "s": 27504, "text": "Old Comments" }, { "code": null, "e": 27554, "s": 27517, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27583, "s": 27554, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 27613, "s": 27583, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27670, "s": 27613, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27724, "s": 27670, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27766, "s": 27724, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27828, "s": 27766, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27871, "s": 27828, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27921, "s": 27871, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Machine Learning in Java. How to build and deploy ML models in... | by Mohammed Alhamid | Towards Data Science
Machine Learning (ML) has bought significant promises in different fields in both academia and industry. Day by day, ML has grown its engagement in a comprehensive list of applications such as image, speech recognition, pattern recognition, optimization, natural language processing, and recommendations, and so many others. Programming computers to learn from experience should eventually eliminate the need for much of this detailed programming effort. — Arthur Samuel 1959. Machine Learning can be divided into four main techniques: regression, classification, clustering, and reinforcement learning. Those techniques solve problems with different natures in mainly two forms: supervised and unsupervised learning. Supervised learning requires the data to be labeled and prepared ahead of training the model. Unsupervised learning comes in handy to handle unlabeled data or data that has unknown characteristics. This article does not describe ML’s concepts or go in in-depth describing the terms used in this field. If you are entirely new, please look at my previous article starting your ML learning journey. Here is a list of well-known libraries in Java for ML. We will describe them one by one and give real-world examples using some of those frameworks. Weka Apache Mahout Deeplearning4j Mallet Spark MLlib The Encog Machine Learning Framework MOA Next to each library, the following icons would indicate the major categories of algorithms provided in each framework by default. Weka is an open-source library developed by the University of Waikato in New Zeland. Weka is written in Java, and it is very well-known for general-purpose machine learning. Weka provides a data file format, called ARFF. ARFF is split into two parts: header and the actual data. The header describes the attributes and their data types. Apache Mahout provides a scalable machine learning library. Mahout uses the MapReduce paradigm and can be used for classification, collaborative filtering, and clustering. Mahout utilizes Apache Hadoop to process multiple parallel tasks. In addition to classification and clustering, Mahout provides recommendation algorithms such as collaborative filtering, facilitating the scalability of building your model quickly. Deeplearning4j is another java library focusing on deep learning. It is one great open-source libraries of deep learning for Java. It is also written in Scala and Java and can be integrated with Hadoop and Spark, providing high processing capabilities. The current release is in the Beta version but comes with excellent documentation and quick start examples (click here). Mallet stands for Machine Learning for Language Toolkit. It is one of few specialized toolkits for natural language processing. It provides capabilities for topic modeling, document classification, clustering, and information extraction. With Mallet, we can ML models to process textual documents. Spark is very well known to accelerate the scalability and overall performance of processing a massive amount of data. Spark MLlib also has high power algorithms to run on spark and plugged into Hadoop workflows. Encog is a Java and C# framework for ML. Envog has libraries for building SVM, NN, Bayesian Networks, HMM, and genetic algorithms. Encog has started as a research project and got almost a thousand citations on Google Scholar. Massive Online Analysis (MOA) provides algorithms for classification, regression, clustering, and recommendations. It also provides libraries for outlier detection and drift detection. It is designed for real-time processing on a stream of produced data. We are going to use a small diabetes dataset. We will first load the data using Weka: import weka.core.Instances;import weka.core.converters.ConverterUtils.DataSource;public class Main { public static void main(String[] args) throws Exception { // Specifying the datasource DataSource dataSource = new DataSource("data.arff"); // Loading the dataset Instances dataInstances = dataSource.getDataSet(); // Displaying the number of instances log.info("The number of loaded instances is: " + dataInstances.numInstances()); log.info("data:" + dataInstances.toString()); }} There are 768 instances in the dataset. Let’s see how to get the number of attributes (features), which should be 9. log.info("The number of attributes in the dataset: " + dataInstances.numAttributes()); Before building any model, we want to identify which column is the target column and see how many classes are found in this column: // Identifying the label indexdataInstances.setClassIndex(dataInstances.numAttributes() - 1);// Getting the number of log.info("The number of classes: " + dataInstances.numClasses()); After loading the dataset and identifying our target attribute, the time now is for building the model. Let’s make a simple tree classifier, J48. // Creating a decision tree classifierJ48 treeClassifier = new J48();treeClassifier.setOptions(new String[] { "-U" });treeClassifier.buildClassifier(dataInstances); In the three lines above, we specified an option to indicate an unpruned tree and provided the data instances for model training. If we print the tree structure of the generated model after training, we can follow how the model internally built its rules: plas <= 127| mass <= 26.4| | preg <= 7: tested_negative (117.0/1.0)| | preg > 7| | | mass <= 0: tested_positive (2.0)| | | mass > 0: tested_negative (13.0)| mass > 26.4| | age <= 28: tested_negative (180.0/22.0)| | age > 28| | | plas <= 99: tested_negative (55.0/10.0)| | | plas > 99| | | | pedi <= 0.56: tested_negative (84.0/34.0)| | | | pedi > 0.56| | | | | preg <= 6| | | | | | age <= 30: tested_positive (4.0)| | | | | | age > 30| | | | | | | age <= 34: tested_negative (7.0/1.0)| | | | | | | age > 34| | | | | | | | mass <= 33.1: tested_positive (6.0)| | | | | | | | mass > 33.1: tested_negative (4.0/1.0)| | | | | preg > 6: tested_positive (13.0)plas > 127| mass <= 29.9| | plas <= 145: tested_negative (41.0/6.0)| | plas > 145| | | age <= 25: tested_negative (4.0)| | | age > 25| | | | age <= 61| | | | | mass <= 27.1: tested_positive (12.0/1.0)| | | | | mass > 27.1| | | | | | pres <= 82| | | | | | | pedi <= 0.396: tested_positive (8.0/1.0)| | | | | | | pedi > 0.396: tested_negative (3.0)| | | | | | pres > 82: tested_negative (4.0)| | | | age > 61: tested_negative (4.0)| mass > 29.9| | plas <= 157| | | pres <= 61: tested_positive (15.0/1.0)| | | pres > 61| | | | age <= 30: tested_negative (40.0/13.0)| | | | age > 30: tested_positive (60.0/17.0)| | plas > 157: tested_positive (92.0/12.0)Number of Leaves : 22Size of the tree : 43 This example will build a Convolution Neural Network (CNN) model to classify the MNIST library. If you are not familiar with MNIST or how the CNN works to classify the handwritten digits, I recommend you have a quick look at my earlier post, which describes these aspects in detail. As always, we will load the dataset and display its size. DataSetIterator MNISTTrain = new MnistDataSetIterator(batchSize,true,seed);DataSetIterator MNISTTest = new MnistDataSetIterator(batchSize,false,seed); Let double check if we get ten unique labels from the dataset: log.info("The number of total labels found in the training dataset " + MNISTTrain.totalOutcomes());log.info("The number of total labels found in the test dataset " + MNISTTest.totalOutcomes()); Next, let’s configure the architecture of the model. We will use two convolution layers plus a flattened layer for the output. Deeplearning4j has several options that you can use to initialize the weight scheme. // Building the CNN modelMultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .seed(seed) // random seed .l2(0.0005) // regularization .weightInit(WeightInit.XAVIER) // initialization of the weight scheme .updater(new Adam(1e-3)) // Setting the optimization algorithm .list() .layer(new ConvolutionLayer.Builder(5, 5) //Setting the stride, the kernel size, and the activation function. .nIn(nChannels) .stride(1,1) .nOut(20) .activation(Activation.IDENTITY) .build()) .layer(new SubsamplingLayer.Builder(PoolingType.MAX) // downsampling the convolution .kernelSize(2,2) .stride(2,2) .build()) .layer(new ConvolutionLayer.Builder(5, 5) // Setting the stride, kernel size, and the activation function. .stride(1,1) .nOut(50) .activation(Activation.IDENTITY) .build()) .layer(new SubsamplingLayer.Builder(PoolingType.MAX) // downsampling the convolution .kernelSize(2,2) .stride(2,2) .build()) .layer(new DenseLayer.Builder().activation(Activation.RELU) .nOut(500).build()) .layer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) .nOut(outputNum) .activation(Activation.SOFTMAX) .build()) // the final output layer is 28x28 with a depth of 1. .setInputType(InputType.convolutionalFlat(28,28,1)) .build(); Once the architecture is set, we need to initialize the mode, set the training dataset, and trigger the model training. MultiLayerNetwork model = new MultiLayerNetwork(conf);// initialize the model weights.model.init();log.info("Step2: start training the model");//Setting a listener every 10 iterations and evaluate on test set on every epochmodel.setListeners(new ScoreIterationListener(10), new EvaluativeListener(MNISTTest, 1, InvocationType.EPOCH_END));// Training the modelmodel.fit(MNISTTrain, nEpochs); During the training, the score listener will provide the confusion matrix of the classification accuracy. Let’s see the accuracy after ten epochs of training: =========================Confusion Matrix========================= 0 1 2 3 4 5 6 7 8 9--------------------------------------------------- 977 0 0 0 0 0 1 1 1 0 | 0 = 0 0 1131 0 1 0 1 2 0 0 0 | 1 = 1 1 2 1019 3 0 0 0 3 4 0 | 2 = 2 0 0 1 1004 0 1 0 1 3 0 | 3 = 3 0 0 0 0 977 0 2 0 1 2 | 4 = 4 1 0 0 9 0 879 1 0 1 1 | 5 = 5 4 2 0 0 1 1 949 0 1 0 | 6 = 6 0 4 2 1 1 0 0 1018 1 1 | 7 = 7 2 0 3 1 0 1 1 2 962 2 | 8 = 8 0 2 0 2 11 2 0 3 2 987 | 9 = 9 As mentioned earlier, Mallet is a powerful toolkit for natural language modeling. We will use a sample corpus provided by the tool David Blei in Mallet package. Mallet has a specific library for annotating textual tokens for classification. Before we load our dataset, Mallet has this concept of pipeline definition where you define your pipeline and then provide the dataset to pass through. ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); The pipeline is defined as an “ArrayList,” which would contain typical steps that we always do before building a topic model. Each text in the document would pass the following steps: Lowercase keywordsTokenize textRemove stopwordsMap to features Lowercase keywords Tokenize text Remove stopwords Map to features pipeList.add( new CharSequenceLowercase() );pipeList.add( new CharSequence2TokenSequence(Pattern.compile("\\p{L}[\\p{L}\\p{P}]+\\p{L}")) );// Setting the dictionary of the stop wordsURL stopWordsFile = getClass().getClassLoader().getResource("stoplists/en.txt");pipeList.add( new TokenSequenceRemoveStopwords(new File(stopWordsFile.toURI()), "UTF-8", false, false, false) );pipeList.add( new TokenSequence2FeatureSequence() ); Once the pipeline is defined, we will pass the instances representing an original text of each document. InstanceList instances = new InstanceList (new SerialPipes(pipeList)); Now the step comes to pass the input file to fill up the instance list. URL inputFileURL = getClass().getClassLoader().getResource(inputFile);Reader fileReader = new InputStreamReader(new FileInputStream(new File(inputFileURL.toURI())), "UTF-8");instances.addThruPipe(new CsvIterator (fileReader, Pattern.compile("^(\\S*)[\\s,]*(\\S*)[\\s,]*(.*)$"), 3, 2, 1)); // data, label, name fields From the last command line, you can notice that we provided instructions on how the CSV file is structured. The source file, available in the resources folder, has around two thousand rows. Each line represents an original document text and consists of three attributes separated by comma (Name, label, and document content). We can print the number of instances found in the input document using the following command: log.info("The number of instances found in the input file is: " + instances.size()); Now, let’s model the document’s topics. Let’s assume that we have 100 different topics in those 2k documents. Mallet enables us to set two variables: alpha and beta weights. Alpha controls the topic-word distributions’ concentration, and beta represents the pre-word weights over the topic-word distributions. int numTopics = 100;// defining the model ParallelTopicModel model = new ParallelTopicModel(numTopics, 1.0, 0.01);// adding the instances to the modelmodel.addInstances(instances); The model we choose in this example is an implementation of LDA (Latent Dirichlet allocation). The algorithm uses a group of observed keywords similarity to classify documents. One of the things I like about Mallet is the API capabilities to design your parallel processing easily. Here, we can define multithread processing for each subsample. model.setNumThreads(2); We only two things left now is defining the number of iterations for the model training and get the training started. model.setNumIterations(50);model.estimate(); I left more details on how to display the topic modeling result in the full example on github. [Book]: Machine Learning in Java by Boštjan Kaluža and published by O’Reilly. [Book]: Machine Learning: End-to-End guide for Java developers by Richard M. Reese, Jennifer L. Reese, Bostjan Kaluza, Dr. Uday Kamath, Krishna Choppella. [Tutorial] Spark MLlib Examples. [Tutorial] Machine Learning with Mallet. All the examples provided in this post are available on my Github reprository.
[ { "code": null, "e": 372, "s": 47, "text": "Machine Learning (ML) has bought significant promises in different fields in both academia and industry. Day by day, ML has grown its engagement in a comprehensive list of applications such as image, speech recognition, pattern recognition, optimization, natural language processing, and recommendations, and so many others." }, { "code": null, "e": 524, "s": 372, "text": "Programming computers to learn from experience should eventually eliminate the need for much of this detailed programming effort. — Arthur Samuel 1959." }, { "code": null, "e": 1162, "s": 524, "text": "Machine Learning can be divided into four main techniques: regression, classification, clustering, and reinforcement learning. Those techniques solve problems with different natures in mainly two forms: supervised and unsupervised learning. Supervised learning requires the data to be labeled and prepared ahead of training the model. Unsupervised learning comes in handy to handle unlabeled data or data that has unknown characteristics. This article does not describe ML’s concepts or go in in-depth describing the terms used in this field. If you are entirely new, please look at my previous article starting your ML learning journey." }, { "code": null, "e": 1311, "s": 1162, "text": "Here is a list of well-known libraries in Java for ML. We will describe them one by one and give real-world examples using some of those frameworks." }, { "code": null, "e": 1316, "s": 1311, "text": "Weka" }, { "code": null, "e": 1330, "s": 1316, "text": "Apache Mahout" }, { "code": null, "e": 1345, "s": 1330, "text": "Deeplearning4j" }, { "code": null, "e": 1352, "s": 1345, "text": "Mallet" }, { "code": null, "e": 1364, "s": 1352, "text": "Spark MLlib" }, { "code": null, "e": 1401, "s": 1364, "text": "The Encog Machine Learning Framework" }, { "code": null, "e": 1405, "s": 1401, "text": "MOA" }, { "code": null, "e": 1536, "s": 1405, "text": "Next to each library, the following icons would indicate the major categories of algorithms provided in each framework by default." }, { "code": null, "e": 1873, "s": 1536, "text": "Weka is an open-source library developed by the University of Waikato in New Zeland. Weka is written in Java, and it is very well-known for general-purpose machine learning. Weka provides a data file format, called ARFF. ARFF is split into two parts: header and the actual data. The header describes the attributes and their data types." }, { "code": null, "e": 2293, "s": 1873, "text": "Apache Mahout provides a scalable machine learning library. Mahout uses the MapReduce paradigm and can be used for classification, collaborative filtering, and clustering. Mahout utilizes Apache Hadoop to process multiple parallel tasks. In addition to classification and clustering, Mahout provides recommendation algorithms such as collaborative filtering, facilitating the scalability of building your model quickly." }, { "code": null, "e": 2667, "s": 2293, "text": "Deeplearning4j is another java library focusing on deep learning. It is one great open-source libraries of deep learning for Java. It is also written in Scala and Java and can be integrated with Hadoop and Spark, providing high processing capabilities. The current release is in the Beta version but comes with excellent documentation and quick start examples (click here)." }, { "code": null, "e": 2965, "s": 2667, "text": "Mallet stands for Machine Learning for Language Toolkit. It is one of few specialized toolkits for natural language processing. It provides capabilities for topic modeling, document classification, clustering, and information extraction. With Mallet, we can ML models to process textual documents." }, { "code": null, "e": 3178, "s": 2965, "text": "Spark is very well known to accelerate the scalability and overall performance of processing a massive amount of data. Spark MLlib also has high power algorithms to run on spark and plugged into Hadoop workflows." }, { "code": null, "e": 3404, "s": 3178, "text": "Encog is a Java and C# framework for ML. Envog has libraries for building SVM, NN, Bayesian Networks, HMM, and genetic algorithms. Encog has started as a research project and got almost a thousand citations on Google Scholar." }, { "code": null, "e": 3659, "s": 3404, "text": "Massive Online Analysis (MOA) provides algorithms for classification, regression, clustering, and recommendations. It also provides libraries for outlier detection and drift detection. It is designed for real-time processing on a stream of produced data." }, { "code": null, "e": 3745, "s": 3659, "text": "We are going to use a small diabetes dataset. We will first load the data using Weka:" }, { "code": null, "e": 4282, "s": 3745, "text": "import weka.core.Instances;import weka.core.converters.ConverterUtils.DataSource;public class Main { public static void main(String[] args) throws Exception { // Specifying the datasource DataSource dataSource = new DataSource(\"data.arff\"); // Loading the dataset Instances dataInstances = dataSource.getDataSet(); // Displaying the number of instances log.info(\"The number of loaded instances is: \" + dataInstances.numInstances()); log.info(\"data:\" + dataInstances.toString()); }}" }, { "code": null, "e": 4399, "s": 4282, "text": "There are 768 instances in the dataset. Let’s see how to get the number of attributes (features), which should be 9." }, { "code": null, "e": 4486, "s": 4399, "text": "log.info(\"The number of attributes in the dataset: \" + dataInstances.numAttributes());" }, { "code": null, "e": 4618, "s": 4486, "text": "Before building any model, we want to identify which column is the target column and see how many classes are found in this column:" }, { "code": null, "e": 4802, "s": 4618, "text": "// Identifying the label indexdataInstances.setClassIndex(dataInstances.numAttributes() - 1);// Getting the number of log.info(\"The number of classes: \" + dataInstances.numClasses());" }, { "code": null, "e": 4948, "s": 4802, "text": "After loading the dataset and identifying our target attribute, the time now is for building the model. Let’s make a simple tree classifier, J48." }, { "code": null, "e": 5113, "s": 4948, "text": "// Creating a decision tree classifierJ48 treeClassifier = new J48();treeClassifier.setOptions(new String[] { \"-U\" });treeClassifier.buildClassifier(dataInstances);" }, { "code": null, "e": 5369, "s": 5113, "text": "In the three lines above, we specified an option to indicate an unpruned tree and provided the data instances for model training. If we print the tree structure of the generated model after training, we can follow how the model internally built its rules:" }, { "code": null, "e": 7030, "s": 5369, "text": "plas <= 127| mass <= 26.4| | preg <= 7: tested_negative (117.0/1.0)| | preg > 7| | | mass <= 0: tested_positive (2.0)| | | mass > 0: tested_negative (13.0)| mass > 26.4| | age <= 28: tested_negative (180.0/22.0)| | age > 28| | | plas <= 99: tested_negative (55.0/10.0)| | | plas > 99| | | | pedi <= 0.56: tested_negative (84.0/34.0)| | | | pedi > 0.56| | | | | preg <= 6| | | | | | age <= 30: tested_positive (4.0)| | | | | | age > 30| | | | | | | age <= 34: tested_negative (7.0/1.0)| | | | | | | age > 34| | | | | | | | mass <= 33.1: tested_positive (6.0)| | | | | | | | mass > 33.1: tested_negative (4.0/1.0)| | | | | preg > 6: tested_positive (13.0)plas > 127| mass <= 29.9| | plas <= 145: tested_negative (41.0/6.0)| | plas > 145| | | age <= 25: tested_negative (4.0)| | | age > 25| | | | age <= 61| | | | | mass <= 27.1: tested_positive (12.0/1.0)| | | | | mass > 27.1| | | | | | pres <= 82| | | | | | | pedi <= 0.396: tested_positive (8.0/1.0)| | | | | | | pedi > 0.396: tested_negative (3.0)| | | | | | pres > 82: tested_negative (4.0)| | | | age > 61: tested_negative (4.0)| mass > 29.9| | plas <= 157| | | pres <= 61: tested_positive (15.0/1.0)| | | pres > 61| | | | age <= 30: tested_negative (40.0/13.0)| | | | age > 30: tested_positive (60.0/17.0)| | plas > 157: tested_positive (92.0/12.0)Number of Leaves : 22Size of the tree : 43" }, { "code": null, "e": 7313, "s": 7030, "text": "This example will build a Convolution Neural Network (CNN) model to classify the MNIST library. If you are not familiar with MNIST or how the CNN works to classify the handwritten digits, I recommend you have a quick look at my earlier post, which describes these aspects in detail." }, { "code": null, "e": 7371, "s": 7313, "text": "As always, we will load the dataset and display its size." }, { "code": null, "e": 7522, "s": 7371, "text": "DataSetIterator MNISTTrain = new MnistDataSetIterator(batchSize,true,seed);DataSetIterator MNISTTest = new MnistDataSetIterator(batchSize,false,seed);" }, { "code": null, "e": 7585, "s": 7522, "text": "Let double check if we get ten unique labels from the dataset:" }, { "code": null, "e": 7779, "s": 7585, "text": "log.info(\"The number of total labels found in the training dataset \" + MNISTTrain.totalOutcomes());log.info(\"The number of total labels found in the test dataset \" + MNISTTest.totalOutcomes());" }, { "code": null, "e": 7991, "s": 7779, "text": "Next, let’s configure the architecture of the model. We will use two convolution layers plus a flattened layer for the output. Deeplearning4j has several options that you can use to initialize the weight scheme." }, { "code": null, "e": 9646, "s": 7991, "text": "// Building the CNN modelMultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() .seed(seed) // random seed .l2(0.0005) // regularization .weightInit(WeightInit.XAVIER) // initialization of the weight scheme .updater(new Adam(1e-3)) // Setting the optimization algorithm .list() .layer(new ConvolutionLayer.Builder(5, 5) //Setting the stride, the kernel size, and the activation function. .nIn(nChannels) .stride(1,1) .nOut(20) .activation(Activation.IDENTITY) .build()) .layer(new SubsamplingLayer.Builder(PoolingType.MAX) // downsampling the convolution .kernelSize(2,2) .stride(2,2) .build()) .layer(new ConvolutionLayer.Builder(5, 5) // Setting the stride, kernel size, and the activation function. .stride(1,1) .nOut(50) .activation(Activation.IDENTITY) .build()) .layer(new SubsamplingLayer.Builder(PoolingType.MAX) // downsampling the convolution .kernelSize(2,2) .stride(2,2) .build()) .layer(new DenseLayer.Builder().activation(Activation.RELU) .nOut(500).build()) .layer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) .nOut(outputNum) .activation(Activation.SOFTMAX) .build()) // the final output layer is 28x28 with a depth of 1. .setInputType(InputType.convolutionalFlat(28,28,1)) .build();" }, { "code": null, "e": 9766, "s": 9646, "text": "Once the architecture is set, we need to initialize the mode, set the training dataset, and trigger the model training." }, { "code": null, "e": 10157, "s": 9766, "text": "MultiLayerNetwork model = new MultiLayerNetwork(conf);// initialize the model weights.model.init();log.info(\"Step2: start training the model\");//Setting a listener every 10 iterations and evaluate on test set on every epochmodel.setListeners(new ScoreIterationListener(10), new EvaluativeListener(MNISTTest, 1, InvocationType.EPOCH_END));// Training the modelmodel.fit(MNISTTrain, nEpochs);" }, { "code": null, "e": 10316, "s": 10157, "text": "During the training, the score listener will provide the confusion matrix of the classification accuracy. Let’s see the accuracy after ten epochs of training:" }, { "code": null, "e": 11064, "s": 10316, "text": "=========================Confusion Matrix========================= 0 1 2 3 4 5 6 7 8 9--------------------------------------------------- 977 0 0 0 0 0 1 1 1 0 | 0 = 0 0 1131 0 1 0 1 2 0 0 0 | 1 = 1 1 2 1019 3 0 0 0 3 4 0 | 2 = 2 0 0 1 1004 0 1 0 1 3 0 | 3 = 3 0 0 0 0 977 0 2 0 1 2 | 4 = 4 1 0 0 9 0 879 1 0 1 1 | 5 = 5 4 2 0 0 1 1 949 0 1 0 | 6 = 6 0 4 2 1 1 0 0 1018 1 1 | 7 = 7 2 0 3 1 0 1 1 2 962 2 | 8 = 8 0 2 0 2 11 2 0 3 2 987 | 9 = 9" }, { "code": null, "e": 11457, "s": 11064, "text": "As mentioned earlier, Mallet is a powerful toolkit for natural language modeling. We will use a sample corpus provided by the tool David Blei in Mallet package. Mallet has a specific library for annotating textual tokens for classification. Before we load our dataset, Mallet has this concept of pipeline definition where you define your pipeline and then provide the dataset to pass through." }, { "code": null, "e": 11507, "s": 11457, "text": "ArrayList<Pipe> pipeList = new ArrayList<Pipe>();" }, { "code": null, "e": 11691, "s": 11507, "text": "The pipeline is defined as an “ArrayList,” which would contain typical steps that we always do before building a topic model. Each text in the document would pass the following steps:" }, { "code": null, "e": 11754, "s": 11691, "text": "Lowercase keywordsTokenize textRemove stopwordsMap to features" }, { "code": null, "e": 11773, "s": 11754, "text": "Lowercase keywords" }, { "code": null, "e": 11787, "s": 11773, "text": "Tokenize text" }, { "code": null, "e": 11804, "s": 11787, "text": "Remove stopwords" }, { "code": null, "e": 11820, "s": 11804, "text": "Map to features" }, { "code": null, "e": 12247, "s": 11820, "text": "pipeList.add( new CharSequenceLowercase() );pipeList.add( new CharSequence2TokenSequence(Pattern.compile(\"\\\\p{L}[\\\\p{L}\\\\p{P}]+\\\\p{L}\")) );// Setting the dictionary of the stop wordsURL stopWordsFile = getClass().getClassLoader().getResource(\"stoplists/en.txt\");pipeList.add( new TokenSequenceRemoveStopwords(new File(stopWordsFile.toURI()), \"UTF-8\", false, false, false) );pipeList.add( new TokenSequence2FeatureSequence() );" }, { "code": null, "e": 12352, "s": 12247, "text": "Once the pipeline is defined, we will pass the instances representing an original text of each document." }, { "code": null, "e": 12423, "s": 12352, "text": "InstanceList instances = new InstanceList (new SerialPipes(pipeList));" }, { "code": null, "e": 12495, "s": 12423, "text": "Now the step comes to pass the input file to fill up the instance list." }, { "code": null, "e": 12819, "s": 12495, "text": "URL inputFileURL = getClass().getClassLoader().getResource(inputFile);Reader fileReader = new InputStreamReader(new FileInputStream(new File(inputFileURL.toURI())), \"UTF-8\");instances.addThruPipe(new CsvIterator (fileReader, Pattern.compile(\"^(\\\\S*)[\\\\s,]*(\\\\S*)[\\\\s,]*(.*)$\"), 3, 2, 1)); // data, label, name fields" }, { "code": null, "e": 13239, "s": 12819, "text": "From the last command line, you can notice that we provided instructions on how the CSV file is structured. The source file, available in the resources folder, has around two thousand rows. Each line represents an original document text and consists of three attributes separated by comma (Name, label, and document content). We can print the number of instances found in the input document using the following command:" }, { "code": null, "e": 13324, "s": 13239, "text": "log.info(\"The number of instances found in the input file is: \" + instances.size());" }, { "code": null, "e": 13634, "s": 13324, "text": "Now, let’s model the document’s topics. Let’s assume that we have 100 different topics in those 2k documents. Mallet enables us to set two variables: alpha and beta weights. Alpha controls the topic-word distributions’ concentration, and beta represents the pre-word weights over the topic-word distributions." }, { "code": null, "e": 13815, "s": 13634, "text": "int numTopics = 100;// defining the model ParallelTopicModel model = new ParallelTopicModel(numTopics, 1.0, 0.01);// adding the instances to the modelmodel.addInstances(instances);" }, { "code": null, "e": 13992, "s": 13815, "text": "The model we choose in this example is an implementation of LDA (Latent Dirichlet allocation). The algorithm uses a group of observed keywords similarity to classify documents." }, { "code": null, "e": 14160, "s": 13992, "text": "One of the things I like about Mallet is the API capabilities to design your parallel processing easily. Here, we can define multithread processing for each subsample." }, { "code": null, "e": 14184, "s": 14160, "text": "model.setNumThreads(2);" }, { "code": null, "e": 14302, "s": 14184, "text": "We only two things left now is defining the number of iterations for the model training and get the training started." }, { "code": null, "e": 14347, "s": 14302, "text": "model.setNumIterations(50);model.estimate();" }, { "code": null, "e": 14442, "s": 14347, "text": "I left more details on how to display the topic modeling result in the full example on github." }, { "code": null, "e": 14522, "s": 14442, "text": "[Book]: Machine Learning in Java by Boštjan Kaluža and published by O’Reilly." }, { "code": null, "e": 14677, "s": 14522, "text": "[Book]: Machine Learning: End-to-End guide for Java developers by Richard M. Reese, Jennifer L. Reese, Bostjan Kaluza, Dr. Uday Kamath, Krishna Choppella." }, { "code": null, "e": 14710, "s": 14677, "text": "[Tutorial] Spark MLlib Examples." }, { "code": null, "e": 14751, "s": 14710, "text": "[Tutorial] Machine Learning with Mallet." } ]
DynamoDB - Load Table
Loading a table generally consists of creating a source file, ensuring the source file conforms to a syntax compatible with DynamoDB, sending the source file to the destination, and then confirming a successful population. Utilize the GUI console, Java, or another option to perform the task. Load data using a combination of the command line and console. You can load data in multiple ways, some of which are as follows − The Console The Command Line Code and also Data Pipeline (a feature discussed later in the tutorial) However, for speed, this example uses both the shell and console. First, load the source data into the destination with the following syntax − aws dynamodb batch-write-item -–request-items file://[filename] For example − aws dynamodb batch-write-item -–request-items file://MyProductData.json Verify the success of the operation by accessing the console at − https://console.aws.amazon.com/dynamodb Choose Tables from the navigation pane, and select the destination table from the table list. Select the Items tab to examine the data you used to populate the table. Select Cancel to return to the table list. Employ Java by first creating a source file. Our source file uses JSON format. Each product has two primary key attributes (ID and Nomenclature) and a JSON map (Stat) − [ { "ID" : ... , "Nomenclature" : ... , "Stat" : { ... } }, { "ID" : ... , "Nomenclature" : ... , "Stat" : { ... } }, ... ] You can review the following example − { "ID" : 122, "Nomenclature" : "Particle Blaster 5000", "Stat" : { "Manufacturer" : "XYZ Inc.", "sales" : "1M+", "quantity" : 500, "img_src" : "http://www.xyz.com/manuals/particleblaster5000.jpg", "description" : "A laser cutter used in plastic manufacturing." } } The next step is to place the file in the directory used by your application. Java primarily uses the putItem and path methods to perform the load. You can review the following code example for processing a file and loading it − import java.io.File; import java.util.Iterator; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode; public class ProductsLoadData { public static void main(String[] args) throws Exception { AmazonDynamoDBClient client = new AmazonDynamoDBClient() .withEndpoint("http://localhost:8000"); DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("Products"); JsonParser parser = new JsonFactory() .createParser(new File("productinfo.json")); JsonNode rootNode = new ObjectMapper().readTree(parser); Iterator<JsonNode> iter = rootNode.iterator(); ObjectNode currentNode; while (iter.hasNext()) { currentNode = (ObjectNode) iter.next(); int ID = currentNode.path("ID").asInt(); String Nomenclature = currentNode.path("Nomenclature").asText(); try { table.putItem(new Item() .withPrimaryKey("ID", ID, "Nomenclature", Nomenclature) .withJSON("Stat", currentNode.path("Stat").toString())); System.out.println("Successful load: " + ID + " " + Nomenclature); } catch (Exception e) { System.err.println("Cannot add product: " + ID + " " + Nomenclature); System.err.println(e.getMessage()); break; } } parser.close(); } } 16 Lectures 1.5 hours Harshit Srivastava 49 Lectures 3.5 hours Niyazi Erdogan 48 Lectures 3 hours Niyazi Erdogan 13 Lectures 1 hours Harshit Srivastava 45 Lectures 4 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2614, "s": 2391, "text": "Loading a table generally consists of creating a source file, ensuring the source file conforms to a syntax compatible with DynamoDB, sending the source file to the destination, and then confirming a successful population." }, { "code": null, "e": 2684, "s": 2614, "text": "Utilize the GUI console, Java, or another option to perform the task." }, { "code": null, "e": 2814, "s": 2684, "text": "Load data using a combination of the command line and console. You can load data in multiple ways, some of which are as follows −" }, { "code": null, "e": 2826, "s": 2814, "text": "The Console" }, { "code": null, "e": 2843, "s": 2826, "text": "The Command Line" }, { "code": null, "e": 2857, "s": 2843, "text": "Code and also" }, { "code": null, "e": 2915, "s": 2857, "text": "Data Pipeline (a feature discussed later in the tutorial)" }, { "code": null, "e": 3058, "s": 2915, "text": "However, for speed, this example uses both the shell and console. First, load the source data into the destination with the following syntax −" }, { "code": null, "e": 3123, "s": 3058, "text": "aws dynamodb batch-write-item -–request-items file://[filename]\n" }, { "code": null, "e": 3137, "s": 3123, "text": "For example −" }, { "code": null, "e": 3210, "s": 3137, "text": "aws dynamodb batch-write-item -–request-items file://MyProductData.json\n" }, { "code": null, "e": 3276, "s": 3210, "text": "Verify the success of the operation by accessing the console at −" }, { "code": null, "e": 3316, "s": 3276, "text": "https://console.aws.amazon.com/dynamodb" }, { "code": null, "e": 3410, "s": 3316, "text": "Choose Tables from the navigation pane, and select the destination table from the table list." }, { "code": null, "e": 3526, "s": 3410, "text": "Select the Items tab to examine the data you used to populate the table. Select Cancel to return to the table list." }, { "code": null, "e": 3695, "s": 3526, "text": "Employ Java by first creating a source file. Our source file uses JSON format. Each product has two primary key attributes (ID and Nomenclature) and a JSON map (Stat) −" }, { "code": null, "e": 3883, "s": 3695, "text": "[ \n { \n \"ID\" : ... , \n \"Nomenclature\" : ... , \n \"Stat\" : { ... }\n }, \n { \n \"ID\" : ... , \n \"Nomenclature\" : ... , \n \"Stat\" : { ... } \n }, \n ... \n] " }, { "code": null, "e": 3922, "s": 3883, "text": "You can review the following example −" }, { "code": null, "e": 4239, "s": 3922, "text": "{ \n \"ID\" : 122, \n \"Nomenclature\" : \"Particle Blaster 5000\", \n \"Stat\" : { \n \"Manufacturer\" : \"XYZ Inc.\", \n \"sales\" : \"1M+\", \n \"quantity\" : 500, \n \"img_src\" : \"http://www.xyz.com/manuals/particleblaster5000.jpg\", \n \"description\" : \"A laser cutter used in plastic manufacturing.\" \n } \n}" }, { "code": null, "e": 4317, "s": 4239, "text": "The next step is to place the file in the directory used by your application." }, { "code": null, "e": 4387, "s": 4317, "text": "Java primarily uses the putItem and path methods to perform the load." }, { "code": null, "e": 4468, "s": 4387, "text": "You can review the following code example for processing a file and loading it −" }, { "code": null, "e": 6326, "s": 4468, "text": "import java.io.File;\nimport java.util.Iterator;\n\nimport com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;\nimport com.amazonaws.services.dynamodbv2.document.DynamoDB;\nimport com.amazonaws.services.dynamodbv2.document.Item;\nimport com.amazonaws.services.dynamodbv2.document.Table;\n\nimport com.fasterxml.jackson.core.JsonFactory;\nimport com.fasterxml.jackson.core.JsonParser;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper\nimport com.fasterxml.jackson.databind.node.ObjectNode;\n\npublic class ProductsLoadData { \n public static void main(String[] args) throws Exception { \n AmazonDynamoDBClient client = new AmazonDynamoDBClient() \n .withEndpoint(\"http://localhost:8000\"); \n \n DynamoDB dynamoDB = new DynamoDB(client); \n Table table = dynamoDB.getTable(\"Products\"); \n JsonParser parser = new JsonFactory() \n .createParser(new File(\"productinfo.json\")); \n \n JsonNode rootNode = new ObjectMapper().readTree(parser); \n Iterator<JsonNode> iter = rootNode.iterator(); \n ObjectNode currentNode; \n \n while (iter.hasNext()) { \n currentNode = (ObjectNode) iter.next(); \n int ID = currentNode.path(\"ID\").asInt(); \n String Nomenclature = currentNode.path(\"Nomenclature\").asText(); \n \n try { \n table.putItem(new Item() \n .withPrimaryKey(\"ID\", ID, \"Nomenclature\", Nomenclature) \n .withJSON(\"Stat\", currentNode.path(\"Stat\").toString()));\n System.out.println(\"Successful load: \" + ID + \" \" + Nomenclature); \n } catch (Exception e) {\n System.err.println(\"Cannot add product: \" + ID + \" \" + Nomenclature);\n System.err.println(e.getMessage()); \n break; \n } \n } \n parser.close(); \n } \n} " }, { "code": null, "e": 6361, "s": 6326, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6381, "s": 6361, "text": " Harshit Srivastava" }, { "code": null, "e": 6416, "s": 6381, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6432, "s": 6416, "text": " Niyazi Erdogan" }, { "code": null, "e": 6465, "s": 6432, "text": "\n 48 Lectures \n 3 hours \n" }, { "code": null, "e": 6481, "s": 6465, "text": " Niyazi Erdogan" }, { "code": null, "e": 6514, "s": 6481, "text": "\n 13 Lectures \n 1 hours \n" }, { "code": null, "e": 6534, "s": 6514, "text": " Harshit Srivastava" }, { "code": null, "e": 6567, "s": 6534, "text": "\n 45 Lectures \n 4 hours \n" }, { "code": null, "e": 6607, "s": 6567, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 6614, "s": 6607, "text": " Print" }, { "code": null, "e": 6625, "s": 6614, "text": " Add Notes" } ]
How to upload files using Selenium Webdriver?
We can upload files using Selenium Webdriver. This is achieved by the sendKeys method. We have to first identify the element which performs the file selection by mentioning the file path [to be uploaded]. This is only applied to an element having a type attribute set to file as a value along with the element tag name as input. The below html code shows the element with type = file value set. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class WndsFileUpl{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //launch application driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"); // identify element WebElement m=driver.findElement(By.xpath("//input[@type='file']")); // windows file upload with file path m.sendKeys("C:\\Users\\Pictures\\Logo.jpg"); //browser close driver.close(); } }
[ { "code": null, "e": 1267, "s": 1062, "text": "We can upload files using Selenium Webdriver. This is achieved by the sendKeys method. We have to first identify the element which performs the file selection by mentioning the file path [to be uploaded]." }, { "code": null, "e": 1457, "s": 1267, "text": "This is only applied to an element having a type attribute set to file as a value along with the element tag name as input. The below html code shows the element with type = file value set." }, { "code": null, "e": 1478, "s": 1457, "text": "Code Implementation." }, { "code": null, "e": 2366, "s": 1478, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class WndsFileUpl{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n\n //implicit wait\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n\n //launch application\n driver.get(\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\");\n\n // identify element\n WebElement m=driver.findElement(By.xpath(\"//input[@type='file']\"));\n\n // windows file upload with file path\n m.sendKeys(\"C:\\\\Users\\\\Pictures\\\\Logo.jpg\");\n\n //browser close\n driver.close();\n }\n}" } ]
Arrays.binarySearch() in Java with examples | Set 1 - GeeksforGeeks
18 Apr, 2022 Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted as by the Arrays.sort() method prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found. Let us glide through the illustration provided below as follows. Illustration: Searching for 35 in byteArr[] = {10,20,15,22,35} will give result as 4 as it is the index of 35 Searching for g in charArr[] = {'g','p','q','c','i'} will give result as 0 as it is the index of 'g' Searching for 22 in intArr[] = {10,20,15,22,35}; will give result as 3 as it is the index of 22 Searching for 1.5 in doubleArr[] = {10.2,15.1,2.2,3.5} will give result as -1 as it is the insertion point of 1.5 Searching for 35.0 in floatArr[] = {10.2f,15.1f,2.2f,3.5f} will give result as -5 as it is the insertion point of 35.0 Searching for 5 in shortArr[] = {10,20,15,22,35} will give result as -1 as it is the insertion point of 5 It is the simplest and most efficient method to find an element in a sorted array in Java Syntax: public static int binarySearch(data_type arr, data_type key) Remember: Here datatype can be any of the primitive data types such as byte, char, double, int, float, short, long, and even object as well. Parameters: The array to be searched The value to be searched for Return Type: index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found. There are certain important points to be kept in mind as follows: If the input list is not sorted, the results are undefined. If there are duplicates, there is no guarantee which one will be found. As above we already have discussed that we can operate this algorithm either Arrays.binarysearch() vs Collections.binarysearch(). Arrays.binarysearch() works for arrays which can be of primitive data type also. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList. Example 1: Java // Java program to demonstrate working of Arrays.// binarySearch() in a sorted array // Importing Arrays class from// java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing byte arrays // to search over them byte byteArr[] = { 10, 20, 15, 22, 35 }; char charArr[] = { 'g', 'p', 'q', 'c', 'i' }; int intArr[] = { 10, 20, 15, 22, 35 }; double doubleArr[] = { 10.2, 15.1, 2.2, 3.5 }; float floatArr[] = { 10.2f, 15.1f, 2.2f, 3.5f }; short shortArr[] = { 10, 20, 15, 22, 35 }; // Using sort() method of Arrays class // and passing arrays to be sorted as in arguments Arrays.sort(byteArr); Arrays.sort(charArr); Arrays.sort(intArr); Arrays.sort(doubleArr); Arrays.sort(floatArr); Arrays.sort(shortArr); // Primitive datatypes byte byteKey = 35; char charKey = 'g'; int intKey = 22; double doubleKey = 1.5; float floatKey = 35; short shortKey = 5; // Now in sorted array we will fetch and // return elements/indiciesaccessing indexes to show // array is really sorted // Print commands where we are implementing System.out.println( byteKey + " found at index = " + Arrays.binarySearch(byteArr, byteKey)); System.out.println( charKey + " found at index = " + Arrays.binarySearch(charArr, charKey)); System.out.println( intKey + " found at index = " + Arrays.binarySearch(intArr, intKey)); System.out.println( doubleKey + " found at index = " + Arrays.binarySearch(doubleArr, doubleKey)); System.out.println( floatKey + " found at index = " + Arrays.binarySearch(floatArr, floatKey)); System.out.println( shortKey + " found at index = " + Arrays.binarySearch(shortArr, shortKey)); }} 35 found at index = 4 g found at index = 1 22 found at index = 3 1.5 found at index = -1 35.0 found at index = -5 5 found at index = -1 There are variants of this method in which we can also specify the range of array to search in. We will be discussing that as well as searching in an Object array in further posts. Example 2: Java // Java Program to Illustrate binarySearch() method// of Collections class // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating empty List List<Integer> al = new ArrayList<Integer>(); // Adding elements to the List al.add(12); al.add(53); al.add(23); al.add(46); al.add(54); // Using binarySearch() method of Collections class // over random inserted element and storing the // index int index = Collections.binarySearch(al, 23); // Print and display the index System.out.print(index); }} 2 This article is contributed by Shikhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. abhimanyu96edu ashrayaman solankimayank sagartomar9927 sumitgumber28 Binary Search Java - util package Java-Arrays Java-Collections Java-Library Java Java Binary Search Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java ArrayList in Java Multidimensional Arrays in Java LinkedList in Java Stack Class in Java Overriding in Java Set in Java Collections in Java Multithreading in Java Singleton Class in Java
[ { "code": null, "e": 24204, "s": 24176, "text": "\n18 Apr, 2022" }, { "code": null, "e": 24653, "s": 24204, "text": "Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted as by the Arrays.sort() method prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found. Let us glide through the illustration provided below as follows." }, { "code": null, "e": 24667, "s": 24653, "text": "Illustration:" }, { "code": null, "e": 25304, "s": 24667, "text": "Searching for 35 in byteArr[] = {10,20,15,22,35}\nwill give result as 4 as it is the index of 35\n\nSearching for g in charArr[] = {'g','p','q','c','i'}\nwill give result as 0 as it is the index of 'g'\n\nSearching for 22 in intArr[] = {10,20,15,22,35};\nwill give result as 3 as it is the index of 22\n\nSearching for 1.5 in doubleArr[] = {10.2,15.1,2.2,3.5}\nwill give result as -1 as it is the insertion point of 1.5\n\nSearching for 35.0 in floatArr[] = {10.2f,15.1f,2.2f,3.5f}\nwill give result as -5 as it is the insertion point of 35.0\n\nSearching for 5 in shortArr[] = {10,20,15,22,35}\nwill give result as -1 as it is the insertion point of 5" }, { "code": null, "e": 25394, "s": 25304, "text": "It is the simplest and most efficient method to find an element in a sorted array in Java" }, { "code": null, "e": 25402, "s": 25394, "text": "Syntax:" }, { "code": null, "e": 25463, "s": 25402, "text": "public static int binarySearch(data_type arr, data_type key)" }, { "code": null, "e": 25604, "s": 25463, "text": "Remember: Here datatype can be any of the primitive data types such as byte, char, double, int, float, short, long, and even object as well." }, { "code": null, "e": 25617, "s": 25604, "text": "Parameters: " }, { "code": null, "e": 25642, "s": 25617, "text": "The array to be searched" }, { "code": null, "e": 25671, "s": 25642, "text": "The value to be searched for" }, { "code": null, "e": 26095, "s": 25671, "text": "Return Type: index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found." }, { "code": null, "e": 26161, "s": 26095, "text": "There are certain important points to be kept in mind as follows:" }, { "code": null, "e": 26221, "s": 26161, "text": "If the input list is not sorted, the results are undefined." }, { "code": null, "e": 26293, "s": 26221, "text": "If there are duplicates, there is no guarantee which one will be found." }, { "code": null, "e": 26593, "s": 26293, "text": "As above we already have discussed that we can operate this algorithm either Arrays.binarysearch() vs Collections.binarysearch(). Arrays.binarysearch() works for arrays which can be of primitive data type also. Collections.binarysearch() works for objects Collections like ArrayList and LinkedList. " }, { "code": null, "e": 26604, "s": 26593, "text": "Example 1:" }, { "code": null, "e": 26609, "s": 26604, "text": "Java" }, { "code": "// Java program to demonstrate working of Arrays.// binarySearch() in a sorted array // Importing Arrays class from// java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing byte arrays // to search over them byte byteArr[] = { 10, 20, 15, 22, 35 }; char charArr[] = { 'g', 'p', 'q', 'c', 'i' }; int intArr[] = { 10, 20, 15, 22, 35 }; double doubleArr[] = { 10.2, 15.1, 2.2, 3.5 }; float floatArr[] = { 10.2f, 15.1f, 2.2f, 3.5f }; short shortArr[] = { 10, 20, 15, 22, 35 }; // Using sort() method of Arrays class // and passing arrays to be sorted as in arguments Arrays.sort(byteArr); Arrays.sort(charArr); Arrays.sort(intArr); Arrays.sort(doubleArr); Arrays.sort(floatArr); Arrays.sort(shortArr); // Primitive datatypes byte byteKey = 35; char charKey = 'g'; int intKey = 22; double doubleKey = 1.5; float floatKey = 35; short shortKey = 5; // Now in sorted array we will fetch and // return elements/indiciesaccessing indexes to show // array is really sorted // Print commands where we are implementing System.out.println( byteKey + \" found at index = \" + Arrays.binarySearch(byteArr, byteKey)); System.out.println( charKey + \" found at index = \" + Arrays.binarySearch(charArr, charKey)); System.out.println( intKey + \" found at index = \" + Arrays.binarySearch(intArr, intKey)); System.out.println( doubleKey + \" found at index = \" + Arrays.binarySearch(doubleArr, doubleKey)); System.out.println( floatKey + \" found at index = \" + Arrays.binarySearch(floatArr, floatKey)); System.out.println( shortKey + \" found at index = \" + Arrays.binarySearch(shortArr, shortKey)); }}", "e": 28677, "s": 26609, "text": null }, { "code": null, "e": 28813, "s": 28677, "text": "35 found at index = 4\ng found at index = 1\n22 found at index = 3\n1.5 found at index = -1\n35.0 found at index = -5\n5 found at index = -1" }, { "code": null, "e": 28994, "s": 28813, "text": "There are variants of this method in which we can also specify the range of array to search in. We will be discussing that as well as searching in an Object array in further posts." }, { "code": null, "e": 29005, "s": 28994, "text": "Example 2:" }, { "code": null, "e": 29010, "s": 29005, "text": "Java" }, { "code": "// Java Program to Illustrate binarySearch() method// of Collections class // Importing required classesimport java.util.ArrayList;import java.util.Collections;import java.util.List; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating empty List List<Integer> al = new ArrayList<Integer>(); // Adding elements to the List al.add(12); al.add(53); al.add(23); al.add(46); al.add(54); // Using binarySearch() method of Collections class // over random inserted element and storing the // index int index = Collections.binarySearch(al, 23); // Print and display the index System.out.print(index); }}", "e": 29778, "s": 29010, "text": null }, { "code": null, "e": 29780, "s": 29778, "text": "2" }, { "code": null, "e": 30196, "s": 29780, "text": "This article is contributed by Shikhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30211, "s": 30196, "text": "abhimanyu96edu" }, { "code": null, "e": 30222, "s": 30211, "text": "ashrayaman" }, { "code": null, "e": 30236, "s": 30222, "text": "solankimayank" }, { "code": null, "e": 30251, "s": 30236, "text": "sagartomar9927" }, { "code": null, "e": 30265, "s": 30251, "text": "sumitgumber28" }, { "code": null, "e": 30279, "s": 30265, "text": "Binary Search" }, { "code": null, "e": 30299, "s": 30279, "text": "Java - util package" }, { "code": null, "e": 30311, "s": 30299, "text": "Java-Arrays" }, { "code": null, "e": 30328, "s": 30311, "text": "Java-Collections" }, { "code": null, "e": 30341, "s": 30328, "text": "Java-Library" }, { "code": null, "e": 30346, "s": 30341, "text": "Java" }, { "code": null, "e": 30351, "s": 30346, "text": "Java" }, { "code": null, "e": 30365, "s": 30351, "text": "Binary Search" }, { "code": null, "e": 30382, "s": 30365, "text": "Java-Collections" }, { "code": null, "e": 30480, "s": 30382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30489, "s": 30480, "text": "Comments" }, { "code": null, "e": 30502, "s": 30489, "text": "Old Comments" }, { "code": null, "e": 30521, "s": 30502, "text": "Interfaces in Java" }, { "code": null, "e": 30539, "s": 30521, "text": "ArrayList in Java" }, { "code": null, "e": 30571, "s": 30539, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30590, "s": 30571, "text": "LinkedList in Java" }, { "code": null, "e": 30610, "s": 30590, "text": "Stack Class in Java" }, { "code": null, "e": 30629, "s": 30610, "text": "Overriding in Java" }, { "code": null, "e": 30641, "s": 30629, "text": "Set in Java" }, { "code": null, "e": 30661, "s": 30641, "text": "Collections in Java" }, { "code": null, "e": 30684, "s": 30661, "text": "Multithreading in Java" } ]
Batch Script - Input / Output - GeeksforGeeks
28 Nov, 2021 In this article, we are going to learn how to take input from users using Batch Script. @echo off echo Batch Script to take input. set /p input= Type any input echo Input is: %input% pause The first ‘echo’ command is used to print a string. In the next line, ‘set /p’ command is used to take user input followed by a variable that will hold user input. set /p input= Type any input Then for printing the user input we will use ‘%’ on both ends of our variable which is used for holding user input in the previous step. echo Input is : %input% ‘ pause ‘ is used to hold the screen until any key is pressed. code for taking user input 1. After saving the above code with .bat format. When we will run the file, the below cmd screen will be shown. After running the file 2. In the next step we will provide any input, as shown. Giving input as Geeks For Geeks 3. After pressing enter we will get user input data as Output, as shown in the below image. Final Output is displayed Batch-script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction SED command in Linux | Set 2 mv command in Linux with examples chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25739, "s": 25651, "text": "In this article, we are going to learn how to take input from users using Batch Script." }, { "code": null, "e": 25840, "s": 25739, "text": "@echo off\necho Batch Script to take input.\nset /p input= Type any input\necho Input is: %input%\npause" }, { "code": null, "e": 25892, "s": 25840, "text": "The first ‘echo’ command is used to print a string." }, { "code": null, "e": 26005, "s": 25892, "text": "In the next line, ‘set /p’ command is used to take user input followed by a variable that will hold user input." }, { "code": null, "e": 26034, "s": 26005, "text": "set /p input= Type any input" }, { "code": null, "e": 26171, "s": 26034, "text": "Then for printing the user input we will use ‘%’ on both ends of our variable which is used for holding user input in the previous step." }, { "code": null, "e": 26195, "s": 26171, "text": "echo Input is : %input%" }, { "code": null, "e": 26258, "s": 26195, "text": "‘ pause ‘ is used to hold the screen until any key is pressed." }, { "code": null, "e": 26285, "s": 26258, "text": "code for taking user input" }, { "code": null, "e": 26397, "s": 26285, "text": "1. After saving the above code with .bat format. When we will run the file, the below cmd screen will be shown." }, { "code": null, "e": 26420, "s": 26397, "text": "After running the file" }, { "code": null, "e": 26477, "s": 26420, "text": "2. In the next step we will provide any input, as shown." }, { "code": null, "e": 26509, "s": 26477, "text": "Giving input as Geeks For Geeks" }, { "code": null, "e": 26601, "s": 26509, "text": "3. After pressing enter we will get user input data as Output, as shown in the below image." }, { "code": null, "e": 26627, "s": 26601, "text": "Final Output is displayed" }, { "code": null, "e": 26640, "s": 26627, "text": "Batch-script" }, { "code": null, "e": 26647, "s": 26640, "text": "Picked" }, { "code": null, "e": 26658, "s": 26647, "text": "Linux-Unix" }, { "code": null, "e": 26756, "s": 26658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26791, "s": 26756, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26817, "s": 26791, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26846, "s": 26817, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26880, "s": 26846, "text": "mv command in Linux with examples" }, { "code": null, "e": 26917, "s": 26880, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26954, "s": 26917, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26996, "s": 26954, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27022, "s": 26996, "text": "Thread functions in C/C++" }, { "code": null, "e": 27058, "s": 27022, "text": "uniq Command in LINUX with examples" } ]
Get the data type of column in Pandas - Python - GeeksforGeeks
28 Jul, 2020 Let’s see how to get data types of columns in the pandas dataframe. First, Let’s create a pandas dataframe. Example: Python3 # importing pandas libraryimport pandas as pd # List of Tuplesemployees = [ ('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary'])# show the dataframedf Output: Dataframe Method 1: Using Dataframe.dtypes attribute. This attribute returns a Series with the data type of each column. Syntax: DataFrame.dtypes. Parameter: None. Returns: dtype of each column. Example 1: Get data types of all columns of a Dataframe. Python3 # importing pandas libraryimport pandas as pd # List of Tuplesemployees = [ ('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary']) # Use Dataframe.dtypes to# give the series of # data types as resultdatatypes = df.dtypes # Print the data types# of each columndatatypes Output: Data types of dataframe Example 2: Get the data type of single column in a Dataframe. Python3 #importing pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary']) # Use Dataframe.dtypes to give # data type of 'Salary' as resultdatatypes = df.dtypes['Salary'] # Print the data types# of single columndatatypes Output: data type of a single column Method 2: Using Dataframe.info() method. This method is used to get a concise summary of the dataframe like: Name of columns Data type of columns Rows in Dataframe non-null entries in each column It will also print column count, names and data types. Syntax: DataFrame.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None) Return: None and prints a summary of a DataFrame. Example: Get data types of all columns of a Dataframe. Python3 # importing pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary']) # Print complete details # about the data framedf.info() Output: summary of the dataframe including datatypes Python pandas-datatypes Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists How To Convert Python Dictionary To JSON? Check if element exists in list in Python Convert integer to string in Python
[ { "code": null, "e": 26177, "s": 26149, "text": "\n28 Jul, 2020" }, { "code": null, "e": 26286, "s": 26177, "text": " Let’s see how to get data types of columns in the pandas dataframe. First, Let’s create a pandas dataframe." }, { "code": null, "e": 26295, "s": 26286, "text": "Example:" }, { "code": null, "e": 26303, "s": 26295, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # List of Tuplesemployees = [ ('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary'])# show the dataframedf", "e": 26911, "s": 26303, "text": null }, { "code": null, "e": 26920, "s": 26911, "text": "Output: " }, { "code": null, "e": 26930, "s": 26920, "text": "Dataframe" }, { "code": null, "e": 26974, "s": 26930, "text": "Method 1: Using Dataframe.dtypes attribute." }, { "code": null, "e": 27041, "s": 26974, "text": "This attribute returns a Series with the data type of each column." }, { "code": null, "e": 27067, "s": 27041, "text": "Syntax: DataFrame.dtypes." }, { "code": null, "e": 27084, "s": 27067, "text": "Parameter: None." }, { "code": null, "e": 27115, "s": 27084, "text": "Returns: dtype of each column." }, { "code": null, "e": 27172, "s": 27115, "text": "Example 1: Get data types of all columns of a Dataframe." }, { "code": null, "e": 27180, "s": 27172, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # List of Tuplesemployees = [ ('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary']) # Use Dataframe.dtypes to# give the series of # data types as resultdatatypes = df.dtypes # Print the data types# of each columndatatypes", "e": 27911, "s": 27180, "text": null }, { "code": null, "e": 27919, "s": 27911, "text": "Output:" }, { "code": null, "e": 27943, "s": 27919, "text": "Data types of dataframe" }, { "code": null, "e": 28005, "s": 27943, "text": "Example 2: Get the data type of single column in a Dataframe." }, { "code": null, "e": 28013, "s": 28005, "text": "Python3" }, { "code": "#importing pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary']) # Use Dataframe.dtypes to give # data type of 'Salary' as resultdatatypes = df.dtypes['Salary'] # Print the data types# of single columndatatypes", "e": 28730, "s": 28013, "text": null }, { "code": null, "e": 28738, "s": 28730, "text": "Output:" }, { "code": null, "e": 28767, "s": 28738, "text": "data type of a single column" }, { "code": null, "e": 28808, "s": 28767, "text": "Method 2: Using Dataframe.info() method." }, { "code": null, "e": 28876, "s": 28808, "text": "This method is used to get a concise summary of the dataframe like:" }, { "code": null, "e": 28892, "s": 28876, "text": "Name of columns" }, { "code": null, "e": 28913, "s": 28892, "text": "Data type of columns" }, { "code": null, "e": 28931, "s": 28913, "text": "Rows in Dataframe" }, { "code": null, "e": 28963, "s": 28931, "text": "non-null entries in each column" }, { "code": null, "e": 29018, "s": 28963, "text": "It will also print column count, names and data types." }, { "code": null, "e": 29117, "s": 29018, "text": "Syntax: DataFrame.info(verbose=None, buf=None, max_cols=None, memory_usage=None, null_counts=None)" }, { "code": null, "e": 29167, "s": 29117, "text": "Return: None and prints a summary of a DataFrame." }, { "code": null, "e": 29222, "s": 29167, "text": "Example: Get data types of all columns of a Dataframe." }, { "code": null, "e": 29230, "s": 29222, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi', 20000), ('Saumya', 32, 'Delhi', 25000), ('Aaditya', 25, 'Mumbai', 40000), ('Saumya', 32, 'Delhi', 35000), ('Saumya', 32, 'Delhi', 30000), ('Saumya', 32, 'Mumbai', 20000), ('Aaditya', 40, 'Dehradun', 24000), ('Seema', 32, 'Delhi', 70000) ] # Create a DataFramedf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City', 'Salary']) # Print complete details # about the data framedf.info()", "e": 29859, "s": 29230, "text": null }, { "code": null, "e": 29867, "s": 29859, "text": "Output:" }, { "code": null, "e": 29912, "s": 29867, "text": "summary of the dataframe including datatypes" }, { "code": null, "e": 29936, "s": 29912, "text": "Python pandas-datatypes" }, { "code": null, "e": 29950, "s": 29936, "text": "Python-pandas" }, { "code": null, "e": 29957, "s": 29950, "text": "Python" }, { "code": null, "e": 30055, "s": 29957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30073, "s": 30055, "text": "Python Dictionary" }, { "code": null, "e": 30105, "s": 30073, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30127, "s": 30105, "text": "Enumerate() in Python" }, { "code": null, "e": 30169, "s": 30127, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30198, "s": 30169, "text": "*args and **kwargs in Python" }, { "code": null, "e": 30242, "s": 30198, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30279, "s": 30242, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30321, "s": 30279, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30363, "s": 30321, "text": "Check if element exists in list in Python" } ]
NumPy - Histogram Using Matplotlib
NumPy has a numpy.histogram() function that is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size corresponding to class interval called bin and variable height corresponding to frequency. The numpy.histogram() function takes the input array and bins as two parameters. The successive elements in bin array act as the boundary of each bin. import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) np.histogram(a,bins = [0,20,40,60,80,100]) hist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) print hist print bins It will produce the following output − [3 4 5 2 1] [0 20 40 60 80 100] Matplotlib can convert this numeric representation of histogram into a graph. The plt() function of pyplot submodule takes the array containing the data and bin array as parameters and converts into a histogram. from matplotlib import pyplot as plt import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) plt.hist(a, bins = [0,20,40,60,80,100]) plt.title("histogram") plt.show() It should produce the following output − 63 Lectures 6 hours Abhilash Nelson 19 Lectures 8 hours DATAhill Solutions Srinivas Reddy 12 Lectures 3 hours DATAhill Solutions Srinivas Reddy 10 Lectures 2.5 hours Akbar Khan 20 Lectures 2 hours Pruthviraja L 63 Lectures 6 hours Anmol Print Add Notes Bookmark this page
[ { "code": null, "e": 2483, "s": 2243, "text": "NumPy has a numpy.histogram() function that is a graphical representation of the frequency distribution of data. Rectangles of equal horizontal size corresponding to class interval called bin and variable height corresponding to frequency." }, { "code": null, "e": 2634, "s": 2483, "text": "The numpy.histogram() function takes the input array and bins as two parameters. The successive elements in bin array act as the boundary of each bin." }, { "code": null, "e": 2842, "s": 2634, "text": "import numpy as np \n \na = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) \nnp.histogram(a,bins = [0,20,40,60,80,100]) \nhist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) \nprint hist \nprint bins " }, { "code": null, "e": 2881, "s": 2842, "text": "It will produce the following output −" }, { "code": null, "e": 2914, "s": 2881, "text": "[3 4 5 2 1]\n[0 20 40 60 80 100]\n" }, { "code": null, "e": 3126, "s": 2914, "text": "Matplotlib can convert this numeric representation of histogram into a graph. The plt() function of pyplot submodule takes the array containing the data and bin array as parameters and converts into a histogram." }, { "code": null, "e": 3325, "s": 3126, "text": "from matplotlib import pyplot as plt \nimport numpy as np \n \na = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) \nplt.hist(a, bins = [0,20,40,60,80,100]) \nplt.title(\"histogram\") \nplt.show()" }, { "code": null, "e": 3366, "s": 3325, "text": "It should produce the following output −" }, { "code": null, "e": 3399, "s": 3366, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3416, "s": 3399, "text": " Abhilash Nelson" }, { "code": null, "e": 3449, "s": 3416, "text": "\n 19 Lectures \n 8 hours \n" }, { "code": null, "e": 3484, "s": 3449, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3517, "s": 3484, "text": "\n 12 Lectures \n 3 hours \n" }, { "code": null, "e": 3552, "s": 3517, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3587, "s": 3552, "text": "\n 10 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3599, "s": 3587, "text": " Akbar Khan" }, { "code": null, "e": 3632, "s": 3599, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 3647, "s": 3632, "text": " Pruthviraja L" }, { "code": null, "e": 3680, "s": 3647, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3687, "s": 3680, "text": " Anmol" }, { "code": null, "e": 3694, "s": 3687, "text": " Print" }, { "code": null, "e": 3705, "s": 3694, "text": " Add Notes" } ]
Java program to check if a string contains any special character
To check if a string contains any special character, the Java program is as follows − Live Demo import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String[] args){ String my_str="This is a sample only !$@"; Pattern my_pattern = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE); Matcher my_match = my_pattern.matcher(my_str); boolean check = my_match.find(); if (check) System.out.println("Special character found in the string"); else System.out.println("Special character not found in the string"); } } Special character found in the string A class named Demo contains the main function, where a string is defined, with some special characters. A pattern is defined that uses regular expressions to check if the string has any special characters. A Boolean value is defined, that checks to see for the same. If the value of Bool is true, a success message is printed, otherwise, a message stating the absence of these special characters is printed on the screen.
[ { "code": null, "e": 1148, "s": 1062, "text": "To check if a string contains any special character, the Java program is as follows −" }, { "code": null, "e": 1159, "s": 1148, "text": " Live Demo" }, { "code": null, "e": 1690, "s": 1159, "text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Demo {\n public static void main(String[] args){\n String my_str=\"This is a sample only !$@\";\n Pattern my_pattern = Pattern.compile(\"[^a-z0-9 ]\", Pattern.CASE_INSENSITIVE);\n Matcher my_match = my_pattern.matcher(my_str);\n boolean check = my_match.find();\n if (check)\n System.out.println(\"Special character found in the string\");\n else\n System.out.println(\"Special character not found in the string\");\n }\n}" }, { "code": null, "e": 1728, "s": 1690, "text": "Special character found in the string" }, { "code": null, "e": 2150, "s": 1728, "text": "A class named Demo contains the main function, where a string is defined, with some special\ncharacters. A pattern is defined that uses regular expressions to check if the string has any special\ncharacters. A Boolean value is defined, that checks to see for the same. If the value of Bool is true, a\nsuccess message is printed, otherwise, a message stating the absence of these special characters is\nprinted on the screen." } ]
Java Program to Swap Two Numbers Using Bitwise XOR Operation - GeeksforGeeks
09 Nov, 2020 Given two numbers x and y. We have to write a Java Program to Swap the contents of two numbers using Bitwise XOR Operation. Input 1: x = 5, y = 10 Output : x = 10, y = 5 Explaination : 1. x = x ^ y -> x = 15 2. y = x ^ y -> y = 5 3. x = x ^ y -> x = 10 Input 2: x = 15, y = 20 Output : x = 20, y = 15 The bitwise XOR operator(represented by ^) compares corresponding bits of two operands and returns 1 if they are equal and 0 if they are not equal. Let’s say we have two numbers x and y, so what actually x^y will do is that it will compare every corresponding bit of x and y, and if they are different, it will generate 1 as the output of that two bits(one of x and one of y) taken into consideration and if bits are same, then it will generate 0 as the output of two bits. Below is the code implementation of the above approach:- Java // Java program to swap the elements using XOR Operatorimport java.io.*;class GFG { public static void main(String[] args) { int x = 5, y = 10; // binary equivalent of 5 is 0101 // binary equivalent of 10 is 1010 // binary equivalent of x will become 1111 ie x=15 x = x ^ y; // binary equivalent of y will become 0101 ie y=5 y = x ^ y; // binary equivalent of x will become 1010 ie x=10 x = x ^ y; System.out.println("The value of x is " + x + " and the value of y is " + y); }} The value of x is 10 and the value of y is 5 Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples HashMap containsKey() Method in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n09 Nov, 2020" }, { "code": null, "e": 23681, "s": 23557, "text": "Given two numbers x and y. We have to write a Java Program to Swap the contents of two numbers using Bitwise XOR Operation." }, { "code": null, "e": 23860, "s": 23681, "text": "Input 1: x = 5, y = 10\nOutput : x = 10, y = 5\nExplaination :\n1. x = x ^ y -> x = 15\n2. y = x ^ y -> y = 5\n3. x = x ^ y -> x = 10\n\nInput 2: x = 15, y = 20\nOutput : x = 20, y = 15\n" }, { "code": null, "e": 24336, "s": 23860, "text": "The bitwise XOR operator(represented by ^) compares corresponding bits of two operands and returns 1 if they are equal and 0 if they are not equal. Let’s say we have two numbers x and y, so what actually x^y will do is that it will compare every corresponding bit of x and y, and if they are different, it will generate 1 as the output of that two bits(one of x and one of y) taken into consideration and if bits are same, then it will generate 0 as the output of two bits." }, { "code": null, "e": 24393, "s": 24336, "text": "Below is the code implementation of the above approach:-" }, { "code": null, "e": 24398, "s": 24393, "text": "Java" }, { "code": "// Java program to swap the elements using XOR Operatorimport java.io.*;class GFG { public static void main(String[] args) { int x = 5, y = 10; // binary equivalent of 5 is 0101 // binary equivalent of 10 is 1010 // binary equivalent of x will become 1111 ie x=15 x = x ^ y; // binary equivalent of y will become 0101 ie y=5 y = x ^ y; // binary equivalent of x will become 1010 ie x=10 x = x ^ y; System.out.println(\"The value of x is \" + x + \" and the value of y is \" + y); }}", "e": 24987, "s": 24398, "text": null }, { "code": null, "e": 25033, "s": 24987, "text": "The value of x is 10 and the value of y is 5\n" }, { "code": null, "e": 25057, "s": 25033, "text": "Technical Scripter 2020" }, { "code": null, "e": 25062, "s": 25057, "text": "Java" }, { "code": null, "e": 25076, "s": 25062, "text": "Java Programs" }, { "code": null, "e": 25095, "s": 25076, "text": "Technical Scripter" }, { "code": null, "e": 25100, "s": 25095, "text": "Java" }, { "code": null, "e": 25198, "s": 25100, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25207, "s": 25198, "text": "Comments" }, { "code": null, "e": 25220, "s": 25207, "text": "Old Comments" }, { "code": null, "e": 25238, "s": 25220, "text": "Hashtable in Java" }, { "code": null, "e": 25259, "s": 25238, "text": "Constructors in Java" }, { "code": null, "e": 25305, "s": 25259, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 25348, "s": 25305, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 25385, "s": 25348, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 25429, "s": 25385, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 25455, "s": 25429, "text": "Java Programming Examples" }, { "code": null, "e": 25489, "s": 25455, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 25536, "s": 25489, "text": "Implementing a Linked List in Java using Class" } ]
Cypress - Get and Post
The Get and Post methods are a part of the Application Programming Interface (API) testing, which can be performed by Cypress. To perform a Get operation, we shall make a HTTP request with the cy.request() and pass the method Get and URL as parameters to that method. The status code reflects, if the request has been accepted and handled correctly. The code 200(means ok) and 201(means created). The implementation of Get method in Cypress is explained below − describe("Get Method", function(){ it("Scenario 2", function(){ cy.request("GET", "https://jsonplaceholder.cypress.io/comments", { }).then((r) => { expect(r.status).to.eq(200) expect(r).to.have.property('headers') expect(r).to.have.property('duration') }); }) }) Execution Results The output is as follows − While using the Post method, we are actually sending information. If we have a group of entities, we can append new ones at the end, with the help of Post. To perform a Post operation, we shall make a HTTP request with the cy.request() and pass the method Post and URL as parameters to that method. Given below is an implementation of Post method in Cypress − describe("Post Method", function(){ it("Scenario 3", function(){ cy.request('https://jsonplaceholder.cypress.io/users?_limit=1') .its('body.0') // yields the first element of the returned list // make a new post on behalf of the user cy.request('POST', 'https://jsonplaceholder.cypress.io/posts', { title: 'Cypress', body: 'Automation Tool', }) }) }); Execution Results The output is given below − 73 Lectures 12 hours Rahul Shetty Print Add Notes Bookmark this page
[ { "code": null, "e": 2624, "s": 2497, "text": "The Get and Post methods are a part of the Application Programming Interface (API) testing, which can be performed by Cypress." }, { "code": null, "e": 2765, "s": 2624, "text": "To perform a Get operation, we shall make a HTTP request with the cy.request() and pass the method Get and URL as parameters to that method." }, { "code": null, "e": 2894, "s": 2765, "text": "The status code reflects, if the request has been accepted and handled correctly. The code 200(means ok) and 201(means created)." }, { "code": null, "e": 2959, "s": 2894, "text": "The implementation of Get method in Cypress is explained below −" }, { "code": null, "e": 3273, "s": 2959, "text": "describe(\"Get Method\", function(){\n it(\"Scenario 2\", function(){\n cy.request(\"GET\", \"https://jsonplaceholder.cypress.io/comments\", {\n }).then((r) => {\n expect(r.status).to.eq(200)\n expect(r).to.have.property('headers')\n expect(r).to.have.property('duration')\n });\n })\n})" }, { "code": null, "e": 3291, "s": 3273, "text": "Execution Results" }, { "code": null, "e": 3318, "s": 3291, "text": "The output is as follows −" }, { "code": null, "e": 3474, "s": 3318, "text": "While using the Post method, we are actually sending information. If we have a group of\nentities, we can append new ones at the end, with the help of Post." }, { "code": null, "e": 3617, "s": 3474, "text": "To perform a Post operation, we shall make a HTTP request with the cy.request() and\npass the method Post and URL as parameters to that method." }, { "code": null, "e": 3678, "s": 3617, "text": "Given below is an implementation of Post method in Cypress −" }, { "code": null, "e": 4084, "s": 3678, "text": "describe(\"Post Method\", function(){\n it(\"Scenario 3\", function(){\n cy.request('https://jsonplaceholder.cypress.io/users?_limit=1')\n .its('body.0') // yields the first element of the returned list\n // make a new post on behalf of the user\n cy.request('POST', 'https://jsonplaceholder.cypress.io/posts', {\n title: 'Cypress',\n body: 'Automation Tool',\n })\n })\n});" }, { "code": null, "e": 4102, "s": 4084, "text": "Execution Results" }, { "code": null, "e": 4130, "s": 4102, "text": "The output is given below −" }, { "code": null, "e": 4164, "s": 4130, "text": "\n 73 Lectures \n 12 hours \n" }, { "code": null, "e": 4178, "s": 4164, "text": " Rahul Shetty" }, { "code": null, "e": 4185, "s": 4178, "text": " Print" }, { "code": null, "e": 4196, "s": 4185, "text": " Add Notes" } ]
How to remove all CSS classes using jQuery ? - GeeksforGeeks
31 Dec, 2020 In this article, we will remove all CSS classes for an element using jQuery. To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element. Syntax: $(selector).removeClass(class_name, function(index, class_name)) Parameters: This function accepts two parameters as mentioned above and described below: class_name: It is optional parameter which is used to specify the class name (one or more class) to remove. Multiple class name separated with space. function: It is optional parameter and it returns one or more class name which need to be removed.index: This parameter is used to return index of element.current_class_name: This parameter returns the class name of selected elements. index: This parameter is used to return index of element.current_class_name: This parameter returns the class name of selected elements. index: This parameter is used to return index of element. current_class_name: This parameter returns the class name of selected elements. Example: HTML <!DOCTYPE html><html lang="en"> <head> <title> How to remove all CSS classes using jQuery? </title> <style> .GFG1 { color: green; } .GFG2 { font-size: 30px; font-weight: bold; } </style> <!-- Import jQuery cdn library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("button").click(function () { $("p").removeClass(); }); }); </script></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to remove all CSS classes using jQuery? </h3> <p class="GFG1 GFG2"> Computer Science Portal </p> <button>Click Here!</button></body> </html> Output: Before button Click: After Button Click: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc jQuery-Misc CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25070, "s": 25042, "text": "\n31 Dec, 2020" }, { "code": null, "e": 25217, "s": 25070, "text": "In this article, we will remove all CSS classes for an element using jQuery. To remove all CSS classes of an element, we use removeClass() method." }, { "code": null, "e": 25311, "s": 25217, "text": "The removeClass() method is used to remove one or more class names from the selected element." }, { "code": null, "e": 25319, "s": 25311, "text": "Syntax:" }, { "code": null, "e": 25384, "s": 25319, "text": "$(selector).removeClass(class_name, function(index, class_name))" }, { "code": null, "e": 25473, "s": 25384, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 25623, "s": 25473, "text": "class_name: It is optional parameter which is used to specify the class name (one or more class) to remove. Multiple class name separated with space." }, { "code": null, "e": 25858, "s": 25623, "text": "function: It is optional parameter and it returns one or more class name which need to be removed.index: This parameter is used to return index of element.current_class_name: This parameter returns the class name of selected elements." }, { "code": null, "e": 25995, "s": 25858, "text": "index: This parameter is used to return index of element.current_class_name: This parameter returns the class name of selected elements." }, { "code": null, "e": 26053, "s": 25995, "text": "index: This parameter is used to return index of element." }, { "code": null, "e": 26133, "s": 26053, "text": "current_class_name: This parameter returns the class name of selected elements." }, { "code": null, "e": 26142, "s": 26133, "text": "Example:" }, { "code": null, "e": 26147, "s": 26142, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to remove all CSS classes using jQuery? </title> <style> .GFG1 { color: green; } .GFG2 { font-size: 30px; font-weight: bold; } </style> <!-- Import jQuery cdn library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"button\").click(function () { $(\"p\").removeClass(); }); }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to remove all CSS classes using jQuery? </h3> <p class=\"GFG1 GFG2\"> Computer Science Portal </p> <button>Click Here!</button></body> </html>", "e": 27016, "s": 26147, "text": null }, { "code": null, "e": 27024, "s": 27016, "text": "Output:" }, { "code": null, "e": 27045, "s": 27024, "text": "Before button Click:" }, { "code": null, "e": 27065, "s": 27045, "text": "After Button Click:" }, { "code": null, "e": 27202, "s": 27065, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27211, "s": 27202, "text": "CSS-Misc" }, { "code": null, "e": 27221, "s": 27211, "text": "HTML-Misc" }, { "code": null, "e": 27233, "s": 27221, "text": "jQuery-Misc" }, { "code": null, "e": 27237, "s": 27233, "text": "CSS" }, { "code": null, "e": 27242, "s": 27237, "text": "HTML" }, { "code": null, "e": 27249, "s": 27242, "text": "JQuery" }, { "code": null, "e": 27266, "s": 27249, "text": "Web Technologies" }, { "code": null, "e": 27271, "s": 27266, "text": "HTML" }, { "code": null, "e": 27369, "s": 27271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27378, "s": 27369, "text": "Comments" }, { "code": null, "e": 27391, "s": 27378, "text": "Old Comments" }, { "code": null, "e": 27428, "s": 27391, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27457, "s": 27428, "text": "Form validation using jQuery" }, { "code": null, "e": 27496, "s": 27457, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27538, "s": 27496, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27573, "s": 27538, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 27633, "s": 27573, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27694, "s": 27633, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27747, "s": 27694, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27797, "s": 27747, "text": "How to Insert Form Data into Database using PHP ?" } ]
SQL - Handling Duplicates
There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records. The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records. The basic syntax of a DISTINCT keyword to eliminate duplicate records is as follows. SELECT DISTINCT column1, column2,.....columnN FROM table_name WHERE [condition] Consider the CUSTOMERS table having the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ First, let us see how the following SELECT query returns duplicate salary records. SQL> SELECT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result where the salary of 2000 is coming twice which is a duplicate record from the original table. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ Now, let us use the DISTINCT keyword with the above SELECT query and see the result. SQL> SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY; This would produce the following result where we do not have any duplicate entry. +----------+ | SALARY | +----------+ | 1500.00 | | 2000.00 | | 4500.00 | | 6500.00 | | 8500.00 | | 10000.00 | +----------+ 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2648, "s": 2453, "text": "There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records." }, { "code": null, "e": 2835, "s": 2648, "text": "The SQL DISTINCT keyword, which we have already discussed is used in conjunction with the SELECT statement to eliminate all the duplicate records and by fetching only the unique records." }, { "code": null, "e": 2920, "s": 2835, "text": "The basic syntax of a DISTINCT keyword to eliminate duplicate records is as follows." }, { "code": null, "e": 3002, "s": 2920, "text": "SELECT DISTINCT column1, column2,.....columnN \nFROM table_name\nWHERE [condition]\n" }, { "code": null, "e": 3061, "s": 3002, "text": "Consider the CUSTOMERS table having the following records." }, { "code": null, "e": 3578, "s": 3061, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 3661, "s": 3578, "text": "First, let us see how the following SELECT query returns duplicate salary records." }, { "code": null, "e": 3715, "s": 3661, "text": "SQL> SELECT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 3849, "s": 3715, "text": "This would produce the following result where the salary of 2000 is coming twice which is a duplicate record from the original table." }, { "code": null, "e": 3993, "s": 3849, "text": "+----------+\n| SALARY |\n+----------+\n| 1500.00 |\n| 2000.00 |\n| 2000.00 |\n| 4500.00 |\n| 6500.00 |\n| 8500.00 |\n| 10000.00 |\n+----------+\n" }, { "code": null, "e": 4078, "s": 3993, "text": "Now, let us use the DISTINCT keyword with the above SELECT query and see the result." }, { "code": null, "e": 4141, "s": 4078, "text": "SQL> SELECT DISTINCT SALARY FROM CUSTOMERS\n ORDER BY SALARY;" }, { "code": null, "e": 4223, "s": 4141, "text": "This would produce the following result where we do not have any duplicate entry." }, { "code": null, "e": 4354, "s": 4223, "text": "+----------+\n| SALARY |\n+----------+\n| 1500.00 |\n| 2000.00 |\n| 4500.00 |\n| 6500.00 |\n| 8500.00 |\n| 10000.00 |\n+----------+\n" }, { "code": null, "e": 4387, "s": 4354, "text": "\n 42 Lectures \n 5 hours \n" }, { "code": null, "e": 4401, "s": 4387, "text": " Anadi Sharma" }, { "code": null, "e": 4434, "s": 4401, "text": "\n 14 Lectures \n 2 hours \n" }, { "code": null, "e": 4448, "s": 4434, "text": " Anadi Sharma" }, { "code": null, "e": 4483, "s": 4448, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4497, "s": 4483, "text": " Anadi Sharma" }, { "code": null, "e": 4530, "s": 4497, "text": "\n 94 Lectures \n 7 hours \n" }, { "code": null, "e": 4552, "s": 4530, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 4587, "s": 4552, "text": "\n 80 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4641, "s": 4587, "text": " Oracle Master Training | 150,000+ Students Worldwide" }, { "code": null, "e": 4674, "s": 4641, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 4702, "s": 4674, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4709, "s": 4702, "text": " Print" }, { "code": null, "e": 4720, "s": 4709, "text": " Add Notes" } ]
How can I create a stored procedure to insert values in a MySQL table?
We can create a stored procedure with an IN operator to insert values in a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data − mysql> Select * from student_info; +------+---------+-----------+------------+ | id | Name | Address | Subject | +------+---------+-----------+------------+ | 100 | Aarav | Delhi | Computers | | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 110 | Rahul | Chandigarh | History | +------+---------+------------+------------+ 4 rows in set (0.00 sec) Now, by creating the procedure named ‘insert_studentinfo’ as follow, we can insert the values in ‘student_info’ table − mysql> DELIMITER // ; mysql> Create PROCEDURE insert_studentinfo(IN p_id int, IN p_name varchar(20),IN p_Address Varchar(20), IN p_subject Varchar(20)) -> BEGIN -> insert into student_info(id, name, address, subject) values (p_id, p_name,p_address, p_subject); -> END // Query OK, 0 rows affected (0.09 sec) Now, invoke the procedure with the values we want to insert in the table as follows − mysql> CALL insert_studentinfo(125,'Raman','Bangalore','Computers')// Query OK, 1 row affected (0.78 sec) mysql> DELIMITER ; // mysql> Select * from Student_info; +-----+---------+------------+------------+ | id | Name | Address | Subject | +-----+---------+------------+------------+ | 100 | Aarav | Delhi | Computers | | 101 | YashPal | Amritsar | History | | 105 | Gaurav | Jaipur | Literature | | 110 | Rahul | Chandigarh | History | | 125 | Raman | Bangalore | Computers | +------+---------+------------+-----------+ 5 rows in set (0.00 sec) The above result set shows that the values get inserted in the table.
[ { "code": null, "e": 1257, "s": 1062, "text": "We can create a stored procedure with an IN operator to insert values in a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −" }, { "code": null, "e": 1670, "s": 1257, "text": "mysql> Select * from student_info;\n+------+---------+-----------+------------+\n| id | Name | Address | Subject |\n+------+---------+-----------+------------+\n| 100 | Aarav | Delhi | Computers |\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n+------+---------+------------+------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1790, "s": 1670, "text": "Now, by creating the procedure named ‘insert_studentinfo’ as follow, we can insert the values in ‘student_info’ table −" }, { "code": null, "e": 2110, "s": 1790, "text": "mysql> DELIMITER // ;\nmysql> Create PROCEDURE insert_studentinfo(IN p_id int, IN p_name varchar(20),IN p_Address Varchar(20), IN p_subject Varchar(20))\n -> BEGIN\n -> insert into student_info(id, name, address, subject) values (p_id, p_name,p_address, p_subject);\n -> END //\nQuery OK, 0 rows affected (0.09 sec)" }, { "code": null, "e": 2196, "s": 2110, "text": "Now, invoke the procedure with the values we want to insert in the table as follows −" }, { "code": null, "e": 2782, "s": 2196, "text": "mysql> CALL insert_studentinfo(125,'Raman','Bangalore','Computers')//\nQuery OK, 1 row affected (0.78 sec)\n\nmysql> DELIMITER ; //\n\nmysql> Select * from Student_info;\n+-----+---------+------------+------------+\n| id | Name | Address | Subject |\n+-----+---------+------------+------------+\n| 100 | Aarav | Delhi | Computers |\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n| 125 | Raman | Bangalore | Computers |\n+------+---------+------------+-----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2852, "s": 2782, "text": "The above result set shows that the values get inserted in the table." } ]
Flatten a binary tree into linked list | Set-3 - GeeksforGeeks
24 Jan, 2022 Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in level order.Examples: Input: 1 / \ 2 5 / \ \ 3 4 6 Output: 1 \ 2 \ 3 \ 4 \ 5 \ 6 Input: 1 / \ 3 4 / 2 \ 5 Output: 1 \ 3 \ 4 \ 2 \ 5 Approach: Recurse the binary tree in Inorder Format, at every stage of function call pass on the address of last node in the flattened linked list so that current node can make itself a right node of the last node. For left child, it’s parent node is the last node in the flattened list For the right child there are two conditions: If there is no left child to the parent, parent node is the last node in the flattened list. If left child is not null then leaf node from left sub-tree is the last node in the flattened list. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program to flatten the binary tree// using previous node approachusing namespace std;#include <iostream>#include <stdlib.h> // Structure to represent a node of the treestruct Node { int data; struct Node* left; struct Node* right;}; Node* AllocNode(int data){ Node* temp = new Node; temp->left = NULL; temp->right = NULL; temp->data = data; return temp;} // Utility function to print the inorder// traversal of the treevoid PrintInorderBinaryTree(Node* root){ if (root == NULL) return; PrintInorderBinaryTree(root->left); std::cout << root->data << " "; PrintInorderBinaryTree(root->right);} // Function to make current node right of// the last node in the listvoid FlattenBinaryTree(Node* root, Node** last){ if (root == NULL) return; Node* left = root->left; Node* right = root->right; // Avoid first iteration where root is // the only node in the list if (root != *last) { (*last)->right = root; (*last)->left = NULL; *last = root; } FlattenBinaryTree(left, last); FlattenBinaryTree(right, last); if (left == NULL && right == NULL) *last = root;} // Driver Codeint main(){ // Build the tree Node* root = AllocNode(1); root->left = AllocNode(2); root->left->left = AllocNode(3); root->left->right = AllocNode(4); root->right = AllocNode(5); root->right->right = AllocNode(6); // Print the inorder traversal of the // original tree std::cout << "Original inorder traversal : "; PrintInorderBinaryTree(root); std::cout << std::endl; // Flatten a binary tree, at the beginning // root node is the only and last in the list Node* last = root; FlattenBinaryTree(root, &last); // Print the inorder traversal of the flattened // binary tree std::cout << "Flattened inorder traversal : "; PrintInorderBinaryTree(root); std::cout << std::endl; return 0;} // Java program to flatten the binary tree// using previous node approachclass GFG{ // Structure to represent a node of the treestatic class Node{ int data; Node left; Node right;}; static Node AllocNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Utility function to print the inorder// traversal of the treestatic void PrintInorderBinaryTree(Node root){ if (root == null) return; PrintInorderBinaryTree(root.left); System.out.print( root.data + " "); PrintInorderBinaryTree(root.right);} static Node last =null; // Function to make current node right of// the last node in the liststatic void FlattenBinaryTree(Node root){ if (root == null) return; Node left = root.left; Node right = root.right; // Avoid first iteration where root is // the only node in the list if (root != last) { (last).right = root; (last).left = null; last = root; } FlattenBinaryTree(left); FlattenBinaryTree(right); if (left == null && right == null) last = root;} // Driver Codepublic static void main(String args[]){ // Build the tree Node root = AllocNode(1); root.left = AllocNode(2); root.left.left = AllocNode(3); root.left.right = AllocNode(4); root.right = AllocNode(5); root.right.right = AllocNode(6); // Print the inorder traversal of the // original tree System.out.print("Original inorder traversal : "); PrintInorderBinaryTree(root); System.out.println(); // Flatten a binary tree, at the beginning // root node is the only and last in the list last = root; FlattenBinaryTree(root); // Print the inorder traversal of the flattened // binary tree System.out.print("Flattened inorder traversal : "); PrintInorderBinaryTree(root); System.out.println(); }} // This code is contributed by Arnab Kundu # Python program to flatten binary tree# using previous node approach # Node class to represent a node of the treeclass Node: def __init__(self, data): self.data = data self.right = None self.left = None # Utility function to print the inorder# traversal of the treedef PrintInorderBinaryTree(root): if(root == None): return PrintInorderBinaryTree(root.left) print(str(root.data), end = " ") PrintInorderBinaryTree(root.right) # Function to make current node right of# the last node in the listdef FlattenBinaryTree(root): # A global variable which maintains the last node # that was added to the linked list global last if(root == None): return left = root.left right = root.right # Avoid first iteration where root is # the only node in the list if(root != last): last.right = root last.left = None last = root FlattenBinaryTree(left) FlattenBinaryTree(right) if(left == None and right == None): last = root # Build the treeroot = Node(1)root.left = Node(2)root.left.left = Node(3)root.left.right = Node(4)root.right = Node(5)root.right.right = Node(6) # Print the inorder traversal of the# original treeprint("Original inorder traversal : ", end = "")PrintInorderBinaryTree(root)print("") # Global variable to maintain the# last node added to the linked listlast = root # Flatten the binary tree, at the beginning# root node is the only node in the listFlattenBinaryTree(root) # Print the inorder traversal of the flattened# binary treeprint("Flattened inorder traversal : ", end = "")PrintInorderBinaryTree(root) # This code is contributed by Pranav Devarakonda // C# program to flatten the binary tree// using previous node approachusing System; class GFG{ // Structure to represent a node of the treepublic class Node{ public int data; public Node left; public Node right;}; static Node AllocNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Utility function to print the inorder// traversal of the treestatic void PrintInorderBinaryTree(Node root){ if (root == null) return; PrintInorderBinaryTree(root.left); Console.Write(root.data + " "); PrintInorderBinaryTree(root.right);} static Node last =null; // Function to make current node right of// the last node in the liststatic void FlattenBinaryTree(Node root){ if (root == null) return; Node left = root.left; Node right = root.right; // Avoid first iteration where root is // the only node in the list if (root != last) { (last).right = root; (last).left = null; last = root; } FlattenBinaryTree(left); FlattenBinaryTree(right); if (left == null && right == null) last = root;} // Driver Codepublic static void Main(String []args){ // Build the tree Node root = AllocNode(1); root.left = AllocNode(2); root.left.left = AllocNode(3); root.left.right = AllocNode(4); root.right = AllocNode(5); root.right.right = AllocNode(6); // Print the inorder traversal of the // original tree Console.Write("Original inorder traversal : "); PrintInorderBinaryTree(root); Console.WriteLine(); // Flatten a binary tree, at the beginning // root node is the only and last in the list last = root; FlattenBinaryTree(root); // Print the inorder traversal of the flattened // binary tree Console.Write("Flattened inorder traversal : "); PrintInorderBinaryTree(root); Console.WriteLine();}} // This code is contributed by 29AjayKumar <script> // Javascript program to flatten the binary tree// using previous node approach // Structure to represent a node of the treeclass Node { constructor() { this.data = 0; this.left = null; this.right = null; } } function AllocNode( data){ var temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Utility function to print the inorder// traversal of the treefunction PrintInorderBinaryTree( root){ if (root == null) return; PrintInorderBinaryTree(root.left); document.write( root.data + " "); PrintInorderBinaryTree(root.right);} var last =null; // Function to make current node right of// the last node in the listfunction FlattenBinaryTree( root){ if (root == null) return; var left = root.left; var right = root.right; // Avoid first iteration where root is // the only node in the list if (root != last) { (last).right = root; (last).left = null; last = root; } FlattenBinaryTree(left); FlattenBinaryTree(right); if (left == null && right == null) last = root;} // Driver Code // Build the treevar root = AllocNode(1);root.left = AllocNode(2);root.left.left = AllocNode(3);root.left.right = AllocNode(4);root.right = AllocNode(5);root.right.right = AllocNode(6); // Print the inorder traversal of the// original treedocument.write("Original inorder traversal : ");PrintInorderBinaryTree(root);document.write("</br>"); // Flatten a binary tree, at the beginning// root node is the only and last in the listlast = root;FlattenBinaryTree(root); // Print the inorder traversal of the flattened// binary treedocument.write("Flattened inorder traversal : ");PrintInorderBinaryTree(root);document.write("</br>"); // This code is contributed by JANA_SAYANTAN.</script> Original inorder traversal : 3 2 4 1 5 6 Flattened inorder traversal : 1 2 3 4 5 6 Pranav Devarakonda andrew1234 29AjayKumar jana_sayantan surinderdawra388 Linked List Tree Linked List Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Linked List vs Array Delete a Linked List node at a given position Queue - Linked List Implementation Merge two sorted linked lists Detect loop in a linked list Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties)
[ { "code": null, "e": 24789, "s": 24761, "text": "\n24 Jan, 2022" }, { "code": null, "e": 25017, "s": 24789, "text": "Given a binary tree, flatten it into linked list in-place. Usage of auxiliary data structure is not allowed. After flattening, left of each node should point to NULL and right should contain next node in level order.Examples: " }, { "code": null, "e": 25422, "s": 25017, "text": "Input: \n 1\n / \\\n 2 5\n / \\ \\\n 3 4 6\n\nOutput:\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\n \\\n 6\n\nInput:\n 1\n / \\\n 3 4\n /\n 2\n \\\n 5\nOutput:\n 1\n \\\n 3\n \\\n 4\n \\\n 2\n \\ \n 5" }, { "code": null, "e": 25759, "s": 25424, "text": "Approach: Recurse the binary tree in Inorder Format, at every stage of function call pass on the address of last node in the flattened linked list so that current node can make itself a right node of the last node. For left child, it’s parent node is the last node in the flattened list For the right child there are two conditions: " }, { "code": null, "e": 25852, "s": 25759, "text": "If there is no left child to the parent, parent node is the last node in the flattened list." }, { "code": null, "e": 25952, "s": 25852, "text": "If left child is not null then leaf node from left sub-tree is the last node in the flattened list." }, { "code": null, "e": 26005, "s": 25952, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26009, "s": 26005, "text": "C++" }, { "code": null, "e": 26014, "s": 26009, "text": "Java" }, { "code": null, "e": 26021, "s": 26014, "text": "Python" }, { "code": null, "e": 26024, "s": 26021, "text": "C#" }, { "code": null, "e": 26035, "s": 26024, "text": "Javascript" }, { "code": "// C++ program to flatten the binary tree// using previous node approachusing namespace std;#include <iostream>#include <stdlib.h> // Structure to represent a node of the treestruct Node { int data; struct Node* left; struct Node* right;}; Node* AllocNode(int data){ Node* temp = new Node; temp->left = NULL; temp->right = NULL; temp->data = data; return temp;} // Utility function to print the inorder// traversal of the treevoid PrintInorderBinaryTree(Node* root){ if (root == NULL) return; PrintInorderBinaryTree(root->left); std::cout << root->data << \" \"; PrintInorderBinaryTree(root->right);} // Function to make current node right of// the last node in the listvoid FlattenBinaryTree(Node* root, Node** last){ if (root == NULL) return; Node* left = root->left; Node* right = root->right; // Avoid first iteration where root is // the only node in the list if (root != *last) { (*last)->right = root; (*last)->left = NULL; *last = root; } FlattenBinaryTree(left, last); FlattenBinaryTree(right, last); if (left == NULL && right == NULL) *last = root;} // Driver Codeint main(){ // Build the tree Node* root = AllocNode(1); root->left = AllocNode(2); root->left->left = AllocNode(3); root->left->right = AllocNode(4); root->right = AllocNode(5); root->right->right = AllocNode(6); // Print the inorder traversal of the // original tree std::cout << \"Original inorder traversal : \"; PrintInorderBinaryTree(root); std::cout << std::endl; // Flatten a binary tree, at the beginning // root node is the only and last in the list Node* last = root; FlattenBinaryTree(root, &last); // Print the inorder traversal of the flattened // binary tree std::cout << \"Flattened inorder traversal : \"; PrintInorderBinaryTree(root); std::cout << std::endl; return 0;}", "e": 27973, "s": 26035, "text": null }, { "code": "// Java program to flatten the binary tree// using previous node approachclass GFG{ // Structure to represent a node of the treestatic class Node{ int data; Node left; Node right;}; static Node AllocNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Utility function to print the inorder// traversal of the treestatic void PrintInorderBinaryTree(Node root){ if (root == null) return; PrintInorderBinaryTree(root.left); System.out.print( root.data + \" \"); PrintInorderBinaryTree(root.right);} static Node last =null; // Function to make current node right of// the last node in the liststatic void FlattenBinaryTree(Node root){ if (root == null) return; Node left = root.left; Node right = root.right; // Avoid first iteration where root is // the only node in the list if (root != last) { (last).right = root; (last).left = null; last = root; } FlattenBinaryTree(left); FlattenBinaryTree(right); if (left == null && right == null) last = root;} // Driver Codepublic static void main(String args[]){ // Build the tree Node root = AllocNode(1); root.left = AllocNode(2); root.left.left = AllocNode(3); root.left.right = AllocNode(4); root.right = AllocNode(5); root.right.right = AllocNode(6); // Print the inorder traversal of the // original tree System.out.print(\"Original inorder traversal : \"); PrintInorderBinaryTree(root); System.out.println(); // Flatten a binary tree, at the beginning // root node is the only and last in the list last = root; FlattenBinaryTree(root); // Print the inorder traversal of the flattened // binary tree System.out.print(\"Flattened inorder traversal : \"); PrintInorderBinaryTree(root); System.out.println(); }} // This code is contributed by Arnab Kundu", "e": 29910, "s": 27973, "text": null }, { "code": "# Python program to flatten binary tree# using previous node approach # Node class to represent a node of the treeclass Node: def __init__(self, data): self.data = data self.right = None self.left = None # Utility function to print the inorder# traversal of the treedef PrintInorderBinaryTree(root): if(root == None): return PrintInorderBinaryTree(root.left) print(str(root.data), end = \" \") PrintInorderBinaryTree(root.right) # Function to make current node right of# the last node in the listdef FlattenBinaryTree(root): # A global variable which maintains the last node # that was added to the linked list global last if(root == None): return left = root.left right = root.right # Avoid first iteration where root is # the only node in the list if(root != last): last.right = root last.left = None last = root FlattenBinaryTree(left) FlattenBinaryTree(right) if(left == None and right == None): last = root # Build the treeroot = Node(1)root.left = Node(2)root.left.left = Node(3)root.left.right = Node(4)root.right = Node(5)root.right.right = Node(6) # Print the inorder traversal of the# original treeprint(\"Original inorder traversal : \", end = \"\")PrintInorderBinaryTree(root)print(\"\") # Global variable to maintain the# last node added to the linked listlast = root # Flatten the binary tree, at the beginning# root node is the only node in the listFlattenBinaryTree(root) # Print the inorder traversal of the flattened# binary treeprint(\"Flattened inorder traversal : \", end = \"\")PrintInorderBinaryTree(root) # This code is contributed by Pranav Devarakonda", "e": 31597, "s": 29910, "text": null }, { "code": "// C# program to flatten the binary tree// using previous node approachusing System; class GFG{ // Structure to represent a node of the treepublic class Node{ public int data; public Node left; public Node right;}; static Node AllocNode(int data){ Node temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Utility function to print the inorder// traversal of the treestatic void PrintInorderBinaryTree(Node root){ if (root == null) return; PrintInorderBinaryTree(root.left); Console.Write(root.data + \" \"); PrintInorderBinaryTree(root.right);} static Node last =null; // Function to make current node right of// the last node in the liststatic void FlattenBinaryTree(Node root){ if (root == null) return; Node left = root.left; Node right = root.right; // Avoid first iteration where root is // the only node in the list if (root != last) { (last).right = root; (last).left = null; last = root; } FlattenBinaryTree(left); FlattenBinaryTree(right); if (left == null && right == null) last = root;} // Driver Codepublic static void Main(String []args){ // Build the tree Node root = AllocNode(1); root.left = AllocNode(2); root.left.left = AllocNode(3); root.left.right = AllocNode(4); root.right = AllocNode(5); root.right.right = AllocNode(6); // Print the inorder traversal of the // original tree Console.Write(\"Original inorder traversal : \"); PrintInorderBinaryTree(root); Console.WriteLine(); // Flatten a binary tree, at the beginning // root node is the only and last in the list last = root; FlattenBinaryTree(root); // Print the inorder traversal of the flattened // binary tree Console.Write(\"Flattened inorder traversal : \"); PrintInorderBinaryTree(root); Console.WriteLine();}} // This code is contributed by 29AjayKumar", "e": 33553, "s": 31597, "text": null }, { "code": "<script> // Javascript program to flatten the binary tree// using previous node approach // Structure to represent a node of the treeclass Node { constructor() { this.data = 0; this.left = null; this.right = null; } } function AllocNode( data){ var temp = new Node(); temp.left = null; temp.right = null; temp.data = data; return temp;} // Utility function to print the inorder// traversal of the treefunction PrintInorderBinaryTree( root){ if (root == null) return; PrintInorderBinaryTree(root.left); document.write( root.data + \" \"); PrintInorderBinaryTree(root.right);} var last =null; // Function to make current node right of// the last node in the listfunction FlattenBinaryTree( root){ if (root == null) return; var left = root.left; var right = root.right; // Avoid first iteration where root is // the only node in the list if (root != last) { (last).right = root; (last).left = null; last = root; } FlattenBinaryTree(left); FlattenBinaryTree(right); if (left == null && right == null) last = root;} // Driver Code // Build the treevar root = AllocNode(1);root.left = AllocNode(2);root.left.left = AllocNode(3);root.left.right = AllocNode(4);root.right = AllocNode(5);root.right.right = AllocNode(6); // Print the inorder traversal of the// original treedocument.write(\"Original inorder traversal : \");PrintInorderBinaryTree(root);document.write(\"</br>\"); // Flatten a binary tree, at the beginning// root node is the only and last in the listlast = root;FlattenBinaryTree(root); // Print the inorder traversal of the flattened// binary treedocument.write(\"Flattened inorder traversal : \");PrintInorderBinaryTree(root);document.write(\"</br>\"); // This code is contributed by JANA_SAYANTAN.</script>", "e": 35443, "s": 33553, "text": null }, { "code": null, "e": 35527, "s": 35443, "text": "Original inorder traversal : 3 2 4 1 5 6 \nFlattened inorder traversal : 1 2 3 4 5 6" }, { "code": null, "e": 35548, "s": 35529, "text": "Pranav Devarakonda" }, { "code": null, "e": 35559, "s": 35548, "text": "andrew1234" }, { "code": null, "e": 35571, "s": 35559, "text": "29AjayKumar" }, { "code": null, "e": 35585, "s": 35571, "text": "jana_sayantan" }, { "code": null, "e": 35602, "s": 35585, "text": "surinderdawra388" }, { "code": null, "e": 35614, "s": 35602, "text": "Linked List" }, { "code": null, "e": 35619, "s": 35614, "text": "Tree" }, { "code": null, "e": 35631, "s": 35619, "text": "Linked List" }, { "code": null, "e": 35636, "s": 35631, "text": "Tree" }, { "code": null, "e": 35734, "s": 35636, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35743, "s": 35734, "text": "Comments" }, { "code": null, "e": 35756, "s": 35743, "text": "Old Comments" }, { "code": null, "e": 35777, "s": 35756, "text": "Linked List vs Array" }, { "code": null, "e": 35823, "s": 35777, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 35858, "s": 35823, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 35888, "s": 35858, "text": "Merge two sorted linked lists" }, { "code": null, "e": 35917, "s": 35888, "text": "Detect loop in a linked list" }, { "code": null, "e": 35952, "s": 35917, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 35981, "s": 35952, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 36024, "s": 35981, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 36086, "s": 36024, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" } ]
Arduino - Arrays
An array is a consecutive group of memory locations that are of the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array. The illustration given below shows an integer array called C that contains 11 elements. You refer to any one of these elements by giving the array name followed by the particular element’s position number in square brackets ([]). The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array). The first element has subscript 0 (zero) and is sometimes called the zeros element. Thus, the elements of array C are C[0] (pronounced “C sub zero”), C[1], C[2] and so on. The highest subscript in array C is 10, which is 1 less than the number of elements in the array (11). Array names follow the same conventions as other variable names. A subscript must be an integer or integer expression (using any integral type). If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. For example, if we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement adds 2 to array element C[11]. A subscripted array name is an lvalue, it can be used on the left side of an assignment, just as non-array variable names can. Let us examine array C in the given figure, more closely. The name of the entire array is C. Its 11 elements are referred to as C[0] to C[10]. The value of C[0] is -45, the value of C[1] is 6, the value of C[2] is 0, the value of C[7] is 62, and the value of C[10] is 78. To print the sum of the values contained in the first three elements of array C, we would write − Serial.print (C[ 0 ] + C[ 1 ] + C[ 2 ] ); To divide the value of C[6] by 2 and assign the result to the variable x, we would write − x = C[ 6 ] / 2; Arrays occupy space in memory. To specify the type of the elements and the number of elements required by an array, use a declaration of the form − type arrayName [ arraySize ] ; The compiler reserves the appropriate amount of memory. (Recall that a declaration, which reserves memory is more properly known as a definition). The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 11 elements for integer array C, use the declaration − int C[ 12 ]; // C is an array of 12 integers Arrays can be declared to contain values of any non-reference data type. For example, an array of type string can be used to store character strings. This section gives many examples that demonstrate how to declare, initialize and manipulate arrays. The program declares a 10-element integer array n. Lines a–b use a For statement to initialize the array elements to zeros. Like other automatic variables, automatic arrays are not implicitly initialized to zero. The first output statement (line c) displays the column headings for the columns printed in the subsequent for statement (lines d–e), which prints the array in tabular format. Example int n[ 10 ] ; // n is an array of 10 integers void setup () { } void loop () { for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0 { n[ i ] = 0; // set element at location i to 0 Serial.print (i) ; Serial.print (‘\r’) ; } for ( int j = 0; j < 10; ++j ) // output each array element's value { Serial.print (n[j]) ; Serial.print (‘\r’) ; } } Result − It will produce the following result − Element Value 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 The elements of an array can also be initialized in the array declaration by following the array name with an equal-to sign and a brace-delimited comma-separated list of initializers. The program uses an initializer list to initialize an integer array with 10 values (line a) and prints the array in tabular format (lines b–c). Example // n is an array of 10 integers int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ; void setup () { } void loop () { for ( int i = 0; i < 10; ++i ) { Serial.print (i) ; Serial.print (‘\r’) ; } for ( int j = 0; j < 10; ++j ) // output each array element's value { Serial.print (n[j]) ; Serial.print (‘\r’) ; } } Result − It will produce the following result − Element Value 0 1 2 3 4 5 6 7 8 9 32 27 64 18 95 14 90 70 60 37 0 1 2 3 4 5 6 7 8 9 32 27 64 18 95 14 90 70 60 37 Often, the elements of an array represent a series of values to be used in a calculation. For example, if the elements of an array represent exam grades, a professor may wish to total the elements of the array and use that sum to calculate the class average for the exam. The program sums the values contained in the 10-element integer array a. Example const int arraySize = 10; // constant variable indicating size of array int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; void setup () { } void loop () { // sum contents of array a for ( int i = 0; i < arraySize; ++i ) total += a[ i ]; Serial.print (“Total of array elements : ”) ; Serial.print(total) ; } Result − It will produce the following result − Total of array elements: 849 Arrays are important to Arduino and should need a lot more attention. The following important concepts related to array should be clear to a Arduino − To pass an array argument to a function, specify the name of the array without any brackets. Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of information arranged in rows and columns. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3105, "s": 2870, "text": "An array is a consecutive group of memory locations that are of the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array." }, { "code": null, "e": 3564, "s": 3105, "text": "The illustration given below shows an integer array called C that contains 11 elements. You refer to any one of these elements by giving the array name followed by the particular element’s position number in square brackets ([]). The position number is more formally called a subscript or index (this number specifies the number of elements from the beginning of the array). The first element has subscript 0 (zero) and is sometimes called the zeros element." }, { "code": null, "e": 3820, "s": 3564, "text": "Thus, the elements of array C are C[0] (pronounced “C sub zero”), C[1], C[2] and so on. The highest subscript in array C is 10, which is 1 less than the number of elements in the array (11). Array names follow the same conventions as other variable names." }, { "code": null, "e": 4159, "s": 3820, "text": "A subscript must be an integer or integer expression (using any integral type). If a program uses an expression as a subscript, then the program evaluates the expression to determine the subscript. For example, if we assume that variable a is equal to 5 and that variable b is equal to 6, then the statement adds 2 to array element C[11]." }, { "code": null, "e": 4286, "s": 4159, "text": "A subscripted array name is an lvalue, it can be used on the left side of an assignment, just as non-array variable names can." }, { "code": null, "e": 4558, "s": 4286, "text": "Let us examine array C in the given figure, more closely. The name of the entire array is C. Its 11 elements are referred to as C[0] to C[10]. The value of C[0] is -45, the value of C[1] is 6, the value of C[2] is 0, the value of C[7] is 62, and the value of C[10] is 78." }, { "code": null, "e": 4656, "s": 4558, "text": "To print the sum of the values contained in the first three elements of array C, we would write −" }, { "code": null, "e": 4699, "s": 4656, "text": "Serial.print (C[ 0 ] + C[ 1 ] + C[ 2 ] );\n" }, { "code": null, "e": 4790, "s": 4699, "text": "To divide the value of C[6] by 2 and assign the result to the variable x, we would write −" }, { "code": null, "e": 4807, "s": 4790, "text": "x = C[ 6 ] / 2;\n" }, { "code": null, "e": 4955, "s": 4807, "text": "Arrays occupy space in memory. To specify the type of the elements and the number of elements required by an array, use a declaration of the form −" }, { "code": null, "e": 4987, "s": 4955, "text": "type arrayName [ arraySize ] ;\n" }, { "code": null, "e": 5295, "s": 4987, "text": "The compiler reserves the appropriate amount of memory. (Recall that a declaration, which reserves memory is more properly known as a definition). The arraySize must be an integer constant greater than zero. For example, to tell the compiler to reserve 11 elements for integer array C, use the declaration −" }, { "code": null, "e": 5341, "s": 5295, "text": "int C[ 12 ]; // C is an array of 12 integers\n" }, { "code": null, "e": 5491, "s": 5341, "text": "Arrays can be declared to contain values of any non-reference data type. For example, an array of type string can be used to store character strings." }, { "code": null, "e": 5591, "s": 5491, "text": "This section gives many examples that demonstrate how to declare, initialize and manipulate arrays." }, { "code": null, "e": 5980, "s": 5591, "text": "The program declares a 10-element integer array n. Lines a–b use a For statement to initialize the array elements to zeros. Like other automatic variables, automatic arrays are not implicitly initialized to zero. The first output statement (line c) displays the column headings for the columns printed in the subsequent for statement (lines d–e), which prints the array in tabular format." }, { "code": null, "e": 5988, "s": 5980, "text": "Example" }, { "code": null, "e": 6392, "s": 5988, "text": "int n[ 10 ] ; // n is an array of 10 integers\n\nvoid setup () {\n\n}\n\nvoid loop () {\n for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0 {\n n[ i ] = 0; // set element at location i to 0\n Serial.print (i) ;\n Serial.print (‘\\r’) ;\n }\n for ( int j = 0; j < 10; ++j ) // output each array element's value {\n Serial.print (n[j]) ;\n Serial.print (‘\\r’) ;\n } \n}" }, { "code": null, "e": 6440, "s": 6392, "text": "Result − It will produce the following result −" }, { "code": null, "e": 6505, "s": 6440, "text": "\n\nElement\nValue\n\n\n\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n\n\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n\n\n\n" }, { "code": null, "e": 6507, "s": 6505, "text": "0" }, { "code": null, "e": 6509, "s": 6507, "text": "1" }, { "code": null, "e": 6511, "s": 6509, "text": "2" }, { "code": null, "e": 6513, "s": 6511, "text": "3" }, { "code": null, "e": 6515, "s": 6513, "text": "4" }, { "code": null, "e": 6517, "s": 6515, "text": "5" }, { "code": null, "e": 6519, "s": 6517, "text": "6" }, { "code": null, "e": 6521, "s": 6519, "text": "7" }, { "code": null, "e": 6523, "s": 6521, "text": "8" }, { "code": null, "e": 6525, "s": 6523, "text": "9" }, { "code": null, "e": 6527, "s": 6525, "text": "0" }, { "code": null, "e": 6529, "s": 6527, "text": "0" }, { "code": null, "e": 6531, "s": 6529, "text": "0" }, { "code": null, "e": 6533, "s": 6531, "text": "0" }, { "code": null, "e": 6535, "s": 6533, "text": "0" }, { "code": null, "e": 6537, "s": 6535, "text": "0" }, { "code": null, "e": 6539, "s": 6537, "text": "0" }, { "code": null, "e": 6541, "s": 6539, "text": "0" }, { "code": null, "e": 6543, "s": 6541, "text": "0" }, { "code": null, "e": 6545, "s": 6543, "text": "0" }, { "code": null, "e": 6873, "s": 6545, "text": "The elements of an array can also be initialized in the array declaration by following the array name with an equal-to sign and a brace-delimited comma-separated list of initializers. The program uses an initializer list to initialize an integer array with 10 values (line a) and prints the array in tabular format (lines b–c)." }, { "code": null, "e": 6881, "s": 6873, "text": "Example" }, { "code": null, "e": 7239, "s": 6881, "text": "// n is an array of 10 integers\nint n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ;\n\nvoid setup () {\n\n}\n\nvoid loop () {\n for ( int i = 0; i < 10; ++i ) {\n Serial.print (i) ;\n Serial.print (‘\\r’) ;\n }\n for ( int j = 0; j < 10; ++j ) // output each array element's value {\n Serial.print (n[j]) ;\n Serial.print (‘\\r’) ;\n } \n}" }, { "code": null, "e": 7287, "s": 7239, "text": "Result − It will produce the following result −" }, { "code": null, "e": 7362, "s": 7287, "text": "\n\nElement\nValue\n\n\n\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n\n\n32\n27\n64\n18\n95\n14\n90\n70\n60\n37\n\n\n\n" }, { "code": null, "e": 7364, "s": 7362, "text": "0" }, { "code": null, "e": 7366, "s": 7364, "text": "1" }, { "code": null, "e": 7368, "s": 7366, "text": "2" }, { "code": null, "e": 7370, "s": 7368, "text": "3" }, { "code": null, "e": 7372, "s": 7370, "text": "4" }, { "code": null, "e": 7374, "s": 7372, "text": "5" }, { "code": null, "e": 7376, "s": 7374, "text": "6" }, { "code": null, "e": 7378, "s": 7376, "text": "7" }, { "code": null, "e": 7380, "s": 7378, "text": "8" }, { "code": null, "e": 7382, "s": 7380, "text": "9" }, { "code": null, "e": 7385, "s": 7382, "text": "32" }, { "code": null, "e": 7388, "s": 7385, "text": "27" }, { "code": null, "e": 7391, "s": 7388, "text": "64" }, { "code": null, "e": 7394, "s": 7391, "text": "18" }, { "code": null, "e": 7397, "s": 7394, "text": "95" }, { "code": null, "e": 7400, "s": 7397, "text": "14" }, { "code": null, "e": 7403, "s": 7400, "text": "90" }, { "code": null, "e": 7406, "s": 7403, "text": "70" }, { "code": null, "e": 7409, "s": 7406, "text": "60" }, { "code": null, "e": 7412, "s": 7409, "text": "37" }, { "code": null, "e": 7757, "s": 7412, "text": "Often, the elements of an array represent a series of values to be used in a calculation. For example, if the elements of an array represent exam grades, a professor may wish to total the elements of the array and use that sum to calculate the class average for the exam. The program sums the values contained in the 10-element integer array a." }, { "code": null, "e": 7765, "s": 7757, "text": "Example" }, { "code": null, "e": 8123, "s": 7765, "text": "const int arraySize = 10; // constant variable indicating size of array\nint a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };\nint total = 0;\n\nvoid setup () {\n\n}\nvoid loop () {\n // sum contents of array a\n for ( int i = 0; i < arraySize; ++i )\n total += a[ i ];\n Serial.print (“Total of array elements : ”) ;\n Serial.print(total) ;\n}" }, { "code": null, "e": 8171, "s": 8123, "text": "Result − It will produce the following result −" }, { "code": null, "e": 8201, "s": 8171, "text": "Total of array elements: 849\n" }, { "code": null, "e": 8352, "s": 8201, "text": "Arrays are important to Arduino and should need a lot more attention. The following important concepts related to array should be clear to a Arduino −" }, { "code": null, "e": 8445, "s": 8352, "text": "To pass an array argument to a function, specify the name of the array without any brackets." }, { "code": null, "e": 8580, "s": 8445, "text": "Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of information arranged in rows and columns." }, { "code": null, "e": 8615, "s": 8580, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 8626, "s": 8615, "text": " Amit Rana" }, { "code": null, "e": 8659, "s": 8626, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 8670, "s": 8659, "text": " Amit Rana" }, { "code": null, "e": 8703, "s": 8670, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 8716, "s": 8703, "text": " Ashraf Said" }, { "code": null, "e": 8751, "s": 8716, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8764, "s": 8751, "text": " Ashraf Said" }, { "code": null, "e": 8796, "s": 8764, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 8809, "s": 8796, "text": " Ashraf Said" }, { "code": null, "e": 8840, "s": 8809, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 8853, "s": 8840, "text": " Ashraf Said" }, { "code": null, "e": 8860, "s": 8853, "text": " Print" }, { "code": null, "e": 8871, "s": 8860, "text": " Add Notes" } ]
Generate Random Float type number in Java
In order to generate Random float type numbers in Java, we use the nextFloat() method of the java.util.Random class. This returns the next random float value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence. Declaration −The java.util.Random.nextFloat() method is declared as follows − public float nextFloat() Let us see a program to generate random float type numbers in Java. Live Demo import java.util.Random; public class Example { public static void main(String[] args) { Random rd = new Random(); // creating Random object System.out.println(rd.nextFloat()); // displaying a random float value between 0.0 and 1.0 } } 0.7739767 Note − The output might vary on Online Compilers.
[ { "code": null, "e": 1300, "s": 1062, "text": "In order to generate Random float type numbers in Java, we use the nextFloat() method of the java.util.Random class. This returns the next random float value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence." }, { "code": null, "e": 1378, "s": 1300, "text": "Declaration −The java.util.Random.nextFloat() method is declared as follows −" }, { "code": null, "e": 1403, "s": 1378, "text": "public float nextFloat()" }, { "code": null, "e": 1471, "s": 1403, "text": "Let us see a program to generate random float type numbers in Java." }, { "code": null, "e": 1482, "s": 1471, "text": " Live Demo" }, { "code": null, "e": 1736, "s": 1482, "text": "import java.util.Random;\npublic class Example {\n public static void main(String[] args) {\n Random rd = new Random(); // creating Random object\n System.out.println(rd.nextFloat()); // displaying a random float value between 0.0 and 1.0\n }\n}" }, { "code": null, "e": 1746, "s": 1736, "text": "0.7739767" }, { "code": null, "e": 1796, "s": 1746, "text": "Note − The output might vary on Online Compilers." } ]
Tcl - Break Statement
The break statement in Tcl language is used for terminating a loop. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop. If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. The syntax for a break statement in Tcl is as follows − break; #!/usr/bin/tclsh set a 10 # while loop execution while {$a < 20 } { puts "value of a: $a" incr a if { $a > 15} { # terminate the loop using break statement break } } When the above code is compiled and executed, it produces the following result − value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 Print Add Notes Bookmark this page
[ { "code": null, "e": 2429, "s": 2201, "text": "The break statement in Tcl language is used for terminating a loop. When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop." }, { "code": null, "e": 2622, "s": 2429, "text": "If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block." }, { "code": null, "e": 2678, "s": 2622, "text": "The syntax for a break statement in Tcl is as follows −" }, { "code": null, "e": 2686, "s": 2678, "text": "break;\n" }, { "code": null, "e": 2880, "s": 2686, "text": "#!/usr/bin/tclsh\n\nset a 10\n\n# while loop execution \nwhile {$a < 20 } {\n puts \"value of a: $a\"\n incr a\n if { $a > 15} {\n # terminate the loop using break statement \n break\n }\n}" }, { "code": null, "e": 2961, "s": 2880, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3052, "s": 2961, "text": "value of a: 10\nvalue of a: 11\nvalue of a: 12\nvalue of a: 13\nvalue of a: 14\nvalue of a: 15\n" }, { "code": null, "e": 3059, "s": 3052, "text": " Print" }, { "code": null, "e": 3070, "s": 3059, "text": " Add Notes" } ]
Whirlpool Hash Function in Python
13 Jul, 2021 Hash Function is a function which has a huge role in making a System Secure as it converts normal data given to it as an irregular value of fixed length. We can imagine it to be a Shaker in our homes. When we put data into this function it outputs an irregular value. The Irregular value it outputs is known as “Hash Value”.Hash Values are simply number but are often written in Hexadecimal. Computers manage values as Binary. Hash value is also a data and are often managed in Binary. Whirlpool is a cryptographic hash function created by Vincent Rijmen and Paulo S.L.M. Barreto. It was first published in 2000 and revised in 2001 and 2003. It was derived form square and Advanced Encryption Standard. It is a block cipher hash function and designed after square block cipher. It takes less than 2^256 bits length input and convert it in 512 bit hash. The first version of whirlpool is called Whirlpool-0 and changed to Whirlpool-T after it’s first revision in 2001 . In this version the S-box is changed and become easier to use in hardware. In 2002 a vulnerability was founded in the Whirlpool-0’s diffusion matrix which was removed by changing the matrix and the name was also changed from Whirlpool-T to Whirlpool.Every block cipher in whirlpool is a 8*8 matrix. The state of the function changes in ever round by using four operations: Hash Value is calculated by using the formula: State = MR*AK*SC*SB(State) Install whirlpool library using pip install whirlpool Example 1: Python3 # Python program to demonstrate# whirlpool hash function import whirlpool string = b"GeeksforGeeks" h1 = whirlpool.new(string)hashed_output = h1.hexdigest() print("The hashed value is")print(hashed_output) Output: The hashed value is 95cb4d2d765eb26a922b3ade5a5837a3bc6b18f9a68cec6392f7bf4284c996dd0dd8775dc77964bb9dd92f204d067d3b2c0f36f968607c88cd378ce094438e5a Example 2: Python3 # Python program to demonstrate# whirlpool hash function import whirlpool string = b"GeeksforGeeks" h1 = whirlpool.new(string)hashed_output = h1.hexdigest() h1.update(b"Geeks")hashed_output = h1.hexdigest() print("The hashed value is")print(hashed_output) Output: The hashed value is c3a2aea5a2b487f1a3ee848870dff8ca5af0adcf7eae2a58b40927e87027918c2e9438909c50c2d2bb73f15392c8fde22c94c85a8ef5d8c3b3e86a839909d58b rajeev0719singh python-utility 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 Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jul, 2021" }, { "code": null, "e": 515, "s": 28, "text": "Hash Function is a function which has a huge role in making a System Secure as it converts normal data given to it as an irregular value of fixed length. We can imagine it to be a Shaker in our homes. When we put data into this function it outputs an irregular value. The Irregular value it outputs is known as “Hash Value”.Hash Values are simply number but are often written in Hexadecimal. Computers manage values as Binary. Hash value is also a data and are often managed in Binary. " }, { "code": null, "e": 1374, "s": 517, "text": "Whirlpool is a cryptographic hash function created by Vincent Rijmen and Paulo S.L.M. Barreto. It was first published in 2000 and revised in 2001 and 2003. It was derived form square and Advanced Encryption Standard. It is a block cipher hash function and designed after square block cipher. It takes less than 2^256 bits length input and convert it in 512 bit hash. The first version of whirlpool is called Whirlpool-0 and changed to Whirlpool-T after it’s first revision in 2001 . In this version the S-box is changed and become easier to use in hardware. In 2002 a vulnerability was founded in the Whirlpool-0’s diffusion matrix which was removed by changing the matrix and the name was also changed from Whirlpool-T to Whirlpool.Every block cipher in whirlpool is a 8*8 matrix. The state of the function changes in ever round by using four operations: " }, { "code": null, "e": 1424, "s": 1376, "text": "Hash Value is calculated by using the formula: " }, { "code": null, "e": 1452, "s": 1424, "text": " State = MR*AK*SC*SB(State)" }, { "code": null, "e": 1486, "s": 1452, "text": "Install whirlpool library using " }, { "code": null, "e": 1508, "s": 1486, "text": "pip install whirlpool" }, { "code": null, "e": 1520, "s": 1508, "text": "Example 1: " }, { "code": null, "e": 1528, "s": 1520, "text": "Python3" }, { "code": "# Python program to demonstrate# whirlpool hash function import whirlpool string = b\"GeeksforGeeks\" h1 = whirlpool.new(string)hashed_output = h1.hexdigest() print(\"The hashed value is\")print(hashed_output)", "e": 1736, "s": 1528, "text": null }, { "code": null, "e": 1745, "s": 1736, "text": "Output: " }, { "code": null, "e": 1896, "s": 1745, "text": "The hashed value is 95cb4d2d765eb26a922b3ade5a5837a3bc6b18f9a68cec6392f7bf4284c996dd0dd8775dc77964bb9dd92f204d067d3b2c0f36f968607c88cd378ce094438e5a " }, { "code": null, "e": 1908, "s": 1896, "text": "Example 2: " }, { "code": null, "e": 1916, "s": 1908, "text": "Python3" }, { "code": "# Python program to demonstrate# whirlpool hash function import whirlpool string = b\"GeeksforGeeks\" h1 = whirlpool.new(string)hashed_output = h1.hexdigest() h1.update(b\"Geeks\")hashed_output = h1.hexdigest() print(\"The hashed value is\")print(hashed_output)", "e": 2174, "s": 1916, "text": null }, { "code": null, "e": 2183, "s": 2174, "text": "Output: " }, { "code": null, "e": 2332, "s": 2183, "text": "The hashed value is c3a2aea5a2b487f1a3ee848870dff8ca5af0adcf7eae2a58b40927e87027918c2e9438909c50c2d2bb73f15392c8fde22c94c85a8ef5d8c3b3e86a839909d58b" }, { "code": null, "e": 2352, "s": 2336, "text": "rajeev0719singh" }, { "code": null, "e": 2367, "s": 2352, "text": "python-utility" }, { "code": null, "e": 2374, "s": 2367, "text": "Python" }, { "code": null, "e": 2472, "s": 2374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2490, "s": 2472, "text": "Python Dictionary" }, { "code": null, "e": 2532, "s": 2490, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2554, "s": 2532, "text": "Enumerate() in Python" }, { "code": null, "e": 2580, "s": 2554, "text": "Python String | replace()" }, { "code": null, "e": 2612, "s": 2580, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2641, "s": 2612, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2668, "s": 2641, "text": "Python Classes and Objects" }, { "code": null, "e": 2698, "s": 2668, "text": "Iterate over a list in Python" }, { "code": null, "e": 2719, "s": 2698, "text": "Python OOPs Concepts" } ]
HTML | <th> nowrap Attribute
26 Jun, 2019 The HTML <th> nowrap Attribute is used to specify that the content present inside the header cell should not wrap. It contains the Boolean value. It is not supported by HTML 5. Syntax: <th nowrap> Example: <!DOCTYPE html><html> <head> <title> HTML th nowrap Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th nowrap Attribute</h2> <table border="1"> <tr> <th>NAME</th> <th nowrap> GeeksforGeeks is a computer science portal </th> </tr> <tr> <td>BITTU</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>EC</td> </tr> </table></body> </html> Output: Supported Browsers: The browser supported by HTML <th> nowrap attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Jun, 2019" }, { "code": null, "e": 205, "s": 28, "text": "The HTML <th> nowrap Attribute is used to specify that the content present inside the header cell should not wrap. It contains the Boolean value. It is not supported by HTML 5." }, { "code": null, "e": 213, "s": 205, "text": "Syntax:" }, { "code": null, "e": 225, "s": 213, "text": "<th nowrap>" }, { "code": null, "e": 234, "s": 225, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML th nowrap Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML th nowrap Attribute</h2> <table border=\"1\"> <tr> <th>NAME</th> <th nowrap> GeeksforGeeks is a computer science portal </th> </tr> <tr> <td>BITTU</td> <td>CSE</td> </tr> <tr> <td>RAKESH</td> <td>EC</td> </tr> </table></body> </html>", "e": 749, "s": 234, "text": null }, { "code": null, "e": 757, "s": 749, "text": "Output:" }, { "code": null, "e": 847, "s": 757, "text": "Supported Browsers: The browser supported by HTML <th> nowrap attribute are listed below:" }, { "code": null, "e": 861, "s": 847, "text": "Google Chrome" }, { "code": null, "e": 879, "s": 861, "text": "Internet Explorer" }, { "code": null, "e": 887, "s": 879, "text": "Firefox" }, { "code": null, "e": 894, "s": 887, "text": "Safari" }, { "code": null, "e": 900, "s": 894, "text": "Opera" }, { "code": null, "e": 916, "s": 900, "text": "HTML-Attributes" }, { "code": null, "e": 921, "s": 916, "text": "HTML" }, { "code": null, "e": 938, "s": 921, "text": "Web Technologies" }, { "code": null, "e": 943, "s": 938, "text": "HTML" }, { "code": null, "e": 1041, "s": 943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1065, "s": 1041, "text": "REST API (Introduction)" }, { "code": null, "e": 1104, "s": 1065, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1143, "s": 1104, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1163, "s": 1143, "text": "Angular File Upload" }, { "code": null, "e": 1192, "s": 1163, "text": "Form validation using jQuery" }, { "code": null, "e": 1225, "s": 1192, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1286, "s": 1225, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1329, "s": 1286, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1401, "s": 1329, "text": "Differences between Functional Components and Class Components in React" } ]
Merge two dataframes with same column names
05 Apr, 2021 In order to merge two data frames with the same column names, we are going to use the pandas.concat(). This function does all the heavy lifting of performing concatenation operations along with an axis of Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes. Syntax: concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy) Import module Create or load first dataframe Create or load second dataframe Concatenate on the basis of same column names Display result Below are various examples that depict how to merge two data frames with the same column names: Example 1: Python3 # import moduleimport pandas as pd # assign dataframesdata1 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['A', 'B', 'C']) data2 = pd.DataFrame([[3, 4], [5, 6]], columns=['A', 'C']) # display dataframesprint('Dataframes:')display(data1)display(data2) # merge two data framesprint('After merging:')pd.concat([data1, data2], axis=0) Output: Example 2: Python3 # import moduleimport pandas as pd # assign dataframesdata1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B']], columns=['Students', 'Avg Marks', 'Section']) data2 = pd.DataFrame([[52, 'C'], [25, 'A']], columns=['Students', 'Section']) # display dataframesprint('Dataframes:')display(data1)display(data2) # merge two data framesprint('After merging:')pd.concat([data1, data2], axis=0) Output: Example 3: Python3 # import moduleimport pandas as pd # assign dataframesdata1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B'], [25, 70.7, 'C']], columns=['Students', 'Avg Marks', 'Section']) data2 = pd.DataFrame([[30, 70.2, 'A'], [25, 65.2, 'B'], [35, 77.7, 'C']], columns=['Students', 'Avg Marks', 'Section']) # display dataframesprint('Dataframes:')display(data1)display(data2) # merge two data framesprint('After merging:')pd.concat([data1, data2], axis=0) Output: Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Apr, 2021" }, { "code": null, "e": 351, "s": 28, "text": "In order to merge two data frames with the same column names, we are going to use the pandas.concat(). This function does all the heavy lifting of performing concatenation operations along with an axis of Pandas objects while performing optional set logic (union or intersection) of the indexes (if any) on the other axes." }, { "code": null, "e": 449, "s": 351, "text": "Syntax: concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy)" }, { "code": null, "e": 463, "s": 449, "text": "Import module" }, { "code": null, "e": 494, "s": 463, "text": "Create or load first dataframe" }, { "code": null, "e": 526, "s": 494, "text": "Create or load second dataframe" }, { "code": null, "e": 572, "s": 526, "text": "Concatenate on the basis of same column names" }, { "code": null, "e": 587, "s": 572, "text": "Display result" }, { "code": null, "e": 683, "s": 587, "text": "Below are various examples that depict how to merge two data frames with the same column names:" }, { "code": null, "e": 695, "s": 683, "text": "Example 1: " }, { "code": null, "e": 703, "s": 695, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign dataframesdata1 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['A', 'B', 'C']) data2 = pd.DataFrame([[3, 4], [5, 6]], columns=['A', 'C']) # display dataframesprint('Dataframes:')display(data1)display(data2) # merge two data framesprint('After merging:')pd.concat([data1, data2], axis=0)", "e": 1090, "s": 703, "text": null }, { "code": null, "e": 1098, "s": 1090, "text": "Output:" }, { "code": null, "e": 1109, "s": 1098, "text": "Example 2:" }, { "code": null, "e": 1117, "s": 1109, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign dataframesdata1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B']], columns=['Students', 'Avg Marks', 'Section']) data2 = pd.DataFrame([[52, 'C'], [25, 'A']], columns=['Students', 'Section']) # display dataframesprint('Dataframes:')display(data1)display(data2) # merge two data framesprint('After merging:')pd.concat([data1, data2], axis=0)", "e": 1545, "s": 1117, "text": null }, { "code": null, "e": 1553, "s": 1545, "text": "Output:" }, { "code": null, "e": 1564, "s": 1553, "text": "Example 3:" }, { "code": null, "e": 1572, "s": 1564, "text": "Python3" }, { "code": "# import moduleimport pandas as pd # assign dataframesdata1 = pd.DataFrame([[25, 77.5, 'A'], [30, 60.2, 'B'], [25, 70.7, 'C']], columns=['Students', 'Avg Marks', 'Section']) data2 = pd.DataFrame([[30, 70.2, 'A'], [25, 65.2, 'B'], [35, 77.7, 'C']], columns=['Students', 'Avg Marks', 'Section']) # display dataframesprint('Dataframes:')display(data1)display(data2) # merge two data framesprint('After merging:')pd.concat([data1, data2], axis=0)", "e": 2103, "s": 1572, "text": null }, { "code": null, "e": 2111, "s": 2103, "text": "Output:" }, { "code": null, "e": 2118, "s": 2111, "text": "Picked" }, { "code": null, "e": 2142, "s": 2118, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2165, "s": 2142, "text": "Python Pandas-exercise" }, { "code": null, "e": 2179, "s": 2165, "text": "Python-pandas" }, { "code": null, "e": 2186, "s": 2179, "text": "Python" }, { "code": null, "e": 2284, "s": 2186, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2302, "s": 2284, "text": "Python Dictionary" }, { "code": null, "e": 2344, "s": 2302, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2366, "s": 2344, "text": "Enumerate() in Python" }, { "code": null, "e": 2398, "s": 2366, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2427, "s": 2398, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2454, "s": 2427, "text": "Python Classes and Objects" }, { "code": null, "e": 2484, "s": 2454, "text": "Iterate over a list in Python" }, { "code": null, "e": 2505, "s": 2484, "text": "Python OOPs Concepts" }, { "code": null, "e": 2541, "s": 2505, "text": "Convert integer to string in Python" } ]
Java Program to Merge Two Sorted Linked Lists in New List
11 Jul, 2022 We are given two sorted List and our goal is to merge these two lists into a new list. For that, we have to write one function which will take two List as an argument which is sorted in increasing order. This function will Merge these two List into one List in increasing order. Input List 1 : 1-> 3-> 4-> 9->10 List 2 : 2-> 5-> 6-> 9 Output New List : 1-> 2-> 3-> 4-> 5-> 6-> 9-> 9-> 10 We have two approaches to solve this problem: IterativeRecursive Iterative Recursive Method 1: Iterative Approach The idea behind this approach is we will take one extra node in the new list which is the Head node of the list. We will take one variable of the type list which is always at the last node of the list so that the appending of a new node becomes easier. We will iterate the loop and check for the smaller element from both lists and append that node to the resultant list. If we reached the end of any list then we will simply append the remaining nodes from the second list. Implementation: Java // Java Program to Merge Two Sorted// Linked Lists in New List// Iteratively import java.io.*; public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; }} class GFG { public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { // New List ListNode result = new ListNode(-1); // variable to point the last node of the list. ListNode p = result; // Iterate the loop while (l1 != null && l2 != null) { // Find the smaller element and append it to the // list. if (l1.val <= l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } // Update the variable p = p.next; } // If anyone list become empty append the remaining // list element of othe list. if (l1 == null) { p.next = l2; } else if (l2 == null) { p.next = l1; } // Return the resultant list without first extra // node return result.next; } // A utility function to print linked list static void printList(ListNode node) { while (node != null) { System.out.print(node.val + " "); node = node.next; } } // Driver code public static void main(String[] args) { ListNode head1 = new ListNode(1); head1.next = new ListNode(3); head1.next.next = new ListNode(5); // 1->3->5 LinkedList created ListNode head2 = new ListNode(0); head2.next = new ListNode(2); head2.next.next = new ListNode(4); // 0->2->4 LinkedList created ListNode mergedhead = mergeTwoLists(head1, head2); printList(mergedhead); }} 0 1 2 3 4 5 Time Complexity: O(N) Auxiliary Space: O(1) Method 2: Recursive Approach One can solve this problem by using the recursion approach. The function will take two sorted lists as an argument. If any list is empty then it simply returns the remaining elements from the other list. Otherwise, it will check for the smaller element from both lists, append the smaller node to the resultant list and recursively call the function for the next node of the list and another list. Implementation: Java // Java Program to Merge Two Sorted// Linked Lists in New List// Recursively import java.io.*; public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; }} class GFG { public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { // New List ListNode result = null; // If anyone list is empty then returns the // remaining elements of other list if (l1 == null) { return l2; } else if (l2 == null) { return l1; } // Find the smaller element and recusivly call the // function with next node if (l1.val <= l2.val) { result = l1; result.next = mergeTwoLists(l1.next, l2); } else { result = l2; result.next = mergeTwoLists(l1, l2.next); } // Return the resultant list return (result); } // A utility function to print linked list static void printList(ListNode node) { while (node != null) { System.out.print(node.val + " "); node = node.next; } } // Driver code public static void main(String[] args) { ListNode head1 = new ListNode(23); head1.next = new ListNode(35); head1.next.next = new ListNode(65); // 23->35->65 LinkedList created ListNode head2 = new ListNode(43); head2.next = new ListNode(59); head2.next.next = new ListNode(60); // 43->59->60 LinkedList created ListNode mergedhead = mergeTwoLists(head1, head2); printList(mergedhead); }} 23 35 43 59 60 65 Time Complexity: O(N) Auxiliary Space: O(N) for call stack since using recursion sagar0719kumar rohitsingh07052 noviced3vq6 Picked Java Java Programs Linked List Linked List Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jul, 2022" }, { "code": null, "e": 308, "s": 28, "text": "We are given two sorted List and our goal is to merge these two lists into a new list. For that, we have to write one function which will take two List as an argument which is sorted in increasing order. This function will Merge these two List into one List in increasing order. " }, { "code": null, "e": 418, "s": 308, "text": "Input\nList 1 : 1-> 3-> 4-> 9->10\nList 2 : 2-> 5-> 6-> 9\n\nOutput\nNew List : 1-> 2-> 3-> 4-> 5-> 6-> 9-> 9-> 10" }, { "code": null, "e": 464, "s": 418, "text": "We have two approaches to solve this problem:" }, { "code": null, "e": 483, "s": 464, "text": "IterativeRecursive" }, { "code": null, "e": 493, "s": 483, "text": "Iterative" }, { "code": null, "e": 503, "s": 493, "text": "Recursive" }, { "code": null, "e": 532, "s": 503, "text": "Method 1: Iterative Approach" }, { "code": null, "e": 645, "s": 532, "text": "The idea behind this approach is we will take one extra node in the new list which is the Head node of the list." }, { "code": null, "e": 785, "s": 645, "text": "We will take one variable of the type list which is always at the last node of the list so that the appending of a new node becomes easier." }, { "code": null, "e": 904, "s": 785, "text": "We will iterate the loop and check for the smaller element from both lists and append that node to the resultant list." }, { "code": null, "e": 1007, "s": 904, "text": "If we reached the end of any list then we will simply append the remaining nodes from the second list." }, { "code": null, "e": 1023, "s": 1007, "text": "Implementation:" }, { "code": null, "e": 1028, "s": 1023, "text": "Java" }, { "code": "// Java Program to Merge Two Sorted// Linked Lists in New List// Iteratively import java.io.*; public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; }} class GFG { public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { // New List ListNode result = new ListNode(-1); // variable to point the last node of the list. ListNode p = result; // Iterate the loop while (l1 != null && l2 != null) { // Find the smaller element and append it to the // list. if (l1.val <= l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } // Update the variable p = p.next; } // If anyone list become empty append the remaining // list element of othe list. if (l1 == null) { p.next = l2; } else if (l2 == null) { p.next = l1; } // Return the resultant list without first extra // node return result.next; } // A utility function to print linked list static void printList(ListNode node) { while (node != null) { System.out.print(node.val + \" \"); node = node.next; } } // Driver code public static void main(String[] args) { ListNode head1 = new ListNode(1); head1.next = new ListNode(3); head1.next.next = new ListNode(5); // 1->3->5 LinkedList created ListNode head2 = new ListNode(0); head2.next = new ListNode(2); head2.next.next = new ListNode(4); // 0->2->4 LinkedList created ListNode mergedhead = mergeTwoLists(head1, head2); printList(mergedhead); }}", "e": 3023, "s": 1028, "text": null }, { "code": null, "e": 3036, "s": 3023, "text": "0 1 2 3 4 5 " }, { "code": null, "e": 3058, "s": 3036, "text": "Time Complexity: O(N)" }, { "code": null, "e": 3080, "s": 3058, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3109, "s": 3080, "text": "Method 2: Recursive Approach" }, { "code": null, "e": 3170, "s": 3109, "text": "One can solve this problem by using the recursion approach. " }, { "code": null, "e": 3226, "s": 3170, "text": "The function will take two sorted lists as an argument." }, { "code": null, "e": 3314, "s": 3226, "text": "If any list is empty then it simply returns the remaining elements from the other list." }, { "code": null, "e": 3508, "s": 3314, "text": "Otherwise, it will check for the smaller element from both lists, append the smaller node to the resultant list and recursively call the function for the next node of the list and another list." }, { "code": null, "e": 3524, "s": 3508, "text": "Implementation:" }, { "code": null, "e": 3529, "s": 3524, "text": "Java" }, { "code": "// Java Program to Merge Two Sorted// Linked Lists in New List// Recursively import java.io.*; public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; }} class GFG { public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { // New List ListNode result = null; // If anyone list is empty then returns the // remaining elements of other list if (l1 == null) { return l2; } else if (l2 == null) { return l1; } // Find the smaller element and recusivly call the // function with next node if (l1.val <= l2.val) { result = l1; result.next = mergeTwoLists(l1.next, l2); } else { result = l2; result.next = mergeTwoLists(l1, l2.next); } // Return the resultant list return (result); } // A utility function to print linked list static void printList(ListNode node) { while (node != null) { System.out.print(node.val + \" \"); node = node.next; } } // Driver code public static void main(String[] args) { ListNode head1 = new ListNode(23); head1.next = new ListNode(35); head1.next.next = new ListNode(65); // 23->35->65 LinkedList created ListNode head2 = new ListNode(43); head2.next = new ListNode(59); head2.next.next = new ListNode(60); // 43->59->60 LinkedList created ListNode mergedhead = mergeTwoLists(head1, head2); printList(mergedhead); }}", "e": 5295, "s": 3529, "text": null }, { "code": null, "e": 5314, "s": 5295, "text": "23 35 43 59 60 65 " }, { "code": null, "e": 5336, "s": 5314, "text": "Time Complexity: O(N)" }, { "code": null, "e": 5395, "s": 5336, "text": "Auxiliary Space: O(N) for call stack since using recursion" }, { "code": null, "e": 5410, "s": 5395, "text": "sagar0719kumar" }, { "code": null, "e": 5426, "s": 5410, "text": "rohitsingh07052" }, { "code": null, "e": 5438, "s": 5426, "text": "noviced3vq6" }, { "code": null, "e": 5445, "s": 5438, "text": "Picked" }, { "code": null, "e": 5450, "s": 5445, "text": "Java" }, { "code": null, "e": 5464, "s": 5450, "text": "Java Programs" }, { "code": null, "e": 5476, "s": 5464, "text": "Linked List" }, { "code": null, "e": 5488, "s": 5476, "text": "Linked List" }, { "code": null, "e": 5493, "s": 5488, "text": "Java" } ]
Maximum profit by buying and selling a share at most k times
08 Jul, 2022 In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions, where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made. Examples: Input: Price = [10, 22, 5, 75, 65, 80] K = 2 Output: 87 Trader earns 87 as sum of 12 and 75 Buy at price 10, sell at 22, buy at 5 and sell at 80 Input: Price = [12, 14, 17, 10, 14, 13, 12, 15] K = 3 Output: 12 Trader earns 12 as the sum of 5, 4 and 3 Buy at price 12, sell at 17, buy at 10 and sell at 14 and buy at 12 and sell at 15 Input: Price = [100, 30, 15, 10, 8, 25, 80] K = 3 Output: 72 Only one transaction. Buy at price 8 and sell at 80. Input: Price = [90, 80, 70, 60, 50] K = 1 Output: 0 Not possible to earn. There are various versions of the problem. If we are allowed to buy and sell only once, then we can use the Maximum difference between the two elements algorithm. If we are allowed to make at most 2 transactions, we can follow approach discussed here. If we are allowed to buy and sell any number of times, we can follow approach discussed here. Method 1 Dynamic Programming In this post, we are only allowed to make at max k transactions. The problem can be solved by using dynamic programming. Let profit[t][i] represent maximum profit using at most t transactions up to day i (including day i). Then the relation is:profit[t][i] = max(profit[t][i-1], max(price[i] – price[j] + profit[t-1][j])) for all j in range [0, i-1] profit[t][i] will be maximum of – profit[t][i-1] which represents not doing any transaction on the ith day.Maximum profit gained by selling on ith day. In order to sell shares on ith day, we need to purchase it on any one of [0, i – 1] days. If we buy shares on jth day and sell it on ith day, max profit will be price[i] – price[j] + profit[t-1][j] where j varies from 0 to i-1. Here profit[t-1][j] is best we could have done with one less transaction till jth day. profit[t][i-1] which represents not doing any transaction on the ith day. Maximum profit gained by selling on ith day. In order to sell shares on ith day, we need to purchase it on any one of [0, i – 1] days. If we buy shares on jth day and sell it on ith day, max profit will be price[i] – price[j] + profit[t-1][j] where j varies from 0 to i-1. Here profit[t-1][j] is best we could have done with one less transaction till jth day. Below is Dynamic Programming based implementation. C++ Java Python3 C# PHP Javascript // C++ program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days#include <climits>#include <iostream>using namespace std; // Function to find out maximum profit by buying// & selling a share atmost k times given stock// price of n daysint maxProfit(int price[], int n, int k){ // table to store results of subproblems // profit[t][i] stores maximum profit using // atmost t transactions up to day i (including // day i) int profit[k + 1][n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { for (int j = 1; j < n; j++) { int max_so_far = INT_MIN; for (int m = 0; m < j; m++) max_so_far = max(max_so_far, price[j] - price[m] + profit[i - 1][m]); profit[i][j] = max(profit[i][j - 1], max_so_far); } } return profit[k][n - 1];} // Driver codeint main(){ int k = 2; int price[] = { 10, 22, 5, 75, 65, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << "Maximum profit is: " << maxProfit(price, n, k); return 0;} // Java program to find out maximum// profit by buying and selling a// share atmost k times given// stock price of n days class GFG { // Function to find out // maximum profit by // buying & selling a // share atmost k times // given stock price of n days static int maxProfit(int[] price, int n, int k) { // table to store results // of subproblems // profit[t][i] stores // maximum profit using // atmost t transactions up // to day i (including day i) int[][] profit = new int[k + 1][n + 1]; // For day 0, you can't // earn money irrespective // of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in // bottom-up fashion for (int i = 1; i <= k; i++) { for (int j = 1; j < n; j++) { int max_so_far = 0; for (int m = 0; m < j; m++) max_so_far = Math.max(max_so_far, price[j] - price[m] + profit[i - 1][m]); profit[i][j] = Math.max(profit[i] [j - 1], max_so_far); } } return profit[k][n - 1]; } // Driver code public static void main(String []args) { int k = 2; int[] price = { 10, 22, 5, 75, 65, 80 }; int n = price.length; System.out.println("Maximum profit is: " + maxProfit(price, n, k)); }} // This code is contributed by Anshul Aggarwal. # Python program to maximize the profit# by doing at most k transactions# given stock prices for n days # Function to find out maximum profit by# buying & selling a share atmost k times# given stock price of n daysdef maxProfit(prices, n, k): # Bottom-up DP approach profit = [[0 for i in range(k + 1)] for j in range(n)] # Profit is zero for the first # day and for zero transactions for i in range(1, n): for j in range(1, k + 1): max_so_far = 0 for l in range(i): max_so_far = max(max_so_far, prices[i] - prices[l] + profit[l][j - 1]) profit[i][j] = max(profit[i - 1][j], max_so_far) return profit[n - 1][k] # Driver codek = 2prices = [10, 22, 5, 75, 65, 80]n = len(prices) print("Maximum profit is:", maxProfit(prices, n, k)) # This code is contributed by vaibhav29498 // C# program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n daysusing System; class GFG { // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n days static int maxProfit(int[] price, int n, int k) { // table to store results of subproblems // profit[t][i] stores maximum profit using atmost // t transactions up to day i (including day i) int[, ] profit = new int[k + 1, n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i, 0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0, j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { for (int j = 1; j < n; j++) { int max_so_far = 0; for (int m = 0; m < j; m++) max_so_far = Math.Max(max_so_far, price[j] - price[m] + profit[i - 1, m]); profit[i, j] = Math.Max(profit[i, j - 1], max_so_far); } } return profit[k, n - 1]; } // Driver code to test above public static void Main() { int k = 2; int[] price = { 10, 22, 5, 75, 65, 80 }; int n = price.Length; Console.Write("Maximum profit is: " + maxProfit(price, n, k)); }} // This code is contributed by Sam007 <?php// PHP program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days // Function to find out maximum profit by buying// & selling a share atmost k times given stock// price of n daysfunction maxProfit($price, $n, $k){ // table to store results of subproblems // profit[t][i] stores maximum profit using // atmost t transactions up to day i (including // day i) $profit[$k + 1][$n + 1] = 0; // For day 0, you can't earn money // irrespective of how many times you trade for ($i = 0; $i <= $k; $i++) $profit[$i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for ($j = 0; $j <= $n; $j++) $profit[0][$j] = 0; // fill the table in // bottom-up fashion for ($i = 1; $i <= $k; $i++) { for ($j = 1; $j < $n; $j++) { $max_so_far = PHP_INT_MIN; for ($m = 0; $m < $j; $m++) $max_so_far = max($max_so_far, $price[$j] - $price[$m] + $profit[$i - 1][$m]); $profit[$i][$j] = max($profit[$i][$j - 1], $max_so_far); } } return $profit[$k][$n - 1];} // Driver code $k = 2; $price = array (10, 22, 5, 75, 65, 80 ); $n = sizeof($price); echo "Maximum profit is: ". maxProfit($price, $n, $k); // This is contributed by mits?> <script> // javascript program to find out maximum// profit by buying and selling a// share atmost k times given// stock price of n days // Function to find out// maximum profit by// buying & selling a// share atmost k times// given stock price of n daysfunction maxProfit(price,n, k){ // table to store results // of subproblems // profit[t][i] stores // maximum profit using // atmost t transactions up // to day i (including day i) var profit = Array(k+1).fill(0).map (x => Array(n+1).fill(0)); // For day 0, you can't // earn money irrespective // of how many times you trade for (i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for (j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in // bottom-up fashion for (i = 1; i <= k; i++) { for (j = 1; j < n; j++) { var max_so_far = 0; for (m = 0; m < j; m++) max_so_far = Math.max(max_so_far, price[j] - price[m] + profit[i - 1][m]); profit[i][j] = Math.max(profit[i] [j - 1], max_so_far); } } return profit[k][n - 1];} // Driver codevar k = 2;var price = [ 10, 22, 5, 75, 65, 80 ];var n = price.length;document.write("Maximum profit is: " + maxProfit(price, n, k)); // This code contributed by shikhasingrajput </script> Output : Maximum profit is: 87 The above solution has time complexity of O(k.n2). It can be reduced if we are able to calculate the maximum profit gained by selling shares on the ith day in constant time.profit[t][i] = max(profit [t][i-1], max(price[i] – price[j] + profit[t-1][j])) for all j in range [0, i-1]If we carefully notice, max(price[i] – price[j] + profit[t-1][j]) for all j in range [0, i-1]can be rewritten as, = price[i] + max(profit[t-1][j] – price[j]) for all j in range [0, i-1] = price[i] + max(prevDiff, profit[t-1][i-1] – price[i-1]) where prevDiff is max(profit[t-1][j] – price[j]) for all j in range [0, i-2]So, if we have already calculated max(profit[t-1][j] – price[j]) for all j in range [0, i-2], we can calculate it for j = i – 1 in constant time. In other words, we don’t have to look back in the range [0, i-1] anymore to find out best day to buy. We can determine that in constant time using below revised relation.profit[t][i] = max(profit[t][i-1], price[i] + max(prevDiff, profit [t-1][i-1] – price[i-1]) where prevDiff is max(profit[t-1][j] – price[j]) for all j in range [0, i-2]Below is its optimized implementation – C++ Java Python3 C# PHP Javascript // C++ program to find out maximum profit by buying// and/ selling a share atmost k times given stock// price of n days#include <climits>#include <iostream>using namespace std; // Function to find out maximum profit by buying &// selling/ a share atmost k times given stock price// of n daysint maxProfit(int price[], int n, int k){ // table to store results of subproblems // profit[t][i] stores maximum profit using atmost // t transactions up to day i (including day i) int profit[k + 1][n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { int prevDiff = INT_MIN; for (int j = 1; j < n; j++) { prevDiff = max(prevDiff, profit[i - 1][j - 1] - price[j - 1]); profit[i][j] = max(profit[i][j - 1], price[j] + prevDiff); } } return profit[k][n - 1];} // Driver Codeint main(){ int k = 3; int price[] = { 12, 14, 17, 10, 14, 13, 12, 15 }; int n = sizeof(price) / sizeof(price[0]); cout << "Maximum profit is: " << maxProfit(price, n, k); return 0;} // Java program to find out maximum// profit by buying and selling a// share atmost k times given stock// price of n daysimport java.io.*; class GFG { // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n days static int maxProfit(int price[], int n, int k) { // table to store results of subproblems // profit[t][i] stores maximum profit // using atmost t transactions up to day // i (including day i) int profit[][] = new int[k + 1][ n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any // transaction (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { int prevDiff = Integer.MIN_VALUE; for (int j = 1; j < n; j++) { prevDiff = Math.max(prevDiff, profit[i - 1][j - 1] - price[j - 1]); profit[i][j] = Math.max(profit[i][j - 1], price[j] + prevDiff); } } return profit[k][n - 1]; } // Driver codepublic static void main (String[] args) { int k = 3; int price[] = {12, 14, 17, 10, 14, 13, 12, 15}; int n = price.length; System.out.println("Maximum profit is: " + maxProfit(price, n, k)); }} // This code is contributed by Sam007 # Python3 program to find out maximum# profit by buying and/ selling a share# at most k times given the stock price# of n days # Function to find out maximum profit# by buying & selling/ a share atmost# k times given stock price of n daysdef maxProfit(price, n, k): # Table to store results of subproblems # profit[t][i] stores maximum profit # using atmost t transactions up to # day i (including day i) profit = [[0 for i in range(n + 1)] for j in range(k + 1)] # Fill the table in bottom-up fashion for i in range(1, k + 1): prevDiff = float('-inf') for j in range(1, n): prevDiff = max(prevDiff, profit[i - 1][j - 1] - price[j - 1]) profit[i][j] = max(profit[i][j - 1], price[j] + prevDiff) return profit[k][n - 1] # Driver Codeif __name__ == "__main__": k = 3 price = [12, 14, 17, 10, 14, 13, 12, 15] n = len(price) print("Maximum profit is:", maxProfit(price, n, k)) # This code is contributed# by Rituraj Jain // C# program to find out maximum profit by buying// and selling a share atmost k times given stock// price of n daysusing System; class GFG { // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n days static int maxProfit(int[] price, int n, int k) { // table to store results of subproblems // profit[t][i] stores maximum profit using atmost // t transactions up to day i (including day i) int[, ] profit = new int[k + 1, n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i, 0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0, j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { int prevDiff = int.MinValue; for (int j = 1; j < n; j++) { prevDiff = Math.Max(prevDiff, profit[i - 1, j - 1] - price[j - 1]); profit[i, j] = Math.Max(profit[i, j - 1], price[j] + prevDiff); } } return profit[k, n - 1]; } // Driver code to test above public static void Main() { int k = 3; int[] price = {12, 14, 17, 10, 14, 13, 12, 15}; int n = price.Length; Console.Write("Maximum profit is: " + maxProfit(price, n, k)); }} // This code is contributed by Sam007 <?php// PHP program to find out maximum// profit by buying and selling a// share atmost k times given stock// price of n days // Function to find out maximum// profit by buying & selling a// share atmost k times given// stock price of n daysfunction maxProfit($price, $n, $k){ // table to store results // of subproblems profit[t][i] // stores maximum profit using // atmost t transactions up to // day i (including day i) $profit[$k + 1][$n + 1]=0; // For day 0, you can't // earn money irrespective // of how many times you trade for ($i = 0; $i <= $k; $i++) $profit[$i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for ($j = 0; $j <= $n; $j++) $profit[0][$j] = 0; // fill the table in // bottom-up fashion $prevDiff = NULL; for ($i = 1; $i <= $k; $i++) { for ($j = 1; $j < $n; $j++) { $prevDiff = max($prevDiff, $profit[$i - 1][$j - 1] - $price[$j - 1]); $profit[$i][$j] = max($profit[$i][$j - 1], $price[$j] + $prevDiff); } } return $profit[$k][$n - 1];} // Driver Code $k = 3; $price = array(12, 14, 17, 10, 14, 13, 12, 15); $n = sizeof($price); echo "Maximum profit is: " , maxProfit($price, $n, $k); // This code is contributed by nitin mittal?> <script> // javascript program to find out maximum// profit by buying and selling a// share atmost k times given stock// price of n days // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n daysfunction maxProfit(price, n , k){ // table to store results of subproblems // profit[t][i] stores maximum profit // using atmost t transactions up to day // i (including day i) var profit = Array(k+1).fill(0).map(x => Array(n+1).fill(0)); // For day 0, you can't earn money // irrespective of how many times you trade for (var i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any // transaction (i.e. k =0) for (j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (var i = 1; i <= k; i++) { var prevDiff = -Number.MAX_VALUE; for (var j = 1; j < n; j++) { prevDiff = Math.max(prevDiff, profit[i - 1][j - 1] - price[j - 1]); profit[i][j] = Math.max(profit[i][j - 1], price[j] + prevDiff); } } return profit[k][n - 1];} // Driver codevar k = 3;var price = [12, 14, 17, 10, 14, 13, 12, 15]; var n = price.length; document.write("Maximum profit is: " + maxProfit(price, n, k));// This code contributed by shikhasingrajput</script> Output : Maximum profit is: 12 The time complexity of the above solution is O(kn) and space complexity is O(nk). Space complexity can further be reduced to O(n) as we use the result from the last transaction. But to make the article easily readable, we have used O(kn) space.This article is contributed by Aditya Goel. Method-2 Memoization(dynamic Programming) One more way we can approach this problem is by considering buying and selling as two different states of the dp. So we will consider the dp as follows: let i be the index of the stock we are at, j be the total transaction reamaining, b represent if we have to sell or buy this stock(1 for buying and 0 for selling) and A represent the array containing stock prices then state transitions will be as follows: dp[i][j][1]=max(-A[i]+dp[j][i+1][0],dp[j][i+1][1]) dp[i][j][0]=max(A[i]+dp[j-1][i+1][1],dp[j][i+1][0]) implementation is as follows: C++ Javascript // C++ program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days#include <bits/stdc++.h>using namespace std; int B;vector<int> A;int dp[501][201][2];int solve(int j, int i, int b){ // if the result has already been calculated return that result if (dp[i][j][b] != -1) return dp[i][j][b]; // if i has reached the end of the array return 0 if (i == B) return 0; // if we have exhausted the number of transaction return 0 if (j == 0) return 0; int res; // if we are to buy stocks if (b == 1) res = max(-A[i] + solve(j, i + 1, 0), solve(j, i + 1, 1)); // if we are to sell stock and complete onr transaction else res = max(A[i] + solve(j - 1, i + 1, 1), solve(j, i + 1, 0)); // return the result return dp[i][j][b] = res;}int maxProfit(int K, int N, int C[]){ A = vector<int>(N, 0); // Copying C to global A for (int i = 0; i < N; i++) A[i] = C[i]; // Initializing DP with -1 for (int i = 0; i <= N; i++) for (int j = 0; j <= K; j++) { dp[i][j][1] = -1; dp[i][j][0] = -1; } // Copying n to global B B = N; return solve(K, 0, 1);} // driver codeint main(){ // TEST 1 int k1 = 3; int price1[] = {12, 14, 17, 10, 14, 13, 12, 15}; int n1 = sizeof(price1) / sizeof(price1[0]); cout << "Maximum profit is: " << maxProfit(k1, n1, price1) << endl; // TEST 2 int k2 = 2; int price2[] = {10, 22, 5, 75, 65, 80}; int n2 = sizeof(price2) / sizeof(price2[0]); cout << "Maximum profit is: " << maxProfit(k2, n2, price2); return 0;}//This code is contributed by Anirudh Singh // JavaScript program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days let B;let A = [];let dp = new Array(501);for (let i = 0; i < 501; i++){ dp[i] = new Array(201); for (let j = 0; j < 201; j++) dp[i][j] = new Array(2);} function solve(j, i, b){ // if the result has already been calculated return that result if (dp[i][j][b] != -1) return dp[i][j][b]; // if i has reached the end of the array return 0 if (i == B) return 0; // if we have exhausted the number of transaction return 0 if (j == 0) return 0; let res; // if we are to buy stocks if (b == 1) res = Math.max(-A[i] + solve(j, i + 1, 0), solve(j, i + 1, 1)); // if we are to sell stock and complete onr transaction else res = Math.max(A[i] + solve(j - 1, i + 1, 1), solve(j, i + 1, 0)); // return the result return dp[i][j][b] = res;} function maxProfit(K, N, C){ A = new Array(N).fill(0); // Copying C to global A for (i = 0; i < N; i++) A[i] = C[i]; // Initializing DP with -1 for (i = 0; i <= N; i++) for (j = 0; j <= K; j++) { dp[i][j][1] = -1; dp[i][j][0] = -1; } // Copying n to global B B = N; return solve(K, 0, 1);} // driver code // TEST 1let k1 = 3;let price1 = [12, 14, 17, 10, 14, 13, 12, 15];let n1 = price1.length;console.log("Maximum profit is: " + maxProfit(k1, n1, price1)); // TEST 2let k2 = 2;let price2 = [10, 22, 5, 75, 65, 80];let n2 = price2.length; console.log("Maximum profit is: " + maxProfit(k2, n2, price2)); //This code is contributed by phasing17 Maximum profit is: 12 Maximum profit is: 87 Time Complexity: O(n*k) Auxiliary Space: O(n*k) This approach and implementaion is contributed by Anirudh Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 Anshul_Aggarwal nitin mittal Mithun Kumar vaibhav29498 rituraj_jain eigenharsha shikhasingrajput surindertarika1234 anirudhsingh11 Accolite Amazon Dynamic Programming Mathematical Accolite Amazon Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Program for Fibonacci numbers Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3 Find if there is a path between two vertices in an undirected graph 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": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 365, "s": 52, "text": "In share trading, a buyer buys shares and sells on a future date. Given the stock price of n days, the trader is allowed to make at most k transactions, where a new transaction can only start after the previous transaction is complete, find out the maximum profit that a share trader could have made. Examples: " }, { "code": null, "e": 923, "s": 365, "text": "Input: \nPrice = [10, 22, 5, 75, 65, 80]\n K = 2\nOutput: 87\nTrader earns 87 as sum of 12 and 75\nBuy at price 10, sell at 22, buy at \n5 and sell at 80\n\nInput: \nPrice = [12, 14, 17, 10, 14, 13, 12, 15]\n K = 3\nOutput: 12\nTrader earns 12 as the sum of 5, 4 and 3\nBuy at price 12, sell at 17, buy at 10 \nand sell at 14 and buy at 12 and sell\nat 15\n \nInput: \nPrice = [100, 30, 15, 10, 8, 25, 80]\n K = 3\nOutput: 72\nOnly one transaction. Buy at price 8 \nand sell at 80.\n\nInput: \nPrice = [90, 80, 70, 60, 50]\n K = 1\nOutput: 0\nNot possible to earn. " }, { "code": null, "e": 1270, "s": 923, "text": "There are various versions of the problem. If we are allowed to buy and sell only once, then we can use the Maximum difference between the two elements algorithm. If we are allowed to make at most 2 transactions, we can follow approach discussed here. If we are allowed to buy and sell any number of times, we can follow approach discussed here. " }, { "code": null, "e": 1299, "s": 1270, "text": "Method 1 Dynamic Programming" }, { "code": null, "e": 1421, "s": 1299, "text": "In this post, we are only allowed to make at max k transactions. The problem can be solved by using dynamic programming. " }, { "code": null, "e": 1695, "s": 1421, "text": "Let profit[t][i] represent maximum profit using at most t transactions up to day i (including day i). Then the relation is:profit[t][i] = max(profit[t][i-1], max(price[i] – price[j] + profit[t-1][j])) for all j in range [0, i-1] profit[t][i] will be maximum of – " }, { "code": null, "e": 2128, "s": 1695, "text": "profit[t][i-1] which represents not doing any transaction on the ith day.Maximum profit gained by selling on ith day. In order to sell shares on ith day, we need to purchase it on any one of [0, i – 1] days. If we buy shares on jth day and sell it on ith day, max profit will be price[i] – price[j] + profit[t-1][j] where j varies from 0 to i-1. Here profit[t-1][j] is best we could have done with one less transaction till jth day." }, { "code": null, "e": 2202, "s": 2128, "text": "profit[t][i-1] which represents not doing any transaction on the ith day." }, { "code": null, "e": 2562, "s": 2202, "text": "Maximum profit gained by selling on ith day. In order to sell shares on ith day, we need to purchase it on any one of [0, i – 1] days. If we buy shares on jth day and sell it on ith day, max profit will be price[i] – price[j] + profit[t-1][j] where j varies from 0 to i-1. Here profit[t-1][j] is best we could have done with one less transaction till jth day." }, { "code": null, "e": 2615, "s": 2562, "text": "Below is Dynamic Programming based implementation. " }, { "code": null, "e": 2619, "s": 2615, "text": "C++" }, { "code": null, "e": 2624, "s": 2619, "text": "Java" }, { "code": null, "e": 2632, "s": 2624, "text": "Python3" }, { "code": null, "e": 2635, "s": 2632, "text": "C#" }, { "code": null, "e": 2639, "s": 2635, "text": "PHP" }, { "code": null, "e": 2650, "s": 2639, "text": "Javascript" }, { "code": "// C++ program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days#include <climits>#include <iostream>using namespace std; // Function to find out maximum profit by buying// & selling a share atmost k times given stock// price of n daysint maxProfit(int price[], int n, int k){ // table to store results of subproblems // profit[t][i] stores maximum profit using // atmost t transactions up to day i (including // day i) int profit[k + 1][n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { for (int j = 1; j < n; j++) { int max_so_far = INT_MIN; for (int m = 0; m < j; m++) max_so_far = max(max_so_far, price[j] - price[m] + profit[i - 1][m]); profit[i][j] = max(profit[i][j - 1], max_so_far); } } return profit[k][n - 1];} // Driver codeint main(){ int k = 2; int price[] = { 10, 22, 5, 75, 65, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << \"Maximum profit is: \" << maxProfit(price, n, k); return 0;}", "e": 4060, "s": 2650, "text": null }, { "code": "// Java program to find out maximum// profit by buying and selling a// share atmost k times given// stock price of n days class GFG { // Function to find out // maximum profit by // buying & selling a // share atmost k times // given stock price of n days static int maxProfit(int[] price, int n, int k) { // table to store results // of subproblems // profit[t][i] stores // maximum profit using // atmost t transactions up // to day i (including day i) int[][] profit = new int[k + 1][n + 1]; // For day 0, you can't // earn money irrespective // of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in // bottom-up fashion for (int i = 1; i <= k; i++) { for (int j = 1; j < n; j++) { int max_so_far = 0; for (int m = 0; m < j; m++) max_so_far = Math.max(max_so_far, price[j] - price[m] + profit[i - 1][m]); profit[i][j] = Math.max(profit[i] [j - 1], max_so_far); } } return profit[k][n - 1]; } // Driver code public static void main(String []args) { int k = 2; int[] price = { 10, 22, 5, 75, 65, 80 }; int n = price.length; System.out.println(\"Maximum profit is: \" + maxProfit(price, n, k)); }} // This code is contributed by Anshul Aggarwal.", "e": 5852, "s": 4060, "text": null }, { "code": "# Python program to maximize the profit# by doing at most k transactions# given stock prices for n days # Function to find out maximum profit by# buying & selling a share atmost k times# given stock price of n daysdef maxProfit(prices, n, k): # Bottom-up DP approach profit = [[0 for i in range(k + 1)] for j in range(n)] # Profit is zero for the first # day and for zero transactions for i in range(1, n): for j in range(1, k + 1): max_so_far = 0 for l in range(i): max_so_far = max(max_so_far, prices[i] - prices[l] + profit[l][j - 1]) profit[i][j] = max(profit[i - 1][j], max_so_far) return profit[n - 1][k] # Driver codek = 2prices = [10, 22, 5, 75, 65, 80]n = len(prices) print(\"Maximum profit is:\", maxProfit(prices, n, k)) # This code is contributed by vaibhav29498", "e": 6813, "s": 5852, "text": null }, { "code": "// C# program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n daysusing System; class GFG { // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n days static int maxProfit(int[] price, int n, int k) { // table to store results of subproblems // profit[t][i] stores maximum profit using atmost // t transactions up to day i (including day i) int[, ] profit = new int[k + 1, n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i, 0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0, j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { for (int j = 1; j < n; j++) { int max_so_far = 0; for (int m = 0; m < j; m++) max_so_far = Math.Max(max_so_far, price[j] - price[m] + profit[i - 1, m]); profit[i, j] = Math.Max(profit[i, j - 1], max_so_far); } } return profit[k, n - 1]; } // Driver code to test above public static void Main() { int k = 2; int[] price = { 10, 22, 5, 75, 65, 80 }; int n = price.Length; Console.Write(\"Maximum profit is: \" + maxProfit(price, n, k)); }} // This code is contributed by Sam007", "e": 8405, "s": 6813, "text": null }, { "code": "<?php// PHP program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days // Function to find out maximum profit by buying// & selling a share atmost k times given stock// price of n daysfunction maxProfit($price, $n, $k){ // table to store results of subproblems // profit[t][i] stores maximum profit using // atmost t transactions up to day i (including // day i) $profit[$k + 1][$n + 1] = 0; // For day 0, you can't earn money // irrespective of how many times you trade for ($i = 0; $i <= $k; $i++) $profit[$i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for ($j = 0; $j <= $n; $j++) $profit[0][$j] = 0; // fill the table in // bottom-up fashion for ($i = 1; $i <= $k; $i++) { for ($j = 1; $j < $n; $j++) { $max_so_far = PHP_INT_MIN; for ($m = 0; $m < $j; $m++) $max_so_far = max($max_so_far, $price[$j] - $price[$m] + $profit[$i - 1][$m]); $profit[$i][$j] = max($profit[$i][$j - 1], $max_so_far); } } return $profit[$k][$n - 1];} // Driver code $k = 2; $price = array (10, 22, 5, 75, 65, 80 ); $n = sizeof($price); echo \"Maximum profit is: \". maxProfit($price, $n, $k); // This is contributed by mits?>", "e": 9847, "s": 8405, "text": null }, { "code": "<script> // javascript program to find out maximum// profit by buying and selling a// share atmost k times given// stock price of n days // Function to find out// maximum profit by// buying & selling a// share atmost k times// given stock price of n daysfunction maxProfit(price,n, k){ // table to store results // of subproblems // profit[t][i] stores // maximum profit using // atmost t transactions up // to day i (including day i) var profit = Array(k+1).fill(0).map (x => Array(n+1).fill(0)); // For day 0, you can't // earn money irrespective // of how many times you trade for (i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for (j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in // bottom-up fashion for (i = 1; i <= k; i++) { for (j = 1; j < n; j++) { var max_so_far = 0; for (m = 0; m < j; m++) max_so_far = Math.max(max_so_far, price[j] - price[m] + profit[i - 1][m]); profit[i][j] = Math.max(profit[i] [j - 1], max_so_far); } } return profit[k][n - 1];} // Driver codevar k = 2;var price = [ 10, 22, 5, 75, 65, 80 ];var n = price.length;document.write(\"Maximum profit is: \" + maxProfit(price, n, k)); // This code contributed by shikhasingrajput </script>", "e": 11321, "s": 9847, "text": null }, { "code": null, "e": 11331, "s": 11321, "text": "Output : " }, { "code": null, "e": 11353, "s": 11331, "text": "Maximum profit is: 87" }, { "code": null, "e": 12506, "s": 11353, "text": "The above solution has time complexity of O(k.n2). It can be reduced if we are able to calculate the maximum profit gained by selling shares on the ith day in constant time.profit[t][i] = max(profit [t][i-1], max(price[i] – price[j] + profit[t-1][j])) for all j in range [0, i-1]If we carefully notice, max(price[i] – price[j] + profit[t-1][j]) for all j in range [0, i-1]can be rewritten as, = price[i] + max(profit[t-1][j] – price[j]) for all j in range [0, i-1] = price[i] + max(prevDiff, profit[t-1][i-1] – price[i-1]) where prevDiff is max(profit[t-1][j] – price[j]) for all j in range [0, i-2]So, if we have already calculated max(profit[t-1][j] – price[j]) for all j in range [0, i-2], we can calculate it for j = i – 1 in constant time. In other words, we don’t have to look back in the range [0, i-1] anymore to find out best day to buy. We can determine that in constant time using below revised relation.profit[t][i] = max(profit[t][i-1], price[i] + max(prevDiff, profit [t-1][i-1] – price[i-1]) where prevDiff is max(profit[t-1][j] – price[j]) for all j in range [0, i-2]Below is its optimized implementation – " }, { "code": null, "e": 12510, "s": 12506, "text": "C++" }, { "code": null, "e": 12515, "s": 12510, "text": "Java" }, { "code": null, "e": 12523, "s": 12515, "text": "Python3" }, { "code": null, "e": 12526, "s": 12523, "text": "C#" }, { "code": null, "e": 12530, "s": 12526, "text": "PHP" }, { "code": null, "e": 12541, "s": 12530, "text": "Javascript" }, { "code": "// C++ program to find out maximum profit by buying// and/ selling a share atmost k times given stock// price of n days#include <climits>#include <iostream>using namespace std; // Function to find out maximum profit by buying &// selling/ a share atmost k times given stock price// of n daysint maxProfit(int price[], int n, int k){ // table to store results of subproblems // profit[t][i] stores maximum profit using atmost // t transactions up to day i (including day i) int profit[k + 1][n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { int prevDiff = INT_MIN; for (int j = 1; j < n; j++) { prevDiff = max(prevDiff, profit[i - 1][j - 1] - price[j - 1]); profit[i][j] = max(profit[i][j - 1], price[j] + prevDiff); } } return profit[k][n - 1];} // Driver Codeint main(){ int k = 3; int price[] = { 12, 14, 17, 10, 14, 13, 12, 15 }; int n = sizeof(price) / sizeof(price[0]); cout << \"Maximum profit is: \" << maxProfit(price, n, k); return 0;}", "e": 13932, "s": 12541, "text": null }, { "code": "// Java program to find out maximum// profit by buying and selling a// share atmost k times given stock// price of n daysimport java.io.*; class GFG { // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n days static int maxProfit(int price[], int n, int k) { // table to store results of subproblems // profit[t][i] stores maximum profit // using atmost t transactions up to day // i (including day i) int profit[][] = new int[k + 1][ n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any // transaction (i.e. k =0) for (int j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { int prevDiff = Integer.MIN_VALUE; for (int j = 1; j < n; j++) { prevDiff = Math.max(prevDiff, profit[i - 1][j - 1] - price[j - 1]); profit[i][j] = Math.max(profit[i][j - 1], price[j] + prevDiff); } } return profit[k][n - 1]; } // Driver codepublic static void main (String[] args) { int k = 3; int price[] = {12, 14, 17, 10, 14, 13, 12, 15}; int n = price.length; System.out.println(\"Maximum profit is: \" + maxProfit(price, n, k)); }} // This code is contributed by Sam007", "e": 15624, "s": 13932, "text": null }, { "code": "# Python3 program to find out maximum# profit by buying and/ selling a share# at most k times given the stock price# of n days # Function to find out maximum profit# by buying & selling/ a share atmost# k times given stock price of n daysdef maxProfit(price, n, k): # Table to store results of subproblems # profit[t][i] stores maximum profit # using atmost t transactions up to # day i (including day i) profit = [[0 for i in range(n + 1)] for j in range(k + 1)] # Fill the table in bottom-up fashion for i in range(1, k + 1): prevDiff = float('-inf') for j in range(1, n): prevDiff = max(prevDiff, profit[i - 1][j - 1] - price[j - 1]) profit[i][j] = max(profit[i][j - 1], price[j] + prevDiff) return profit[k][n - 1] # Driver Codeif __name__ == \"__main__\": k = 3 price = [12, 14, 17, 10, 14, 13, 12, 15] n = len(price) print(\"Maximum profit is:\", maxProfit(price, n, k)) # This code is contributed# by Rituraj Jain", "e": 16735, "s": 15624, "text": null }, { "code": "// C# program to find out maximum profit by buying// and selling a share atmost k times given stock// price of n daysusing System; class GFG { // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n days static int maxProfit(int[] price, int n, int k) { // table to store results of subproblems // profit[t][i] stores maximum profit using atmost // t transactions up to day i (including day i) int[, ] profit = new int[k + 1, n + 1]; // For day 0, you can't earn money // irrespective of how many times you trade for (int i = 0; i <= k; i++) profit[i, 0] = 0; // profit is 0 if we don't do any transaction // (i.e. k =0) for (int j = 0; j <= n; j++) profit[0, j] = 0; // fill the table in bottom-up fashion for (int i = 1; i <= k; i++) { int prevDiff = int.MinValue; for (int j = 1; j < n; j++) { prevDiff = Math.Max(prevDiff, profit[i - 1, j - 1] - price[j - 1]); profit[i, j] = Math.Max(profit[i, j - 1], price[j] + prevDiff); } } return profit[k, n - 1]; } // Driver code to test above public static void Main() { int k = 3; int[] price = {12, 14, 17, 10, 14, 13, 12, 15}; int n = price.Length; Console.Write(\"Maximum profit is: \" + maxProfit(price, n, k)); }} // This code is contributed by Sam007", "e": 18316, "s": 16735, "text": null }, { "code": "<?php// PHP program to find out maximum// profit by buying and selling a// share atmost k times given stock// price of n days // Function to find out maximum// profit by buying & selling a// share atmost k times given// stock price of n daysfunction maxProfit($price, $n, $k){ // table to store results // of subproblems profit[t][i] // stores maximum profit using // atmost t transactions up to // day i (including day i) $profit[$k + 1][$n + 1]=0; // For day 0, you can't // earn money irrespective // of how many times you trade for ($i = 0; $i <= $k; $i++) $profit[$i][0] = 0; // profit is 0 if we don't // do any transaction // (i.e. k =0) for ($j = 0; $j <= $n; $j++) $profit[0][$j] = 0; // fill the table in // bottom-up fashion $prevDiff = NULL; for ($i = 1; $i <= $k; $i++) { for ($j = 1; $j < $n; $j++) { $prevDiff = max($prevDiff, $profit[$i - 1][$j - 1] - $price[$j - 1]); $profit[$i][$j] = max($profit[$i][$j - 1], $price[$j] + $prevDiff); } } return $profit[$k][$n - 1];} // Driver Code $k = 3; $price = array(12, 14, 17, 10, 14, 13, 12, 15); $n = sizeof($price); echo \"Maximum profit is: \" , maxProfit($price, $n, $k); // This code is contributed by nitin mittal?>", "e": 19731, "s": 18316, "text": null }, { "code": "<script> // javascript program to find out maximum// profit by buying and selling a// share atmost k times given stock// price of n days // Function to find out maximum profit by // buying & selling/ a share atmost k times // given stock price of n daysfunction maxProfit(price, n , k){ // table to store results of subproblems // profit[t][i] stores maximum profit // using atmost t transactions up to day // i (including day i) var profit = Array(k+1).fill(0).map(x => Array(n+1).fill(0)); // For day 0, you can't earn money // irrespective of how many times you trade for (var i = 0; i <= k; i++) profit[i][0] = 0; // profit is 0 if we don't do any // transaction (i.e. k =0) for (j = 0; j <= n; j++) profit[0][j] = 0; // fill the table in bottom-up fashion for (var i = 1; i <= k; i++) { var prevDiff = -Number.MAX_VALUE; for (var j = 1; j < n; j++) { prevDiff = Math.max(prevDiff, profit[i - 1][j - 1] - price[j - 1]); profit[i][j] = Math.max(profit[i][j - 1], price[j] + prevDiff); } } return profit[k][n - 1];} // Driver codevar k = 3;var price = [12, 14, 17, 10, 14, 13, 12, 15]; var n = price.length; document.write(\"Maximum profit is: \" + maxProfit(price, n, k));// This code contributed by shikhasingrajput</script>", "e": 21181, "s": 19731, "text": null }, { "code": null, "e": 21191, "s": 21181, "text": "Output : " }, { "code": null, "e": 21213, "s": 21191, "text": "Maximum profit is: 12" }, { "code": null, "e": 21502, "s": 21213, "text": "The time complexity of the above solution is O(kn) and space complexity is O(nk). Space complexity can further be reduced to O(n) as we use the result from the last transaction. But to make the article easily readable, we have used O(kn) space.This article is contributed by Aditya Goel. " }, { "code": null, "e": 21544, "s": 21502, "text": "Method-2 Memoization(dynamic Programming)" }, { "code": null, "e": 21697, "s": 21544, "text": "One more way we can approach this problem is by considering buying and selling as two different states of the dp. So we will consider the dp as follows:" }, { "code": null, "e": 21953, "s": 21697, "text": "let i be the index of the stock we are at, j be the total transaction reamaining, b represent if we have to sell or buy this stock(1 for buying and 0 for selling) and A represent the array containing stock prices then state transitions will be as follows:" }, { "code": null, "e": 22004, "s": 21953, "text": "dp[i][j][1]=max(-A[i]+dp[j][i+1][0],dp[j][i+1][1])" }, { "code": null, "e": 22056, "s": 22004, "text": "dp[i][j][0]=max(A[i]+dp[j-1][i+1][1],dp[j][i+1][0])" }, { "code": null, "e": 22086, "s": 22056, "text": "implementation is as follows:" }, { "code": null, "e": 22090, "s": 22086, "text": "C++" }, { "code": null, "e": 22101, "s": 22090, "text": "Javascript" }, { "code": "// C++ program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days#include <bits/stdc++.h>using namespace std; int B;vector<int> A;int dp[501][201][2];int solve(int j, int i, int b){ // if the result has already been calculated return that result if (dp[i][j][b] != -1) return dp[i][j][b]; // if i has reached the end of the array return 0 if (i == B) return 0; // if we have exhausted the number of transaction return 0 if (j == 0) return 0; int res; // if we are to buy stocks if (b == 1) res = max(-A[i] + solve(j, i + 1, 0), solve(j, i + 1, 1)); // if we are to sell stock and complete onr transaction else res = max(A[i] + solve(j - 1, i + 1, 1), solve(j, i + 1, 0)); // return the result return dp[i][j][b] = res;}int maxProfit(int K, int N, int C[]){ A = vector<int>(N, 0); // Copying C to global A for (int i = 0; i < N; i++) A[i] = C[i]; // Initializing DP with -1 for (int i = 0; i <= N; i++) for (int j = 0; j <= K; j++) { dp[i][j][1] = -1; dp[i][j][0] = -1; } // Copying n to global B B = N; return solve(K, 0, 1);} // driver codeint main(){ // TEST 1 int k1 = 3; int price1[] = {12, 14, 17, 10, 14, 13, 12, 15}; int n1 = sizeof(price1) / sizeof(price1[0]); cout << \"Maximum profit is: \" << maxProfit(k1, n1, price1) << endl; // TEST 2 int k2 = 2; int price2[] = {10, 22, 5, 75, 65, 80}; int n2 = sizeof(price2) / sizeof(price2[0]); cout << \"Maximum profit is: \" << maxProfit(k2, n2, price2); return 0;}//This code is contributed by Anirudh Singh", "e": 23810, "s": 22101, "text": null }, { "code": "// JavaScript program to find out maximum profit by// buying and selling a share atmost k times// given stock price of n days let B;let A = [];let dp = new Array(501);for (let i = 0; i < 501; i++){ dp[i] = new Array(201); for (let j = 0; j < 201; j++) dp[i][j] = new Array(2);} function solve(j, i, b){ // if the result has already been calculated return that result if (dp[i][j][b] != -1) return dp[i][j][b]; // if i has reached the end of the array return 0 if (i == B) return 0; // if we have exhausted the number of transaction return 0 if (j == 0) return 0; let res; // if we are to buy stocks if (b == 1) res = Math.max(-A[i] + solve(j, i + 1, 0), solve(j, i + 1, 1)); // if we are to sell stock and complete onr transaction else res = Math.max(A[i] + solve(j - 1, i + 1, 1), solve(j, i + 1, 0)); // return the result return dp[i][j][b] = res;} function maxProfit(K, N, C){ A = new Array(N).fill(0); // Copying C to global A for (i = 0; i < N; i++) A[i] = C[i]; // Initializing DP with -1 for (i = 0; i <= N; i++) for (j = 0; j <= K; j++) { dp[i][j][1] = -1; dp[i][j][0] = -1; } // Copying n to global B B = N; return solve(K, 0, 1);} // driver code // TEST 1let k1 = 3;let price1 = [12, 14, 17, 10, 14, 13, 12, 15];let n1 = price1.length;console.log(\"Maximum profit is: \" + maxProfit(k1, n1, price1)); // TEST 2let k2 = 2;let price2 = [10, 22, 5, 75, 65, 80];let n2 = price2.length; console.log(\"Maximum profit is: \" + maxProfit(k2, n2, price2)); //This code is contributed by phasing17", "e": 25478, "s": 23810, "text": null }, { "code": null, "e": 25522, "s": 25478, "text": "Maximum profit is: 12\nMaximum profit is: 87" }, { "code": null, "e": 25546, "s": 25522, "text": "Time Complexity: O(n*k)" }, { "code": null, "e": 25570, "s": 25546, "text": "Auxiliary Space: O(n*k)" }, { "code": null, "e": 25636, "s": 25570, "text": " This approach and implementaion is contributed by Anirudh Singh." }, { "code": null, "e": 25760, "s": 25636, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 25767, "s": 25760, "text": "Sam007" }, { "code": null, "e": 25783, "s": 25767, "text": "Anshul_Aggarwal" }, { "code": null, "e": 25796, "s": 25783, "text": "nitin mittal" }, { "code": null, "e": 25809, "s": 25796, "text": "Mithun Kumar" }, { "code": null, "e": 25822, "s": 25809, "text": "vaibhav29498" }, { "code": null, "e": 25835, "s": 25822, "text": "rituraj_jain" }, { "code": null, "e": 25847, "s": 25835, "text": "eigenharsha" }, { "code": null, "e": 25864, "s": 25847, "text": "shikhasingrajput" }, { "code": null, "e": 25883, "s": 25864, "text": "surindertarika1234" }, { "code": null, "e": 25898, "s": 25883, "text": "anirudhsingh11" }, { "code": null, "e": 25907, "s": 25898, "text": "Accolite" }, { "code": null, "e": 25914, "s": 25907, "text": "Amazon" }, { "code": null, "e": 25934, "s": 25914, "text": "Dynamic Programming" }, { "code": null, "e": 25947, "s": 25934, "text": "Mathematical" }, { "code": null, "e": 25956, "s": 25947, "text": "Accolite" }, { "code": null, "e": 25963, "s": 25956, "text": "Amazon" }, { "code": null, "e": 25983, "s": 25963, "text": "Dynamic Programming" }, { "code": null, "e": 25996, "s": 25983, "text": "Mathematical" }, { "code": null, "e": 26094, "s": 25996, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26126, "s": 26094, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 26156, "s": 26126, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 26194, "s": 26156, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 26232, "s": 26194, "text": "Longest Increasing Subsequence | DP-3" }, { "code": null, "e": 26300, "s": 26232, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 26330, "s": 26300, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 26373, "s": 26330, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 26433, "s": 26373, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 26448, "s": 26433, "text": "C++ Data Types" } ]
SQL | Alternative Quote Operator
21 Mar, 2018 This post is a continuation of the SQL Concatenation Operator. Now, suppose we want to use apostrophe in our literal value but we can’t use it directly. See Incorrect code:SELECT id, first_name, last_name, salary,first_name||’ has salary’s ‘||salaryAS “new” FROM one So above we are getting error, because Oracle server thinking that the first apostrophe is for the starting literal and the second apostrophe is for the ending literal, so what about the third apostrophe???. That’s why we get error. Alternative Quote Operator(q) :To overcome the above problem Oracle introduce an operator known as Alternative Quote Operator(q). Let’s see through an example: Query that uses Alternative Quote Operator(q) SELECT id, first_name, last_name, salary, first_name||q'{ has salary's }'||salary AS "new" FROM myTable Output: See, we are able to use apostrophe in the new column as a literal value of myTable ID FIRST_NAME LAST_NAME SALARY new 3 Shane Watson 50000 Shane has salary's 50000 1 Rajat Rawat 10000 Rajat has salary's 10000 2 Geeks ForGeeks 20000 Geeks has salary's 20000 3 MS Dhoni 90000 MS has salary's 90000 Here above see, q'{ indicates starting of our literal value and then we use }’ which indicates end of our literal value. So see here we have used apostrophe in our literal value easily(means we easily use ‘s in salary) without any error that’s why we get output as Rajat has salary‘s 50000. So to use apostrophe in literal we first need to use q which is known as alternative quote operator after that we need to use an apostrophe ‘ and after that we need to use a delimiter and after delimiter we write our literal value, when we finished writing our literal value then again we need to close the delimiter which we have opened before and after that we need to put an apostrophe again and hence in this way we can use apostrophe in our literal value. This concept is known as Alternative Quote Operator(q). We can use any character such as {, <, (, [, ! or any character as delimiter. These characters are known as delimiters. 1 another example : Without using Quote Operator: Here we get Error since we are using apostrophe in our literal value directly. Error code below: SELECT id, name, dept, name||' work's in '||dept||' department' AS "work" FROM myTable2 Using Quote Operator:SELECT id, name, dept, name||q'[ work’s in ‘]’||dept||’department’ AS “work” FROM myTable2 Output: See, we are able to use apostrophe in the work column as a literal value of myTable2 ID NAME DEPT work 1 RR Executive RR work's in 'Executive department 2 GFG HR GFG work's in 'HR department 3 Steve Sales Steve work's in 'Sales department 4 Bhuvi CSE Bhuvi work's in 'CSE department Here above see, q'[ indicates starting of our literal value and the we use ]’ which indicate end of our literal value. So see here we have used apostrophe in our literal value easily(means we easily use ‘s in work) without any error that’s why we get output as RR work’s in Executive Department.] Here above we use [ as delimiter so it is not a limitation in using delimiter means we can use any character as delimiter. References:About Alternative Quote Operator,Performing SQL Queries Online SQL-Clauses-Operators SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL What is Temporary Table in SQL? SQL | Sub queries in From Clause SQL using Python RANK() Function in SQL Server SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates How to Write a SQL Query For a Specific Date Range and Date Time?
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Mar, 2018" }, { "code": null, "e": 117, "s": 54, "text": "This post is a continuation of the SQL Concatenation Operator." }, { "code": null, "e": 207, "s": 117, "text": "Now, suppose we want to use apostrophe in our literal value but we can’t use it directly." }, { "code": null, "e": 321, "s": 207, "text": "See Incorrect code:SELECT id, first_name, last_name, salary,first_name||’ has salary’s ‘||salaryAS “new” FROM one" }, { "code": null, "e": 554, "s": 321, "text": "So above we are getting error, because Oracle server thinking that the first apostrophe is for the starting literal and the second apostrophe is for the ending literal, so what about the third apostrophe???. That’s why we get error." }, { "code": null, "e": 584, "s": 554, "text": "Alternative Quote Operator(q)" }, { "code": null, "e": 684, "s": 584, "text": ":To overcome the above problem Oracle introduce an operator known as Alternative Quote Operator(q)." }, { "code": null, "e": 714, "s": 684, "text": "Let’s see through an example:" }, { "code": null, "e": 866, "s": 714, "text": "Query that uses Alternative Quote Operator(q)\nSELECT id, first_name, last_name, salary,\nfirst_name||q'{ has salary's }'||salary \nAS \"new\" FROM myTable\n" }, { "code": null, "e": 1249, "s": 866, "text": "\nOutput:\nSee, we are able to use apostrophe in the\nnew column as a literal value of myTable \n\nID FIRST_NAME LAST_NAME SALARY new\n3 Shane Watson 50000 Shane has salary's 50000\n1 Rajat Rawat 10000 Rajat has salary's 10000\n2 Geeks ForGeeks 20000 Geeks has salary's 20000\n3 MS Dhoni 90000 MS has salary's 90000\n" }, { "code": null, "e": 1540, "s": 1249, "text": "Here above see, q'{ indicates starting of our literal value and then we use }’ which indicates end of our literal value. So see here we have used apostrophe in our literal value easily(means we easily use ‘s in salary) without any error that’s why we get output as Rajat has salary‘s 50000." }, { "code": null, "e": 2057, "s": 1540, "text": "So to use apostrophe in literal we first need to use q which is known as alternative quote operator after that we need to use an apostrophe ‘ and after that we need to use a delimiter and after delimiter we write our literal value, when we finished writing our literal value then again we need to close the delimiter which we have opened before and after that we need to put an apostrophe again and hence in this way we can use apostrophe in our literal value. This concept is known as Alternative Quote Operator(q)." }, { "code": null, "e": 2177, "s": 2057, "text": "We can use any character such as {, <, (, [, ! or any character as delimiter. These characters are known as delimiters." }, { "code": null, "e": 2195, "s": 2177, "text": "1 another example" }, { "code": null, "e": 2197, "s": 2195, "text": ":" }, { "code": null, "e": 2227, "s": 2197, "text": "Without using Quote Operator:" }, { "code": null, "e": 2415, "s": 2227, "text": "Here we get Error since we are using apostrophe in our literal value directly.\n\nError code below:\nSELECT id, name, dept, name||' work's in '||dept||'\n department' AS \"work\" FROM myTable2\n" }, { "code": null, "e": 2527, "s": 2415, "text": "Using Quote Operator:SELECT id, name, dept, name||q'[ work’s in ‘]’||dept||’department’ AS “work” FROM myTable2" }, { "code": null, "e": 2879, "s": 2527, "text": "Output:\nSee, we are able to use apostrophe in the \nwork column as a literal value of myTable2 \n\nID NAME DEPT work\n1 RR Executive RR work's in 'Executive department\n2 GFG HR GFG work's in 'HR department\n3 Steve Sales Steve work's in 'Sales department\n4 Bhuvi CSE Bhuvi work's in 'CSE department\n" }, { "code": null, "e": 3176, "s": 2879, "text": "Here above see, q'[ indicates starting of our literal value and the we use ]’ which indicate end of our literal value. So see here we have used apostrophe in our literal value easily(means we easily use ‘s in work) without any error that’s why we get output as RR work’s in Executive Department.]" }, { "code": null, "e": 3299, "s": 3176, "text": "Here above we use [ as delimiter so it is not a limitation in using delimiter means we can use any character as delimiter." }, { "code": null, "e": 3373, "s": 3299, "text": "References:About Alternative Quote Operator,Performing SQL Queries Online" }, { "code": null, "e": 3395, "s": 3373, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 3399, "s": 3395, "text": "SQL" }, { "code": null, "e": 3403, "s": 3399, "text": "SQL" }, { "code": null, "e": 3501, "s": 3403, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3567, "s": 3501, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3591, "s": 3567, "text": "Window functions in SQL" }, { "code": null, "e": 3623, "s": 3591, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3656, "s": 3623, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3673, "s": 3656, "text": "SQL using Python" }, { "code": null, "e": 3703, "s": 3673, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 3781, "s": 3703, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 3817, "s": 3781, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 3848, "s": 3817, "text": "SQL Query to Compare Two Dates" } ]
Polygon Clipping | Sutherland–Hodgman Algorithm
27 May, 2022 A convex polygon and a convex clipping area are given. The task is to clip polygon edges using the Sutherland–Hodgman Algorithm. Input is in the form of vertices of the polygon in clockwise order. Examples: Input : Polygon : (100,150), (200,250), (300,200) Clipping Area : (150,150), (150,200), (200,200), (200,150) i.e. a Square Output : (150, 162) (150, 200) (200, 200) (200, 174) Example 2 Input : Polygon : (100,150), (200,250), (300,200) Clipping Area : (100,300), (300,300), (200,100) Output : (242, 185) (166, 166) (150, 200) (200, 250) (260, 220) Overview of the algorithm: Consider each edge e of clipping Area and do following: a) Clip given polygon against e. How to clip against an edge of clipping area?The edge (of clipping area) is extended infinitely to create a boundary and all the vertices are clipped using this boundary. The new list of vertices generated is passed to the next edge of the clip polygon in clockwise fashion until all the edges have been used. There are four possible cases for any given edge of given polygon against current clipping edge e. 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. Both vertices are inside : Only the second vertex is added to the output listFirst vertex is outside while second one is inside : Both the point of intersection of the edge with the clip boundary and the second vertex are added to the output listFirst vertex is inside while second one is outside : Only the point of intersection of the edge with the clip boundary is added to the output listBoth vertices are outside : No vertices are added to the output list Both vertices are inside : Only the second vertex is added to the output list First vertex is outside while second one is inside : Both the point of intersection of the edge with the clip boundary and the second vertex are added to the output list First vertex is inside while second one is outside : Only the point of intersection of the edge with the clip boundary is added to the output list Both vertices are outside : No vertices are added to the output list There are two sub-problems that need to be discussed before implementing the algorithm:- To decide if a point is inside or outside the clipper polygonIf the vertices of the clipper polygon are given in clockwise order then all the points lying on the right side of the clipper edges are inside that polygon. This can be calculated using : To find the point of intersection of an edge with the clip boundaryIf two points of each line(1,2 & 3,4) are known, then their point of intersection can be calculated using the formula :- // C++ program for implementing Sutherland–Hodgman// algorithm for polygon clipping#include<iostream>using namespace std; const int MAX_POINTS = 20; // Returns x-value of point of intersection of two// linesint x_intersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4){ int num = (x1*y2 - y1*x2) * (x3-x4) - (x1-x2) * (x3*y4 - y3*x4); int den = (x1-x2) * (y3-y4) - (y1-y2) * (x3-x4); return num/den;} // Returns y-value of point of intersection of// two linesint y_intersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4){ int num = (x1*y2 - y1*x2) * (y3-y4) - (y1-y2) * (x3*y4 - y3*x4); int den = (x1-x2) * (y3-y4) - (y1-y2) * (x3-x4); return num/den;} // This functions clips all the edges w.r.t one clip// edge of clipping areavoid clip(int poly_points[][2], int &poly_size, int x1, int y1, int x2, int y2){ int new_points[MAX_POINTS][2], new_poly_size = 0; // (ix,iy),(kx,ky) are the co-ordinate values of // the points for (int i = 0; i < poly_size; i++) { // i and k form a line in polygon int k = (i+1) % poly_size; int ix = poly_points[i][0], iy = poly_points[i][1]; int kx = poly_points[k][0], ky = poly_points[k][1]; // Calculating position of first point // w.r.t. clipper line int i_pos = (x2-x1) * (iy-y1) - (y2-y1) * (ix-x1); // Calculating position of second point // w.r.t. clipper line int k_pos = (x2-x1) * (ky-y1) - (y2-y1) * (kx-x1); // Case 1 : When both points are inside if (i_pos < 0 && k_pos < 0) { //Only second point is added new_points[new_poly_size][0] = kx; new_points[new_poly_size][1] = ky; new_poly_size++; } // Case 2: When only first point is outside else if (i_pos >= 0 && k_pos < 0) { // Point of intersection with edge // and the second point is added new_points[new_poly_size][0] = x_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_points[new_poly_size][1] = y_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_poly_size++; new_points[new_poly_size][0] = kx; new_points[new_poly_size][1] = ky; new_poly_size++; } // Case 3: When only second point is outside else if (i_pos < 0 && k_pos >= 0) { //Only point of intersection with edge is added new_points[new_poly_size][0] = x_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_points[new_poly_size][1] = y_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_poly_size++; } // Case 4: When both points are outside else { //No points are added } } // Copying new points into original array // and changing the no. of vertices poly_size = new_poly_size; for (int i = 0; i < poly_size; i++) { poly_points[i][0] = new_points[i][0]; poly_points[i][1] = new_points[i][1]; }} // Implements Sutherland–Hodgman algorithmvoid suthHodgClip(int poly_points[][2], int poly_size, int clipper_points[][2], int clipper_size){ //i and k are two consecutive indexes for (int i=0; i<clipper_size; i++) { int k = (i+1) % clipper_size; // We pass the current array of vertices, it's size // and the end points of the selected clipper line clip(poly_points, poly_size, clipper_points[i][0], clipper_points[i][1], clipper_points[k][0], clipper_points[k][1]); } // Printing vertices of clipped polygon for (int i=0; i < poly_size; i++) cout << '(' << poly_points[i][0] << ", " << poly_points[i][1] << ") ";} //Driver codeint main(){ // Defining polygon vertices in clockwise order int poly_size = 3; int poly_points[20][2] = {{100,150}, {200,250}, {300,200}}; // Defining clipper polygon vertices in clockwise order // 1st Example with square clipper int clipper_size = 4; int clipper_points[][2] = {{150,150}, {150,200}, {200,200}, {200,150} }; // 2nd Example with triangle clipper /*int clipper_size = 3; int clipper_points[][2] = {{100,300}, {300,300}, {200,100}};*/ //Calling the clipping function suthHodgClip(poly_points, poly_size, clipper_points, clipper_size); return 0;} Output: (150, 162) (150, 200) (200, 200) (200, 174) Related Articles:Line Clipping | Set 1 (Cohen–Sutherland Algorithm)Point Clipping Algorithm in Computer Graphics This article is contributed by Nabaneet Roy. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. varshagumber28 computer-graphics Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Optimum location of point to minimize total distance Check if two given circles touch or intersect each other Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Check whether a given point lies inside a triangle or not Program for Point of Intersection of Two Lines Find K Closest Points to the Origin Given n line segments, find if any two segments intersect Closest Pair of Points | O(nlogn) Implementation Count maximum points on same line
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2022" }, { "code": null, "e": 249, "s": 52, "text": "A convex polygon and a convex clipping area are given. The task is to clip polygon edges using the Sutherland–Hodgman Algorithm. Input is in the form of vertices of the polygon in clockwise order." }, { "code": null, "e": 259, "s": 249, "text": "Examples:" }, { "code": null, "e": 663, "s": 259, "text": "Input : Polygon : (100,150), (200,250), (300,200)\n Clipping Area : (150,150), (150,200), (200,200), \n (200,150) i.e. a Square \nOutput : (150, 162) (150, 200) (200, 200) (200, 174) \n\n\nExample 2\nInput : Polygon : (100,150), (200,250), (300,200)\n Clipping Area : (100,300), (300,300), (200,100) \nOutput : (242, 185) (166, 166) (150, 200) (200, 250) (260, 220) \n\n" }, { "code": null, "e": 690, "s": 663, "text": "Overview of the algorithm:" }, { "code": null, "e": 784, "s": 690, "text": "Consider each edge e of clipping Area and do following:\n a) Clip given polygon against e.\n" }, { "code": null, "e": 1094, "s": 784, "text": "How to clip against an edge of clipping area?The edge (of clipping area) is extended infinitely to create a boundary and all the vertices are clipped using this boundary. The new list of vertices generated is passed to the next edge of the clip polygon in clockwise fashion until all the edges have been used." }, { "code": null, "e": 1193, "s": 1094, "text": "There are four possible cases for any given edge of given polygon against current clipping edge e." }, { "code": null, "e": 1202, "s": 1193, "text": "Chapters" }, { "code": null, "e": 1229, "s": 1202, "text": "descriptions off, selected" }, { "code": null, "e": 1279, "s": 1229, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1302, "s": 1279, "text": "captions off, selected" }, { "code": null, "e": 1310, "s": 1302, "text": "English" }, { "code": null, "e": 1334, "s": 1310, "text": "This is a modal window." }, { "code": null, "e": 1403, "s": 1334, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1425, "s": 1403, "text": "End of dialog window." }, { "code": null, "e": 1886, "s": 1425, "text": "Both vertices are inside : Only the second vertex is added to the output listFirst vertex is outside while second one is inside : Both the point of intersection of the edge with the clip boundary and the second vertex are added to the output listFirst vertex is inside while second one is outside : Only the point of intersection of the edge with the clip boundary is added to the output listBoth vertices are outside : No vertices are added to the output list" }, { "code": null, "e": 1964, "s": 1886, "text": "Both vertices are inside : Only the second vertex is added to the output list" }, { "code": null, "e": 2134, "s": 1964, "text": "First vertex is outside while second one is inside : Both the point of intersection of the edge with the clip boundary and the second vertex are added to the output list" }, { "code": null, "e": 2281, "s": 2134, "text": "First vertex is inside while second one is outside : Only the point of intersection of the edge with the clip boundary is added to the output list" }, { "code": null, "e": 2350, "s": 2281, "text": "Both vertices are outside : No vertices are added to the output list" }, { "code": null, "e": 2439, "s": 2350, "text": "There are two sub-problems that need to be discussed before implementing the algorithm:-" }, { "code": null, "e": 2689, "s": 2439, "text": "To decide if a point is inside or outside the clipper polygonIf the vertices of the clipper polygon are given in clockwise order then all the points lying on the right side of the clipper edges are inside that polygon. This can be calculated using :" }, { "code": null, "e": 2877, "s": 2689, "text": "To find the point of intersection of an edge with the clip boundaryIf two points of each line(1,2 & 3,4) are known, then their point of intersection can be calculated using the formula :-" }, { "code": "// C++ program for implementing Sutherland–Hodgman// algorithm for polygon clipping#include<iostream>using namespace std; const int MAX_POINTS = 20; // Returns x-value of point of intersection of two// linesint x_intersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4){ int num = (x1*y2 - y1*x2) * (x3-x4) - (x1-x2) * (x3*y4 - y3*x4); int den = (x1-x2) * (y3-y4) - (y1-y2) * (x3-x4); return num/den;} // Returns y-value of point of intersection of// two linesint y_intersect(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4){ int num = (x1*y2 - y1*x2) * (y3-y4) - (y1-y2) * (x3*y4 - y3*x4); int den = (x1-x2) * (y3-y4) - (y1-y2) * (x3-x4); return num/den;} // This functions clips all the edges w.r.t one clip// edge of clipping areavoid clip(int poly_points[][2], int &poly_size, int x1, int y1, int x2, int y2){ int new_points[MAX_POINTS][2], new_poly_size = 0; // (ix,iy),(kx,ky) are the co-ordinate values of // the points for (int i = 0; i < poly_size; i++) { // i and k form a line in polygon int k = (i+1) % poly_size; int ix = poly_points[i][0], iy = poly_points[i][1]; int kx = poly_points[k][0], ky = poly_points[k][1]; // Calculating position of first point // w.r.t. clipper line int i_pos = (x2-x1) * (iy-y1) - (y2-y1) * (ix-x1); // Calculating position of second point // w.r.t. clipper line int k_pos = (x2-x1) * (ky-y1) - (y2-y1) * (kx-x1); // Case 1 : When both points are inside if (i_pos < 0 && k_pos < 0) { //Only second point is added new_points[new_poly_size][0] = kx; new_points[new_poly_size][1] = ky; new_poly_size++; } // Case 2: When only first point is outside else if (i_pos >= 0 && k_pos < 0) { // Point of intersection with edge // and the second point is added new_points[new_poly_size][0] = x_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_points[new_poly_size][1] = y_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_poly_size++; new_points[new_poly_size][0] = kx; new_points[new_poly_size][1] = ky; new_poly_size++; } // Case 3: When only second point is outside else if (i_pos < 0 && k_pos >= 0) { //Only point of intersection with edge is added new_points[new_poly_size][0] = x_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_points[new_poly_size][1] = y_intersect(x1, y1, x2, y2, ix, iy, kx, ky); new_poly_size++; } // Case 4: When both points are outside else { //No points are added } } // Copying new points into original array // and changing the no. of vertices poly_size = new_poly_size; for (int i = 0; i < poly_size; i++) { poly_points[i][0] = new_points[i][0]; poly_points[i][1] = new_points[i][1]; }} // Implements Sutherland–Hodgman algorithmvoid suthHodgClip(int poly_points[][2], int poly_size, int clipper_points[][2], int clipper_size){ //i and k are two consecutive indexes for (int i=0; i<clipper_size; i++) { int k = (i+1) % clipper_size; // We pass the current array of vertices, it's size // and the end points of the selected clipper line clip(poly_points, poly_size, clipper_points[i][0], clipper_points[i][1], clipper_points[k][0], clipper_points[k][1]); } // Printing vertices of clipped polygon for (int i=0; i < poly_size; i++) cout << '(' << poly_points[i][0] << \", \" << poly_points[i][1] << \") \";} //Driver codeint main(){ // Defining polygon vertices in clockwise order int poly_size = 3; int poly_points[20][2] = {{100,150}, {200,250}, {300,200}}; // Defining clipper polygon vertices in clockwise order // 1st Example with square clipper int clipper_size = 4; int clipper_points[][2] = {{150,150}, {150,200}, {200,200}, {200,150} }; // 2nd Example with triangle clipper /*int clipper_size = 3; int clipper_points[][2] = {{100,300}, {300,300}, {200,100}};*/ //Calling the clipping function suthHodgClip(poly_points, poly_size, clipper_points, clipper_size); return 0;}", "e": 7553, "s": 2877, "text": null }, { "code": null, "e": 7561, "s": 7553, "text": "Output:" }, { "code": null, "e": 7606, "s": 7561, "text": "(150, 162) (150, 200) (200, 200) (200, 174)\n" }, { "code": null, "e": 7719, "s": 7606, "text": "Related Articles:Line Clipping | Set 1 (Cohen–Sutherland Algorithm)Point Clipping Algorithm in Computer Graphics" }, { "code": null, "e": 8015, "s": 7719, "text": "This article is contributed by Nabaneet Roy. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8140, "s": 8015, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8155, "s": 8140, "text": "varshagumber28" }, { "code": null, "e": 8173, "s": 8155, "text": "computer-graphics" }, { "code": null, "e": 8183, "s": 8173, "text": "Geometric" }, { "code": null, "e": 8193, "s": 8183, "text": "Geometric" }, { "code": null, "e": 8291, "s": 8193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8340, "s": 8291, "text": "Program for distance between two points on earth" }, { "code": null, "e": 8393, "s": 8340, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 8450, "s": 8393, "text": "Check if two given circles touch or intersect each other" }, { "code": null, "e": 8503, "s": 8450, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 8561, "s": 8503, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 8608, "s": 8561, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 8644, "s": 8608, "text": "Find K Closest Points to the Origin" }, { "code": null, "e": 8702, "s": 8644, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 8751, "s": 8702, "text": "Closest Pair of Points | O(nlogn) Implementation" } ]
How to Print Hard Copy using Tkinter?
24 Jan, 2021 Prerequisite: Tkinter, win32api Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task. In this article, we will discuss how to print a hard copy in the printer using Tkinter. Make a Tkinter window. Add One Button. Open the file which you want to print using the askopenfilename() method in Tkinter. Print it using ShellExecute() method in win32api. Python3 # Import Required Libraryfrom tkinter import * # Create Tkinter Objectroot = Tk() # Set Title and geometryroot.title('Print Hard Copies') root.geometry("200x200") # Make ButtonButton(root,text="Print FIle").pack() # Execute Tkinterroot.mainloop() Output: askopenfilename: This method is used to open a given file. filedialog.askopenfilename(mode=’r’, filetypes=[(‘any name you want to display’, ‘extension of file type’)]) ShellExecute: It is used to execute shell commands of a system. win32api.ShellExecute(hwnd, dir, bShow, op, file, params, **args) hwnd: The handle of the parent window, or zero for no parent. This window receives associate message boxes an application produces (for example, for error reporting). op: The operation to perform. is also “open”, “print”, or None, that defaults to “open”. file: The name of the file to open. params: The parameters to pass, if the file name contains associate viable. ought to be None for a document file. dir: The initial directory for the application. bShow: Specifies whether the appliance is shown once it’s opened. If the lpszFile parameter specifies a document file, this parameter is zero. Below is the Implementation Python3 # Import Required Libraryfrom tkinter import *import win32apifrom tkinter import filedialog # Create Tkinter Objectroot = Tk() # Set Title and geometryroot.title('Print Hard Copies')root.geometry("200x200") # Print File Functiondef print_file(): # Ask for file (Which you want to print) file_to_print = filedialog.askopenfilename( initialdir="/", title="Select file", filetypes=(("Text files", "*.txt"), ("all files", "*.*"))) if file_to_print: # Print Hard Copy of File win32api.ShellExecute(0, "print", file_to_print, None, ".", 0) # Make ButtonButton(root, text="Print FIle", command=print_file).pack() # Execute Tkinterroot.mainloop() On execution of the above python script, a tkinter window will pop up which will require to upload a text file, after uploading, the text file gets printed. Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 60, "s": 28, "text": "Prerequisite: Tkinter, win32api" }, { "code": null, "e": 410, "s": 60, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task." }, { "code": null, "e": 498, "s": 410, "text": "In this article, we will discuss how to print a hard copy in the printer using Tkinter." }, { "code": null, "e": 521, "s": 498, "text": "Make a Tkinter window." }, { "code": null, "e": 537, "s": 521, "text": "Add One Button." }, { "code": null, "e": 622, "s": 537, "text": "Open the file which you want to print using the askopenfilename() method in Tkinter." }, { "code": null, "e": 672, "s": 622, "text": "Print it using ShellExecute() method in win32api." }, { "code": null, "e": 680, "s": 672, "text": "Python3" }, { "code": "# Import Required Libraryfrom tkinter import * # Create Tkinter Objectroot = Tk() # Set Title and geometryroot.title('Print Hard Copies') root.geometry(\"200x200\") # Make ButtonButton(root,text=\"Print FIle\").pack() # Execute Tkinterroot.mainloop()", "e": 932, "s": 680, "text": null }, { "code": null, "e": 940, "s": 932, "text": "Output:" }, { "code": null, "e": 999, "s": 940, "text": "askopenfilename: This method is used to open a given file." }, { "code": null, "e": 1108, "s": 999, "text": "filedialog.askopenfilename(mode=’r’, filetypes=[(‘any name you want to display’, ‘extension of file type’)])" }, { "code": null, "e": 1172, "s": 1108, "text": "ShellExecute: It is used to execute shell commands of a system." }, { "code": null, "e": 1238, "s": 1172, "text": "win32api.ShellExecute(hwnd, dir, bShow, op, file, params, **args)" }, { "code": null, "e": 1405, "s": 1238, "text": "hwnd: The handle of the parent window, or zero for no parent. This window receives associate message boxes an application produces (for example, for error reporting)." }, { "code": null, "e": 1494, "s": 1405, "text": "op: The operation to perform. is also “open”, “print”, or None, that defaults to “open”." }, { "code": null, "e": 1530, "s": 1494, "text": "file: The name of the file to open." }, { "code": null, "e": 1644, "s": 1530, "text": "params: The parameters to pass, if the file name contains associate viable. ought to be None for a document file." }, { "code": null, "e": 1692, "s": 1644, "text": "dir: The initial directory for the application." }, { "code": null, "e": 1835, "s": 1692, "text": "bShow: Specifies whether the appliance is shown once it’s opened. If the lpszFile parameter specifies a document file, this parameter is zero." }, { "code": null, "e": 1863, "s": 1835, "text": "Below is the Implementation" }, { "code": null, "e": 1871, "s": 1863, "text": "Python3" }, { "code": "# Import Required Libraryfrom tkinter import *import win32apifrom tkinter import filedialog # Create Tkinter Objectroot = Tk() # Set Title and geometryroot.title('Print Hard Copies')root.geometry(\"200x200\") # Print File Functiondef print_file(): # Ask for file (Which you want to print) file_to_print = filedialog.askopenfilename( initialdir=\"/\", title=\"Select file\", filetypes=((\"Text files\", \"*.txt\"), (\"all files\", \"*.*\"))) if file_to_print: # Print Hard Copy of File win32api.ShellExecute(0, \"print\", file_to_print, None, \".\", 0) # Make ButtonButton(root, text=\"Print FIle\", command=print_file).pack() # Execute Tkinterroot.mainloop()", "e": 2567, "s": 1871, "text": null }, { "code": null, "e": 2724, "s": 2567, "text": "On execution of the above python script, a tkinter window will pop up which will require to upload a text file, after uploading, the text file gets printed." }, { "code": null, "e": 2749, "s": 2724, "text": "Python Tkinter-exercises" }, { "code": null, "e": 2764, "s": 2749, "text": "Python-tkinter" }, { "code": null, "e": 2771, "s": 2764, "text": "Python" }, { "code": null, "e": 2869, "s": 2771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2901, "s": 2869, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2928, "s": 2901, "text": "Python Classes and Objects" }, { "code": null, "e": 2949, "s": 2928, "text": "Python OOPs Concepts" }, { "code": null, "e": 2972, "s": 2949, "text": "Introduction To PYTHON" }, { "code": null, "e": 3028, "s": 2972, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3059, "s": 3028, "text": "Python | os.path.join() method" }, { "code": null, "e": 3101, "s": 3059, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3143, "s": 3101, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3182, "s": 3143, "text": "Python | Get unique values from a list" } ]
Python Tkinter – Canvas Widget
31 Aug, 2021 Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs.Note: For more information, refer to Python GUI – tkinter The Canvas widget lets us display various graphics on the application. It can be used to draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs. Syntax: C = Canvas(root, height, width, bd, bg, ..) Optional parameters: root = root window. height = height of the canvas widget. width = width of the canvas widget. bg = background colour for canvas. bd = border of the canvas window. scrollregion (w, n, e, s)tuple defined as a region for scrolling left, top, bottom and right. highlightcolor colour shown in the focus highlight. cursor It can be defined as a cursor for the canvas which can be a circle, a do, an arrow etc. confine decides if canvas can be accessed outside the scroll region. relief type of the border which can be SUNKEN, RAISED, GROOVE and RIDGE. Creating an Oval oval = C.create_oval(x0, y0, x1, y1, options) Creating an arc arc = C.create_arc(20, 50, 190, 240, start=0, extent=110, fill="red") Creating a Line line = C.create_line(x0, y0, x1, y1, ..., xn, yn, options) Creating a polygon oval = C.create_polygon(x0, y0, x1, y1, ...xn, yn, options) Example 1: Simple Shapes Drawing Python3 from tkinter import * root = Tk() C = Canvas(root, bg="yellow", height=250, width=300) line = C.create_line(108, 120, 320, 40, fill="green") arc = C.create_arc(180, 150, 80, 210, start=0, extent=220, fill="red") oval = C.create_oval(80, 30, 140, 150, fill="blue") C.pack()mainloop() Output: Example 2: Simple Paint App Python3 from tkinter import * root = Tk() # Create Titleroot.title( "Paint App ") # specify sizeroot.geometry("500x350") # define function when # mouse double click is enableddef paint( event ): # Co-ordinates. x1, y1, x2, y2 = ( event.x - 3 ),( event.y - 3 ), ( event.x + 3 ),( event.y + 3 ) # Colour Colour = "#000fff000" # specify type of display w.create_line( x1, y1, x2, y2, fill = Colour ) # create canvas widget.w = Canvas(root, width = 400, height = 250) # call function when double# click is enabled.w.bind( "<B1-Motion>", paint ) # create label.l = Label( root, text = "Double Click and Drag to draw." )l.pack()w.pack() mainloop() Output: adityanarayan890singh shubhamkochar Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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 ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Aug, 2021" }, { "code": null, "e": 319, "s": 52, "text": "Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most commonly used and the most basic GUI framework available in python. Tkinter uses an object-oriented approach to make GUIs.Note: For more information, refer to Python GUI – tkinter" }, { "code": null, "e": 526, "s": 319, "text": "The Canvas widget lets us display various graphics on the application. It can be used to draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs." }, { "code": null, "e": 535, "s": 526, "text": "Syntax: " }, { "code": null, "e": 579, "s": 535, "text": "C = Canvas(root, height, width, bd, bg, ..)" }, { "code": null, "e": 601, "s": 579, "text": "Optional parameters: " }, { "code": null, "e": 621, "s": 601, "text": "root = root window." }, { "code": null, "e": 659, "s": 621, "text": "height = height of the canvas widget." }, { "code": null, "e": 695, "s": 659, "text": "width = width of the canvas widget." }, { "code": null, "e": 730, "s": 695, "text": "bg = background colour for canvas." }, { "code": null, "e": 764, "s": 730, "text": "bd = border of the canvas window." }, { "code": null, "e": 858, "s": 764, "text": "scrollregion (w, n, e, s)tuple defined as a region for scrolling left, top, bottom and right." }, { "code": null, "e": 910, "s": 858, "text": "highlightcolor colour shown in the focus highlight." }, { "code": null, "e": 1005, "s": 910, "text": "cursor It can be defined as a cursor for the canvas which can be a circle, a do, an arrow etc." }, { "code": null, "e": 1074, "s": 1005, "text": "confine decides if canvas can be accessed outside the scroll region." }, { "code": null, "e": 1149, "s": 1074, "text": "relief type of the border which can be SUNKEN, RAISED, GROOVE and RIDGE. " }, { "code": null, "e": 1166, "s": 1149, "text": "Creating an Oval" }, { "code": null, "e": 1213, "s": 1166, "text": " oval = C.create_oval(x0, y0, x1, y1, options)" }, { "code": null, "e": 1229, "s": 1213, "text": "Creating an arc" }, { "code": null, "e": 1300, "s": 1229, "text": " arc = C.create_arc(20, 50, 190, 240, start=0, extent=110, fill=\"red\")" }, { "code": null, "e": 1316, "s": 1300, "text": "Creating a Line" }, { "code": null, "e": 1376, "s": 1316, "text": " line = C.create_line(x0, y0, x1, y1, ..., xn, yn, options)" }, { "code": null, "e": 1395, "s": 1376, "text": "Creating a polygon" }, { "code": null, "e": 1456, "s": 1395, "text": " oval = C.create_polygon(x0, y0, x1, y1, ...xn, yn, options)" }, { "code": null, "e": 1490, "s": 1456, "text": "Example 1: Simple Shapes Drawing " }, { "code": null, "e": 1498, "s": 1490, "text": "Python3" }, { "code": "from tkinter import * root = Tk() C = Canvas(root, bg=\"yellow\", height=250, width=300) line = C.create_line(108, 120, 320, 40, fill=\"green\") arc = C.create_arc(180, 150, 80, 210, start=0, extent=220, fill=\"red\") oval = C.create_oval(80, 30, 140, 150, fill=\"blue\") C.pack()mainloop()", "e": 1926, "s": 1498, "text": null }, { "code": null, "e": 1935, "s": 1926, "text": "Output: " }, { "code": null, "e": 1964, "s": 1935, "text": "Example 2: Simple Paint App " }, { "code": null, "e": 1972, "s": 1964, "text": "Python3" }, { "code": "from tkinter import * root = Tk() # Create Titleroot.title( \"Paint App \") # specify sizeroot.geometry(\"500x350\") # define function when # mouse double click is enableddef paint( event ): # Co-ordinates. x1, y1, x2, y2 = ( event.x - 3 ),( event.y - 3 ), ( event.x + 3 ),( event.y + 3 ) # Colour Colour = \"#000fff000\" # specify type of display w.create_line( x1, y1, x2, y2, fill = Colour ) # create canvas widget.w = Canvas(root, width = 400, height = 250) # call function when double# click is enabled.w.bind( \"<B1-Motion>\", paint ) # create label.l = Label( root, text = \"Double Click and Drag to draw.\" )l.pack()w.pack() mainloop()", "e": 2658, "s": 1972, "text": null }, { "code": null, "e": 2667, "s": 2658, "text": "Output: " }, { "code": null, "e": 2689, "s": 2667, "text": "adityanarayan890singh" }, { "code": null, "e": 2703, "s": 2689, "text": "shubhamkochar" }, { "code": null, "e": 2718, "s": 2703, "text": "Python-tkinter" }, { "code": null, "e": 2725, "s": 2718, "text": "Python" }, { "code": null, "e": 2823, "s": 2725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2851, "s": 2823, "text": "Read JSON file using Python" }, { "code": null, "e": 2901, "s": 2851, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2923, "s": 2901, "text": "Python map() function" }, { "code": null, "e": 2967, "s": 2923, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3009, "s": 2967, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3031, "s": 3009, "text": "Enumerate() in Python" }, { "code": null, "e": 3066, "s": 3031, "text": "Read a file line by line in Python" }, { "code": null, "e": 3092, "s": 3066, "text": "Python String | replace()" }, { "code": null, "e": 3124, "s": 3092, "text": "How to Install PIP on Windows ?" } ]
Discrete Mathematics | Representing Relations
13 Dec, 2019 Prerequisite – Introduction and types of RelationsRelations are represented using ordered pairs, matrix and digraphs: Ordered Pairs –In this set of ordered pairs of x and y are used to represent relation. In this corresponding values of x and y are represented using parenthesis.Example: {(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)} This represent square of a number which means if x=1 then y = x*x = 1 and so on. Representing using Matrix –In this zero-one is used to represent the relationship that exists between two sets. In this if a element is present then it is represented by 1 else it is represented by 0. In this method it is easy to judge if a relation is reflexive, symmetric or transitive just by looking at the matrix.Suppose R is a relation from X={x1, x2, .....xn} to Y={y1, y2....yn} It is represented by :- M[i, j]={1, if (Xi, Yj) belongs to R 0, if (Xi, Yj) does not belong to R} If A={1, 2, 3} and B={1, 2} and Relation R isR = {(2, 1), (3, 1), (3, 2)}then all corresponding value of Relation will be represented by “1” else “0”.It is represented as:It’s corresponding possible relations are:Digraph –A digraph is known was directed graph. It consists of set ‘V’ of vertices and with the edges ‘E’. Here E is represented by ordered pair of Vertices.In the edge (a, b), a is the initial vertex and b is the final vertex.If edge is (a, a) then this is regarded as loop.Example: Suppose we have relation formingR = {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} This relation is represented using digraph as:My Personal Notes arrow_drop_upSave Ordered Pairs –In this set of ordered pairs of x and y are used to represent relation. In this corresponding values of x and y are represented using parenthesis.Example: {(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)} This represent square of a number which means if x=1 then y = x*x = 1 and so on. Example: {(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)} This represent square of a number which means if x=1 then y = x*x = 1 and so on. Representing using Matrix –In this zero-one is used to represent the relationship that exists between two sets. In this if a element is present then it is represented by 1 else it is represented by 0. In this method it is easy to judge if a relation is reflexive, symmetric or transitive just by looking at the matrix.Suppose R is a relation from X={x1, x2, .....xn} to Y={y1, y2....yn} It is represented by :- M[i, j]={1, if (Xi, Yj) belongs to R 0, if (Xi, Yj) does not belong to R} If A={1, 2, 3} and B={1, 2} and Relation R isR = {(2, 1), (3, 1), (3, 2)}then all corresponding value of Relation will be represented by “1” else “0”.It is represented as:It’s corresponding possible relations are: Suppose R is a relation from X={x1, x2, .....xn} to Y={y1, y2....yn} It is represented by :- M[i, j]={1, if (Xi, Yj) belongs to R 0, if (Xi, Yj) does not belong to R} If A={1, 2, 3} and B={1, 2} and Relation R isR = {(2, 1), (3, 1), (3, 2)}then all corresponding value of Relation will be represented by “1” else “0”. It is represented as: It’s corresponding possible relations are: Digraph –A digraph is known was directed graph. It consists of set ‘V’ of vertices and with the edges ‘E’. Here E is represented by ordered pair of Vertices.In the edge (a, b), a is the initial vertex and b is the final vertex.If edge is (a, a) then this is regarded as loop.Example: Suppose we have relation formingR = {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} This relation is represented using digraph as:My Personal Notes arrow_drop_upSave Example: Suppose we have relation forming R = {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} This relation is represented using digraph as: Discrete Mathematics Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Dec, 2019" }, { "code": null, "e": 170, "s": 52, "text": "Prerequisite – Introduction and types of RelationsRelations are represented using ordered pairs, matrix and digraphs:" }, { "code": null, "e": 1621, "s": 170, "text": "Ordered Pairs –In this set of ordered pairs of x and y are used to represent relation. In this corresponding values of x and y are represented using parenthesis.Example: {(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)}\nThis represent square of a number which means if x=1 then y = x*x = 1 and so on.\nRepresenting using Matrix –In this zero-one is used to represent the relationship that exists between two sets. In this if a element is present then it is represented by 1 else it is represented by 0. In this method it is easy to judge if a relation is reflexive, symmetric or transitive just by looking at the matrix.Suppose R is a relation from X={x1, x2, .....xn} to Y={y1, y2....yn}\nIt is represented by :-\nM[i, j]={1, if (Xi, Yj) belongs to R\n 0, if (Xi, Yj) does not belong to R}\nIf A={1, 2, 3} and B={1, 2} and Relation R isR = {(2, 1), (3, 1), (3, 2)}then all corresponding value of Relation will be represented by “1” else “0”.It is represented as:It’s corresponding possible relations are:Digraph –A digraph is known was directed graph. It consists of set ‘V’ of vertices and with the edges ‘E’. Here E is represented by ordered pair of Vertices.In the edge (a, b), a is the initial vertex and b is the final vertex.If edge is (a, a) then this is regarded as loop.Example: Suppose we have relation formingR = {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} This relation is represented using digraph as:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 1916, "s": 1621, "text": "Ordered Pairs –In this set of ordered pairs of x and y are used to represent relation. In this corresponding values of x and y are represented using parenthesis.Example: {(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)}\nThis represent square of a number which means if x=1 then y = x*x = 1 and so on.\n" }, { "code": null, "e": 2050, "s": 1916, "text": "Example: {(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)}\nThis represent square of a number which means if x=1 then y = x*x = 1 and so on.\n" }, { "code": null, "e": 2757, "s": 2050, "text": "Representing using Matrix –In this zero-one is used to represent the relationship that exists between two sets. In this if a element is present then it is represented by 1 else it is represented by 0. In this method it is easy to judge if a relation is reflexive, symmetric or transitive just by looking at the matrix.Suppose R is a relation from X={x1, x2, .....xn} to Y={y1, y2....yn}\nIt is represented by :-\nM[i, j]={1, if (Xi, Yj) belongs to R\n 0, if (Xi, Yj) does not belong to R}\nIf A={1, 2, 3} and B={1, 2} and Relation R isR = {(2, 1), (3, 1), (3, 2)}then all corresponding value of Relation will be represented by “1” else “0”.It is represented as:It’s corresponding possible relations are:" }, { "code": null, "e": 2933, "s": 2757, "text": "Suppose R is a relation from X={x1, x2, .....xn} to Y={y1, y2....yn}\nIt is represented by :-\nM[i, j]={1, if (Xi, Yj) belongs to R\n 0, if (Xi, Yj) does not belong to R}\n" }, { "code": null, "e": 3084, "s": 2933, "text": "If A={1, 2, 3} and B={1, 2} and Relation R isR = {(2, 1), (3, 1), (3, 2)}then all corresponding value of Relation will be represented by “1” else “0”." }, { "code": null, "e": 3106, "s": 3084, "text": "It is represented as:" }, { "code": null, "e": 3149, "s": 3106, "text": "It’s corresponding possible relations are:" }, { "code": null, "e": 3600, "s": 3149, "text": "Digraph –A digraph is known was directed graph. It consists of set ‘V’ of vertices and with the edges ‘E’. Here E is represented by ordered pair of Vertices.In the edge (a, b), a is the initial vertex and b is the final vertex.If edge is (a, a) then this is regarded as loop.Example: Suppose we have relation formingR = {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} This relation is represented using digraph as:My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 3642, "s": 3600, "text": "Example: Suppose we have relation forming" }, { "code": null, "e": 3696, "s": 3642, "text": "R = {(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)} " }, { "code": null, "e": 3743, "s": 3696, "text": "This relation is represented using digraph as:" }, { "code": null, "e": 3764, "s": 3743, "text": "Discrete Mathematics" }, { "code": null, "e": 3788, "s": 3764, "text": "Engineering Mathematics" }, { "code": null, "e": 3796, "s": 3788, "text": "GATE CS" } ]
HTML | DOM Style overflow Property
02 Jun, 2022 The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. The content may be hidden, shown or a scrollbar maybe shown according to the value. Syntax: It returns the overflow property. object.style.overflow It is used to set the overflow property. object.style.overflow = "visible|hidden|scroll|auto|initial| inherit" Return Values: It returns a string value, which represents the content that renders outside the element box. Property Values: visible: The content is not clipped and may overflow out of the containing element. Example: html <!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: hidden; } button { margin-top: 60px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick="setOverflow()"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'visible'; } </script></body> </html> Output:Before clicking the button: Before clicking the button: After clicking the button: hidden: The content is clipped and hidden to fit the element. No scrollbars are provided when using this value. Example: html <!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; } button { margin-top: 60px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick="setOverflow()"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'hidden'; } </script></body> </html> Output:Before clicking the button: Before clicking the button: After clicking the button: scroll: The content is clipped to fit the element box and scrollbars are provided to help scroll the overflowed content. The scrollbar here is added even if the content is not clipped. Example: html <!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: hidden; } button { margin-top: 60px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick="setOverflow()"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'scroll'; } </script></body> </html> Output:Before clicking the button: Before clicking the button: After clicking the button: auto: The behavior of auto depends on the content and scrollbars are added only when the content overflows. Example: html <!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: visible; } button { margin-top: 60px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick="setOverflow()"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'auto'; } </script></body> </html> Output:Before clicking the button: Before clicking the button: After clicking the button: initial: It is used to set this property to its default value. Example: html <!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: scroll; } button { margin-top: 60px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick="setOverflow()"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'initial'; } </script></body> </html> Output:Before clicking the button: Before clicking the button: After clicking the button: inherit: This inherits the property from its parent. Example: html <!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> #parent { overflow: auto; } .content { background-color: lightgreen; height: 150px; width: 200px; } button { margin-top: 60px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div id="parent"> <div class="content"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions.<br>The portal also has dedicated GATE preparation and competitive programming sections. </div> </div> <button onclick="setOverflow()"> Change overflow </button> <!-- Script to set overflow to inherit --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'inherit'; } </script></body> </html> Output: Before clicking the button: After clicking the button: Supported Browsers: The browser supported by DOM Style overflow property are listed below: Google Chrome 1 and above Edge 12 and above Internet Explorer 4 and above Firefox 1 and above Opera 7 and above Apple Safari 1 and above chhabradhanvi kumargaurav97520 HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Jun, 2022" }, { "code": null, "e": 260, "s": 53, "text": "The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. The content may be hidden, shown or a scrollbar maybe shown according to the value. " }, { "code": null, "e": 268, "s": 260, "text": "Syntax:" }, { "code": null, "e": 302, "s": 268, "text": "It returns the overflow property." }, { "code": null, "e": 324, "s": 302, "text": "object.style.overflow" }, { "code": null, "e": 365, "s": 324, "text": "It is used to set the overflow property." }, { "code": null, "e": 435, "s": 365, "text": "object.style.overflow = \"visible|hidden|scroll|auto|initial|\ninherit\"" }, { "code": null, "e": 544, "s": 435, "text": "Return Values: It returns a string value, which represents the content that renders outside the element box." }, { "code": null, "e": 561, "s": 544, "text": "Property Values:" }, { "code": null, "e": 646, "s": 561, "text": "visible: The content is not clipped and may overflow out of the containing element. " }, { "code": null, "e": 656, "s": 646, "text": "Example: " }, { "code": null, "e": 661, "s": 656, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: hidden; } button { margin-top: 60px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick=\"setOverflow()\"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'visible'; } </script></body> </html> ", "e": 1927, "s": 661, "text": null }, { "code": null, "e": 1962, "s": 1927, "text": "Output:Before clicking the button:" }, { "code": null, "e": 1990, "s": 1962, "text": "Before clicking the button:" }, { "code": null, "e": 2019, "s": 1992, "text": "After clicking the button:" }, { "code": null, "e": 2134, "s": 2021, "text": "hidden: The content is clipped and hidden to fit the element. No scrollbars are provided when using this value. " }, { "code": null, "e": 2144, "s": 2134, "text": "Example: " }, { "code": null, "e": 2149, "s": 2144, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; } button { margin-top: 60px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick=\"setOverflow()\"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'hidden'; } </script></body> </html> ", "e": 3385, "s": 2149, "text": null }, { "code": null, "e": 3420, "s": 3385, "text": "Output:Before clicking the button:" }, { "code": null, "e": 3448, "s": 3420, "text": "Before clicking the button:" }, { "code": null, "e": 3475, "s": 3448, "text": "After clicking the button:" }, { "code": null, "e": 3662, "s": 3477, "text": "scroll: The content is clipped to fit the element box and scrollbars are provided to help scroll the overflowed content. The scrollbar here is added even if the content is not clipped." }, { "code": null, "e": 3672, "s": 3662, "text": "Example: " }, { "code": null, "e": 3677, "s": 3672, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: hidden; } button { margin-top: 60px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick=\"setOverflow()\"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'scroll'; } </script></body> </html> ", "e": 4942, "s": 3677, "text": null }, { "code": null, "e": 4977, "s": 4942, "text": "Output:Before clicking the button:" }, { "code": null, "e": 5005, "s": 4977, "text": "Before clicking the button:" }, { "code": null, "e": 5034, "s": 5007, "text": "After clicking the button:" }, { "code": null, "e": 5145, "s": 5036, "text": "auto: The behavior of auto depends on the content and scrollbars are added only when the content overflows. " }, { "code": null, "e": 5155, "s": 5145, "text": "Example: " }, { "code": null, "e": 5160, "s": 5155, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: visible; } button { margin-top: 60px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick=\"setOverflow()\"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'auto'; } </script></body> </html> ", "e": 6424, "s": 5160, "text": null }, { "code": null, "e": 6459, "s": 6424, "text": "Output:Before clicking the button:" }, { "code": null, "e": 6487, "s": 6459, "text": "Before clicking the button:" }, { "code": null, "e": 6517, "s": 6489, "text": "After clicking the button: " }, { "code": null, "e": 6581, "s": 6517, "text": "initial: It is used to set this property to its default value. " }, { "code": null, "e": 6591, "s": 6581, "text": "Example: " }, { "code": null, "e": 6596, "s": 6591, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> .content { background-color: lightgreen; height: 150px; width: 200px; overflow: scroll; } button { margin-top: 60px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. <br>The portal also has dedicated GATE preparation and competitive programming sections. </div> <button onclick=\"setOverflow()\"> Change overflow </button> <!-- Script to set overflow to visible --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'initial'; } </script></body> </html> ", "e": 7862, "s": 6596, "text": null }, { "code": null, "e": 7897, "s": 7862, "text": "Output:Before clicking the button:" }, { "code": null, "e": 7925, "s": 7897, "text": "Before clicking the button:" }, { "code": null, "e": 7954, "s": 7927, "text": "After clicking the button:" }, { "code": null, "e": 8010, "s": 7956, "text": "inherit: This inherits the property from its parent. " }, { "code": null, "e": 8020, "s": 8010, "text": "Example: " }, { "code": null, "e": 8025, "s": 8020, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> DOM Style overflow Property </title> <style> #parent { overflow: auto; } .content { background-color: lightgreen; height: 150px; width: 200px; } button { margin-top: 60px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>DOM Style overflow Property</b> <p> The Style overflow property in HTML DOM is used to specify the behavior of the content when it overflows the element box. </p> <div id=\"parent\"> <div class=\"content\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions.<br>The portal also has dedicated GATE preparation and competitive programming sections. </div> </div> <button onclick=\"setOverflow()\"> Change overflow </button> <!-- Script to set overflow to inherit --> <script> function setOverflow() { elem = document.querySelector('.content'); elem.style.overflow = 'inherit'; } </script></body> </html> ", "e": 9375, "s": 8025, "text": null }, { "code": null, "e": 9383, "s": 9375, "text": "Output:" }, { "code": null, "e": 9411, "s": 9383, "text": "Before clicking the button:" }, { "code": null, "e": 9441, "s": 9413, "text": "After clicking the button: " }, { "code": null, "e": 9532, "s": 9441, "text": "Supported Browsers: The browser supported by DOM Style overflow property are listed below:" }, { "code": null, "e": 9559, "s": 9532, "text": "Google Chrome 1 and above" }, { "code": null, "e": 9578, "s": 9559, "text": "Edge 12 and above" }, { "code": null, "e": 9608, "s": 9578, "text": "Internet Explorer 4 and above" }, { "code": null, "e": 9628, "s": 9608, "text": "Firefox 1 and above" }, { "code": null, "e": 9646, "s": 9628, "text": "Opera 7 and above" }, { "code": null, "e": 9671, "s": 9646, "text": "Apple Safari 1 and above" }, { "code": null, "e": 9685, "s": 9671, "text": "chhabradhanvi" }, { "code": null, "e": 9702, "s": 9685, "text": "kumargaurav97520" }, { "code": null, "e": 9711, "s": 9702, "text": "HTML-DOM" }, { "code": null, "e": 9718, "s": 9711, "text": "Picked" }, { "code": null, "e": 9723, "s": 9718, "text": "HTML" }, { "code": null, "e": 9740, "s": 9723, "text": "Web Technologies" }, { "code": null, "e": 9745, "s": 9740, "text": "HTML" } ]
Structural Directives in Angular - GeeksforGeeks
31 Jul, 2020 Structural directives are responsible for the Structure and Layout of the DOM Element. It is used to hide or display the things on the DOM. Structural Directives can be easily identified using the ‘*’. Every Structural Directive is preceded by a ‘*’ symbol.Some of the Build in Structural Directives with Examples are as follows: 1. *ngIf: ngIf is used to display or hide the DOM Element based on the expression value assigned to it. The expression value may be either true or false. Syntax: <div *ngIf="boolean"> </div> In the above Syntax, boolean stands for either true or false value. Hence, it leads to 2 valid syntaxes as below : <div *ngIf="true"> </div> <div *ngIf="false"> </div> Example of *ngIf: <div *ngIf="false"> This text will be hidden <h1 [ngStyle]="{'color':'#FF0000'}"> GFG Structural Directive Example </h1></div><div *ngIf="true"> This text will be displayed <h1 [ngStyle]="{'color':'#00FF00'}"> GFG Structural Directive Example </h1></div> Output: *ngIf Example 2. *ngIf-else: ngIf-else works like a simple If-else statement, wherein if the condition is true then ‘If’ DOM element is rendered, else the other DOM Element is rendered. Angular uses ng-template with element selector in order to display the else section on DOM. Syntax: <div *ngIf="boolean; else id_selector"> </div> <ng-template #id_selector> </ng-template> In the above Syntax, boolean stands for either true or false value. If the boolean value is true then Element in If is rendered on the DOM, else another element is rendered on the DOM .Example of *ngIf- else: <div *ngIf="false;else id_selector"> This text will be hidden <h1 [ngStyle]="{'color':'#FF0000'}"> GFG Structural Directive If Part </h1></div><ng-template #id_selector> This text will be displayed <h1 [ngStyle]="{'color':'#00FF00'}"> GFG Structural Directive Else Part </h1></ng-template> Output: *ngIf – else Example 3. *ngFor:*ngFor is used to loop through the dynamic lists in the DOM. Simply, it is used to build data presentation lists and tables in HTML DOM. Syntax: <div *ngFor="let item of item-list"> </div> Example of *ngFor: Consider that you are having a list as shown below: items = ["GfG 1", "GfG 2", "GfG 3", "GfG 4"]; <div *ngFor="let item of items"> <p > {{item}} </p></div> Output: *ngFor example Example-2 of *ngFor with Indexes:Consider that you are having a list as shown below : items = ["GfG ", "GfG ", "GfG ", "GfG "]; <div *ngFor="let item of items;let i=index"> <p > {{item}} {{i}} </p></div> Output:Here, the index starts from ‘0’ and not ‘1’ *ngFor with Indexes 4. *ngSwitch :ngSwitch is used to choose between multiple case statements defined by the expressions inside the *ngSwitchCase and display on the DOM Element according to that. If no expression is matched, the default case DOM Element is displayed. Syntax: <div [ngSwitch]="expression"> <div *ngSwitchCase="expression_1"></div> <div *ngSwitchCase="expression_2"></div> <div *ngSwitchDefault></div> </div> In the above syntax, the expression is checked with each case and then the case matching with the expression is rendered on DOM else the Default case is rendered on the DOM.Example of *ngSwitch: <div [ngSwitch]="'one'"> <div *ngSwitchCase="'one'">One is Displayed</div> <div *ngSwitchCase="'two'">Two is Displayed</div> <div *ngSwitchDefault>Default Option is Displayed</div> </div> In the above example, the expression ‘one’ in ngSwitch is matched to the expression in ngSwitchCase. Hence, the Element displayed on DOM is ” One is Displayed “. Output: ngSwitch Case example AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to create module with Routing in Angular 9 ? How to setup 404 page in angular routing ? 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": 24718, "s": 24690, "text": "\n31 Jul, 2020" }, { "code": null, "e": 25048, "s": 24718, "text": "Structural directives are responsible for the Structure and Layout of the DOM Element. It is used to hide or display the things on the DOM. Structural Directives can be easily identified using the ‘*’. Every Structural Directive is preceded by a ‘*’ symbol.Some of the Build in Structural Directives with Examples are as follows:" }, { "code": null, "e": 25058, "s": 25048, "text": "1. *ngIf:" }, { "code": null, "e": 25202, "s": 25058, "text": "ngIf is used to display or hide the DOM Element based on the expression value assigned to it. The expression value may be either true or false." }, { "code": null, "e": 25210, "s": 25202, "text": "Syntax:" }, { "code": null, "e": 25239, "s": 25210, "text": "<div *ngIf=\"boolean\"> </div>" }, { "code": null, "e": 25354, "s": 25239, "text": "In the above Syntax, boolean stands for either true or false value. Hence, it leads to 2 valid syntaxes as below :" }, { "code": null, "e": 25410, "s": 25354, "text": "<div *ngIf=\"true\"> </div>\n<div *ngIf=\"false\"> </div>\n" }, { "code": null, "e": 25428, "s": 25410, "text": "Example of *ngIf:" }, { "code": "<div *ngIf=\"false\"> This text will be hidden <h1 [ngStyle]=\"{'color':'#FF0000'}\"> GFG Structural Directive Example </h1></div><div *ngIf=\"true\"> This text will be displayed <h1 [ngStyle]=\"{'color':'#00FF00'}\"> GFG Structural Directive Example </h1></div>", "e": 25695, "s": 25428, "text": null }, { "code": null, "e": 25703, "s": 25695, "text": "Output:" }, { "code": null, "e": 25717, "s": 25703, "text": "*ngIf Example" }, { "code": null, "e": 25732, "s": 25717, "text": "2. *ngIf-else:" }, { "code": null, "e": 25981, "s": 25732, "text": "ngIf-else works like a simple If-else statement, wherein if the condition is true then ‘If’ DOM element is rendered, else the other DOM Element is rendered. Angular uses ng-template with element selector in order to display the else section on DOM." }, { "code": null, "e": 25989, "s": 25981, "text": "Syntax:" }, { "code": null, "e": 26081, "s": 25989, "text": "<div *ngIf=\"boolean; else id_selector\"> </div>\n<ng-template #id_selector> </ng-template>\n" }, { "code": null, "e": 26290, "s": 26081, "text": "In the above Syntax, boolean stands for either true or false value. If the boolean value is true then Element in If is rendered on the DOM, else another element is rendered on the DOM .Example of *ngIf- else:" }, { "code": "<div *ngIf=\"false;else id_selector\"> This text will be hidden <h1 [ngStyle]=\"{'color':'#FF0000'}\"> GFG Structural Directive If Part </h1></div><ng-template #id_selector> This text will be displayed <h1 [ngStyle]=\"{'color':'#00FF00'}\"> GFG Structural Directive Else Part </h1></ng-template>", "e": 26600, "s": 26290, "text": null }, { "code": null, "e": 26608, "s": 26600, "text": "Output:" }, { "code": null, "e": 26629, "s": 26608, "text": "*ngIf – else Example" }, { "code": null, "e": 26776, "s": 26629, "text": "3. *ngFor:*ngFor is used to loop through the dynamic lists in the DOM. Simply, it is used to build data presentation lists and tables in HTML DOM." }, { "code": null, "e": 26784, "s": 26776, "text": "Syntax:" }, { "code": null, "e": 26829, "s": 26784, "text": "<div *ngFor=\"let item of item-list\"> </div>" }, { "code": null, "e": 26848, "s": 26829, "text": "Example of *ngFor:" }, { "code": null, "e": 26900, "s": 26848, "text": "Consider that you are having a list as shown below:" }, { "code": null, "e": 26947, "s": 26900, "text": "items = [\"GfG 1\", \"GfG 2\", \"GfG 3\", \"GfG 4\"];\n" }, { "code": "<div *ngFor=\"let item of items\"> <p > {{item}} </p></div>", "e": 27006, "s": 26947, "text": null }, { "code": null, "e": 27014, "s": 27006, "text": "Output:" }, { "code": null, "e": 27029, "s": 27014, "text": "*ngFor example" }, { "code": null, "e": 27115, "s": 27029, "text": "Example-2 of *ngFor with Indexes:Consider that you are having a list as shown below :" }, { "code": null, "e": 27158, "s": 27115, "text": "items = [\"GfG \", \"GfG \", \"GfG \", \"GfG \"];\n" }, { "code": "<div *ngFor=\"let item of items;let i=index\"> <p > {{item}} {{i}} </p></div>", "e": 27235, "s": 27158, "text": null }, { "code": null, "e": 27286, "s": 27235, "text": "Output:Here, the index starts from ‘0’ and not ‘1’" }, { "code": null, "e": 27306, "s": 27286, "text": "*ngFor with Indexes" }, { "code": null, "e": 27562, "s": 27306, "text": "4. *ngSwitch :ngSwitch is used to choose between multiple case statements defined by the expressions inside the *ngSwitchCase and display on the DOM Element according to that. If no expression is matched, the default case DOM Element is displayed. Syntax:" }, { "code": null, "e": 27723, "s": 27562, "text": "<div [ngSwitch]=\"expression\">\n <div *ngSwitchCase=\"expression_1\"></div> \n <div *ngSwitchCase=\"expression_2\"></div> \n <div *ngSwitchDefault></div> \n</div>\n" }, { "code": null, "e": 27918, "s": 27723, "text": "In the above syntax, the expression is checked with each case and then the case matching with the expression is rendered on DOM else the Default case is rendered on the DOM.Example of *ngSwitch:" }, { "code": "<div [ngSwitch]=\"'one'\"> <div *ngSwitchCase=\"'one'\">One is Displayed</div> <div *ngSwitchCase=\"'two'\">Two is Displayed</div> <div *ngSwitchDefault>Default Option is Displayed</div> </div>", "e": 28114, "s": 27918, "text": null }, { "code": null, "e": 28285, "s": 28114, "text": "In the above example, the expression ‘one’ in ngSwitch is matched to the expression in ngSwitchCase. Hence, the Element displayed on DOM is ” One is Displayed “. Output: " }, { "code": null, "e": 28308, "s": 28285, "text": "ngSwitch Case example " }, { "code": null, "e": 28329, "s": 28308, "text": "AngularJS-Directives" }, { "code": null, "e": 28339, "s": 28329, "text": "AngularJS" }, { "code": null, "e": 28356, "s": 28339, "text": "Web Technologies" }, { "code": null, "e": 28454, "s": 28356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28463, "s": 28454, "text": "Comments" }, { "code": null, "e": 28476, "s": 28463, "text": "Old Comments" }, { "code": null, "e": 28511, "s": 28476, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28564, "s": 28511, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28588, "s": 28564, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28637, "s": 28588, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 28680, "s": 28637, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 28736, "s": 28680, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28769, "s": 28736, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28831, "s": 28769, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28874, "s": 28831, "text": "How to fetch data from an API in ReactJS ?" } ]
Cheat-sheet for Google Colab. In this tutorial, you will learn how to... | by Tanu N Prabhu | Towards Data Science
Google Colab is an amazing tool that lets us build and execute an outstanding data science model and provides us with an opportunity to document our journey. As Google Colab provides us code cells to type the code, it also provides us with text cells to add the text. In this tutorial, we will focus more on the text cell and see how we can master it by using some simple commands that I will discuss in this tutorial. If you love documenting (like me) then you will enjoy reading this tutorial. You can start exploring Google Colab from below given link. Believe me, it’s an amazing tool. colab.research.google.com Below I will discuss some main handy tricks and shortcuts that can use and become a pro in documenting. If you know Markdown, XML, and HTML coding then this might be a cakewalk or if you are not familiar with either of those well today is the day to learn them all. Google Colab supports both Markdown and HTML documentation. You can any of these to document. Just a heads-up the whole code for this tutorial can also be found on my GitHub repository below: github.com All right, let’s get started. To experiment with all of these commands use the “Text cell” Below is the shortcut command for headings. There are different types of headings from Heading 1 to 6. Use # heading-name, the more you append # the size of the heading decreases as seen below: Similarly, you can use HTML tags such as h1, h2, h3, h4, h5 and h6 for headings as shown below: Bold make the text bolder and increases the text’s visibility. To make the text bold in markdown surround it by ** (two stars) for example **Text-to-be-bold** Using HTML we can bold the text by using the b tag as seen below: Similar to bold the text can also be italicized To make the text italicize in markdown surround it by * (one star) for example *Text-to-be-italicize* Also, this can be written in HTML using the i tag as shown below: Used to strike through the text. A horizontal line is drawn in the middle of the text. To strikethrough, the text in markdown surround the text with two tilde’s character ~~, such as ~~Text to be striked~~. In HTML we can use the s tag to strikethrough the text. Also, we can combine all the formatting commands and style the text as shown below. As we all know there are two types of lists: Ordered ListUnordered List Ordered List Unordered List As the name suggests an ordered list has an order (1, 2, 3,... or other). But an unordered list has no order, as shown below. In markdown for the ordered list, you can straightaway just type numbers like 1, 2, 3, and so on. But for the unordered list, you can start with a * and this intern creates a bullet list. We can use the HTML tags to play with the lists as shown below: In the ordered list there are normal list, type 1, A, a, I, i types as shown below: Normal list Use the ol tag and for the list contents use the li tag as shown below: Type = “1” Just add type = "1" inside the ol tag this will create an ordered list of 1, 2, 3, and so on. The list items will be numbered with numbers (default). Type = “A” Just add type = "A" inside the ol tag this will create an ordered list of A, B, C, and so on. The list items will be numbered with uppercase letters. Type = “a” Just add type = "a" inside the ol tag this will create an ordered list of a, b, c, and so on. The list items will be numbered with lowercase letters. Type = “I” Just add type = "I" inside the ol tag this will create an ordered list of I, II, III, and so on. The list items will be numbered with uppercase roman numbers. Type = “i” Just add type = "i" inside the ol tag this will create an ordered list of i, ii, iii, and so on. The list items will be numbered with lowercase roman numbers. In the ordered list there are normal list, disc, square, circle, and none types as shown below: Normal list Use the ul tag and for the list contents use the li tag as shown below: Disc Just add type = "disc" inside the ul tag to create a disc-shaped list. Circle Just add type = "circle" inside the ul tag to create a circle-shaped list. Square Just add type = "square" inside the ul tag to create a square-shaped list. None Just add type = "none" inside the ul tag to create a none-shaped list. In this case, the list will have no points as shown below A description list is a list of terms, with a description of each term. The dl tag consists dt which defines the name of the list and the dd tag describes each list. Nested lists are basically lists within lists. An ordered list will start counting from 1. If you want to count from a specified number, you can use the start attribute as shown below: To know more in-depth about the list in HTML please refer to the article below: www.w3schools.com Links or hyperlinks allow users to click their way from page to page. In markdown write the title of the link inside square brackets [ ] and write the webpage address inside round brackets or parenthesis ( ). Make sure you write the title first, followed by the link. In HTML for the hyperlinks, you can use the anchor a and href tag as shown below: Sometimes one image is worth one thousand words. People can easily understand the concepts better by seeing an image. Similar to the link you need to insert the link of the image inside the parenthesis. Make sure you append ! at the beginning. If your link is broken or not valid, then the alt text would be displayed. Image hover You can simultaneously hover on the text to see the title of the image. To do this, you can put the text of your choice inside the command as shown below: ![alt text](https://media.makeameme.org/created/online-class-cant.jpg "Online Class Memes") In HTML we can include an image using the img tag and you need to provide the source of the image to the src tag. Adjusting height and width You can adjust the height and width of the image. Also, you can embed a GIF image too as shown below. Images along with captions It’s a great practice to give credit to the images taken from different sources (I mean citing the images or providing the captions). With the help of figcaption tag we can provide captions to the images. You can play with the align tag and try to align the caption according to your preference. There are two things that you need to understand here are: Inline CodeSyntax highlighting Inline Code Syntax highlighting Sometimes you might want to insert a few code samples you can use Inline codes. To use the inline code, you can use the backticks (``). Surround it with backticks as shown above. This is used when you write huge lines of codes inside Google Colab’s text editor. Sometimes including huge python code snippets is not a good idea using inline codes, use syntax highlight in this case. You must embed the code within ```as shown below Default syntax highlighting This works irrespective of any programming language. Python syntax highlighting This can be used explicitly for python programming. You should include the name pythonat the beginning. Javascript syntax highlighting This can be used explicitly for JavaScript programming. You should include the name javascript at the beginning. C programming syntax highlighting This can be used explicitly for C programming. You should include the name c at the beginning. As seen above you can highlight the code snippets based on different programming languages. There are a few times you might want to represent the information in the form of tables. You must use the | as an operator for different columns. By default, the table headers would be in bold. Colons can be used to align columns. If you need to create any table then use the below tool to generate tables for you. All you have to do select the type of table generators such as Latex, HTML, Markdown, and others. Enter the contents inside the table and then click on Generate. You can then copy-paste the generated code in the text editor and see a beautiful table without minimum effort. www.tablesgenerator.com In the case of HTML, you must use the table tag along with tr which is for the table rows and th is for the table headers (Company Name and Founder) in this case. The td is for the table description. You can also use the align tag and align the contents accordingly. This is very useful when you need to differentiate some text like NOTE , HINT or any extra useful information. You need to use the > for the indentation. Similarly in HTML you can use the blockquote tag for the same purpose. It is often a wonderful practice to draw a horizontal ruler after every chapter, or any concept while you are writing. This just helps in differentiating things from one another. In case of markdown, you need to just use 3 --- (Minus). In case of HTML, you need to use the tag hr for inserting a horizontal ruler. Often many times you will write big paragraphs in your notebooks, but sometimes you might want to justify them just to make it look neat. Here, you can use the align tag with justify as a value. Similarly, you can use right , left , and center values and align the paragraph accordingly. Some times you might want to start a new paragraph, so you will need to put a line break in between both of them. There are two options here either you can just press the “Enter” key and leave a line of space in the between or you can use the br tag also called a line break. If you are using the notebooks for research purpose then you need to write a lot of equations and mathematical symbols. Make sure you write the symbol name between $ and start with \ after the first $. Follow the same rules i.e surround the equations between $ and start with / after the first $. To see more about the mathematical equations and symbols, please refer to the link below: csrgxtu.github.io All right, folks, that’s the end of the tutorial. I hope you learned many new things today. I tried to keep this tutorial short but as there were many concepts I had to maximize it. But this cheat-sheet will be useful in most of the interviews (technical documentation) or when you are documenting your Jupiter notebooks. If I find more tips and tricks, then I will provide the details here. Until then, stay safe and have a wonderful day. See you next time.
[ { "code": null, "e": 761, "s": 171, "text": "Google Colab is an amazing tool that lets us build and execute an outstanding data science model and provides us with an opportunity to document our journey. As Google Colab provides us code cells to type the code, it also provides us with text cells to add the text. In this tutorial, we will focus more on the text cell and see how we can master it by using some simple commands that I will discuss in this tutorial. If you love documenting (like me) then you will enjoy reading this tutorial. You can start exploring Google Colab from below given link. Believe me, it’s an amazing tool." }, { "code": null, "e": 787, "s": 761, "text": "colab.research.google.com" }, { "code": null, "e": 1245, "s": 787, "text": "Below I will discuss some main handy tricks and shortcuts that can use and become a pro in documenting. If you know Markdown, XML, and HTML coding then this might be a cakewalk or if you are not familiar with either of those well today is the day to learn them all. Google Colab supports both Markdown and HTML documentation. You can any of these to document. Just a heads-up the whole code for this tutorial can also be found on my GitHub repository below:" }, { "code": null, "e": 1256, "s": 1245, "text": "github.com" }, { "code": null, "e": 1286, "s": 1256, "text": "All right, let’s get started." }, { "code": null, "e": 1347, "s": 1286, "text": "To experiment with all of these commands use the “Text cell”" }, { "code": null, "e": 1450, "s": 1347, "text": "Below is the shortcut command for headings. There are different types of headings from Heading 1 to 6." }, { "code": null, "e": 1541, "s": 1450, "text": "Use # heading-name, the more you append # the size of the heading decreases as seen below:" }, { "code": null, "e": 1637, "s": 1541, "text": "Similarly, you can use HTML tags such as h1, h2, h3, h4, h5 and h6 for headings as shown below:" }, { "code": null, "e": 1700, "s": 1637, "text": "Bold make the text bolder and increases the text’s visibility." }, { "code": null, "e": 1796, "s": 1700, "text": "To make the text bold in markdown surround it by ** (two stars) for example **Text-to-be-bold**" }, { "code": null, "e": 1862, "s": 1796, "text": "Using HTML we can bold the text by using the b tag as seen below:" }, { "code": null, "e": 1910, "s": 1862, "text": "Similar to bold the text can also be italicized" }, { "code": null, "e": 2012, "s": 1910, "text": "To make the text italicize in markdown surround it by * (one star) for example *Text-to-be-italicize*" }, { "code": null, "e": 2078, "s": 2012, "text": "Also, this can be written in HTML using the i tag as shown below:" }, { "code": null, "e": 2165, "s": 2078, "text": "Used to strike through the text. A horizontal line is drawn in the middle of the text." }, { "code": null, "e": 2285, "s": 2165, "text": "To strikethrough, the text in markdown surround the text with two tilde’s character ~~, such as ~~Text to be striked~~." }, { "code": null, "e": 2341, "s": 2285, "text": "In HTML we can use the s tag to strikethrough the text." }, { "code": null, "e": 2425, "s": 2341, "text": "Also, we can combine all the formatting commands and style the text as shown below." }, { "code": null, "e": 2470, "s": 2425, "text": "As we all know there are two types of lists:" }, { "code": null, "e": 2497, "s": 2470, "text": "Ordered ListUnordered List" }, { "code": null, "e": 2510, "s": 2497, "text": "Ordered List" }, { "code": null, "e": 2525, "s": 2510, "text": "Unordered List" }, { "code": null, "e": 2651, "s": 2525, "text": "As the name suggests an ordered list has an order (1, 2, 3,... or other). But an unordered list has no order, as shown below." }, { "code": null, "e": 2839, "s": 2651, "text": "In markdown for the ordered list, you can straightaway just type numbers like 1, 2, 3, and so on. But for the unordered list, you can start with a * and this intern creates a bullet list." }, { "code": null, "e": 2903, "s": 2839, "text": "We can use the HTML tags to play with the lists as shown below:" }, { "code": null, "e": 2987, "s": 2903, "text": "In the ordered list there are normal list, type 1, A, a, I, i types as shown below:" }, { "code": null, "e": 2999, "s": 2987, "text": "Normal list" }, { "code": null, "e": 3071, "s": 2999, "text": "Use the ol tag and for the list contents use the li tag as shown below:" }, { "code": null, "e": 3082, "s": 3071, "text": "Type = “1”" }, { "code": null, "e": 3232, "s": 3082, "text": "Just add type = \"1\" inside the ol tag this will create an ordered list of 1, 2, 3, and so on. The list items will be numbered with numbers (default)." }, { "code": null, "e": 3243, "s": 3232, "text": "Type = “A”" }, { "code": null, "e": 3393, "s": 3243, "text": "Just add type = \"A\" inside the ol tag this will create an ordered list of A, B, C, and so on. The list items will be numbered with uppercase letters." }, { "code": null, "e": 3404, "s": 3393, "text": "Type = “a”" }, { "code": null, "e": 3554, "s": 3404, "text": "Just add type = \"a\" inside the ol tag this will create an ordered list of a, b, c, and so on. The list items will be numbered with lowercase letters." }, { "code": null, "e": 3565, "s": 3554, "text": "Type = “I”" }, { "code": null, "e": 3724, "s": 3565, "text": "Just add type = \"I\" inside the ol tag this will create an ordered list of I, II, III, and so on. The list items will be numbered with uppercase roman numbers." }, { "code": null, "e": 3735, "s": 3724, "text": "Type = “i”" }, { "code": null, "e": 3894, "s": 3735, "text": "Just add type = \"i\" inside the ol tag this will create an ordered list of i, ii, iii, and so on. The list items will be numbered with lowercase roman numbers." }, { "code": null, "e": 3990, "s": 3894, "text": "In the ordered list there are normal list, disc, square, circle, and none types as shown below:" }, { "code": null, "e": 4002, "s": 3990, "text": "Normal list" }, { "code": null, "e": 4074, "s": 4002, "text": "Use the ul tag and for the list contents use the li tag as shown below:" }, { "code": null, "e": 4079, "s": 4074, "text": "Disc" }, { "code": null, "e": 4150, "s": 4079, "text": "Just add type = \"disc\" inside the ul tag to create a disc-shaped list." }, { "code": null, "e": 4157, "s": 4150, "text": "Circle" }, { "code": null, "e": 4232, "s": 4157, "text": "Just add type = \"circle\" inside the ul tag to create a circle-shaped list." }, { "code": null, "e": 4239, "s": 4232, "text": "Square" }, { "code": null, "e": 4314, "s": 4239, "text": "Just add type = \"square\" inside the ul tag to create a square-shaped list." }, { "code": null, "e": 4319, "s": 4314, "text": "None" }, { "code": null, "e": 4448, "s": 4319, "text": "Just add type = \"none\" inside the ul tag to create a none-shaped list. In this case, the list will have no points as shown below" }, { "code": null, "e": 4614, "s": 4448, "text": "A description list is a list of terms, with a description of each term. The dl tag consists dt which defines the name of the list and the dd tag describes each list." }, { "code": null, "e": 4661, "s": 4614, "text": "Nested lists are basically lists within lists." }, { "code": null, "e": 4799, "s": 4661, "text": "An ordered list will start counting from 1. If you want to count from a specified number, you can use the start attribute as shown below:" }, { "code": null, "e": 4879, "s": 4799, "text": "To know more in-depth about the list in HTML please refer to the article below:" }, { "code": null, "e": 4897, "s": 4879, "text": "www.w3schools.com" }, { "code": null, "e": 4967, "s": 4897, "text": "Links or hyperlinks allow users to click their way from page to page." }, { "code": null, "e": 5165, "s": 4967, "text": "In markdown write the title of the link inside square brackets [ ] and write the webpage address inside round brackets or parenthesis ( ). Make sure you write the title first, followed by the link." }, { "code": null, "e": 5247, "s": 5165, "text": "In HTML for the hyperlinks, you can use the anchor a and href tag as shown below:" }, { "code": null, "e": 5365, "s": 5247, "text": "Sometimes one image is worth one thousand words. People can easily understand the concepts better by seeing an image." }, { "code": null, "e": 5566, "s": 5365, "text": "Similar to the link you need to insert the link of the image inside the parenthesis. Make sure you append ! at the beginning. If your link is broken or not valid, then the alt text would be displayed." }, { "code": null, "e": 5578, "s": 5566, "text": "Image hover" }, { "code": null, "e": 5733, "s": 5578, "text": "You can simultaneously hover on the text to see the title of the image. To do this, you can put the text of your choice inside the command as shown below:" }, { "code": null, "e": 5825, "s": 5733, "text": "![alt text](https://media.makeameme.org/created/online-class-cant.jpg \"Online Class Memes\")" }, { "code": null, "e": 5939, "s": 5825, "text": "In HTML we can include an image using the img tag and you need to provide the source of the image to the src tag." }, { "code": null, "e": 5966, "s": 5939, "text": "Adjusting height and width" }, { "code": null, "e": 6068, "s": 5966, "text": "You can adjust the height and width of the image. Also, you can embed a GIF image too as shown below." }, { "code": null, "e": 6095, "s": 6068, "text": "Images along with captions" }, { "code": null, "e": 6300, "s": 6095, "text": "It’s a great practice to give credit to the images taken from different sources (I mean citing the images or providing the captions). With the help of figcaption tag we can provide captions to the images." }, { "code": null, "e": 6391, "s": 6300, "text": "You can play with the align tag and try to align the caption according to your preference." }, { "code": null, "e": 6450, "s": 6391, "text": "There are two things that you need to understand here are:" }, { "code": null, "e": 6481, "s": 6450, "text": "Inline CodeSyntax highlighting" }, { "code": null, "e": 6493, "s": 6481, "text": "Inline Code" }, { "code": null, "e": 6513, "s": 6493, "text": "Syntax highlighting" }, { "code": null, "e": 6692, "s": 6513, "text": "Sometimes you might want to insert a few code samples you can use Inline codes. To use the inline code, you can use the backticks (``). Surround it with backticks as shown above." }, { "code": null, "e": 6944, "s": 6692, "text": "This is used when you write huge lines of codes inside Google Colab’s text editor. Sometimes including huge python code snippets is not a good idea using inline codes, use syntax highlight in this case. You must embed the code within ```as shown below" }, { "code": null, "e": 6972, "s": 6944, "text": "Default syntax highlighting" }, { "code": null, "e": 7025, "s": 6972, "text": "This works irrespective of any programming language." }, { "code": null, "e": 7052, "s": 7025, "text": "Python syntax highlighting" }, { "code": null, "e": 7156, "s": 7052, "text": "This can be used explicitly for python programming. You should include the name pythonat the beginning." }, { "code": null, "e": 7187, "s": 7156, "text": "Javascript syntax highlighting" }, { "code": null, "e": 7300, "s": 7187, "text": "This can be used explicitly for JavaScript programming. You should include the name javascript at the beginning." }, { "code": null, "e": 7334, "s": 7300, "text": "C programming syntax highlighting" }, { "code": null, "e": 7429, "s": 7334, "text": "This can be used explicitly for C programming. You should include the name c at the beginning." }, { "code": null, "e": 7521, "s": 7429, "text": "As seen above you can highlight the code snippets based on different programming languages." }, { "code": null, "e": 7610, "s": 7521, "text": "There are a few times you might want to represent the information in the form of tables." }, { "code": null, "e": 7715, "s": 7610, "text": "You must use the | as an operator for different columns. By default, the table headers would be in bold." }, { "code": null, "e": 7752, "s": 7715, "text": "Colons can be used to align columns." }, { "code": null, "e": 8110, "s": 7752, "text": "If you need to create any table then use the below tool to generate tables for you. All you have to do select the type of table generators such as Latex, HTML, Markdown, and others. Enter the contents inside the table and then click on Generate. You can then copy-paste the generated code in the text editor and see a beautiful table without minimum effort." }, { "code": null, "e": 8134, "s": 8110, "text": "www.tablesgenerator.com" }, { "code": null, "e": 8334, "s": 8134, "text": "In the case of HTML, you must use the table tag along with tr which is for the table rows and th is for the table headers (Company Name and Founder) in this case. The td is for the table description." }, { "code": null, "e": 8401, "s": 8334, "text": "You can also use the align tag and align the contents accordingly." }, { "code": null, "e": 8512, "s": 8401, "text": "This is very useful when you need to differentiate some text like NOTE , HINT or any extra useful information." }, { "code": null, "e": 8555, "s": 8512, "text": "You need to use the > for the indentation." }, { "code": null, "e": 8626, "s": 8555, "text": "Similarly in HTML you can use the blockquote tag for the same purpose." }, { "code": null, "e": 8805, "s": 8626, "text": "It is often a wonderful practice to draw a horizontal ruler after every chapter, or any concept while you are writing. This just helps in differentiating things from one another." }, { "code": null, "e": 8862, "s": 8805, "text": "In case of markdown, you need to just use 3 --- (Minus)." }, { "code": null, "e": 8940, "s": 8862, "text": "In case of HTML, you need to use the tag hr for inserting a horizontal ruler." }, { "code": null, "e": 9135, "s": 8940, "text": "Often many times you will write big paragraphs in your notebooks, but sometimes you might want to justify them just to make it look neat. Here, you can use the align tag with justify as a value." }, { "code": null, "e": 9228, "s": 9135, "text": "Similarly, you can use right , left , and center values and align the paragraph accordingly." }, { "code": null, "e": 9504, "s": 9228, "text": "Some times you might want to start a new paragraph, so you will need to put a line break in between both of them. There are two options here either you can just press the “Enter” key and leave a line of space in the between or you can use the br tag also called a line break." }, { "code": null, "e": 9624, "s": 9504, "text": "If you are using the notebooks for research purpose then you need to write a lot of equations and mathematical symbols." }, { "code": null, "e": 9706, "s": 9624, "text": "Make sure you write the symbol name between $ and start with \\ after the first $." }, { "code": null, "e": 9801, "s": 9706, "text": "Follow the same rules i.e surround the equations between $ and start with / after the first $." }, { "code": null, "e": 9891, "s": 9801, "text": "To see more about the mathematical equations and symbols, please refer to the link below:" }, { "code": null, "e": 9909, "s": 9891, "text": "csrgxtu.github.io" } ]
5 Extensions That Will Make You Switch to Jupyter Lab | by Frank Andrade | Towards Data Science
Jupyter Lab is known as Jupyter’s next-generation notebook interface. It integrates the notebook, console, text editor, and terminal into a single interactive and collaborative environment. Apart from bringing the classical notebooks and text editor, Jupyter Lab also offers third-party extensions. As we’ve seen in a previous article, Jupyter Notebook only provides a limited number of native extensions; however, Jupyter Lab contains a robust and thriving third-party extension community. In this guide, I’ll show you 5 extensions that will make you think about switching to Jupyter Lab. In case you’ve been using only Jupyter Notebooks and never heard of Jupyter Lab, below there’s a quick setup (jump to the extension section, in case you’re familiar with Jupyter Lab) Table of Contents1. Installing JupyterLab2. How to Install Extensions3. Extensions Available by Default on JupyterLab 3.0+4. Extension 1: JupyterLab Spreadsheet5. Extension 2: Interactive Graphs with Plotly and Chart Editor6. Extension 3: Drawing with JupyterLab-DrawIO7. Extension 4: Auto-completion to A Next Level with Kite8. Extension 5: Debugger As mentioned in its documentation, you can easily install Jupyter Lab with conda or pip. # condaconda install -c conda-forge jupyterlab# pippip install jupyterlab After the installation, run the following command to open Jupyter Lab jupyter lab There are two types of JupyterLab extensions: source extensions and prebuilt extensions. Source extensions require Node.js to be installed. According to the documentation, you can install Node.js with the following command. # condaconda install -c conda-forge nodejs# pippip install nodejs However, I still got the message “You need to install Node.js” when trying to install extensions. I solve this issue by downloading the “recommended for most users” Node.js from its website and installing it directly. Once you have Node.js, everything is set to install extensions. There are 2 ways to install extensions in Jupyter Lab. You can easily install extensions with the extensions manager. Just follow these steps. Click the extensions manager icon located on the left sidebar.Click on the “Enable” button.Search any library you want and then install it. Click the extensions manager icon located on the left sidebar. Click on the “Enable” button. Search any library you want and then install it. To install extensions, run the following code in the command prompt or terminal jupyter labextension install name-of-extension Instead of writingname-of-extension, you can also write the local directory containing the extension, a gzipped tarball, or a URL to a gzipped tarball. In case you want to specify a specific version, write name-of-extension@version, for example. jupyter labextension install name-of-extension@1.2.3 Note: After installing any extension, a message “A build is needed to include the latest changes” will show up below the search box. Make sure you click the “rebuild” button every time you install a new extension, then wait till a new message pop up and click “save and reload” Now it’s time to see the extension that I believe might tempt you to switch to Jupyter Lab! For JupyterLab 3.0 or above, there are some extensions available by default like a table of content. Also, as you can see in the gif below, it’s possible to drag each tab side-by-side, resize them, copy cells between notebooks, drag and drop cells, hide code, and change themes without installing any extension! By default, you can open multiple .csv files on Jupyter Lab; however, if you try to open a .xlsx file you’ll get an error. This is when you need to install a third-party extension called jupyterlab-spreadsheet To install it, just write jupyterlab-spreadsheet on the search box or run the command jupyter labextension install jupyterlab-spreadsheet. A spreadsheet in Jupyter Lab looks like this. Plotly is a graphing library that makes interactive graphs. It’s also available in Jupyter Notebook, but with the jupyterlab-chart-editor you can even edit Plotly charts through a user-friendly point-and-click interface. First, make sure you have the Plotly library installed (pip install plotly) and also JupyterLab has theipywidgets packages installed. #conda conda install jupyterlab "ipywidgets>=7.5"# pippip install jupyterlab "ipywidgets>=7.5" Then open up a terminal and run jupyter labextension install jupyterlab-plotly to install the Plotly extension. After this, you should be able to plot interactive graphs like the one below (use the code here to try your first plot) Now you can easily edit these Plotly graphs with JupyterLab-chart-editor. Open up a terminal and run jupyter labextension install jupyterlab-chart-editor to install the chart editor. To see it in action you have to save a Plotly figure you made to JSON pio.write_json(fig, 'example.plotly') In this example I made a file named ‘example.plotly’. To open it right-click ‘example.plotly’ from the file menu and open with "Plotly Editor". A window like this should open. Here you can make some changes and then use the file menu to save the file again and import it back to your original notebook. fig_styled = pio.read_json('example.plotly') Draw.io is a free online diagram software for making flowcharts, process diagrams, etc. With thejupyterlab-drawiothird-party app, you can have all the functionalities inside Jupyter Lab. To install it, just search jupyterlab-drawioor run the command jupyter labextension install jupyterlab-drawio. Then a new “Diagram” icon should show up in the Launcher tab. Click on it to open a new .dio file. Now you can draw anything you want! Kite takes auto-completion to a next level with fast completions that are context-aware of your code. Although Jupyter Notebook offers auto-completion, it contains some bugs that make writing code not as fluent as in your favorite text editor or IDE. Fortunately, with Kite you will get longer multi-line completions where you would typically get none. On top of that, you can view Python docs with just mouse-hover, plus find helpful examples and how-tos. To install it, make sure you have the following requirements: JupyterLab >=2.2.0 Kite Engine Python 3.6+ with pip To install the Kite Engine, go to their Github page and scroll down until the Installation section. Download the installer for your OS and install it like any program. If the installation was successful, you should see Kite among the installed extensions. Now write some code to see Kite’s autocompletion in action. To check all the text editors/IDE compatible open Kite, then go to settings, and click on plugins. A useful feature that most IDE support and Jupyter lacks is the debugger. It comes by default with Jupyter 3.0 +; however, if you don’t have it on Jupyter Lab, follow the steps below to install it. First, search jupyterlab/debuggeror run the command jupyter labextension install jupyterlab/debugger to install the debugger. Then, in the back-end, a kernel implementing the Jupyter Debug Protocol is required. For now, the only kernel implementing this protocol is xeus-python a new Jupyter kernel for the Python programming language. To install xeus-python, run the following command on the terminal. # condaconda install xeus-python -c conda-forge#pippip install xeus-python Just keep in mind that the pip option is still experimental. Once xeus-python and the debugger extension are installed, open a new xpython and click the bug icon on the right to expand the debugger. That’s it! Other cool extensions like Google Drive, Github, and language packs are also available. Make your life easier with a new extension! Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)
[ { "code": null, "e": 361, "s": 171, "text": "Jupyter Lab is known as Jupyter’s next-generation notebook interface. It integrates the notebook, console, text editor, and terminal into a single interactive and collaborative environment." }, { "code": null, "e": 761, "s": 361, "text": "Apart from bringing the classical notebooks and text editor, Jupyter Lab also offers third-party extensions. As we’ve seen in a previous article, Jupyter Notebook only provides a limited number of native extensions; however, Jupyter Lab contains a robust and thriving third-party extension community. In this guide, I’ll show you 5 extensions that will make you think about switching to Jupyter Lab." }, { "code": null, "e": 944, "s": 761, "text": "In case you’ve been using only Jupyter Notebooks and never heard of Jupyter Lab, below there’s a quick setup (jump to the extension section, in case you’re familiar with Jupyter Lab)" }, { "code": null, "e": 1295, "s": 944, "text": "Table of Contents1. Installing JupyterLab2. How to Install Extensions3. Extensions Available by Default on JupyterLab 3.0+4. Extension 1: JupyterLab Spreadsheet5. Extension 2: Interactive Graphs with Plotly and Chart Editor6. Extension 3: Drawing with JupyterLab-DrawIO7. Extension 4: Auto-completion to A Next Level with Kite8. Extension 5: Debugger" }, { "code": null, "e": 1384, "s": 1295, "text": "As mentioned in its documentation, you can easily install Jupyter Lab with conda or pip." }, { "code": null, "e": 1458, "s": 1384, "text": "# condaconda install -c conda-forge jupyterlab# pippip install jupyterlab" }, { "code": null, "e": 1528, "s": 1458, "text": "After the installation, run the following command to open Jupyter Lab" }, { "code": null, "e": 1540, "s": 1528, "text": "jupyter lab" }, { "code": null, "e": 1764, "s": 1540, "text": "There are two types of JupyterLab extensions: source extensions and prebuilt extensions. Source extensions require Node.js to be installed. According to the documentation, you can install Node.js with the following command." }, { "code": null, "e": 1830, "s": 1764, "text": "# condaconda install -c conda-forge nodejs# pippip install nodejs" }, { "code": null, "e": 2048, "s": 1830, "text": "However, I still got the message “You need to install Node.js” when trying to install extensions. I solve this issue by downloading the “recommended for most users” Node.js from its website and installing it directly." }, { "code": null, "e": 2167, "s": 2048, "text": "Once you have Node.js, everything is set to install extensions. There are 2 ways to install extensions in Jupyter Lab." }, { "code": null, "e": 2255, "s": 2167, "text": "You can easily install extensions with the extensions manager. Just follow these steps." }, { "code": null, "e": 2395, "s": 2255, "text": "Click the extensions manager icon located on the left sidebar.Click on the “Enable” button.Search any library you want and then install it." }, { "code": null, "e": 2458, "s": 2395, "text": "Click the extensions manager icon located on the left sidebar." }, { "code": null, "e": 2488, "s": 2458, "text": "Click on the “Enable” button." }, { "code": null, "e": 2537, "s": 2488, "text": "Search any library you want and then install it." }, { "code": null, "e": 2617, "s": 2537, "text": "To install extensions, run the following code in the command prompt or terminal" }, { "code": null, "e": 2664, "s": 2617, "text": "jupyter labextension install name-of-extension" }, { "code": null, "e": 2910, "s": 2664, "text": "Instead of writingname-of-extension, you can also write the local directory containing the extension, a gzipped tarball, or a URL to a gzipped tarball. In case you want to specify a specific version, write name-of-extension@version, for example." }, { "code": null, "e": 2963, "s": 2910, "text": "jupyter labextension install name-of-extension@1.2.3" }, { "code": null, "e": 3241, "s": 2963, "text": "Note: After installing any extension, a message “A build is needed to include the latest changes” will show up below the search box. Make sure you click the “rebuild” button every time you install a new extension, then wait till a new message pop up and click “save and reload”" }, { "code": null, "e": 3333, "s": 3241, "text": "Now it’s time to see the extension that I believe might tempt you to switch to Jupyter Lab!" }, { "code": null, "e": 3645, "s": 3333, "text": "For JupyterLab 3.0 or above, there are some extensions available by default like a table of content. Also, as you can see in the gif below, it’s possible to drag each tab side-by-side, resize them, copy cells between notebooks, drag and drop cells, hide code, and change themes without installing any extension!" }, { "code": null, "e": 3855, "s": 3645, "text": "By default, you can open multiple .csv files on Jupyter Lab; however, if you try to open a .xlsx file you’ll get an error. This is when you need to install a third-party extension called jupyterlab-spreadsheet" }, { "code": null, "e": 4040, "s": 3855, "text": "To install it, just write jupyterlab-spreadsheet on the search box or run the command jupyter labextension install jupyterlab-spreadsheet. A spreadsheet in Jupyter Lab looks like this." }, { "code": null, "e": 4261, "s": 4040, "text": "Plotly is a graphing library that makes interactive graphs. It’s also available in Jupyter Notebook, but with the jupyterlab-chart-editor you can even edit Plotly charts through a user-friendly point-and-click interface." }, { "code": null, "e": 4395, "s": 4261, "text": "First, make sure you have the Plotly library installed (pip install plotly) and also JupyterLab has theipywidgets packages installed." }, { "code": null, "e": 4490, "s": 4395, "text": "#conda conda install jupyterlab \"ipywidgets>=7.5\"# pippip install jupyterlab \"ipywidgets>=7.5\"" }, { "code": null, "e": 4722, "s": 4490, "text": "Then open up a terminal and run jupyter labextension install jupyterlab-plotly to install the Plotly extension. After this, you should be able to plot interactive graphs like the one below (use the code here to try your first plot)" }, { "code": null, "e": 4905, "s": 4722, "text": "Now you can easily edit these Plotly graphs with JupyterLab-chart-editor. Open up a terminal and run jupyter labextension install jupyterlab-chart-editor to install the chart editor." }, { "code": null, "e": 4975, "s": 4905, "text": "To see it in action you have to save a Plotly figure you made to JSON" }, { "code": null, "e": 5013, "s": 4975, "text": "pio.write_json(fig, 'example.plotly')" }, { "code": null, "e": 5189, "s": 5013, "text": "In this example I made a file named ‘example.plotly’. To open it right-click ‘example.plotly’ from the file menu and open with \"Plotly Editor\". A window like this should open." }, { "code": null, "e": 5316, "s": 5189, "text": "Here you can make some changes and then use the file menu to save the file again and import it back to your original notebook." }, { "code": null, "e": 5361, "s": 5316, "text": "fig_styled = pio.read_json('example.plotly')" }, { "code": null, "e": 5548, "s": 5361, "text": "Draw.io is a free online diagram software for making flowcharts, process diagrams, etc. With thejupyterlab-drawiothird-party app, you can have all the functionalities inside Jupyter Lab." }, { "code": null, "e": 5721, "s": 5548, "text": "To install it, just search jupyterlab-drawioor run the command jupyter labextension install jupyterlab-drawio. Then a new “Diagram” icon should show up in the Launcher tab." }, { "code": null, "e": 5794, "s": 5721, "text": "Click on it to open a new .dio file. Now you can draw anything you want!" }, { "code": null, "e": 6045, "s": 5794, "text": "Kite takes auto-completion to a next level with fast completions that are context-aware of your code. Although Jupyter Notebook offers auto-completion, it contains some bugs that make writing code not as fluent as in your favorite text editor or IDE." }, { "code": null, "e": 6251, "s": 6045, "text": "Fortunately, with Kite you will get longer multi-line completions where you would typically get none. On top of that, you can view Python docs with just mouse-hover, plus find helpful examples and how-tos." }, { "code": null, "e": 6313, "s": 6251, "text": "To install it, make sure you have the following requirements:" }, { "code": null, "e": 6332, "s": 6313, "text": "JupyterLab >=2.2.0" }, { "code": null, "e": 6344, "s": 6332, "text": "Kite Engine" }, { "code": null, "e": 6365, "s": 6344, "text": "Python 3.6+ with pip" }, { "code": null, "e": 6681, "s": 6365, "text": "To install the Kite Engine, go to their Github page and scroll down until the Installation section. Download the installer for your OS and install it like any program. If the installation was successful, you should see Kite among the installed extensions. Now write some code to see Kite’s autocompletion in action." }, { "code": null, "e": 6780, "s": 6681, "text": "To check all the text editors/IDE compatible open Kite, then go to settings, and click on plugins." }, { "code": null, "e": 6978, "s": 6780, "text": "A useful feature that most IDE support and Jupyter lacks is the debugger. It comes by default with Jupyter 3.0 +; however, if you don’t have it on Jupyter Lab, follow the steps below to install it." }, { "code": null, "e": 7381, "s": 6978, "text": "First, search jupyterlab/debuggeror run the command jupyter labextension install jupyterlab/debugger to install the debugger. Then, in the back-end, a kernel implementing the Jupyter Debug Protocol is required. For now, the only kernel implementing this protocol is xeus-python a new Jupyter kernel for the Python programming language. To install xeus-python, run the following command on the terminal." }, { "code": null, "e": 7456, "s": 7381, "text": "# condaconda install xeus-python -c conda-forge#pippip install xeus-python" }, { "code": null, "e": 7655, "s": 7456, "text": "Just keep in mind that the pip option is still experimental. Once xeus-python and the debugger extension are installed, open a new xpython and click the bug icon on the right to expand the debugger." }, { "code": null, "e": 7798, "s": 7655, "text": "That’s it! Other cool extensions like Google Drive, Github, and language packs are also available. Make your life easier with a new extension!" } ]
How to download image from url in Android?
This example demonstrates how do I download image from url in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true"> </ImageView> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/image" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/button" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.InputStream; public class MainActivity extends AppCompatActivity { String url = "https://images.pexels.com/photos/1226302/pexels-photo1226302.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"; ImageView image; Button button; ProgressDialog mProgressDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = (ImageView) findViewById(R.id.image); button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new DownloadImage().execute(url); } }); } private class DownloadImage extends AsyncTask { @Override protected void onPreExecute() { super.onPreExecute(); mProgressDialog = new ProgressDialog(MainActivity.this); mProgressDialog.setTitle("Download Image Tutorial"); mProgressDialog.setMessage("Loading..."); mProgressDialog.setIndeterminate(false); mProgressDialog.show(); } @Override protected Bitmap doInBackground(String... URL) { String imageURL = URL[0]; Bitmap bitmap = null; try { // Download Image from URL InputStream input = new java.net.URL(imageURL).openStream(); // Decode Bitmap bitmap = BitmapFactory.decodeStream(input); } catch (Exception e) { e.printStackTrace(); } return bitmap; } @Override protected void onPostExecute(Bitmap result) { // Set the bitmap into ImageView image.setImageBitmap(result); // Close progressdialog mProgressDialog.dismiss(); } } } Step 4 − Open resources -> string.xml and add the following code − <resources> <string name="app_name">Sample</string> <string name="menu_settings">Settings</string> <string name="button">Download Image</string> </resources> Step 5 − 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" ></uses-permission> <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": 1133, "s": 1062, "text": "This example demonstrates how do I download image from url in android." }, { "code": null, "e": 1262, "s": 1133, "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": 1327, "s": 1262, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2028, "s": 1327, "text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" >\n <ImageView\n android:id=\"@+id/image\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\">\n </ImageView>\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/image\"\n android:layout_centerHorizontal=\"true\"\n android:layout_centerVertical=\"true\"\n android:text=\"@string/button\" />\n</RelativeLayout>" }, { "code": null, "e": 2085, "s": 2028, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4198, "s": 2085, "text": "import android.app.ProgressDialog;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.os.AsyncTask;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport java.io.InputStream;\npublic class MainActivity extends AppCompatActivity {\n String url = \"https://images.pexels.com/photos/1226302/pexels-photo1226302.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500\";\n ImageView image;\n Button button;\n ProgressDialog mProgressDialog;\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n image = (ImageView) findViewById(R.id.image);\n button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n new DownloadImage().execute(url);\n }\n });\n }\n private class DownloadImage extends AsyncTask {\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n mProgressDialog = new ProgressDialog(MainActivity.this);\n mProgressDialog.setTitle(\"Download Image Tutorial\");\n mProgressDialog.setMessage(\"Loading...\");\n mProgressDialog.setIndeterminate(false);\n mProgressDialog.show();\n }\n @Override\n protected Bitmap doInBackground(String... URL) {\n String imageURL = URL[0];\n Bitmap bitmap = null;\n try {\n // Download Image from URL\n InputStream input = new java.net.URL(imageURL).openStream();\n // Decode Bitmap\n bitmap = BitmapFactory.decodeStream(input);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return bitmap;\n }\n @Override\n protected void onPostExecute(Bitmap result) {\n // Set the bitmap into ImageView\n image.setImageBitmap(result);\n // Close progressdialog\n mProgressDialog.dismiss();\n }\n }\n}" }, { "code": null, "e": 4265, "s": 4198, "text": "Step 4 − Open resources -> string.xml and add the following code −" }, { "code": null, "e": 4432, "s": 4265, "text": "<resources>\n <string name=\"app_name\">Sample</string>\n <string name=\"menu_settings\">Settings</string>\n <string name=\"button\">Download Image</string>\n</resources>" }, { "code": null, "e": 4487, "s": 4432, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5240, "s": 4487, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <uses-permission android:name=\"android.permission.INTERNET\" ></uses-permission>\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": 5587, "s": 5240, "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": 5628, "s": 5587, "text": "Click here to download the project code." } ]
F# - Structures
A structure in F# is a value type data type. It helps you to make a single variable, hold related data of various data types. The struct keyword is used for creating a structure. Syntax for defining a structure is as follows − [ attributes ] type [accessibility-modifier] type-name = struct type-definition-elements end // or [ attributes ] [<StructAttribute>] type [accessibility-modifier] type-name = type-definition-elements There are two syntaxes. The first syntax is mostly used, because, if you use the struct and end keywords, you can omit the StructAttribute attribute. The structure definition elements provide − Member declarations and definitions. Constructors and mutable and immutable fields. Members and interface implementations. Unlike classes, structures cannot be inherited and cannot contain let or do bindings. Since, structures do not have let bindings; you must declare fields in structures by using the val keyword. When you define a field and its type using val keyword, you cannot initialize the field value, instead they are initialized to zero or null. So for a structure having an implicit constructor, the val declarations be annotated with the DefaultValue attribute. The following program creates a line structure along with a constructor. The program calculates the length of a line using the structure − type Line = struct val X1 : float val Y1 : float val X2 : float val Y2 : float new (x1, y1, x2, y2) = {X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;} end let calcLength(a : Line)= let sqr a = a * a sqrt(sqr(a.X1 - a.X2) + sqr(a.Y1 - a.Y2) ) let aLine = new Line(1.0, 1.0, 4.0, 5.0) let length = calcLength aLine printfn "Length of the Line: %g " length When you compile and execute the program, it yields the following output − Length of the Line: 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2340, "s": 2161, "text": "A structure in F# is a value type data type. It helps you to make a single variable, hold related data of various data types. The struct keyword is used for creating a structure." }, { "code": null, "e": 2388, "s": 2340, "text": "Syntax for defining a structure is as follows −" }, { "code": null, "e": 2605, "s": 2388, "text": "[ attributes ]\ntype [accessibility-modifier] type-name =\n struct\n type-definition-elements\n end\n// or\n[ attributes ]\n[<StructAttribute>]\ntype [accessibility-modifier] type-name =\n type-definition-elements\n" }, { "code": null, "e": 2755, "s": 2605, "text": "There are two syntaxes. The first syntax is mostly used, because, if you use the struct and end keywords, you can omit the StructAttribute attribute." }, { "code": null, "e": 2799, "s": 2755, "text": "The structure definition elements provide −" }, { "code": null, "e": 2836, "s": 2799, "text": "Member declarations and definitions." }, { "code": null, "e": 2883, "s": 2836, "text": "Constructors and mutable and immutable fields." }, { "code": null, "e": 2922, "s": 2883, "text": "Members and interface implementations." }, { "code": null, "e": 3116, "s": 2922, "text": "Unlike classes, structures cannot be inherited and cannot contain let or do bindings. Since, structures do not have let bindings; you must declare fields in structures by using the val keyword." }, { "code": null, "e": 3375, "s": 3116, "text": "When you define a field and its type using val keyword, you cannot initialize the field value, instead they are initialized to zero or null. So for a structure having an implicit constructor, the val declarations be annotated with the DefaultValue attribute." }, { "code": null, "e": 3514, "s": 3375, "text": "The following program creates a line structure along with a constructor. The program calculates the length of a line using the structure −" }, { "code": null, "e": 3886, "s": 3514, "text": "type Line = struct\n val X1 : float\n val Y1 : float\n val X2 : float\n val Y2 : float\n\n new (x1, y1, x2, y2) =\n {X1 = x1; Y1 = y1; X2 = x2; Y2 = y2;}\nend\nlet calcLength(a : Line)=\n let sqr a = a * a\n sqrt(sqr(a.X1 - a.X2) + sqr(a.Y1 - a.Y2) )\n\nlet aLine = new Line(1.0, 1.0, 4.0, 5.0)\nlet length = calcLength aLine\nprintfn \"Length of the Line: %g \" length" }, { "code": null, "e": 3961, "s": 3886, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3984, "s": 3961, "text": "Length of the Line: 5\n" }, { "code": null, "e": 3991, "s": 3984, "text": " Print" }, { "code": null, "e": 4002, "s": 3991, "text": " Add Notes" } ]