title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
VBA - Join Function
A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method. Join(List[,delimiter]) List − A required parameter. An array that contains the substrings that are to be joined. List − A required parameter. An array that contains the substrings that are to be joined. Delimiter − An optional parameter. The character, which used as a delimiter while returning the string. The default delimiter is Space. Delimiter − An optional parameter. The character, which used as a delimiter while returning the string. The default delimiter is Space. Add a button and add the following function. Private Sub Constant_demo_Click() ' Join using spaces a = array("Red","Blue","Yellow") b = join(a) msgbox("The value of b " & " is :" & b) ' Join using $ b = join(a,"$") msgbox("The Join result after using delimiter is : " & b) End Sub When you execute the above function, it produces the following output. The value of b is :Red Blue Yellow The Join result after using delimiter is : Red$Blue$Yellow 101 Lectures 6 hours Pavan Lalwani 41 Lectures 3 hours Arnold Higuit 80 Lectures 5.5 hours Prashant Panchal 25 Lectures 2 hours Prashant Panchal 26 Lectures 2 hours Arnold Higuit 92 Lectures 10.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2082, "s": 1935, "text": "A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method." }, { "code": null, "e": 2107, "s": 2082, "text": "Join(List[,delimiter]) \n" }, { "code": null, "e": 2197, "s": 2107, "text": "List − A required parameter. An array that contains the substrings that are to be joined." }, { "code": null, "e": 2287, "s": 2197, "text": "List − A required parameter. An array that contains the substrings that are to be joined." }, { "code": null, "e": 2423, "s": 2287, "text": "Delimiter − An optional parameter. The character, which used as a delimiter while returning the string. The default delimiter is Space." }, { "code": null, "e": 2559, "s": 2423, "text": "Delimiter − An optional parameter. The character, which used as a delimiter while returning the string. The default delimiter is Space." }, { "code": null, "e": 2604, "s": 2559, "text": "Add a button and add the following function." }, { "code": null, "e": 2865, "s": 2604, "text": "Private Sub Constant_demo_Click()\n ' Join using spaces\n a = array(\"Red\",\"Blue\",\"Yellow\")\n b = join(a)\n msgbox(\"The value of b \" & \" is :\" & b)\n \n ' Join using $\n b = join(a,\"$\")\n msgbox(\"The Join result after using delimiter is : \" & b)\nEnd Sub" }, { "code": null, "e": 2936, "s": 2865, "text": "When you execute the above function, it produces the following output." }, { "code": null, "e": 3031, "s": 2936, "text": "The value of b is :Red Blue Yellow\nThe Join result after using delimiter is : Red$Blue$Yellow\n" }, { "code": null, "e": 3065, "s": 3031, "text": "\n 101 Lectures \n 6 hours \n" }, { "code": null, "e": 3080, "s": 3065, "text": " Pavan Lalwani" }, { "code": null, "e": 3113, "s": 3080, "text": "\n 41 Lectures \n 3 hours \n" }, { "code": null, "e": 3128, "s": 3113, "text": " Arnold Higuit" }, { "code": null, "e": 3163, "s": 3128, "text": "\n 80 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3181, "s": 3163, "text": " Prashant Panchal" }, { "code": null, "e": 3214, "s": 3181, "text": "\n 25 Lectures \n 2 hours \n" }, { "code": null, "e": 3232, "s": 3214, "text": " Prashant Panchal" }, { "code": null, "e": 3265, "s": 3232, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 3280, "s": 3265, "text": " Arnold Higuit" }, { "code": null, "e": 3316, "s": 3280, "text": "\n 92 Lectures \n 10.5 hours \n" }, { "code": null, "e": 3344, "s": 3316, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3351, "s": 3344, "text": " Print" }, { "code": null, "e": 3362, "s": 3351, "text": " Add Notes" } ]
AWT TextField Class
The textField component allows the user to edit single line of text.When the user types a key in the text field the event is sent to the TextField. The key event may be key pressed, Key released or key typed. The key event is passed to the registered KeyListener. It is also possible to for an ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by pressing the return key. Following is the declaration for java.awt.TextField class: public class TextField extends TextComponent TextField() Constructs a new text field. TextField(int columns) Constructs a new empty text field with the specified number of columns. TextField(String text) Constructs a new text field initialized with the specified text. TextField(String text, int columns) Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns. void addActionListener(ActionListener l) Adds the specified action listener to receive action events from this text field. void addNotify() Creates the TextField's peer. boolean echoCharIsSet() Indicates whether or not this text field has a character set for echoing. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this TextField. ActionListener[] getActionListeners() Returns an array of all the action listeners registered on this textfield. int getColumns() Gets the number of columns in this text field. char getEchoChar() Gets the character that is to be used for echoing. <T extends EventListener> T[] getListeners(Class<T> listenerType) Returns an array of all the objects currently registered as FooListeners upon this TextField. Dimension getMinimumSize() Gets the minumum dimensions for this text field. Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text field with the specified number of columns. Dimension getPreferredSize() Gets the preferred size of this text field. Dimension getPreferredSize(int columns) Gets the preferred size of this text field with the specified number of columns. Dimension minimumSize() Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). Dimension minimumSize(int columns) Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int). protected String paramString() Returns a string representing the state of this TextField. Dimension preferredSize() Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). Dimension preferredSize(int columns) Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int). protected void processActionEvent(ActionEvent e) Processes action events occurring on this text field by dispatching them to any registered ActionListener objects. protected void processEvent(AWTEvent e) Processes events on this text field. void removeActionListener(ActionListener l) Removes the specified action listener so that it no longer receives action events from this text field. void setColumns(int columns) Sets the number of columns in this text field. void setEchoChar(char c) Sets the echo character for this text field. void setEchoCharacter(char c) Deprecated. As of JDK version 1.1, replaced by setEchoChar(char). void setText(String t) Sets the text that is presented by this text component to be the specified text. This class inherits methods from the following classes: java.awt.TextComponent java.awt.TextComponent java.awt.Component java.awt.Component java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showTextFieldDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showTextFieldDemo(){ headerLabel.setText("Control in action: TextField"); Label namelabel= new Label("User ID: ", Label.RIGHT); Label passwordLabel = new Label("Password: ", Label.CENTER); final TextField userText = new TextField(6); final TextField passwordText = new TextField(6); passwordText.setEchoChar('*'); Button loginButton = new Button("Login"); loginButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String data = "Username: " + userText.getText(); data += ", Password: " + passwordText.getText(); statusLabel.setText(data); } }); controlPanel.add(namelabel); controlPanel.add(userText); controlPanel.add(passwordLabel); controlPanel.add(passwordText); controlPanel.add(loginButton); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 2159, "s": 1747, "text": "The textField component allows the user to edit single line of text.When the user types a key in the text field the event is sent to the TextField. The key event may be key pressed, Key released or key typed. The key event is passed to the registered KeyListener. It is also possible to for an ActionEvent if the ActionEvent is enabled on the textfield then ActionEvent may be fired by pressing the return key." }, { "code": null, "e": 2218, "s": 2159, "text": "Following is the declaration for java.awt.TextField class:" }, { "code": null, "e": 2266, "s": 2218, "text": "public class TextField\n extends TextComponent" }, { "code": null, "e": 2279, "s": 2266, "text": "TextField() " }, { "code": null, "e": 2309, "s": 2279, "text": " Constructs a new text field." }, { "code": null, "e": 2332, "s": 2309, "text": "TextField(int columns)" }, { "code": null, "e": 2404, "s": 2332, "text": "Constructs a new empty text field with the specified number of columns." }, { "code": null, "e": 2429, "s": 2404, "text": "TextField(String text) " }, { "code": null, "e": 2494, "s": 2429, "text": "Constructs a new text field initialized with the specified text." }, { "code": null, "e": 2532, "s": 2494, "text": "TextField(String text, int columns) " }, { "code": null, "e": 2670, "s": 2532, "text": "Constructs a new text field initialized with the specified text to be displayed, and wide enough to hold the specified number of columns." }, { "code": null, "e": 2712, "s": 2670, "text": "void addActionListener(ActionListener l) " }, { "code": null, "e": 2794, "s": 2712, "text": "Adds the specified action listener to receive action events from this text field." }, { "code": null, "e": 2812, "s": 2794, "text": "void addNotify() " }, { "code": null, "e": 2842, "s": 2812, "text": "Creates the TextField's peer." }, { "code": null, "e": 2867, "s": 2842, "text": "boolean echoCharIsSet() " }, { "code": null, "e": 2941, "s": 2867, "text": "Indicates whether or not this text field has a character set for echoing." }, { "code": null, "e": 2983, "s": 2941, "text": "AccessibleContext getAccessibleContext() " }, { "code": null, "e": 3042, "s": 2983, "text": "Gets the AccessibleContext associated with this TextField." }, { "code": null, "e": 3081, "s": 3042, "text": "ActionListener[] getActionListeners() " }, { "code": null, "e": 3156, "s": 3081, "text": "Returns an array of all the action listeners registered on this textfield." }, { "code": null, "e": 3174, "s": 3156, "text": "int getColumns() " }, { "code": null, "e": 3221, "s": 3174, "text": "Gets the number of columns in this text field." }, { "code": null, "e": 3241, "s": 3221, "text": "char getEchoChar() " }, { "code": null, "e": 3292, "s": 3241, "text": "Gets the character that is to be used for echoing." }, { "code": null, "e": 3359, "s": 3292, "text": "<T extends EventListener> T[] getListeners(Class<T> listenerType) " }, { "code": null, "e": 3453, "s": 3359, "text": "Returns an array of all the objects currently registered as FooListeners upon this TextField." }, { "code": null, "e": 3481, "s": 3453, "text": "Dimension getMinimumSize() " }, { "code": null, "e": 3530, "s": 3481, "text": "Gets the minumum dimensions for this text field." }, { "code": null, "e": 3651, "s": 3530, "text": "Dimension getMinimumSize(int columns) Gets the minumum dimensions for a text field with the specified number of columns." }, { "code": null, "e": 3681, "s": 3651, "text": "Dimension getPreferredSize() " }, { "code": null, "e": 3725, "s": 3681, "text": "Gets the preferred size of this text field." }, { "code": null, "e": 3766, "s": 3725, "text": "Dimension getPreferredSize(int columns) " }, { "code": null, "e": 3847, "s": 3766, "text": "Gets the preferred size of this text field with the specified number of columns." }, { "code": null, "e": 3872, "s": 3847, "text": "Dimension minimumSize() " }, { "code": null, "e": 3938, "s": 3872, "text": " Deprecated. As of JDK version 1.1, replaced by getMinimumSize()." }, { "code": null, "e": 3974, "s": 3938, "text": "Dimension minimumSize(int columns) " }, { "code": null, "e": 4042, "s": 3974, "text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int)." }, { "code": null, "e": 4074, "s": 4042, "text": "protected String paramString() " }, { "code": null, "e": 4133, "s": 4074, "text": "Returns a string representing the state of this TextField." }, { "code": null, "e": 4160, "s": 4133, "text": "Dimension preferredSize() " }, { "code": null, "e": 4227, "s": 4160, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize()." }, { "code": null, "e": 4265, "s": 4227, "text": "Dimension preferredSize(int columns) " }, { "code": null, "e": 4335, "s": 4265, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int)." }, { "code": null, "e": 4385, "s": 4335, "text": "protected void processActionEvent(ActionEvent e) " }, { "code": null, "e": 4500, "s": 4385, "text": "Processes action events occurring on this text field by dispatching them to any registered ActionListener objects." }, { "code": null, "e": 4541, "s": 4500, "text": "protected void processEvent(AWTEvent e) " }, { "code": null, "e": 4578, "s": 4541, "text": "Processes events on this text field." }, { "code": null, "e": 4623, "s": 4578, "text": "void removeActionListener(ActionListener l) " }, { "code": null, "e": 4727, "s": 4623, "text": "Removes the specified action listener so that it no longer receives action events from this text field." }, { "code": null, "e": 4757, "s": 4727, "text": "void setColumns(int columns) " }, { "code": null, "e": 4804, "s": 4757, "text": "Sets the number of columns in this text field." }, { "code": null, "e": 4831, "s": 4804, "text": "void setEchoChar(char c) \n" }, { "code": null, "e": 4876, "s": 4831, "text": "Sets the echo character for this text field." }, { "code": null, "e": 4907, "s": 4876, "text": "void setEchoCharacter(char c) " }, { "code": null, "e": 4973, "s": 4907, "text": "Deprecated. As of JDK version 1.1, replaced by setEchoChar(char)." }, { "code": null, "e": 4997, "s": 4973, "text": "void setText(String t) " }, { "code": null, "e": 5078, "s": 4997, "text": "Sets the text that is presented by this text component to be the specified text." }, { "code": null, "e": 5134, "s": 5078, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 5157, "s": 5134, "text": "java.awt.TextComponent" }, { "code": null, "e": 5180, "s": 5157, "text": "java.awt.TextComponent" }, { "code": null, "e": 5199, "s": 5180, "text": "java.awt.Component" }, { "code": null, "e": 5218, "s": 5199, "text": "java.awt.Component" }, { "code": null, "e": 5235, "s": 5218, "text": "java.lang.Object" }, { "code": null, "e": 5252, "s": 5235, "text": "java.lang.Object" }, { "code": null, "e": 5366, "s": 5252, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 7539, "s": 5366, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showTextFieldDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showTextFieldDemo(){\n headerLabel.setText(\"Control in action: TextField\"); \n\n Label namelabel= new Label(\"User ID: \", Label.RIGHT);\n Label passwordLabel = new Label(\"Password: \", Label.CENTER);\n final TextField userText = new TextField(6);\n final TextField passwordText = new TextField(6);\n passwordText.setEchoChar('*');\n\n Button loginButton = new Button(\"Login\");\n \n loginButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) { \n String data = \"Username: \" + userText.getText();\n data += \", Password: \" + passwordText.getText();\n statusLabel.setText(data); \n }\n }); \n\n controlPanel.add(namelabel);\n controlPanel.add(userText);\n controlPanel.add(passwordLabel); \n controlPanel.add(passwordText);\n controlPanel.add(loginButton);\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 7630, "s": 7539, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 7686, "s": 7630, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java" }, { "code": null, "e": 7783, "s": 7686, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 7833, "s": 7783, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo" }, { "code": null, "e": 7861, "s": 7833, "text": "Verify the following output" }, { "code": null, "e": 7894, "s": 7861, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 7902, "s": 7894, "text": " EduOLC" }, { "code": null, "e": 7909, "s": 7902, "text": " Print" }, { "code": null, "e": 7920, "s": 7909, "text": " Add Notes" } ]
Java break Keyword
❮ Java Keywords End the loop when i is equal to 4: for (int i = 0; i < 10; i++) { if (i == 4) { break; } System.out.println(i); } Try it Yourself » The break keyword is used to break out a for loop, a while loop or a switch block. Break out of a while loop: int i = 0;while (i < 10) { System.out.println(i); i++; if (i == 4) { break; } } Try it Yourself » Use the continue keyword to end the current iteration in a loop, but continue with the next. Read more about for loops in our Java For Loops Tutorial. Read more about while loops in our Java While Loops Tutorial. Read more about break and continue in our Java Break Tutorial. ❮ Java Keywords 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": 18, "s": 0, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 53, "s": 18, "text": "End the loop when i is equal to 4:" }, { "code": null, "e": 143, "s": 53, "text": "for (int i = 0; i < 10; i++) {\n if (i == 4) {\n break;\n }\n System.out.println(i);\n}\n" }, { "code": null, "e": 163, "s": 143, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 247, "s": 163, "text": "The break keyword is used to break out a\nfor loop, a while \nloop or a switch block." }, { "code": null, "e": 274, "s": 247, "text": "Break out of a while loop:" }, { "code": null, "e": 367, "s": 274, "text": "int i = 0;while (i < 10) {\n System.out.println(i);\n i++;\n if (i == 4) {\n break;\n }\n}\n" }, { "code": null, "e": 387, "s": 367, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 481, "s": 387, "text": "Use the continue \nkeyword to end the current iteration in a loop, but continue with the next." }, { "code": null, "e": 539, "s": 481, "text": "Read more about for loops in our Java For Loops Tutorial." }, { "code": null, "e": 601, "s": 539, "text": "Read more about while loops in our Java While Loops Tutorial." }, { "code": null, "e": 664, "s": 601, "text": "Read more about break and continue in our Java Break Tutorial." }, { "code": null, "e": 682, "s": 664, "text": "\n❮ Java Keywords\n" }, { "code": null, "e": 715, "s": 682, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 757, "s": 715, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 864, "s": 757, "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": 883, "s": 864, "text": "help@w3schools.com" } ]
How to create histogram with relative frequency in R?
The relative frequency histogram can be created for the column of an R data frame or a vector that contains discrete data. For this purpose, we can use PlotRelativeFrequency function of HistogramTools package along with hist function to generate histogram. For example, if we have a vector x for which we want to create a histogram with relative frequencies then it can be done as PlotRelativeFrequency(hist(x)). Consider the below vector − Live Demo x<-sample(1:5,20,replace=TRUE) x [1] 2 1 1 4 3 5 5 4 1 3 5 1 4 1 3 4 4 1 1 1 Loading HistogramTools package and creating histogram of x with relative frequency − library("HistogramTools") PlotRelativeFrequency(hist(x)) Live Demo y<-sample(1:10,100,replace=TRUE) y [1] 7 6 8 9 5 1 2 9 6 7 2 1 3 3 6 7 7 4 9 5 10 5 10 6 6 [26] 4 10 9 5 1 9 7 9 9 2 7 8 8 10 10 8 5 9 8 3 6 9 8 9 10 [51] 6 6 6 4 8 8 6 10 2 7 6 5 1 8 7 9 2 6 2 9 2 5 8 3 2 [76] 3 2 4 5 9 5 5 9 4 2 6 3 10 3 2 7 9 4 8 10 6 5 8 8 2 PlotRelativeFrequency(hist(y))
[ { "code": null, "e": 1475, "s": 1062, "text": "The relative frequency histogram can be created for the column of an R data frame or a vector that contains discrete data. For this purpose, we can use PlotRelativeFrequency function of HistogramTools package along with hist function to generate histogram. For example, if we have a vector x for which we want to create a histogram with relative frequencies then it can be done as PlotRelativeFrequency(hist(x))." }, { "code": null, "e": 1503, "s": 1475, "text": "Consider the below vector −" }, { "code": null, "e": 1514, "s": 1503, "text": " Live Demo" }, { "code": null, "e": 1547, "s": 1514, "text": "x<-sample(1:5,20,replace=TRUE)\nx" }, { "code": null, "e": 1591, "s": 1547, "text": "[1] 2 1 1 4 3 5 5 4 1 3 5 1 4 1 3 4 4 1 1 1" }, { "code": null, "e": 1676, "s": 1591, "text": "Loading HistogramTools package and creating histogram of x with relative frequency −" }, { "code": null, "e": 1733, "s": 1676, "text": "library(\"HistogramTools\")\nPlotRelativeFrequency(hist(x))" }, { "code": null, "e": 1744, "s": 1733, "text": " Live Demo" }, { "code": null, "e": 1779, "s": 1744, "text": "y<-sample(1:10,100,replace=TRUE)\ny" }, { "code": null, "e": 2007, "s": 1779, "text": "[1] 7 6 8 9 5 1 2 9 6 7 2 1 3 3 6 7 7 4 9 5 10 5 10 6 6\n[26] 4 10 9 5 1 9 7 9 9 2 7 8 8 10 10 8 5 9 8 3 6 9 8 9 10\n[51] 6 6 6 4 8 8 6 10 2 7 6 5 1 8 7 9 2 6 2 9 2 5 8 3 2\n[76] 3 2 4 5 9 5 5 9 4 2 6 3 10 3 2 7 9 4 8 10 6 5 8 8 2" }, { "code": null, "e": 2038, "s": 2007, "text": "PlotRelativeFrequency(hist(y))" } ]
Second most repeated word in a sequence - GeeksforGeeks
04 Apr, 2022 Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence.(Considering no two words are the second most repeated, there will be always a single word). Examples: Input : {"aaa", "bbb", "ccc", "bbb", "aaa", "aaa"} Output : bbb Input : {"geeks", "for", "geeks", "for", "geeks", "aaa"} Output : for Asked in : Amazon C++ Java Python3 C# Javascript // C++ program to find out the second// most repeated word#include <bits/stdc++.h>using namespace std; // Function to find the wordstring secMostRepeated(vector<string> seq){ // Store all the words with its occurrence unordered_map<string, int> occ; for (int i = 0; i < seq.size(); i++) occ[seq[i]]++; // find the second largest occurrence int first_max = INT_MIN, sec_max = INT_MIN; for (auto it = occ.begin(); it != occ.end(); it++) { if (it->second > first_max) { sec_max = first_max; first_max = it->second; } else if (it->second > sec_max && it->second != first_max) sec_max = it->second; } // Return string with occurrence equals // to sec_max for (auto it = occ.begin(); it != occ.end(); it++) if (it->second == sec_max) return it->first;} // Driver programint main(){ vector<string> seq = { "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" }; cout << secMostRepeated(seq); return 0;} // Java program to find out the second// most repeated word import java.util.*; class GFG{ // Method to find the word static String secMostRepeated(Vector<String> seq) { // Store all the words with its occurrence HashMap<String, Integer> occ = new HashMap<String,Integer>(seq.size()){ @Override public Integer get(Object key) { return containsKey(key) ? super.get(key) : 0; } }; for (int i = 0; i < seq.size(); i++) occ.put(seq.get(i), occ.get(seq.get(i))+1); // find the second largest occurrence int first_max = Integer.MIN_VALUE, sec_max = Integer.MIN_VALUE; Iterator<Map.Entry<String, Integer>> itr = occ.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Integer> entry = itr.next(); int v = entry.getValue(); if( v > first_max) { sec_max = first_max; first_max = v; } else if (v > sec_max && v != first_max) sec_max = v; } // Return string with occurrence equals // to sec_max itr = occ.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Integer> entry = itr.next(); int v = entry.getValue(); if (v == sec_max) return entry.getKey(); } return null; } // Driver method public static void main(String[] args) { String arr[] = { "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" }; List<String> seq = Arrays.asList(arr); System.out.println(secMostRepeated(new Vector<>(seq))); } }// This program is contributed by Gaurav Miglani # Python3 program to find out the second# most repeated word # Function to find the worddef secMostRepeated(seq): # Store all the words with its occurrence occ = {} for i in range(len(seq)): occ[seq[i]] = occ.get(seq[i], 0) + 1 # Find the second largest occurrence first_max = -10**8 sec_max = -10**8 for it in occ: if (occ[it] > first_max): sec_max = first_max first_max = occ[it] elif (occ[it] > sec_max and occ[it] != first_max): sec_max = occ[it] # Return with occurrence equals # to sec_max for it in occ: if (occ[it] == sec_max): return it # Driver codeif __name__ == '__main__': seq = [ "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" ] print(secMostRepeated(seq)) # This code is contributed by mohit kumar 29 // C# program to find out the second// most repeated wordusing System;using System.Collections.Generic; class GFG{ // Method to find the word static String secMostRepeated(List<String> seq) { // Store all the words with its occurrence Dictionary<String, int> occ = new Dictionary<String, int>(); for (int i = 0; i < seq.Count; i++) if(occ.ContainsKey(seq[i])) occ[seq[i]] = occ[seq[i]] + 1; else occ.Add(seq[i], 1); // find the second largest occurrence int first_max = int.MinValue, sec_max = int.MinValue; foreach(KeyValuePair<String, int> entry in occ) { int v = entry.Value; if( v > first_max) { sec_max = first_max; first_max = v; } else if (v > sec_max && v != first_max) sec_max = v; } // Return string with occurrence equals // to sec_max foreach(KeyValuePair<String, int> entry in occ) { int v = entry.Value; if (v == sec_max) return entry.Key; } return null; } // Driver method public static void Main(String[] args) { String []arr = { "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" }; List<String> seq = new List<String>(arr); Console.WriteLine(secMostRepeated(seq)); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to find out the second// most repeated word // Function to find the wordfunction secMostRepeated(seq){ // Store all the words with its occurrence let occ = new Map(); for (let i = 0; i < seq.length; i++) { if(occ.has(seq[i])){ occ.set(seq[i], occ.get(seq[i])+1); } else occ.set(seq[i], 1); } // find the second largest occurrence let first_max = Number.MIN_VALUE, sec_max = Number.MIN_VALUE; for (let [key,value] of occ) { if (value > first_max) { sec_max = first_max; first_max = value; } else if (value > sec_max && value != first_max) sec_max = value; } // Return string with occurrence equals // to sec_max for (let [key,value] of occ) if (value == sec_max) return key;} // Driver programlet seq = [ "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" ];document.write(secMostRepeated(seq)); // This code is contributed by shinjanpatra</script> Output: ccc Reference: https://www.careercup.com/question?id=5748104113422336This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. Rajput-Ji mohit kumar 29 shinjanpatra simmytarika5 gyaneshsharma09 Amazon Goldman Sachs Hash Strings Amazon Goldman Sachs Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashing | Set 2 (Separate Chaining) Counting frequencies of array elements Most frequent element in an array Sort string of characters Return maximum occurring character in an input string Reverse a string in Java Write a program to reverse an array or string Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 24765, "s": 24737, "text": "\n04 Apr, 2022" }, { "code": null, "e": 24979, "s": 24765, "text": "Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence.(Considering no two words are the second most repeated, there will be always a single word)." }, { "code": null, "e": 24990, "s": 24979, "text": "Examples: " }, { "code": null, "e": 25146, "s": 24990, "text": "Input : {\"aaa\", \"bbb\", \"ccc\", \"bbb\", \n \"aaa\", \"aaa\"}\nOutput : bbb\n\nInput : {\"geeks\", \"for\", \"geeks\", \"for\", \n \"geeks\", \"aaa\"}\nOutput : for" }, { "code": null, "e": 25164, "s": 25146, "text": "Asked in : Amazon" }, { "code": null, "e": 25168, "s": 25164, "text": "C++" }, { "code": null, "e": 25173, "s": 25168, "text": "Java" }, { "code": null, "e": 25181, "s": 25173, "text": "Python3" }, { "code": null, "e": 25184, "s": 25181, "text": "C#" }, { "code": null, "e": 25195, "s": 25184, "text": "Javascript" }, { "code": "// C++ program to find out the second// most repeated word#include <bits/stdc++.h>using namespace std; // Function to find the wordstring secMostRepeated(vector<string> seq){ // Store all the words with its occurrence unordered_map<string, int> occ; for (int i = 0; i < seq.size(); i++) occ[seq[i]]++; // find the second largest occurrence int first_max = INT_MIN, sec_max = INT_MIN; for (auto it = occ.begin(); it != occ.end(); it++) { if (it->second > first_max) { sec_max = first_max; first_max = it->second; } else if (it->second > sec_max && it->second != first_max) sec_max = it->second; } // Return string with occurrence equals // to sec_max for (auto it = occ.begin(); it != occ.end(); it++) if (it->second == sec_max) return it->first;} // Driver programint main(){ vector<string> seq = { \"ccc\", \"aaa\", \"ccc\", \"ddd\", \"aaa\", \"aaa\" }; cout << secMostRepeated(seq); return 0;}", "e": 26242, "s": 25195, "text": null }, { "code": "// Java program to find out the second// most repeated word import java.util.*; class GFG{ // Method to find the word static String secMostRepeated(Vector<String> seq) { // Store all the words with its occurrence HashMap<String, Integer> occ = new HashMap<String,Integer>(seq.size()){ @Override public Integer get(Object key) { return containsKey(key) ? super.get(key) : 0; } }; for (int i = 0; i < seq.size(); i++) occ.put(seq.get(i), occ.get(seq.get(i))+1); // find the second largest occurrence int first_max = Integer.MIN_VALUE, sec_max = Integer.MIN_VALUE; Iterator<Map.Entry<String, Integer>> itr = occ.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Integer> entry = itr.next(); int v = entry.getValue(); if( v > first_max) { sec_max = first_max; first_max = v; } else if (v > sec_max && v != first_max) sec_max = v; } // Return string with occurrence equals // to sec_max itr = occ.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, Integer> entry = itr.next(); int v = entry.getValue(); if (v == sec_max) return entry.getKey(); } return null; } // Driver method public static void main(String[] args) { String arr[] = { \"ccc\", \"aaa\", \"ccc\", \"ddd\", \"aaa\", \"aaa\" }; List<String> seq = Arrays.asList(arr); System.out.println(secMostRepeated(new Vector<>(seq))); } }// This program is contributed by Gaurav Miglani", "e": 28054, "s": 26242, "text": null }, { "code": "# Python3 program to find out the second# most repeated word # Function to find the worddef secMostRepeated(seq): # Store all the words with its occurrence occ = {} for i in range(len(seq)): occ[seq[i]] = occ.get(seq[i], 0) + 1 # Find the second largest occurrence first_max = -10**8 sec_max = -10**8 for it in occ: if (occ[it] > first_max): sec_max = first_max first_max = occ[it] elif (occ[it] > sec_max and occ[it] != first_max): sec_max = occ[it] # Return with occurrence equals # to sec_max for it in occ: if (occ[it] == sec_max): return it # Driver codeif __name__ == '__main__': seq = [ \"ccc\", \"aaa\", \"ccc\", \"ddd\", \"aaa\", \"aaa\" ] print(secMostRepeated(seq)) # This code is contributed by mohit kumar 29", "e": 28922, "s": 28054, "text": null }, { "code": "// C# program to find out the second// most repeated wordusing System;using System.Collections.Generic; class GFG{ // Method to find the word static String secMostRepeated(List<String> seq) { // Store all the words with its occurrence Dictionary<String, int> occ = new Dictionary<String, int>(); for (int i = 0; i < seq.Count; i++) if(occ.ContainsKey(seq[i])) occ[seq[i]] = occ[seq[i]] + 1; else occ.Add(seq[i], 1); // find the second largest occurrence int first_max = int.MinValue, sec_max = int.MinValue; foreach(KeyValuePair<String, int> entry in occ) { int v = entry.Value; if( v > first_max) { sec_max = first_max; first_max = v; } else if (v > sec_max && v != first_max) sec_max = v; } // Return string with occurrence equals // to sec_max foreach(KeyValuePair<String, int> entry in occ) { int v = entry.Value; if (v == sec_max) return entry.Key; } return null; } // Driver method public static void Main(String[] args) { String []arr = { \"ccc\", \"aaa\", \"ccc\", \"ddd\", \"aaa\", \"aaa\" }; List<String> seq = new List<String>(arr); Console.WriteLine(secMostRepeated(seq)); }} // This code is contributed by Rajput-Ji", "e": 30507, "s": 28922, "text": null }, { "code": "<script> // JavaScript program to find out the second// most repeated word // Function to find the wordfunction secMostRepeated(seq){ // Store all the words with its occurrence let occ = new Map(); for (let i = 0; i < seq.length; i++) { if(occ.has(seq[i])){ occ.set(seq[i], occ.get(seq[i])+1); } else occ.set(seq[i], 1); } // find the second largest occurrence let first_max = Number.MIN_VALUE, sec_max = Number.MIN_VALUE; for (let [key,value] of occ) { if (value > first_max) { sec_max = first_max; first_max = value; } else if (value > sec_max && value != first_max) sec_max = value; } // Return string with occurrence equals // to sec_max for (let [key,value] of occ) if (value == sec_max) return key;} // Driver programlet seq = [ \"ccc\", \"aaa\", \"ccc\", \"ddd\", \"aaa\", \"aaa\" ];document.write(secMostRepeated(seq)); // This code is contributed by shinjanpatra</script>", "e": 31520, "s": 30507, "text": null }, { "code": null, "e": 31529, "s": 31520, "text": "Output: " }, { "code": null, "e": 31533, "s": 31529, "text": "ccc" }, { "code": null, "e": 32019, "s": 31533, "text": "Reference: https://www.careercup.com/question?id=5748104113422336This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. " }, { "code": null, "e": 32029, "s": 32019, "text": "Rajput-Ji" }, { "code": null, "e": 32044, "s": 32029, "text": "mohit kumar 29" }, { "code": null, "e": 32057, "s": 32044, "text": "shinjanpatra" }, { "code": null, "e": 32070, "s": 32057, "text": "simmytarika5" }, { "code": null, "e": 32086, "s": 32070, "text": "gyaneshsharma09" }, { "code": null, "e": 32093, "s": 32086, "text": "Amazon" }, { "code": null, "e": 32107, "s": 32093, "text": "Goldman Sachs" }, { "code": null, "e": 32112, "s": 32107, "text": "Hash" }, { "code": null, "e": 32120, "s": 32112, "text": "Strings" }, { "code": null, "e": 32127, "s": 32120, "text": "Amazon" }, { "code": null, "e": 32141, "s": 32127, "text": "Goldman Sachs" }, { "code": null, "e": 32146, "s": 32141, "text": "Hash" }, { "code": null, "e": 32154, "s": 32146, "text": "Strings" }, { "code": null, "e": 32252, "s": 32154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32261, "s": 32252, "text": "Comments" }, { "code": null, "e": 32274, "s": 32261, "text": "Old Comments" }, { "code": null, "e": 32310, "s": 32274, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 32349, "s": 32310, "text": "Counting frequencies of array elements" }, { "code": null, "e": 32383, "s": 32349, "text": "Most frequent element in an array" }, { "code": null, "e": 32409, "s": 32383, "text": "Sort string of characters" }, { "code": null, "e": 32463, "s": 32409, "text": "Return maximum occurring character in an input string" }, { "code": null, "e": 32488, "s": 32463, "text": "Reverse a string in Java" }, { "code": null, "e": 32534, "s": 32488, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 32568, "s": 32534, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 32583, "s": 32568, "text": "C++ Data Types" } ]
How to change the local user account password using PowerShell?
To change the local user account password using PowerShell, we can use the Set-LocalUser command with the Password parameter. This password parameter should be in the secure string. So we need to ask the user to input the password as a secure string or need to explicitly convert the plain text password to the secure string. For example, $localuser = Read-Host "Enter Local UserName" $password = Read-Host "Enter local user account password " -AsSecureString Set-LocalUser -Name $localuser -Password $password -Verbose If you need to set the password without asking the user prompt then you need to convert the plain text password to the secure string forcefully as shown below. $password = "Admin123" | ConvertTo-SecureString -AsPlainText -Force Set-LocalUser -Name TestUser -Password $password -Verbose To set the local user password on the remote computer, use Invoke-Command. Invoke-Command -ComputerName Computer1, Computer2 -ScriptBlock{ $password = "Admin123" | ConvertTo-SecureString -AsPlainText -Force Set-LocalUser -Name 'TestUser' -Password $password -Verbose } The above command will set the local user account password on the remote servers computer1 and Computer2.
[ { "code": null, "e": 1401, "s": 1062, "text": "To change the local user account password using PowerShell, we can use the Set-LocalUser command with the Password parameter. This password parameter should be in the secure string. So we need to ask the user to input the password as a secure string or need to explicitly convert the plain text password to the secure string. For example," }, { "code": null, "e": 1582, "s": 1401, "text": "$localuser = Read-Host \"Enter Local UserName\"\n$password = Read-Host \"Enter local user account password \"\n-AsSecureString\nSet-LocalUser -Name $localuser -Password $password -Verbose" }, { "code": null, "e": 1742, "s": 1582, "text": "If you need to set the password without asking the user prompt then you need to convert the plain text password to the secure string forcefully as shown below." }, { "code": null, "e": 1868, "s": 1742, "text": "$password = \"Admin123\" | ConvertTo-SecureString\n-AsPlainText -Force\nSet-LocalUser -Name TestUser -Password $password -Verbose" }, { "code": null, "e": 1943, "s": 1868, "text": "To set the local user password on the remote computer, use Invoke-Command." }, { "code": null, "e": 2143, "s": 1943, "text": "Invoke-Command -ComputerName Computer1, Computer2 -ScriptBlock{\n $password = \"Admin123\" | ConvertTo-SecureString -AsPlainText -Force\n Set-LocalUser -Name 'TestUser' -Password $password -Verbose\n}" }, { "code": null, "e": 2249, "s": 2143, "text": "The above command will set the local user account password on the remote servers computer1 and Computer2." } ]
sort_heap function in C++ - GeeksforGeeks
14 Aug, 2018 The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another.Defined in header It has two versions, which are defined below:.1. Comparing elements using “<":Syntax: template void sort_heap(RandIter start, RandIter end); start, end : the range of elements to sort Return Value: Since, return type is void, so it doesnot return any value. Implementation template void sort_heap( RandIter start, RandIter end ); { while (start != end) std::pop_heap(start, end--); } 2. By comparing using a pre-defined function:Syntax: template void sort_heap(RandIter start, RandIter end, Comp cmpfn); start, end : the range of elements to sort comp: comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ?true if the first argument is less than the second. Return Value : Since, its return type is void, so it doesnot return any value. Implementation template void sort_heap( RandIter start, RandIter end, Comp cmpfn ); { while (start != end) std::pop_heap(start, end--, cmpfn); } // CPP program to illustrate// std::sort_heap#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = {8, 6, 2, 1, 5, 10}; make_heap(v.begin(), v.end()); cout << "heap: "; for (const auto &i : v) { cout << i << ' '; } sort_heap(v.begin(), v.end()); std::cout <<endl<< "now sorted: "; for (const auto &i : v) { cout << i << ' '; } std::cout <<endl;} Output: heap: 10 6 8 1 5 2 now sorted: 1 2 5 6 8 10 Another Example : // CPP program to illustrate// std::sort_heap#include <vector>#include <algorithm>#include <functional>#include <iostream> int main( ) { using namespace std; vector <int> vt1, vt2; vector <int>::iterator Itera1, Itera2; int i; for ( i = 1 ; i <=5 ; i++ ) vt1.push_back( i ); random_shuffle( vt1.begin( ), vt1.end( ) ); cout << "vector vt1 is ( " ; for ( Itera1 = vt1.begin( ) ; Itera1 != vt1.end( ) ; Itera1++ ) cout << *Itera1 << " "; cout << ")" << endl; sort_heap (vt1.begin( ), vt1.end( ) ); cout << "heap vt1 sorted range: ( " ; for ( Itera1 = vt1.begin( ) ; Itera1 != vt1.end( ) ; Itera1++ ) cout << *Itera1 << " "; cout << ")" << endl;} Output: vector vt1 is ( 5 4 2 3 1 ) heap vt1 sorted range: ( 1 2 3 4 5 ) This article is contributed by Shivani Ghughtyal. 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. cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Friend class and function in C++ Sorting a vector in C++ Iterators in C++ STL Convert string to char array in C++ Inline Functions in C++ Multithreading in C++ List in C++ Standard Template Library (STL) new and delete operators in C++ for dynamic memory
[ { "code": null, "e": 24124, "s": 24096, "text": "\n14 Aug, 2018" }, { "code": null, "e": 24297, "s": 24124, "text": "The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order." }, { "code": null, "e": 24429, "s": 24297, "text": "The second form allows you to specify a comparison function that determines when one element is less than another.Defined in header" }, { "code": null, "e": 24515, "s": 24429, "text": "It has two versions, which are defined below:.1. Comparing elements using “<\":Syntax:" }, { "code": null, "e": 24694, "s": 24515, "text": "template \nvoid sort_heap(RandIter start, RandIter end);\nstart, end : the range of elements to sort\nReturn Value: Since, return type is void, so it doesnot return any value. " }, { "code": null, "e": 24709, "s": 24694, "text": "Implementation" }, { "code": null, "e": 24833, "s": 24709, "text": "template\nvoid sort_heap( RandIter start, RandIter end );\n{\n while (start != end)\n std::pop_heap(start, end--);\n}\n" }, { "code": null, "e": 24886, "s": 24833, "text": "2. By comparing using a pre-defined function:Syntax:" }, { "code": null, "e": 25244, "s": 24886, "text": "template \nvoid sort_heap(RandIter start, RandIter end, Comp cmpfn);\nstart, end : the range of elements to sort\ncomp: comparison function object (i.e. an object that satisfies the requirements of Compare) \nwhich returns ?true if the first argument is less than the second.\nReturn Value : Since, its return type is void, so it doesnot return any value. \n" }, { "code": null, "e": 25259, "s": 25244, "text": "Implementation" }, { "code": null, "e": 25402, "s": 25259, "text": "template\nvoid sort_heap( RandIter start, RandIter end, Comp cmpfn );\n{\n while (start != end)\n std::pop_heap(start, end--, cmpfn);\n}\n" }, { "code": "// CPP program to illustrate// std::sort_heap#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v = {8, 6, 2, 1, 5, 10}; make_heap(v.begin(), v.end()); cout << \"heap: \"; for (const auto &i : v) { cout << i << ' '; } sort_heap(v.begin(), v.end()); std::cout <<endl<< \"now sorted: \"; for (const auto &i : v) { cout << i << ' '; } std::cout <<endl;}", "e": 25913, "s": 25402, "text": null }, { "code": null, "e": 25921, "s": 25913, "text": "Output:" }, { "code": null, "e": 25968, "s": 25921, "text": "heap: 10 6 8 1 5 2 \nnow sorted: 1 2 5 6 8 10 \n" }, { "code": null, "e": 25986, "s": 25968, "text": "Another Example :" }, { "code": "// CPP program to illustrate// std::sort_heap#include <vector>#include <algorithm>#include <functional>#include <iostream> int main( ) { using namespace std; vector <int> vt1, vt2; vector <int>::iterator Itera1, Itera2; int i; for ( i = 1 ; i <=5 ; i++ ) vt1.push_back( i ); random_shuffle( vt1.begin( ), vt1.end( ) ); cout << \"vector vt1 is ( \" ; for ( Itera1 = vt1.begin( ) ; Itera1 != vt1.end( ) ; Itera1++ ) cout << *Itera1 << \" \"; cout << \")\" << endl; sort_heap (vt1.begin( ), vt1.end( ) ); cout << \"heap vt1 sorted range: ( \" ; for ( Itera1 = vt1.begin( ) ; Itera1 != vt1.end( ) ; Itera1++ ) cout << *Itera1 << \" \"; cout << \")\" << endl;} ", "e": 26684, "s": 25986, "text": null }, { "code": null, "e": 26692, "s": 26684, "text": "Output:" }, { "code": null, "e": 26758, "s": 26692, "text": "vector vt1 is ( 5 4 2 3 1 )\nheap vt1 sorted range: ( 1 2 3 4 5 )\n" }, { "code": null, "e": 27063, "s": 26758, "text": "This article is contributed by Shivani Ghughtyal. 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": 27188, "s": 27063, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27210, "s": 27188, "text": "cpp-algorithm-library" }, { "code": null, "e": 27214, "s": 27210, "text": "STL" }, { "code": null, "e": 27218, "s": 27214, "text": "C++" }, { "code": null, "e": 27222, "s": 27218, "text": "STL" }, { "code": null, "e": 27226, "s": 27222, "text": "CPP" }, { "code": null, "e": 27324, "s": 27226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27352, "s": 27324, "text": "Operator Overloading in C++" }, { "code": null, "e": 27372, "s": 27352, "text": "Polymorphism in C++" }, { "code": null, "e": 27405, "s": 27372, "text": "Friend class and function in C++" }, { "code": null, "e": 27429, "s": 27405, "text": "Sorting a vector in C++" }, { "code": null, "e": 27450, "s": 27429, "text": "Iterators in C++ STL" }, { "code": null, "e": 27486, "s": 27450, "text": "Convert string to char array in C++" }, { "code": null, "e": 27510, "s": 27486, "text": "Inline Functions in C++" }, { "code": null, "e": 27532, "s": 27510, "text": "Multithreading in C++" }, { "code": null, "e": 27576, "s": 27532, "text": "List in C++ Standard Template Library (STL)" } ]
Program to find sum of digits until it is one digit number in Python
Suppose we have a positive number n, we will add all of its digits to get a new number. Now repeat this operation until it is less than 10. So, if the input is like 9625, then the output will be 4. To solve this, we will follow these steps − Define a method solve(), this will take n if n < 10, thenreturn n return n s := 0 l := the floor of (log(n) base 10 + 1) while l > 0, dos := s + (n mod 10)n := quotient of n / 10l := l - 1 s := s + (n mod 10) n := quotient of n / 10 l := l - 1 return solve(s) Let us see the following implementation to get better understanding − Live Demo import math class Solution: def solve(self, n): if n < 10: return n s = 0 l = math.floor(math.log(n, 10) + 1) while l > 0: s += n % 10 n //= 10 l -= 1 return self.solve(s) ob = Solution() print(ob.solve(9625)) 9625 4
[ { "code": null, "e": 1202, "s": 1062, "text": "Suppose we have a positive number n, we will add all of its digits to get a new number. Now\nrepeat this operation until it is less than 10." }, { "code": null, "e": 1260, "s": 1202, "text": "So, if the input is like 9625, then the output will be 4." }, { "code": null, "e": 1304, "s": 1260, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1346, "s": 1304, "text": "Define a method solve(), this will take n" }, { "code": null, "e": 1370, "s": 1346, "text": "if n < 10, thenreturn n" }, { "code": null, "e": 1379, "s": 1370, "text": "return n" }, { "code": null, "e": 1386, "s": 1379, "text": "s := 0" }, { "code": null, "e": 1425, "s": 1386, "text": "l := the floor of (log(n) base 10 + 1)" }, { "code": null, "e": 1493, "s": 1425, "text": "while l > 0, dos := s + (n mod 10)n := quotient of n / 10l := l - 1" }, { "code": null, "e": 1513, "s": 1493, "text": "s := s + (n mod 10)" }, { "code": null, "e": 1537, "s": 1513, "text": "n := quotient of n / 10" }, { "code": null, "e": 1548, "s": 1537, "text": "l := l - 1" }, { "code": null, "e": 1564, "s": 1548, "text": "return solve(s)" }, { "code": null, "e": 1634, "s": 1564, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1645, "s": 1634, "text": " Live Demo" }, { "code": null, "e": 1924, "s": 1645, "text": "import math\nclass Solution:\n def solve(self, n):\n if n < 10:\n return n\n s = 0\n l = math.floor(math.log(n, 10) + 1)\n while l > 0:\n s += n % 10\n n //= 10\n l -= 1\n return self.solve(s)\nob = Solution()\nprint(ob.solve(9625))" }, { "code": null, "e": 1929, "s": 1924, "text": "9625" }, { "code": null, "e": 1931, "s": 1929, "text": "4" } ]
Draw an ellipse on an image using OpenCV
In this program, we will draw an ellipse on an image in using the OpenCV library. We will use the OpenCV function ellipse() for the same. Step 1: Import cv2. Step 2: Read the image using imread(). Step 3: Set the center coordinates. Step 4: Set the axes length. Step 5: Set the angle. Step 6: Set start and end angle. Step 6: Set the color. Step 7: Set the thickness. Step 8: Draw the ellipse by passing the above parameters in the cv2.ellipse function along with the original image. Step 9: Display the final output. import cv2 image = cv2.imread('testimage.jpg') center_coordinates = (120, 100) axesLength = (100, 50) angle = 0 startAngle = 0 endAngle = 360 color = (0, 0, 255) thickness = 5 image = cv2.ellipse(image, center_coordinates, axesLength, angle, startAngle, endAngle, color, thickness) cv2.imshow('Ellipse', image)
[ { "code": null, "e": 1200, "s": 1062, "text": "In this program, we will draw an ellipse on an image in using the OpenCV library. We will use the OpenCV function ellipse() for the same." }, { "code": null, "e": 1580, "s": 1200, "text": "Step 1: Import cv2.\nStep 2: Read the image using imread().\nStep 3: Set the center coordinates.\nStep 4: Set the axes length.\nStep 5: Set the angle.\nStep 6: Set start and end angle.\nStep 6: Set the color.\nStep 7: Set the thickness.\nStep 8: Draw the ellipse by passing the above parameters in the cv2.ellipse function along with the original image.\nStep 9: Display the final output." }, { "code": null, "e": 1893, "s": 1580, "text": "import cv2\nimage = cv2.imread('testimage.jpg')\ncenter_coordinates = (120, 100)\n\naxesLength = (100, 50)\nangle = 0\nstartAngle = 0\nendAngle = 360\ncolor = (0, 0, 255)\nthickness = 5\nimage = cv2.ellipse(image, center_coordinates, axesLength, angle, startAngle, endAngle, color, thickness)\n\ncv2.imshow('Ellipse', image)" } ]
Online Code Practice - Tutorials Point
Support Class File Util Class File Extra Class File
[ { "code": null, "e": 29, "s": 10, "text": "Support Class File" }, { "code": null, "e": 45, "s": 29, "text": "Util Class File" } ]
Dimensionality Reduction in Data Mining | by Uditha Maduranga | Towards Data Science
Big data is the large scale of data sets that have multi-level variables and that grow really fast. Volume is the most important aspect of big data. With the recent technological advancements happened in data processing and computer science field, the recent explosion of big data, in both number of records and attributes, has triggered few challenges in the data mining and overall in data science. Extremely big size of data in big data forms multidimensional datasets. Having multiple dimensions for the in a large data set makes the job of analyzing those or looking for any kind of patterns in the data really hard. High dimensional data can be obtained from various sources, depending on what kind of process one is interested in. Any process in nature progresses as a result of many different variables, some of which are observable or measurable and some are not. When we are to get data of any kind of simulation accurately, we get to deal with higher dimensional data. Dimensionality reduction is the process of reducing the number of random variables or attributes under consideration. High-dimensionality data reduction, as part of a data pre-processing-step, is extremely important in many real-world applications. High-dimensionality reduction has emerged as one of the significant tasks in data mining applications. For an example you may have a dataset with hundreds of features (columns in your database). Then dimensionality reduction is that you reduce those features of attributes of data by combining or merging them in such a way that it will not loose much of the significant characteristics of the original dataset. One of the major problem that occurs with high dimensional data is widely known as the “Curse of Dimensionality”. This pushes us to reduce the dimensions of our data if we want to use them for analysis. The curse of dimensionality refers to the phenomena that occur when classifying, organizing, and analyzing high dimensional data that does not occur in low dimensional spaces, specifically the issue of data sparsity and “closeness” of data. Above sequence of graphs shows the issue of closeness of data when the underlying dimension increases. As the data space seen above moves from one dimension to two dimensions and finally to three dimensions, the given data fills less and less of the data space. The volume of data that is needed in order to maintain an accurate representation of the space, grows exponentially with the dimension. When the dimension increases, with the sparsity, the distance between two independant points increases. That results in less similarity among the data points which will result in more error when it comes to most of the machine learning and other techniques used in data mining. To compensate we will have to feed very large number of data points but with higher dimensions it’s practically impossible and even it’s possible it will be inefficient. In order to overcome above mentioned challenges that come with higher dimensional data, there is this need of reducing the dimensions of the data that is planned to be analysed and visualized. Dimensionality reduction is accomplished based on either feature selection or feature extraction. Feature selection is based on omitting those features from the available measurements which do not contribute to class separability. In other words, redundant and irrelevant features are ignored. Feature extraction, on the other hand, considers the whole information content and maps the useful information content into a lower dimensional feature space. One can differentiate the techniques used for dimensionality reduction as linear techniques and non-linear techniques as well. But here those techniques will be described based on the feature selection and feature extraction standpoint. As a stand-alone task, feature selection can be unsupervised (e.g. Variance Thresholds) or supervised (e.g. Genetic Algorithms). You can also combine multiple methods if needed. This technique looks for the variance from one observation to another of a given feature and then if the variance is not different in each observation according to the given threshold, feature that is responsible for that observation is removed. Features that don’t change much don’t add much effective information. Using variance thresholds is an easy and relatively safe way to reduce dimensionality at the start of your modeling process. But this alone will not be sufficient if you want to reduce the dimensions as it’s highly subjective and you need to tune the variance threshold manually. This kind of feature selection can be implemented using both Python and R. Here the features are taken into account and checked whether those features are correlated to each other closely. If they are, the overall effect to the final output of both of the features would be similar even to the result we get when we used one of those features. Which one should you remove? Well, you’d first calculate all pair-wise correlations. Then, if the correlation between a pair of features is above a given threshold, you’d remove the one that has larger mean absolute correlation with other features. Like the previous technique, this is also based on intuition and hence the burden of tuning the thresholds in such a way that the useful information will not be neglected, will fall upon the user. Because of the those reasons, algorithms with built-in feature selection or algorithms like PCA are preferred over this one. They are search algorithms that are inspired by evolutionary biology and natural selection, combining mutation and cross-over to efficiently traverse large solution spaces. Genetic Algorithms are used to find an optimal binary vector, where each bit is associated with a feature. If theth bit of this vector equals 1, then the that feature is allowed to participate in classification.If the bit is a 0, then the corresponding feature does not participate. In feature selection, “genes” represent individual features and the “organism” represents a candidate set of features. Each organism in the “population” is graded on a fitness score such as model performance on a hold-out set. The fittest organisms survive and reproduce, repeating until the population converges on a solution some generations later. You can have a further understanding on genetic algorithm here. [Start] Generate random population of n chromosomes (suitable solutions for the problem)[Fitness] Evaluate the fitness f(x) of each chromosome x in the population[New population] Create a new population by repeating following steps until the new population is complete : [Selection] Select two parent chromosomes from a population according to their fitness (the better fitness, the bigger chance to be selected) [Crossover] With a crossover probability cross over the parents to form a new offspring (children). If no crossover was performed, offspring is an exact copy of parents. [Mutation] With a mutation probability mutate new offspring at each locus (position in chromosome). [Accepting] Place new offspring in a new population[Replace] Use new generated population for a further run of algorithm[Test] If the end condition is satisfied, stop, and return the best solution in current population[Loop] Go to step 2 [Fitness] This can efficiently select features from very high dimensional datasets, where exhaustive search is unfeasible. But in most of the cases one might think that this is not worth the hassle which is quite true depending on the context as using PCA or built-in selection would be far more simpler. In statistics, stepwise regression is a method of fitting regression models in which the choice of predictive variables is carried out by an automatic procedure. In each step, a variable is considered for addition to or subtraction from the set of explanatory variables based on some prespecified criterion. Usually, this takes the form of a sequence of F-tests or t-tests, but other techniques are possible, such as adjusted R2, Akaike information criterion, Bayesian information criterion, Mallows’s Cp, PRESS, or false discovery rate. You can get a better understanding of stepwise regression here. This has two flavors: forward and backward. For forward stepwise search, you start without any features. Then, you’d train a 1-feature model using each of your candidate features and keep the version with the best performance. You’d continue adding features, one at a time, until your performance improvements stall. Backward stepwise search is the same process, just reversed: start with all features in your model and then remove one at a time until performance starts to drop substantially. This is a greedy algorithm and commonly has a lower performance than the supervised methods such as regularizations etc. Feature extraction is for creating a new, smaller set of features that still captures most of the useful information. This can come as supervised(e.g. LDA) and unsupervised(e.g. PCA) methods. LDA uses the information from multiple features to create a new axis and projects the data on to the new axis in such a way as to minimizes the variance and maximizes the distance between the means of the classes. LDA is a supervised method that can only be used with labeled data. It consists of statistical properties of your data, calculated for each class. For a single input variable (x) this is the mean and the variance of the variable for each class. For multiple variables, this is the same properties calculated over the multivariate Gaussian, namely the means and the covariance matrix. The LDA transformation is also dependent on scale, so you should normalize your dataset first. LDA is a supervised, so it needs labeled data. It offers variations (i.e. quadratic LDA) to tackle specific roadblocks. But the new features that are being created are hard to interpret using LDA. PCA is a dimensionality reduction that identifies important relationships in our data, transforms the existing data based on these relationships, and then quantifies the importance of these relationships so we can keep the most important relationships. To remember this definition, we can break it down into four steps: We identify the relationship among features through a Covariance Matrix.Through the linear transformation or eigendecomposition of the Covariance Matrix, we get eigenvectors and eigenvalues.Then we transform our data using Eigenvectors into principal components.Lastly, we quantify the importance of these relationships using Eigenvalues and keep the important principal components. We identify the relationship among features through a Covariance Matrix. Through the linear transformation or eigendecomposition of the Covariance Matrix, we get eigenvectors and eigenvalues. Then we transform our data using Eigenvectors into principal components. Lastly, we quantify the importance of these relationships using Eigenvalues and keep the important principal components. The new features that are created by PCA are orthogonal, which means that they are uncorrelated. Furthermore, they are ranked in order of their “explained variance.” The first principal component (PC1) explains the most variance in your dataset, PC2 explains the second-most variance, and so on. you can reduce dimensionality by limiting the number of principal components to keep based on cumulative explained variance. The PCA transformation is also dependent on scale, so you should normalize your dataset first. PCA is a find linear correlations between the features given. This means that only if you have some of the variables in your dataset that are linearly correlated, this will be helpful. t-SNE is non-linear dimensionality reduction technique which is typically used to visualize high dimensional datasets. Some of the main applications of t-SNE are Natural Language Processing (NLP), speech processing, etc. t-SNE works by minimizing the divergence between a distribution constituted by the pairwise probability similarities of the input features in the original high dimensional space and its equivalent in the reduced low dimensional space. t-SNE makes then use of the Kullback-Leiber (KL) divergence in order to measure the dissimilarity of the two different distributions. The KL divergence is then minimized using gradient descent. Here the lower dimensional space is modeled using t distribution while the higher dimensional space is modeled using Gaussian distribution. Autoencoders are a family of Machine Learning algorithms which can be used as a dimensionality reduction technique. Autoencoders also use non-linear transformations to project data from a high dimension to a lower one. Autoencoders are neural networks that are trained to reconstruct their original inputs. Basically autoencoders consist with two parts. Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space.Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space). Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space. Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space). In the above diagram the middle layer represents the large number of input features within smaller number of neurons thus giving a dense and smaller representation of the inputs. Since it’s a neural network based solution for feature extraction it might need large sets of data to train. I hope you enjoyed this article, thank you for reading!
[ { "code": null, "e": 1152, "s": 172, "text": "Big data is the large scale of data sets that have multi-level variables and that grow really fast. Volume is the most important aspect of big data. With the recent technological advancements happened in data processing and computer science field, the recent explosion of big data, in both number of records and attributes, has triggered few challenges in the data mining and overall in data science. Extremely big size of data in big data forms multidimensional datasets. Having multiple dimensions for the in a large data set makes the job of analyzing those or looking for any kind of patterns in the data really hard. High dimensional data can be obtained from various sources, depending on what kind of process one is interested in. Any process in nature progresses as a result of many different variables, some of which are observable or measurable and some are not. When we are to get data of any kind of simulation accurately, we get to deal with higher dimensional data." }, { "code": null, "e": 2016, "s": 1152, "text": "Dimensionality reduction is the process of reducing the number of random variables or attributes under consideration. High-dimensionality data reduction, as part of a data pre-processing-step, is extremely important in many real-world applications. High-dimensionality reduction has emerged as one of the significant tasks in data mining applications. For an example you may have a dataset with hundreds of features (columns in your database). Then dimensionality reduction is that you reduce those features of attributes of data by combining or merging them in such a way that it will not loose much of the significant characteristics of the original dataset. One of the major problem that occurs with high dimensional data is widely known as the “Curse of Dimensionality”. This pushes us to reduce the dimensions of our data if we want to use them for analysis." }, { "code": null, "e": 2257, "s": 2016, "text": "The curse of dimensionality refers to the phenomena that occur when classifying, organizing, and analyzing high dimensional data that does not occur in low dimensional spaces, specifically the issue of data sparsity and “closeness” of data." }, { "code": null, "e": 2655, "s": 2257, "text": "Above sequence of graphs shows the issue of closeness of data when the underlying dimension increases. As the data space seen above moves from one dimension to two dimensions and finally to three dimensions, the given data fills less and less of the data space. The volume of data that is needed in order to maintain an accurate representation of the space, grows exponentially with the dimension." }, { "code": null, "e": 3103, "s": 2655, "text": "When the dimension increases, with the sparsity, the distance between two independant points increases. That results in less similarity among the data points which will result in more error when it comes to most of the machine learning and other techniques used in data mining. To compensate we will have to feed very large number of data points but with higher dimensions it’s practically impossible and even it’s possible it will be inefficient." }, { "code": null, "e": 3296, "s": 3103, "text": "In order to overcome above mentioned challenges that come with higher dimensional data, there is this need of reducing the dimensions of the data that is planned to be analysed and visualized." }, { "code": null, "e": 3749, "s": 3296, "text": "Dimensionality reduction is accomplished based on either feature selection or feature extraction. Feature selection is based on omitting those features from the available measurements which do not contribute to class separability. In other words, redundant and irrelevant features are ignored. Feature extraction, on the other hand, considers the whole information content and maps the useful information content into a lower dimensional feature space." }, { "code": null, "e": 3986, "s": 3749, "text": "One can differentiate the techniques used for dimensionality reduction as linear techniques and non-linear techniques as well. But here those techniques will be described based on the feature selection and feature extraction standpoint." }, { "code": null, "e": 4164, "s": 3986, "text": "As a stand-alone task, feature selection can be unsupervised (e.g. Variance Thresholds) or supervised (e.g. Genetic Algorithms). You can also combine multiple methods if needed." }, { "code": null, "e": 4835, "s": 4164, "text": "This technique looks for the variance from one observation to another of a given feature and then if the variance is not different in each observation according to the given threshold, feature that is responsible for that observation is removed. Features that don’t change much don’t add much effective information. Using variance thresholds is an easy and relatively safe way to reduce dimensionality at the start of your modeling process. But this alone will not be sufficient if you want to reduce the dimensions as it’s highly subjective and you need to tune the variance threshold manually. This kind of feature selection can be implemented using both Python and R." }, { "code": null, "e": 5675, "s": 4835, "text": "Here the features are taken into account and checked whether those features are correlated to each other closely. If they are, the overall effect to the final output of both of the features would be similar even to the result we get when we used one of those features. Which one should you remove? Well, you’d first calculate all pair-wise correlations. Then, if the correlation between a pair of features is above a given threshold, you’d remove the one that has larger mean absolute correlation with other features. Like the previous technique, this is also based on intuition and hence the burden of tuning the thresholds in such a way that the useful information will not be neglected, will fall upon the user. Because of the those reasons, algorithms with built-in feature selection or algorithms like PCA are preferred over this one." }, { "code": null, "e": 6546, "s": 5675, "text": "They are search algorithms that are inspired by evolutionary biology and natural selection, combining mutation and cross-over to efficiently traverse large solution spaces. Genetic Algorithms are used to find an optimal binary vector, where each bit is associated with a feature. If theth bit of this vector equals 1, then the that feature is allowed to participate in classification.If the bit is a 0, then the corresponding feature does not participate. In feature selection, “genes” represent individual features and the “organism” represents a candidate set of features. Each organism in the “population” is graded on a fitness score such as model performance on a hold-out set. The fittest organisms survive and reproduce, repeating until the population converges on a solution some generations later. You can have a further understanding on genetic algorithm here." }, { "code": null, "e": 7497, "s": 6546, "text": "[Start] Generate random population of n chromosomes (suitable solutions for the problem)[Fitness] Evaluate the fitness f(x) of each chromosome x in the population[New population] Create a new population by repeating following steps until the new population is complete : [Selection] Select two parent chromosomes from a population according to their fitness (the better fitness, the bigger chance to be selected) [Crossover] With a crossover probability cross over the parents to form a new offspring (children). If no crossover was performed, offspring is an exact copy of parents. [Mutation] With a mutation probability mutate new offspring at each locus (position in chromosome). [Accepting] Place new offspring in a new population[Replace] Use new generated population for a further run of algorithm[Test] If the end condition is satisfied, stop, and return the best solution in current population[Loop] Go to step 2 [Fitness]" }, { "code": null, "e": 7792, "s": 7497, "text": "This can efficiently select features from very high dimensional datasets, where exhaustive search is unfeasible. But in most of the cases one might think that this is not worth the hassle which is quite true depending on the context as using PCA or built-in selection would be far more simpler." }, { "code": null, "e": 8394, "s": 7792, "text": "In statistics, stepwise regression is a method of fitting regression models in which the choice of predictive variables is carried out by an automatic procedure. In each step, a variable is considered for addition to or subtraction from the set of explanatory variables based on some prespecified criterion. Usually, this takes the form of a sequence of F-tests or t-tests, but other techniques are possible, such as adjusted R2, Akaike information criterion, Bayesian information criterion, Mallows’s Cp, PRESS, or false discovery rate. You can get a better understanding of stepwise regression here." }, { "code": null, "e": 8888, "s": 8394, "text": "This has two flavors: forward and backward. For forward stepwise search, you start without any features. Then, you’d train a 1-feature model using each of your candidate features and keep the version with the best performance. You’d continue adding features, one at a time, until your performance improvements stall. Backward stepwise search is the same process, just reversed: start with all features in your model and then remove one at a time until performance starts to drop substantially." }, { "code": null, "e": 9009, "s": 8888, "text": "This is a greedy algorithm and commonly has a lower performance than the supervised methods such as regularizations etc." }, { "code": null, "e": 9201, "s": 9009, "text": "Feature extraction is for creating a new, smaller set of features that still captures most of the useful information. This can come as supervised(e.g. LDA) and unsupervised(e.g. PCA) methods." }, { "code": null, "e": 9894, "s": 9201, "text": "LDA uses the information from multiple features to create a new axis and projects the data on to the new axis in such a way as to minimizes the variance and maximizes the distance between the means of the classes. LDA is a supervised method that can only be used with labeled data. It consists of statistical properties of your data, calculated for each class. For a single input variable (x) this is the mean and the variance of the variable for each class. For multiple variables, this is the same properties calculated over the multivariate Gaussian, namely the means and the covariance matrix. The LDA transformation is also dependent on scale, so you should normalize your dataset first." }, { "code": null, "e": 10091, "s": 9894, "text": "LDA is a supervised, so it needs labeled data. It offers variations (i.e. quadratic LDA) to tackle specific roadblocks. But the new features that are being created are hard to interpret using LDA." }, { "code": null, "e": 10411, "s": 10091, "text": "PCA is a dimensionality reduction that identifies important relationships in our data, transforms the existing data based on these relationships, and then quantifies the importance of these relationships so we can keep the most important relationships. To remember this definition, we can break it down into four steps:" }, { "code": null, "e": 10794, "s": 10411, "text": "We identify the relationship among features through a Covariance Matrix.Through the linear transformation or eigendecomposition of the Covariance Matrix, we get eigenvectors and eigenvalues.Then we transform our data using Eigenvectors into principal components.Lastly, we quantify the importance of these relationships using Eigenvalues and keep the important principal components." }, { "code": null, "e": 10867, "s": 10794, "text": "We identify the relationship among features through a Covariance Matrix." }, { "code": null, "e": 10986, "s": 10867, "text": "Through the linear transformation or eigendecomposition of the Covariance Matrix, we get eigenvectors and eigenvalues." }, { "code": null, "e": 11059, "s": 10986, "text": "Then we transform our data using Eigenvectors into principal components." }, { "code": null, "e": 11180, "s": 11059, "text": "Lastly, we quantify the importance of these relationships using Eigenvalues and keep the important principal components." }, { "code": null, "e": 11881, "s": 11180, "text": "The new features that are created by PCA are orthogonal, which means that they are uncorrelated. Furthermore, they are ranked in order of their “explained variance.” The first principal component (PC1) explains the most variance in your dataset, PC2 explains the second-most variance, and so on. you can reduce dimensionality by limiting the number of principal components to keep based on cumulative explained variance. The PCA transformation is also dependent on scale, so you should normalize your dataset first. PCA is a find linear correlations between the features given. This means that only if you have some of the variables in your dataset that are linearly correlated, this will be helpful." }, { "code": null, "e": 12102, "s": 11881, "text": "t-SNE is non-linear dimensionality reduction technique which is typically used to visualize high dimensional datasets. Some of the main applications of t-SNE are Natural Language Processing (NLP), speech processing, etc." }, { "code": null, "e": 12531, "s": 12102, "text": "t-SNE works by minimizing the divergence between a distribution constituted by the pairwise probability similarities of the input features in the original high dimensional space and its equivalent in the reduced low dimensional space. t-SNE makes then use of the Kullback-Leiber (KL) divergence in order to measure the dissimilarity of the two different distributions. The KL divergence is then minimized using gradient descent." }, { "code": null, "e": 12671, "s": 12531, "text": "Here the lower dimensional space is modeled using t distribution while the higher dimensional space is modeled using Gaussian distribution." }, { "code": null, "e": 13025, "s": 12671, "text": "Autoencoders are a family of Machine Learning algorithms which can be used as a dimensionality reduction technique. Autoencoders also use non-linear transformations to project data from a high dimension to a lower one. Autoencoders are neural networks that are trained to reconstruct their original inputs. Basically autoencoders consist with two parts." }, { "code": null, "e": 13380, "s": 13025, "text": "Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space.Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space)." }, { "code": null, "e": 13573, "s": 13380, "text": "Encoder: takes the input data and compress it, so that to remove all the possible noise and unhelpful information. The output of the Encoder stage is usually called bottleneck or latent-space." }, { "code": null, "e": 13736, "s": 13573, "text": "Decoder: takes as input the encoded latent space and tries to reproduce the original Autoencoder input using just it’s compressed form (the encoded latent space)." }, { "code": null, "e": 14024, "s": 13736, "text": "In the above diagram the middle layer represents the large number of input features within smaller number of neurons thus giving a dense and smaller representation of the inputs. Since it’s a neural network based solution for feature extraction it might need large sets of data to train." } ]
Listing out directories and files in Python - GeeksforGeeks
22 Oct, 2017 The following is a list of some of the important methods/functions in Python with descriptions that you should know to understand this article. len() – It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc.str() – It is used to transform data value(integers, floats, list) into string.abspath() – It returns the absolute path of the file/directory name passed as an argument.enumerate() – Returns an enumerate object for the passed iterable that can be used to iterate over the items of iterable with an access to their indexes.list() – It is used to create a list by using an existing iterable(list, tuple, dictionary, set).listdir() – It is used to list the directory contents. The path of directory is passed as an argument.isfile() – It checks whether the passed parameter denotes the path to a file. If yes then returns True otherwise Falseisdir() – It checks whether the passed parameter denotes the path to a directory. If yes then returns True otherwise Falseappend() – It is used to append items on list. len() – It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc. str() – It is used to transform data value(integers, floats, list) into string. abspath() – It returns the absolute path of the file/directory name passed as an argument. enumerate() – Returns an enumerate object for the passed iterable that can be used to iterate over the items of iterable with an access to their indexes. list() – It is used to create a list by using an existing iterable(list, tuple, dictionary, set). listdir() – It is used to list the directory contents. The path of directory is passed as an argument. isfile() – It checks whether the passed parameter denotes the path to a file. If yes then returns True otherwise False isdir() – It checks whether the passed parameter denotes the path to a directory. If yes then returns True otherwise False append() – It is used to append items on list. Please see the below code executed on interactive Python terminal to have a quick walk through on the usages of above functions/methods. >>> nums = [1,2,3,4,5] # list>>> name = "Alexander">>> details = {"name": "Hemkesh", "age": 23, "active": True}>>> >>> # Using len()... >>> len(nums)5>>> len(name)9>>> len(details)3>>> >>> # Using str()... >>> str(12)'12'>>> str(nums)'[1, 2, 3, 4, 5]'>>> str(details)"{'active': True, 'age': 23, 'name': 'Hemkesh'}">>> >>> # Using abspath()... >>> import os>>> os.listdir(".")['Django', 'Prep', 'python-the-snake']>>> os.path.abspath("./Django") # pass ".\Django" on windows'/Users/admin/projects/Python/Django'>>> os.path.abspath("Django")'/Users/admin/projects/Python/Django'>>> >>> # Using enumerate()...>>> enumerate(nums)<enumerate object at 0x100620b90>>>> >>> for index, item in enumerate(nums):... print index, item... 0 11 22 33 44 5>>> >>> # Using list()...>>> list()[]>>> list(details )['active', 'age', 'name']>>> list(name)['A', 'l', 'e', 'x', 'a', 'n', 'd', 'e', 'r']>>> >>> # Using isfile() & isdir()... >>> os.path.isdir("Django")True>>> os.path.isfile("Django")False>>>>>> os.path.isdir("./python-the-snake/README.md")False>>> os.path.isfile("./python-the-snake/README.md")True>>> >>> # Using append()...>>> nums.append(12)>>> nums[1, 2, 3, 4, 5, 12]>>> nums.append(67)>>> nums[1, 2, 3, 4, 5, 12, 67]>>> >>> # Don't press "Run on IDE" button available on right. You will get error ... # as the statements are already executed on interactive terminal....>>> Path structure on different OSWindows uses \ (back slash) as a path separator, eg. C:\Users\Desktop\Linux based system like MAC OS X, Linux uses / (forward slash), eg. /Users/Desktop/ Let’s have a quick overview the working of above methods and functions as we are using this in our final program. # Python version : 2.7.12 # len()# To count number of items in a list# To count number of characters in a stringevens = [ 2, 34, 6, 8, 10]print len(evens) city = "Bangalore"print len(city), "\n" # str() : Converting into string representationodds = [ 1, 3, 67, 45, 83, 59]year = 2017 print oddsprint str(odds) + " A list.\n" print yearprint str(year) + " A year.\n" # enumerate() : iterating over index & value of a listfor (index, item) in enumerate(odds): print index, item # abspath() : Getting absolute path of passed argument(path)import osabsolute_path = os.path.abspath(".")print "\n", absolute_path, "\n" # isdir() : To check if passed argument is valid directory pathanswer = os.path.isdir("/Users/admin/Desktop/js")print answer # isfile() : To check if the passed argument is valid file pathanswer = os.path.isfile("/Users/admin/Desktop/js/array.js")print answer, "\n" # list() : To create listdetails = { "name":"Rojert Rendrick", "age":24, "city":"Bangalore" }keys = list( details )print keys, "\n" # append() : Appending items to listprint evensevens.append(98)evens.append(64)print evens, "\n" # repetition operator(*) on stringsprint "Python"*3print "#"*20 Output: 5 9 [1, 3, 67, 45, 83, 59] [1, 3, 67, 45, 83, 59] A list. 2017 2017 A year. 0 1 1 3 2 67 3 45 4 83 5 59 /Users/admin/projects/Python/PythonFiles True True ['city', 'age', 'name'] [2, 34, 6, 8, 10] [2, 34, 6, 8, 10, 98, 64] PythonPythonPython #################### There are number of Python files & directories inside /Users/admin/projects/Python/PythonFiles, we will list out all these. Suppose current working directory is /Users/admin/projects/Python/Django/E-Commerce-projects/ecommerce-2/src, which has some files and folders inside it. In your case, it will be different. You will only need to pass the exact path of the directory that you want to list out. The following is the python code to display all the files and directories based on the passed absolute or relative path. If path is not specified in the calling statement then the contents of current working directory will be displayed. # This Python code is for Python version : 2.7.12 def show_directories(dir_list, path): """ A function that lists the directories """ import os s = "%s%d%s"%("\n", len(dir_list), " directories of " + os.path.abspath(path)) l = len(s) print s print "="*l for index, dir in enumerate(dir_list): print str(index+1) + ") ", dir def show_files(file_list, path): """ A function that lists the files """ import os s = "%s%d%s"%("\n", len(file_list), " files of " + os.path.abspath(path)) l = len(s) print s print "="*l for index, file in enumerate(file_list): print str(index+1) + ") ", file def show_cwd_contents( path="." ): # A function that calls 2 functions to separately # listing out directories and files. # It takes a default argument as cwd(.). We can # pass other paths too. import os f_list = [] d_list = list() try: for f in os.listdir(path): if os.path.isfile(os.path.join(path, f)): f_list.append(f) else: if os.path.isdir(os.path.join(path, f)): d_list.append(f) except: print "\nError, once check the path" return show_files(f_list, path) show_directories(d_list, path) if __name__ == "__main__": # If this module is imported in other module then # we need to separately call show_cwd_contents() Or # show_cwd_contents(path). show_cwd_contents() show_cwd_contents("/Users/admin/projects/Python/PythonFiles") Output: 5 files of /Users/admin/projects/Python/Django/E-Commerce-projects/ecommerce-2/src =================================================================================== 1) .gitignore 2) db.sqlite3 3) manage.py 4) requirements.txt 5) todo.txt 5 directories of /Users/admin/projects/Python/Django/E-Commerce-projects/ecommerce-2/src ========================================================================================= 1) ecommerce2 2) newsletter 3) products 4) static_in_pro 5) templates 70 files of /Users/admin/projects/Python/PythonFiles ===================================================== 1) 2_list_iterators.py 2) app.py 3) class_script_exec.py 4) class_variables.py 5) date_and_time.py 6) datetime.txt 7) dict.py 8) dictionary.py 9) django_home.html 10) error_handling.py 11) error_handling_output.py 12) error_handling_output.txt 13) execution_pickle.py 14) fb_task.py 15) for.py 16) gfg_sum_of_primes_in_numbers.py 17) hackerrank_numbers.py 18) hck_addition_aint_simple.py 19) hck_biased_chandan.py 20) hck_c_counts.py 21) hck_c_counts2.py 22) hck_c_counts3.py 23) hck_cool_numbers.py 24) hck_earth_fans.py 25) hck_earth_fans_2.py 26) hck_earth_fans_3.py 27) hck_earth_fans_final_on_28_dec_2016.py 28) hck_Little_Jhool_and_psychic_powers.py 29) hck_lonely_monk.py 30) hck_lonely_monk_orig.py 31) hck_maximum_AND.py 32) hck_min_max_problem.py 33) hck_monk_and_power_of_time.py 34) hck_numbers_rotation.py 35) hck_palindomic_numbers.py 36) hck_print_hackerearth.py 37) hck_print_hackerearth_2_way.py 38) hck_range_query.py 39) hck_recursive_functions.py 40) hck_recursive_sums.py 41) hck_strange_addition.py 42) hck_sum_of_numbers.py 43) interactive_img_resolutions.txt 44) json.py 45) json.pyc 46) katyperry.py 47) lambda_expression.py 48) linked_list_delete_nodes_at_front.py 49) linked_list_delete_nodes_at_front_output.txt 50) linked_list_is_palindrome_gfg.py 51) linked_list_is_palindrome_gfg_output.text 52) linked_list_is_palindrome_gfg_testing.py 53) linked_list_node_deletion_from_any_position.txt 54) linked_list_node_deletion_from_end.py 55) linked_list_node_deletion_from_end_output.txt 56) linked_list_node_deletion_from_middle.py 57) linked_list_node_insertion_at_beginning.py 58) linked_list_node_insertion_at_end.py 59) linked_list_node_insertion_at_middel_output.txt 60) linked_list_node_insertion_at_middle.py 61) map.py 62) merge_lists.py 63) mufeez_android_interview.py 64) python_for_loops.py 65) python_for_loops2.py 66) remove_dupliates.py 67) show_dir_and_files.py 68) show_dir_and_files_test.py 69) smarika_urllib_python2.7.10.py 70) while.py 2 directories of /Users/admin/projects/Python/PythonFiles ========================================================== 1) socket_programming 2) wx This article is contributed by Rishikesh Agrawani. 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. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 23975, "s": 23947, "text": "\n22 Oct, 2017" }, { "code": null, "e": 24119, "s": 23975, "text": "The following is a list of some of the important methods/functions in Python with descriptions that you should know to understand this article." }, { "code": null, "e": 25046, "s": 24119, "text": "len() – It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc.str() – It is used to transform data value(integers, floats, list) into string.abspath() – It returns the absolute path of the file/directory name passed as an argument.enumerate() – Returns an enumerate object for the passed iterable that can be used to iterate over the items of iterable with an access to their indexes.list() – It is used to create a list by using an existing iterable(list, tuple, dictionary, set).listdir() – It is used to list the directory contents. The path of directory is passed as an argument.isfile() – It checks whether the passed parameter denotes the path to a file. If yes then returns True otherwise Falseisdir() – It checks whether the passed parameter denotes the path to a directory. If yes then returns True otherwise Falseappend() – It is used to append items on list." }, { "code": null, "e": 25166, "s": 25046, "text": "len() – It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc." }, { "code": null, "e": 25246, "s": 25166, "text": "str() – It is used to transform data value(integers, floats, list) into string." }, { "code": null, "e": 25337, "s": 25246, "text": "abspath() – It returns the absolute path of the file/directory name passed as an argument." }, { "code": null, "e": 25491, "s": 25337, "text": "enumerate() – Returns an enumerate object for the passed iterable that can be used to iterate over the items of iterable with an access to their indexes." }, { "code": null, "e": 25589, "s": 25491, "text": "list() – It is used to create a list by using an existing iterable(list, tuple, dictionary, set)." }, { "code": null, "e": 25692, "s": 25589, "text": "listdir() – It is used to list the directory contents. The path of directory is passed as an argument." }, { "code": null, "e": 25811, "s": 25692, "text": "isfile() – It checks whether the passed parameter denotes the path to a file. If yes then returns True otherwise False" }, { "code": null, "e": 25934, "s": 25811, "text": "isdir() – It checks whether the passed parameter denotes the path to a directory. If yes then returns True otherwise False" }, { "code": null, "e": 25981, "s": 25934, "text": "append() – It is used to append items on list." }, { "code": null, "e": 26118, "s": 25981, "text": "Please see the below code executed on interactive Python terminal to have a quick walk through on the usages of above functions/methods." }, { "code": ">>> nums = [1,2,3,4,5] # list>>> name = \"Alexander\">>> details = {\"name\": \"Hemkesh\", \"age\": 23, \"active\": True}>>> >>> # Using len()... >>> len(nums)5>>> len(name)9>>> len(details)3>>> >>> # Using str()... >>> str(12)'12'>>> str(nums)'[1, 2, 3, 4, 5]'>>> str(details)\"{'active': True, 'age': 23, 'name': 'Hemkesh'}\">>> >>> # Using abspath()... >>> import os>>> os.listdir(\".\")['Django', 'Prep', 'python-the-snake']>>> os.path.abspath(\"./Django\") # pass \".\\Django\" on windows'/Users/admin/projects/Python/Django'>>> os.path.abspath(\"Django\")'/Users/admin/projects/Python/Django'>>> >>> # Using enumerate()...>>> enumerate(nums)<enumerate object at 0x100620b90>>>> >>> for index, item in enumerate(nums):... print index, item... 0 11 22 33 44 5>>> >>> # Using list()...>>> list()[]>>> list(details )['active', 'age', 'name']>>> list(name)['A', 'l', 'e', 'x', 'a', 'n', 'd', 'e', 'r']>>> >>> # Using isfile() & isdir()... >>> os.path.isdir(\"Django\")True>>> os.path.isfile(\"Django\")False>>>>>> os.path.isdir(\"./python-the-snake/README.md\")False>>> os.path.isfile(\"./python-the-snake/README.md\")True>>> >>> # Using append()...>>> nums.append(12)>>> nums[1, 2, 3, 4, 5, 12]>>> nums.append(67)>>> nums[1, 2, 3, 4, 5, 12, 67]>>> >>> # Don't press \"Run on IDE\" button available on right. You will get error ... # as the statements are already executed on interactive terminal....>>>", "e": 27502, "s": 26118, "text": null }, { "code": null, "e": 27686, "s": 27502, "text": "Path structure on different OSWindows uses \\ (back slash) as a path separator, eg. C:\\Users\\Desktop\\Linux based system like MAC OS X, Linux uses / (forward slash), eg. /Users/Desktop/" }, { "code": null, "e": 27800, "s": 27686, "text": "Let’s have a quick overview the working of above methods and functions as we are using this in our final program." }, { "code": "# Python version : 2.7.12 # len()# To count number of items in a list# To count number of characters in a stringevens = [ 2, 34, 6, 8, 10]print len(evens) city = \"Bangalore\"print len(city), \"\\n\" # str() : Converting into string representationodds = [ 1, 3, 67, 45, 83, 59]year = 2017 print oddsprint str(odds) + \" A list.\\n\" print yearprint str(year) + \" A year.\\n\" # enumerate() : iterating over index & value of a listfor (index, item) in enumerate(odds): print index, item # abspath() : Getting absolute path of passed argument(path)import osabsolute_path = os.path.abspath(\".\")print \"\\n\", absolute_path, \"\\n\" # isdir() : To check if passed argument is valid directory pathanswer = os.path.isdir(\"/Users/admin/Desktop/js\")print answer # isfile() : To check if the passed argument is valid file pathanswer = os.path.isfile(\"/Users/admin/Desktop/js/array.js\")print answer, \"\\n\" # list() : To create listdetails = { \"name\":\"Rojert Rendrick\", \"age\":24, \"city\":\"Bangalore\" }keys = list( details )print keys, \"\\n\" # append() : Appending items to listprint evensevens.append(98)evens.append(64)print evens, \"\\n\" # repetition operator(*) on stringsprint \"Python\"*3print \"#\"*20", "e": 28997, "s": 27800, "text": null }, { "code": null, "e": 29005, "s": 28997, "text": "Output:" }, { "code": null, "e": 29282, "s": 29005, "text": "5\n9 \n\n[1, 3, 67, 45, 83, 59]\n[1, 3, 67, 45, 83, 59] A list.\n\n2017\n2017 A year.\n\n0 1\n1 3\n2 67\n3 45\n4 83\n5 59\n\n/Users/admin/projects/Python/PythonFiles \n\nTrue\nTrue \n\n['city', 'age', 'name'] \n\n[2, 34, 6, 8, 10]\n[2, 34, 6, 8, 10, 98, 64] \n\nPythonPythonPython\n####################\n" }, { "code": null, "e": 29406, "s": 29282, "text": "There are number of Python files & directories inside /Users/admin/projects/Python/PythonFiles, we will list out all these." }, { "code": null, "e": 29560, "s": 29406, "text": "Suppose current working directory is /Users/admin/projects/Python/Django/E-Commerce-projects/ecommerce-2/src, which has some files and folders inside it." }, { "code": null, "e": 29682, "s": 29560, "text": "In your case, it will be different. You will only need to pass the exact path of the directory that you want to list out." }, { "code": null, "e": 29803, "s": 29682, "text": "The following is the python code to display all the files and directories based on the passed absolute or relative path." }, { "code": null, "e": 29919, "s": 29803, "text": "If path is not specified in the calling statement then the contents of current working directory will be displayed." }, { "code": "# This Python code is for Python version : 2.7.12 def show_directories(dir_list, path): \"\"\" A function that lists the directories \"\"\" import os s = \"%s%d%s\"%(\"\\n\", len(dir_list), \" directories of \" + os.path.abspath(path)) l = len(s) print s print \"=\"*l for index, dir in enumerate(dir_list): print str(index+1) + \") \", dir def show_files(file_list, path): \"\"\" A function that lists the files \"\"\" import os s = \"%s%d%s\"%(\"\\n\", len(file_list), \" files of \" + os.path.abspath(path)) l = len(s) print s print \"=\"*l for index, file in enumerate(file_list): print str(index+1) + \") \", file def show_cwd_contents( path=\".\" ): # A function that calls 2 functions to separately # listing out directories and files. # It takes a default argument as cwd(.). We can # pass other paths too. import os f_list = [] d_list = list() try: for f in os.listdir(path): if os.path.isfile(os.path.join(path, f)): f_list.append(f) else: if os.path.isdir(os.path.join(path, f)): d_list.append(f) except: print \"\\nError, once check the path\" return show_files(f_list, path) show_directories(d_list, path) if __name__ == \"__main__\": # If this module is imported in other module then # we need to separately call show_cwd_contents() Or # show_cwd_contents(path). show_cwd_contents() show_cwd_contents(\"/Users/admin/projects/Python/PythonFiles\")", "e": 31461, "s": 29919, "text": null }, { "code": null, "e": 31469, "s": 31461, "text": "Output:" }, { "code": null, "e": 34277, "s": 31469, "text": "5 files of /Users/admin/projects/Python/Django/E-Commerce-projects/ecommerce-2/src\n===================================================================================\n1) .gitignore\n2) db.sqlite3\n3) manage.py\n4) requirements.txt\n5) todo.txt\n\n5 directories of /Users/admin/projects/Python/Django/E-Commerce-projects/ecommerce-2/src\n=========================================================================================\n1) ecommerce2\n2) newsletter\n3) products\n4) static_in_pro\n5) templates\n\n70 files of /Users/admin/projects/Python/PythonFiles\n=====================================================\n1) 2_list_iterators.py\n2) app.py\n3) class_script_exec.py\n4) class_variables.py\n5) date_and_time.py\n6) datetime.txt\n7) dict.py\n8) dictionary.py\n9) django_home.html\n10) error_handling.py\n11) error_handling_output.py\n12) error_handling_output.txt\n13) execution_pickle.py\n14) fb_task.py\n15) for.py\n16) gfg_sum_of_primes_in_numbers.py\n17) hackerrank_numbers.py\n18) hck_addition_aint_simple.py\n19) hck_biased_chandan.py\n20) hck_c_counts.py\n21) hck_c_counts2.py\n22) hck_c_counts3.py\n23) hck_cool_numbers.py\n24) hck_earth_fans.py\n25) hck_earth_fans_2.py\n26) hck_earth_fans_3.py\n27) hck_earth_fans_final_on_28_dec_2016.py\n28) hck_Little_Jhool_and_psychic_powers.py\n29) hck_lonely_monk.py\n30) hck_lonely_monk_orig.py\n31) hck_maximum_AND.py\n32) hck_min_max_problem.py\n33) hck_monk_and_power_of_time.py\n34) hck_numbers_rotation.py\n35) hck_palindomic_numbers.py\n36) hck_print_hackerearth.py\n37) hck_print_hackerearth_2_way.py\n38) hck_range_query.py\n39) hck_recursive_functions.py\n40) hck_recursive_sums.py\n41) hck_strange_addition.py\n42) hck_sum_of_numbers.py\n43) interactive_img_resolutions.txt\n44) json.py\n45) json.pyc\n46) katyperry.py\n47) lambda_expression.py\n48) linked_list_delete_nodes_at_front.py\n49) linked_list_delete_nodes_at_front_output.txt\n50) linked_list_is_palindrome_gfg.py\n51) linked_list_is_palindrome_gfg_output.text\n52) linked_list_is_palindrome_gfg_testing.py\n53) linked_list_node_deletion_from_any_position.txt\n54) linked_list_node_deletion_from_end.py\n55) linked_list_node_deletion_from_end_output.txt\n56) linked_list_node_deletion_from_middle.py\n57) linked_list_node_insertion_at_beginning.py\n58) linked_list_node_insertion_at_end.py\n59) linked_list_node_insertion_at_middel_output.txt\n60) linked_list_node_insertion_at_middle.py\n61) map.py\n62) merge_lists.py\n63) mufeez_android_interview.py\n64) python_for_loops.py\n65) python_for_loops2.py\n66) remove_dupliates.py\n67) show_dir_and_files.py\n68) show_dir_and_files_test.py\n69) smarika_urllib_python2.7.10.py\n70) while.py\n\n2 directories of /Users/admin/projects/Python/PythonFiles\n==========================================================\n1) socket_programming\n2) wx\n" }, { "code": null, "e": 34583, "s": 34277, "text": "This article is contributed by Rishikesh Agrawani. 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": 34708, "s": 34583, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 34723, "s": 34708, "text": "python-utility" }, { "code": null, "e": 34730, "s": 34723, "text": "Python" }, { "code": null, "e": 34828, "s": 34730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34837, "s": 34828, "text": "Comments" }, { "code": null, "e": 34850, "s": 34837, "text": "Old Comments" }, { "code": null, "e": 34868, "s": 34850, "text": "Python Dictionary" }, { "code": null, "e": 34903, "s": 34868, "text": "Read a file line by line in Python" }, { "code": null, "e": 34925, "s": 34903, "text": "Enumerate() in Python" }, { "code": null, "e": 34957, "s": 34925, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34987, "s": 34957, "text": "Iterate over a list in Python" }, { "code": null, "e": 35029, "s": 34987, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 35055, "s": 35029, "text": "Python String | replace()" }, { "code": null, "e": 35098, "s": 35055, "text": "Python program to convert a list to string" }, { "code": null, "e": 35142, "s": 35098, "text": "Reading and Writing to text files in Python" } ]
C library function - signal()
The C library function void (*signal(int sig, void (*func)(int)))(int) sets a function to handle signal i.e. a signal handler with signal number sig. Following is the declaration for signal() function. void (*signal(int sig, void (*func)(int)))(int) sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers − sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers − SIGABRT (Signal Abort) Abnormal termination, such as is initiated by the function. SIGFPE (Signal Floating-Point Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation). SIGILL (Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data. SIGINT (Signal Interrupt) Interactive attention signal. Generally generated by the application user. SIGSEGV (Signal Segmentation Violation) Invalid access to storage − When a program tries to read or write outside the memory it is allocated for it. SIGTERM (Signal Terminate) Termination request sent to program. func − This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions − func − This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions − SIG_DFL Default handling − The signal is handled by the default action for that particular signal. SIG_IGN Ignore Signal − The signal is ignored. This function returns the previous value of the signal handler, or SIG_ERR on error. The following example shows the usage of signal() function. #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <signal.h> void sighandler(int); int main () { signal(SIGINT, sighandler); while(1) { printf("Going to sleep for a second...\n"); sleep(1); } return(0); } void sighandler(int signum) { printf("Caught signal %d, coming out...\n", signum); exit(1); } Let us compile and run the above program that will produce the following result and program will go in infinite loop. To come out of the program we used CTRL + C keys. Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Going to sleep for a second... Caught signal 2, coming out... 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": 2157, "s": 2007, "text": "The C library function void (*signal(int sig, void (*func)(int)))(int) sets a function to handle signal i.e. a signal handler with signal number sig." }, { "code": null, "e": 2209, "s": 2157, "text": "Following is the declaration for signal() function." }, { "code": null, "e": 2257, "s": 2209, "text": "void (*signal(int sig, void (*func)(int)))(int)" }, { "code": null, "e": 2384, "s": 2257, "text": "sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers −" }, { "code": null, "e": 2511, "s": 2384, "text": "sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers −" }, { "code": null, "e": 2519, "s": 2511, "text": "SIGABRT" }, { "code": null, "e": 2594, "s": 2519, "text": "(Signal Abort) Abnormal termination, such as is initiated by the function." }, { "code": null, "e": 2601, "s": 2594, "text": "SIGFPE" }, { "code": null, "e": 2776, "s": 2601, "text": "(Signal Floating-Point Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation)." }, { "code": null, "e": 2783, "s": 2776, "text": "SIGILL" }, { "code": null, "e": 2952, "s": 2783, "text": "(Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data." }, { "code": null, "e": 2959, "s": 2952, "text": "SIGINT" }, { "code": null, "e": 3053, "s": 2959, "text": "(Signal Interrupt) Interactive attention signal. Generally generated by the application user." }, { "code": null, "e": 3061, "s": 3053, "text": "SIGSEGV" }, { "code": null, "e": 3202, "s": 3061, "text": "(Signal Segmentation Violation) Invalid access to storage − When a program tries to read or write outside the memory it is allocated for it." }, { "code": null, "e": 3210, "s": 3202, "text": "SIGTERM" }, { "code": null, "e": 3266, "s": 3210, "text": "(Signal Terminate) Termination request sent to program." }, { "code": null, "e": 3402, "s": 3266, "text": "func − This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions −" }, { "code": null, "e": 3538, "s": 3402, "text": "func − This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions −" }, { "code": null, "e": 3546, "s": 3538, "text": "SIG_DFL" }, { "code": null, "e": 3637, "s": 3546, "text": "Default handling − The signal is handled by the default action for that particular signal." }, { "code": null, "e": 3645, "s": 3637, "text": "SIG_IGN" }, { "code": null, "e": 3684, "s": 3645, "text": "Ignore Signal − The signal is ignored." }, { "code": null, "e": 3769, "s": 3684, "text": "This function returns the previous value of the signal handler, or SIG_ERR on error." }, { "code": null, "e": 3829, "s": 3769, "text": "The following example shows the usage of signal() function." }, { "code": null, "e": 4181, "s": 3829, "text": "#include <stdio.h>\n#include <unistd.h>\n#include <stdlib.h>\n#include <signal.h>\n\nvoid sighandler(int);\n\nint main () {\n signal(SIGINT, sighandler);\n\n while(1) {\n printf(\"Going to sleep for a second...\\n\");\n sleep(1); \n }\n return(0);\n}\n\nvoid sighandler(int signum) {\n printf(\"Caught signal %d, coming out...\\n\", signum);\n exit(1);\n}" }, { "code": null, "e": 4349, "s": 4181, "text": "Let us compile and run the above program that will produce the following result and program will go in infinite loop. To come out of the program we used CTRL + C keys." }, { "code": null, "e": 4536, "s": 4349, "text": "Going to sleep for a second...\nGoing to sleep for a second...\nGoing to sleep for a second...\nGoing to sleep for a second...\nGoing to sleep for a second...\nCaught signal 2, coming out...\n" }, { "code": null, "e": 4569, "s": 4536, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4584, "s": 4569, "text": " Nishant Malik" }, { "code": null, "e": 4619, "s": 4584, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4634, "s": 4619, "text": " Nishant Malik" }, { "code": null, "e": 4669, "s": 4634, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4683, "s": 4669, "text": " Asif Hussain" }, { "code": null, "e": 4716, "s": 4683, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 4734, "s": 4716, "text": " Richa Maheshwari" }, { "code": null, "e": 4769, "s": 4734, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4788, "s": 4769, "text": " Vandana Annavaram" }, { "code": null, "e": 4821, "s": 4788, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 4833, "s": 4821, "text": " Amit Diwan" }, { "code": null, "e": 4840, "s": 4833, "text": " Print" }, { "code": null, "e": 4851, "s": 4840, "text": " Add Notes" } ]
Merge and remove duplicates in JavaScript Array
Suppose, we have two arrays of literals like these − const arr1 = [2, 4, 5, 3, 7, 8, 9]; const arr2 = [1, 4, 5, 2, 3, 7, 6]; We are required to write a JavaScript function that takes in two such arrays and returns a new array with all the duplicates removed (should appear only once). The code for this will be − const arr1 = [2, 4, 5, 3, 7, 8, 9]; const arr2 = [1, 4, 5, 2, 3, 7, 6]; const mergeArrays = (first, second) => { const { length: l1 } = first; const { length: l2 } = second; const res = []; let temp = 0; for(let i = 0; i < l1+l2; i++){ if(i >= l1){ temp = i - l1; if(!res.includes(first[temp])){ res.push(first[temp]); }; }else{ temp = i; if(!res.includes(second[temp])){ res.push(second[temp]); }; }; }; return res; }; console.log(mergeArrays(arr1, arr2)); The output in the console − [ 1, 4, 5, 2, 3, 7, 6, 8, 9 ]
[ { "code": null, "e": 1115, "s": 1062, "text": "Suppose, we have two arrays of literals like these −" }, { "code": null, "e": 1187, "s": 1115, "text": "const arr1 = [2, 4, 5, 3, 7, 8, 9];\nconst arr2 = [1, 4, 5, 2, 3, 7, 6];" }, { "code": null, "e": 1347, "s": 1187, "text": "We are required to write a JavaScript function that takes in two such arrays and returns a new\narray with all the duplicates removed (should appear only once)." }, { "code": null, "e": 1375, "s": 1347, "text": "The code for this will be −" }, { "code": null, "e": 1950, "s": 1375, "text": "const arr1 = [2, 4, 5, 3, 7, 8, 9];\nconst arr2 = [1, 4, 5, 2, 3, 7, 6];\nconst mergeArrays = (first, second) => {\n const { length: l1 } = first;\n const { length: l2 } = second;\n const res = [];\n let temp = 0;\n for(let i = 0; i < l1+l2; i++){\n if(i >= l1){\n temp = i - l1;\n if(!res.includes(first[temp])){\n res.push(first[temp]);\n };\n }else{\n temp = i;\n if(!res.includes(second[temp])){\n res.push(second[temp]);\n };\n };\n };\n return res;\n};\nconsole.log(mergeArrays(arr1, arr2));" }, { "code": null, "e": 1978, "s": 1950, "text": "The output in the console −" }, { "code": null, "e": 2014, "s": 1978, "text": "[\n 1, 4, 5, 2, 3,\n 7, 6, 8, 9\n]" } ]
Human Activity Recognition (HAR) Tutorial with Keras and Core ML (Part 1) | by Nils | Towards Data Science
Keras and Apple’s Core ML are a very powerful toolset if you want to quickly deploy a neural network on any iOS device. Most other tutorials focus on the popular MNIST data set for image recognition. We will go beyond this widely covered machine learning example. Instead, you will learn how to process time-sliced, multi-dimensional sensor data. To be more specific, we will train a deep neural network (DNN) to recognize the type of movement (Walking, Running, Jogging, etc.) based on a given set of accelerometer data from a mobile device carried around a person’s waist. We will use a WISDM data set for this tutorial (WISDM). The approach presented in this article should work well for any other sensor data that you might come across within the Internet of Things (IOT). This article walks you through the following steps: Load accelerometer data from the WISDM data set Convert and reformat accelerometer data into a time-sliced representation Visualize the accelerometer data Reshape the multi-dimensional tabular data so that it is accepted by Keras Split up the data set into training, validation, and test set Define a deep neural network model in Keras which can later be processed by Apple’s Core ML Train the deep neural network for human activity recognition data Validate the performance of the trained DNN against the test data using learning curve and confusion matrix Export the trained Keras DNN model for Core ML Ensure that the Core ML model was exported correctly by conducting a sample prediction in Python Create a playground in Xcode and import the already trained Keras model Use Apple’s Core ML library in order to predict the outcomes for a given data set using Swift Prerequisites in order to conduct all steps explained in this article (including the version number that the code was tested with): Python (version 3.6.5) Keras (version 2.1.6) TensorFlow (version 1.7.0) Coremltools (version 2.0) Out of scope for this article: The creation of the perfect machine learning model with the highest possible performance for this type of problem statement is not the focus of this walkthrough. You might wonder why Keras was chosen for this article over other frameworks, namely TensorFlow. There are two key reasons: Keras is very simple to learn and has a modern, more intuitive API than TensorFlow while still leveraging the capabilities of TensorFlow in the backend There are multiple TensorFlow APIs; while trying to use the more convenient estimator API (which is also recommended by the TensorFlow team — you can find more information here) I ran into compilation issues when converting the trained estimator to Core ML Before we walk through the different steps in Python and Xcode, let’s take a brief look at the problem statement and our solution approach. The data set that we are using is a collection of accelerometer data taken from a smartphone that various people carried with them while conducting six different exercises (Downstairs, Jogging, Sitting, Standing, Upstairs, Walking). For each exercise the acceleration for the x, y, and z axis was measured and captured with a timestamp and person ID. With this available data, we would like to train a neural network in order to understand if a person carrying a smartphone is performing any of the six activities. Once the neural network has been trained on the existing data, it should be able to correctly predict the type of activity a person is conducting when given previously unseen data. The solution to this problem is a deep neural network. Based on the available data it will learn how to differentiate between each of the six activities. We can then show new data to the neural network and it will tell us what the user is doing at any particular point in time. The solution to this problem is depicted in the figure below. The typical steps for solving a machine learning problem are depicted below. We will run through a very similar process throughout this article. First we need to import all necessary python libraries. If you are missing some of them, install them using the pip installer. After importing the libraries, let’s set some standard parameters and print out the Keras version that we have installed. The WISDM dataset contains six different labels (Downstairs, Jogging, Sitting, Standing, Upstairs, Walking). Since we will use the list of labels multiple times, we create a constant for them (LABELS). The next constant TIME_PERIODS stores the length of the time segment. The constant STEP_DISTANCE determines the amount of overlap between two consecutive time segments. keras version 2.1.6 Next, you need to download the dataset form here and store it locally. The important file is WISDM_ar_v1.1_raw.txt. Before doing the import, let’s define a few convenience functions in order to read the data and show some basic information about the data. The data is loaded into the dataframe successfully. Now we can display the first 20 records of the dataframe and get some more insight regarding the distribution of the data. Number of columns in the dataframe: 6Number of rows in the dataframe: 1098203 As we can see, we have more data for walking and jogging activities than we have for the other activities. Also we can see that 36 persons have participated in the experiment. Next, let’s take a look at the accelerometer data for each of the three axis for all six possible activities. The data is recorded at a sampling rate of 20 Hz (20 values per second). Since we show the first 180 records, each chart shows a 9 second interval for each of the six activities (calculation: 0.05 * 180 = 9 seconds). We will use two functions (which I have borrowed from here) to plot the data. As expected, there is a higher acceleration for activities such as jogging and walking compared to sitting. Before we continue, we will add one more column with the name “ActivityEncoded” to the dataframe with the encoded value for each activity: Downstairs, Jogging, Sitting, Standing, Upstairs, Walking This is needed since the deep neural network cannot work with non-numerical labels. With the LabelEncoder, we are able to easily to convert back to the original label text. It is important to separate the whole data set into a training set and a test set. Often times, you see mistakes on how the data is split. However you decide to split the data, you never want information from the test set to bleed into your training set. This might be great for the overall performance of your model during training and then validation against the test set. But your model is very unlikely to generalize well for data it has not seen yet. The idea behind splitting: We want our neural network to learn from a few persons which have been through the experiment. Next, we then want to see how well our neural network predicts the movements of persons it has not seen before. Only worrying about having at least a few example records per activity is not sufficient. You will run the risk that you have maybe three records of activity “Walking” for person 5 in the training set and one record for activity “Walking” for person 5 in the test set. Of course, with this type of situation, your model will perform great because it has already seen the movement pattern of person 5 during training. Always be critical about the performance of your DNN — it might be because of the wrong data split in the first place. In our case, let’s split based on the user IDs. We will keep users with ID 1 to 28 for training the model and users with ID greater than 28 for the test set. Next, we need to normalize our features within our training data. Of course there are various ways on how to normalize. Please keep in mind that you use the same normalization algorithm later when feeding new data into your neural network. Otherwise your preditions will be off. On top of the normalization we will also apply rounding to the three features. The data contained in the dataframe is not ready yet to be fed into a neural network. Therefore we need to reshape it. Let’s create another function for this called “create_segments_and_labels”. This function will take in the dataframe and the label names (the constant that we have defined at the beginning) as well as the length of each record. In our case, let’s go with 80 steps (see constant defined earlier). Taking into consideration the 20 Hz sampling rate, this equals to 4 second time intervals (calculation: 0.05 * 80 = 4). Besides reshaping the data, the function will also separate the features (x-acceleration, y-acceleration, z-acceleration) and the labels (associated activity). By now, you should have both 20.868 records in x_train as well as in y_train. Each of the 20.868 records in x_train is a two dimensional matrix of the shape 80x3. x_train shape: (20868, 80, 3)20868 training samplesy_train shape: (20868,) For constructing our deep neural network, we should now store the following dimensions: Number of time periods: This is the number of time periods within one record (since we wanted to have a 4 second time interval, this number is 80 in our case) Number of sensors: This is 3 since we only use the acceleration over the x, y, and z axis Number of classes: This is the amount of nodes for our output layer in the neural network. Since we want our neural network to predict the type of activity, we will take the number of classes from the encoder that we have used earlier. ['Downstairs', 'Jogging', 'Sitting', 'Standing', 'Upstairs', 'Walking'] The data that we would like to feed into our network is two dimensional (80x3). Unfortunately, Keras and Core ML in conjunction are not able to process multi-dimensional input data. Therefore we need to “flatten” the data for our input layer into the neural network. Instead of feeding a matrix of shape 80x3 we will feed in a list of 240 values. x_train shape: (20868, 240)input_shape: 240 Before continuing, we need to convert all feature data (x_train) and label data (y_train) into a datatype accepted by Keras. We are almost done with the preparation of our data. One last step we need to do is to conduct one-hot-encoding of our labels. Please only execute this line once! New y_train shape: (20868, 6) By now, you have completed all the heavy-lifting on your side. The data is ready in such a format that Keras will be able to process it. I have decided to create a neural network with 3 hidden layers of 100 fully connected nodes each (feel free to play around with the shape of the network or even switch to more complex ones like a convolutional neural network). Important remark: as you remember, we have reshaped our input data from a 80x3 matrix into a vector of length 240 so that Apple’s Core ML can later process our data. In order to reverse this, our first layer in the neural network will reshape the data into the “old” format. The last two layers will again flatten the data and then run a softmax activation function in order to calculate the probability for each class. Remember, that we are working with six classes in our case (Downstairs, Jogging, Sitting, Standing, Upstairs, Walking). _________________________________________________________________Layer (type) Output Shape Param # =================================================================reshape_2 (Reshape) (None, 80, 3) 0 _________________________________________________________________dense_5 (Dense) (None, 80, 100) 400 _________________________________________________________________dense_6 (Dense) (None, 80, 100) 10100 _________________________________________________________________dense_7 (Dense) (None, 80, 100) 10100 _________________________________________________________________flatten_2 (Flatten) (None, 8000) 0 _________________________________________________________________dense_8 (Dense) (None, 6) 48006 =================================================================Total params: 68,606Trainable params: 68,606Non-trainable params: 0_________________________________________________________________None Next, we will train the model with our training data that we have prepared earlier. We will define an early stopping callback monitor on training accuracy: if the training fails to improve for two consecutive epochs, then the training will stop with the best model. The hyperparameter used for the training are quite simple: We will use a batch size of 400 records and will train the model for 50 epochs. For model training, we will use a 80:20 split to separate training data and validation data. It is that simple. So let’s go ahead and train our model. There are some good explanations out there on the different hyperparameters, for instance here. The performance of this simple DNN is OK. We have validation accuracy of approximately 74%. This could definitely improved, maybe with further hyperparameter tuning and especially with a modified neural network design. Before we go on with the test validation, we will print the learning curve for both the training and validation data set. precision recall f1-score support 0.0 0.70 0.42 0.53 1864 1.0 0.98 0.98 0.98 6567 2.0 0.99 0.99 0.99 1050 3.0 0.99 0.99 0.99 833 4.0 0.66 0.63 0.64 2342 5.0 0.85 0.93 0.89 8212avg / total 0.87 0.87 0.87 20868 Let’s continue with this model and see how it performs against the test data that we have held back earlier. In our case, we will check the performance against the movements of the six users that the model has not yet seen. 6584/6584 [==============================] - 1s 128us/stepAccuracy on test data: 0.76Loss on test data: 1.39 The accuracy on the test data is 76%. This means that our model generalizes well for persons it has not yet seen. Let’s see where our model wrongly predicted the labels. precision recall f1-score support 0 0.61 0.27 0.37 650 1 0.80 0.95 0.87 1990 2 0.82 0.99 0.90 452 3 0.91 0.74 0.81 370 4 0.48 0.42 0.45 725 5 0.77 0.79 0.78 2397avg / total 0.74 0.76 0.74 6584 As you can see, the precision of the model is good for predicting jogging (1), sitting (2), standing (3), and walking (5). The model has problems for clearly identifying upstairs and downstairs activities. There is of course still great potential for improving the model, e.g. by using more advanced neural network designs like convolutional neural networks (CNN) or Long Short Term Memory (LSTM). I might explore this in a later article. For our purpose of showing the end to end process, the result is good enough. If you are happy with the model and its performance, you should convert it now to be used with Core ML. The convert function only takes in a few arguments: The reference to your Keras model The name that you want to give the input data; in our case we are feeding acceleration data into the network The name that you want to assign to the outputs The “human-readable” label names; you can again use our LABEL constant that we defined in the beginning input { name: "acceleration" type { multiArrayType { shape: 240 dataType: DOUBLE } }}output { name: "output" type { dictionaryType { stringKeyType { } } }}output { name: "classLabel" type { stringType { } }}predictedFeatureName: "classLabel"predictedProbabilitiesName: "output" Before using your Core ML model, let’s make sure that the export was successful and that both our Keras model as well as the Core ML model provide the same prediction when given a random data set. Prediction from Keras:JoggingPrediction from Coreml:Jogging Great news! For the record with index 1, both Keras and Core ML predict the same label which is Jogging. We are now ready to use our Core ML model on any iOS device. In this article you have learned how to load and transform complex accelerometer data and run it through a deep neural network in Keras. You exported the trained model into a Core ML file. In my next article, I will walk you through the steps necessary in order to use this trained Core ML model within a simple Swift program. You can then use this knowledge to deploy the DNN to any iOS device. The Jupyter notebook for this article is available on github. Official Anaconda website Official Keras website Official TensorFlow website Official Apple Core ML documentation Official Apple coremltools github repository Good overview to decide which framework is for you: TensorFlow or Keras Good article by Aaqib Saeed on convolutional neural networks (CNN) for human activity recognition (also using the WISDM dataset) Another article also using the WISDM dataset implemented with TensorFlow and a more sophisticated LSTM model written by Venelin Valkov The postings on this site are my own and do not necessarily represent the postings, strategies or opinions of my employer.
[ { "code": null, "e": 518, "s": 171, "text": "Keras and Apple’s Core ML are a very powerful toolset if you want to quickly deploy a neural network on any iOS device. Most other tutorials focus on the popular MNIST data set for image recognition. We will go beyond this widely covered machine learning example. Instead, you will learn how to process time-sliced, multi-dimensional sensor data." }, { "code": null, "e": 802, "s": 518, "text": "To be more specific, we will train a deep neural network (DNN) to recognize the type of movement (Walking, Running, Jogging, etc.) based on a given set of accelerometer data from a mobile device carried around a person’s waist. We will use a WISDM data set for this tutorial (WISDM)." }, { "code": null, "e": 1000, "s": 802, "text": "The approach presented in this article should work well for any other sensor data that you might come across within the Internet of Things (IOT). This article walks you through the following steps:" }, { "code": null, "e": 1048, "s": 1000, "text": "Load accelerometer data from the WISDM data set" }, { "code": null, "e": 1122, "s": 1048, "text": "Convert and reformat accelerometer data into a time-sliced representation" }, { "code": null, "e": 1155, "s": 1122, "text": "Visualize the accelerometer data" }, { "code": null, "e": 1230, "s": 1155, "text": "Reshape the multi-dimensional tabular data so that it is accepted by Keras" }, { "code": null, "e": 1292, "s": 1230, "text": "Split up the data set into training, validation, and test set" }, { "code": null, "e": 1384, "s": 1292, "text": "Define a deep neural network model in Keras which can later be processed by Apple’s Core ML" }, { "code": null, "e": 1450, "s": 1384, "text": "Train the deep neural network for human activity recognition data" }, { "code": null, "e": 1558, "s": 1450, "text": "Validate the performance of the trained DNN against the test data using learning curve and confusion matrix" }, { "code": null, "e": 1605, "s": 1558, "text": "Export the trained Keras DNN model for Core ML" }, { "code": null, "e": 1702, "s": 1605, "text": "Ensure that the Core ML model was exported correctly by conducting a sample prediction in Python" }, { "code": null, "e": 1774, "s": 1702, "text": "Create a playground in Xcode and import the already trained Keras model" }, { "code": null, "e": 1868, "s": 1774, "text": "Use Apple’s Core ML library in order to predict the outcomes for a given data set using Swift" }, { "code": null, "e": 2000, "s": 1868, "text": "Prerequisites in order to conduct all steps explained in this article (including the version number that the code was tested with):" }, { "code": null, "e": 2023, "s": 2000, "text": "Python (version 3.6.5)" }, { "code": null, "e": 2045, "s": 2023, "text": "Keras (version 2.1.6)" }, { "code": null, "e": 2072, "s": 2045, "text": "TensorFlow (version 1.7.0)" }, { "code": null, "e": 2098, "s": 2072, "text": "Coremltools (version 2.0)" }, { "code": null, "e": 2291, "s": 2098, "text": "Out of scope for this article: The creation of the perfect machine learning model with the highest possible performance for this type of problem statement is not the focus of this walkthrough." }, { "code": null, "e": 2415, "s": 2291, "text": "You might wonder why Keras was chosen for this article over other frameworks, namely TensorFlow. There are two key reasons:" }, { "code": null, "e": 2567, "s": 2415, "text": "Keras is very simple to learn and has a modern, more intuitive API than TensorFlow while still leveraging the capabilities of TensorFlow in the backend" }, { "code": null, "e": 2824, "s": 2567, "text": "There are multiple TensorFlow APIs; while trying to use the more convenient estimator API (which is also recommended by the TensorFlow team — you can find more information here) I ran into compilation issues when converting the trained estimator to Core ML" }, { "code": null, "e": 3315, "s": 2824, "text": "Before we walk through the different steps in Python and Xcode, let’s take a brief look at the problem statement and our solution approach. The data set that we are using is a collection of accelerometer data taken from a smartphone that various people carried with them while conducting six different exercises (Downstairs, Jogging, Sitting, Standing, Upstairs, Walking). For each exercise the acceleration for the x, y, and z axis was measured and captured with a timestamp and person ID." }, { "code": null, "e": 3660, "s": 3315, "text": "With this available data, we would like to train a neural network in order to understand if a person carrying a smartphone is performing any of the six activities. Once the neural network has been trained on the existing data, it should be able to correctly predict the type of activity a person is conducting when given previously unseen data." }, { "code": null, "e": 4000, "s": 3660, "text": "The solution to this problem is a deep neural network. Based on the available data it will learn how to differentiate between each of the six activities. We can then show new data to the neural network and it will tell us what the user is doing at any particular point in time. The solution to this problem is depicted in the figure below." }, { "code": null, "e": 4145, "s": 4000, "text": "The typical steps for solving a machine learning problem are depicted below. We will run through a very similar process throughout this article." }, { "code": null, "e": 4272, "s": 4145, "text": "First we need to import all necessary python libraries. If you are missing some of them, install them using the pip installer." }, { "code": null, "e": 4765, "s": 4272, "text": "After importing the libraries, let’s set some standard parameters and print out the Keras version that we have installed. The WISDM dataset contains six different labels (Downstairs, Jogging, Sitting, Standing, Upstairs, Walking). Since we will use the list of labels multiple times, we create a constant for them (LABELS). The next constant TIME_PERIODS stores the length of the time segment. The constant STEP_DISTANCE determines the amount of overlap between two consecutive time segments." }, { "code": null, "e": 4786, "s": 4765, "text": "keras version 2.1.6" }, { "code": null, "e": 5042, "s": 4786, "text": "Next, you need to download the dataset form here and store it locally. The important file is WISDM_ar_v1.1_raw.txt. Before doing the import, let’s define a few convenience functions in order to read the data and show some basic information about the data." }, { "code": null, "e": 5217, "s": 5042, "text": "The data is loaded into the dataframe successfully. Now we can display the first 20 records of the dataframe and get some more insight regarding the distribution of the data." }, { "code": null, "e": 5295, "s": 5217, "text": "Number of columns in the dataframe: 6Number of rows in the dataframe: 1098203" }, { "code": null, "e": 5471, "s": 5295, "text": "As we can see, we have more data for walking and jogging activities than we have for the other activities. Also we can see that 36 persons have participated in the experiment." }, { "code": null, "e": 5876, "s": 5471, "text": "Next, let’s take a look at the accelerometer data for each of the three axis for all six possible activities. The data is recorded at a sampling rate of 20 Hz (20 values per second). Since we show the first 180 records, each chart shows a 9 second interval for each of the six activities (calculation: 0.05 * 180 = 9 seconds). We will use two functions (which I have borrowed from here) to plot the data." }, { "code": null, "e": 6181, "s": 5876, "text": "As expected, there is a higher acceleration for activities such as jogging and walking compared to sitting. Before we continue, we will add one more column with the name “ActivityEncoded” to the dataframe with the encoded value for each activity: Downstairs, Jogging, Sitting, Standing, Upstairs, Walking" }, { "code": null, "e": 6354, "s": 6181, "text": "This is needed since the deep neural network cannot work with non-numerical labels. With the LabelEncoder, we are able to easily to convert back to the original label text." }, { "code": null, "e": 6810, "s": 6354, "text": "It is important to separate the whole data set into a training set and a test set. Often times, you see mistakes on how the data is split. However you decide to split the data, you never want information from the test set to bleed into your training set. This might be great for the overall performance of your model during training and then validation against the test set. But your model is very unlikely to generalize well for data it has not seen yet." }, { "code": null, "e": 7044, "s": 6810, "text": "The idea behind splitting: We want our neural network to learn from a few persons which have been through the experiment. Next, we then want to see how well our neural network predicts the movements of persons it has not seen before." }, { "code": null, "e": 7580, "s": 7044, "text": "Only worrying about having at least a few example records per activity is not sufficient. You will run the risk that you have maybe three records of activity “Walking” for person 5 in the training set and one record for activity “Walking” for person 5 in the test set. Of course, with this type of situation, your model will perform great because it has already seen the movement pattern of person 5 during training. Always be critical about the performance of your DNN — it might be because of the wrong data split in the first place." }, { "code": null, "e": 7738, "s": 7580, "text": "In our case, let’s split based on the user IDs. We will keep users with ID 1 to 28 for training the model and users with ID greater than 28 for the test set." }, { "code": null, "e": 8096, "s": 7738, "text": "Next, we need to normalize our features within our training data. Of course there are various ways on how to normalize. Please keep in mind that you use the same normalization algorithm later when feeding new data into your neural network. Otherwise your preditions will be off. On top of the normalization we will also apply rounding to the three features." }, { "code": null, "e": 8791, "s": 8096, "text": "The data contained in the dataframe is not ready yet to be fed into a neural network. Therefore we need to reshape it. Let’s create another function for this called “create_segments_and_labels”. This function will take in the dataframe and the label names (the constant that we have defined at the beginning) as well as the length of each record. In our case, let’s go with 80 steps (see constant defined earlier). Taking into consideration the 20 Hz sampling rate, this equals to 4 second time intervals (calculation: 0.05 * 80 = 4). Besides reshaping the data, the function will also separate the features (x-acceleration, y-acceleration, z-acceleration) and the labels (associated activity)." }, { "code": null, "e": 8954, "s": 8791, "text": "By now, you should have both 20.868 records in x_train as well as in y_train. Each of the 20.868 records in x_train is a two dimensional matrix of the shape 80x3." }, { "code": null, "e": 9031, "s": 8954, "text": "x_train shape: (20868, 80, 3)20868 training samplesy_train shape: (20868,)" }, { "code": null, "e": 9119, "s": 9031, "text": "For constructing our deep neural network, we should now store the following dimensions:" }, { "code": null, "e": 9278, "s": 9119, "text": "Number of time periods: This is the number of time periods within one record (since we wanted to have a 4 second time interval, this number is 80 in our case)" }, { "code": null, "e": 9368, "s": 9278, "text": "Number of sensors: This is 3 since we only use the acceleration over the x, y, and z axis" }, { "code": null, "e": 9604, "s": 9368, "text": "Number of classes: This is the amount of nodes for our output layer in the neural network. Since we want our neural network to predict the type of activity, we will take the number of classes from the encoder that we have used earlier." }, { "code": null, "e": 9676, "s": 9604, "text": "['Downstairs', 'Jogging', 'Sitting', 'Standing', 'Upstairs', 'Walking']" }, { "code": null, "e": 10023, "s": 9676, "text": "The data that we would like to feed into our network is two dimensional (80x3). Unfortunately, Keras and Core ML in conjunction are not able to process multi-dimensional input data. Therefore we need to “flatten” the data for our input layer into the neural network. Instead of feeding a matrix of shape 80x3 we will feed in a list of 240 values." }, { "code": null, "e": 10067, "s": 10023, "text": "x_train shape: (20868, 240)input_shape: 240" }, { "code": null, "e": 10192, "s": 10067, "text": "Before continuing, we need to convert all feature data (x_train) and label data (y_train) into a datatype accepted by Keras." }, { "code": null, "e": 10355, "s": 10192, "text": "We are almost done with the preparation of our data. One last step we need to do is to conduct one-hot-encoding of our labels. Please only execute this line once!" }, { "code": null, "e": 10386, "s": 10355, "text": "New y_train shape: (20868, 6)" }, { "code": null, "e": 10750, "s": 10386, "text": "By now, you have completed all the heavy-lifting on your side. The data is ready in such a format that Keras will be able to process it. I have decided to create a neural network with 3 hidden layers of 100 fully connected nodes each (feel free to play around with the shape of the network or even switch to more complex ones like a convolutional neural network)." }, { "code": null, "e": 11290, "s": 10750, "text": "Important remark: as you remember, we have reshaped our input data from a 80x3 matrix into a vector of length 240 so that Apple’s Core ML can later process our data. In order to reverse this, our first layer in the neural network will reshape the data into the “old” format. The last two layers will again flatten the data and then run a softmax activation function in order to calculate the probability for each class. Remember, that we are working with six classes in our case (Downstairs, Jogging, Sitting, Standing, Upstairs, Walking)." }, { "code": null, "e": 12402, "s": 11290, "text": "_________________________________________________________________Layer (type) Output Shape Param # =================================================================reshape_2 (Reshape) (None, 80, 3) 0 _________________________________________________________________dense_5 (Dense) (None, 80, 100) 400 _________________________________________________________________dense_6 (Dense) (None, 80, 100) 10100 _________________________________________________________________dense_7 (Dense) (None, 80, 100) 10100 _________________________________________________________________flatten_2 (Flatten) (None, 8000) 0 _________________________________________________________________dense_8 (Dense) (None, 6) 48006 =================================================================Total params: 68,606Trainable params: 68,606Non-trainable params: 0_________________________________________________________________None" }, { "code": null, "e": 13054, "s": 12402, "text": "Next, we will train the model with our training data that we have prepared earlier. We will define an early stopping callback monitor on training accuracy: if the training fails to improve for two consecutive epochs, then the training will stop with the best model. The hyperparameter used for the training are quite simple: We will use a batch size of 400 records and will train the model for 50 epochs. For model training, we will use a 80:20 split to separate training data and validation data. It is that simple. So let’s go ahead and train our model. There are some good explanations out there on the different hyperparameters, for instance here." }, { "code": null, "e": 13395, "s": 13054, "text": "The performance of this simple DNN is OK. We have validation accuracy of approximately 74%. This could definitely improved, maybe with further hyperparameter tuning and especially with a modified neural network design. Before we go on with the test validation, we will print the learning curve for both the training and validation data set." }, { "code": null, "e": 13799, "s": 13395, "text": "precision recall f1-score support 0.0 0.70 0.42 0.53 1864 1.0 0.98 0.98 0.98 6567 2.0 0.99 0.99 0.99 1050 3.0 0.99 0.99 0.99 833 4.0 0.66 0.63 0.64 2342 5.0 0.85 0.93 0.89 8212avg / total 0.87 0.87 0.87 20868" }, { "code": null, "e": 14023, "s": 13799, "text": "Let’s continue with this model and see how it performs against the test data that we have held back earlier. In our case, we will check the performance against the movements of the six users that the model has not yet seen." }, { "code": null, "e": 14132, "s": 14023, "text": "6584/6584 [==============================] - 1s 128us/stepAccuracy on test data: 0.76Loss on test data: 1.39" }, { "code": null, "e": 14302, "s": 14132, "text": "The accuracy on the test data is 76%. This means that our model generalizes well for persons it has not yet seen. Let’s see where our model wrongly predicted the labels." }, { "code": null, "e": 14720, "s": 14302, "text": " precision recall f1-score support 0 0.61 0.27 0.37 650 1 0.80 0.95 0.87 1990 2 0.82 0.99 0.90 452 3 0.91 0.74 0.81 370 4 0.48 0.42 0.45 725 5 0.77 0.79 0.78 2397avg / total 0.74 0.76 0.74 6584" }, { "code": null, "e": 14926, "s": 14720, "text": "As you can see, the precision of the model is good for predicting jogging (1), sitting (2), standing (3), and walking (5). The model has problems for clearly identifying upstairs and downstairs activities." }, { "code": null, "e": 15237, "s": 14926, "text": "There is of course still great potential for improving the model, e.g. by using more advanced neural network designs like convolutional neural networks (CNN) or Long Short Term Memory (LSTM). I might explore this in a later article. For our purpose of showing the end to end process, the result is good enough." }, { "code": null, "e": 15393, "s": 15237, "text": "If you are happy with the model and its performance, you should convert it now to be used with Core ML. The convert function only takes in a few arguments:" }, { "code": null, "e": 15427, "s": 15393, "text": "The reference to your Keras model" }, { "code": null, "e": 15536, "s": 15427, "text": "The name that you want to give the input data; in our case we are feeding acceleration data into the network" }, { "code": null, "e": 15584, "s": 15536, "text": "The name that you want to assign to the outputs" }, { "code": null, "e": 15688, "s": 15584, "text": "The “human-readable” label names; you can again use our LABEL constant that we defined in the beginning" }, { "code": null, "e": 16013, "s": 15688, "text": "input { name: \"acceleration\" type { multiArrayType { shape: 240 dataType: DOUBLE } }}output { name: \"output\" type { dictionaryType { stringKeyType { } } }}output { name: \"classLabel\" type { stringType { } }}predictedFeatureName: \"classLabel\"predictedProbabilitiesName: \"output\"" }, { "code": null, "e": 16210, "s": 16013, "text": "Before using your Core ML model, let’s make sure that the export was successful and that both our Keras model as well as the Core ML model provide the same prediction when given a random data set." }, { "code": null, "e": 16270, "s": 16210, "text": "Prediction from Keras:JoggingPrediction from Coreml:Jogging" }, { "code": null, "e": 16436, "s": 16270, "text": "Great news! For the record with index 1, both Keras and Core ML predict the same label which is Jogging. We are now ready to use our Core ML model on any iOS device." }, { "code": null, "e": 16832, "s": 16436, "text": "In this article you have learned how to load and transform complex accelerometer data and run it through a deep neural network in Keras. You exported the trained model into a Core ML file. In my next article, I will walk you through the steps necessary in order to use this trained Core ML model within a simple Swift program. You can then use this knowledge to deploy the DNN to any iOS device." }, { "code": null, "e": 16894, "s": 16832, "text": "The Jupyter notebook for this article is available on github." }, { "code": null, "e": 16920, "s": 16894, "text": "Official Anaconda website" }, { "code": null, "e": 16943, "s": 16920, "text": "Official Keras website" }, { "code": null, "e": 16971, "s": 16943, "text": "Official TensorFlow website" }, { "code": null, "e": 17008, "s": 16971, "text": "Official Apple Core ML documentation" }, { "code": null, "e": 17053, "s": 17008, "text": "Official Apple coremltools github repository" }, { "code": null, "e": 17125, "s": 17053, "text": "Good overview to decide which framework is for you: TensorFlow or Keras" }, { "code": null, "e": 17254, "s": 17125, "text": "Good article by Aaqib Saeed on convolutional neural networks (CNN) for human activity recognition (also using the WISDM dataset)" }, { "code": null, "e": 17389, "s": 17254, "text": "Another article also using the WISDM dataset implemented with TensorFlow and a more sophisticated LSTM model written by Venelin Valkov" } ]
Bokeh, Bokehjs, and Observablehq. A venture out of Jupyter’s orbit | by Jeremy Teitelbaum | Towards Data Science
The Bokeh visualization library has become one of my favorite tools for displaying data while working with python in the jupyter notebook. Bokeh is powerful, easy to use, has accessible interactive features, and produces beautiful graphs. As I’ve worked with Bokeh over the past months, however, and learned a bit more about its internals, I’ve come to realize that the python API for Bokeh in jupyter is just a small part of the entire Bokeh package. In addition to that API, Bokeh includes a server package and a javascript library called bokehjs. In fact, Bokeh’s python “plotting” package doesn’t do any plotting at all; rather, it is a language for describing plots that get serialized into a json package and passed to bokehjs for rendering in the browser. As I experimented with adding more interactivity to my plots, it gradually became clear to me that knowing some javascript — which I didn’t — and having a clearer understanding of bokehjs would let me do a lot more with Bokeh. Meanwhile, for entirely different reasons, I came across Observablehq. Observablehq is created by a team led by Mike Bostock, the developer of the javascript D3 visualization package. At first glance, it looks very much like a cloud-hosted jupyter notebook based on javascript. Given my goals of exploring bokehjs and learning some javascript, I naively thought Observablehq was the perfect tool for me. Well, it’s not so simple, because Observablehq isn’t just a javascript version of the jupyter notebook, it’s something quite different, and quite beautiful in its own way; and bokehjs isn’t a completely natural fit for the Observablehq world. Still, I learned a lot about both bokehjs and Observablehq in trying to bring these worlds together, and I see a lot of potential for further development. Here are a brief progress report and some tips if you’d like to take this journey as well. As I mentioned above, when I looked at the Observablehq user interface, my first reaction was this is just Jupyter for javascript! As the little animation above shows, Observable has notebooks, with cells, and you enter javascript (or markdown) into the cells; hit shift-enter, and the cell gets evaluated. Sounds like Jupyter, right? But Observable notebooks are profoundly different — each cell has a value, and the cells are assembled together into a graph based on references. When the value of one cell changes, all cells that depend on that cell are re-evaluated. It’s sort of like a spreadsheet of little javascript programs. This design means that Observable notebooks support a high degree of interactivity in a natural way far beyond the ability of jupyter notebooks. If you’re intrigued, your best option is to read the excellent articles at the Observablehq site. Beyond the introductory articles, check out in particular: Observable for jupyter users How Observable runs The first step in experimenting with the bokehjs in an observable notebook is to get the library loaded. For this step, I had help from Bryan Chen’s Hello, Bokehjs notebook. Putting the following code in an observable notebook cell, and hitting Shift-Enter, does the trick: Without spending too much time on the details, it is worth pointing out that the code that loads Bokeh is enclosed in braces so that it gets executed as a unit. As I mentioned earlier, each cell in an observable notebook is like a self-contained javascript program, and the cells are executed and re-executed depending on the dependency graph among their references. The crucial require statements in this code act via side effects, rather than by returning a value. That means Observable doesn’t understand the dependencies among those statements; if put in separate cells, they could be executed in any order. More generally, Observable isn’t set up to deal with functions that act via side effects, and one needs to be careful using them. This particular cell is a viewof construct, and its effect is to assign the variable Bokeh the reference to window.Bokeh where the bokehjs javascript library is attached, while displaying the contents of the message variable which is an html string indicating what’s going on. You can save yourself some typing and, instead of including the code above, take advantage of Observable’s ability to import cells across notebooks and just use: import {Bokeh} from "@jeremy9959/bokeh-experiments" Now that we have the library loaded, let’s draw a plot. I’ll follow the example of a hierarchical bar chart from the bokehjs distribution. You can look directly at the observable notebook where I draw this plot. The first part of the notebook just sets up the data by creating cells corresponding to the fruits and years data, well as the corresponding year by year counts. For example, the year by year counts are stored in the variable data which is declared directly: // help the parser out by putting {} in ()data = ({ 2015: [2,1,4,3,2,4] , 2016:[5,3,3,2,4,6], 2017: [ 3,2,4,4,5,3],}) Notice that the braces used in javascript explicit object creation need parentheses to help the observable parser out. The Bokeh code to create the plot is taken directly from the file in the bokehjs distribution (though I made the plot a bit wider): Finally, we render the plot into a cell in the observable notebook using Bokehjs’s embed function. The result is the plot I’ve drawn above. So far, this is a bit underwhelming, since we could have drawn the same plot in a jupyter notebook using the python API with no trouble at all. To illustrate why this approach is interesting, let me point out two major benefits we get by working in observable. We can inspect the javascript objects. One of the reasons I was interested in Observable in the first place is because I’m trying to learn javascript and trying to understand the inner workings of bokehjs. It’s certainly possible to use the browser’s javascript console to poke around the internals of bokehjs, but observable gives an elegant interface. For example, in producing the plot we constructed a Figure object called P. The image below shows what Observable can reveal about this figure, and using the little triangles you can open up the object and probe its inner structure. (Note: it’s important to load the non-minified bokehjs package if you want to do this, or the class ID’s will be incomprehensible in this output.) We can inspect the javascript objects. One of the reasons I was interested in Observable in the first place is because I’m trying to learn javascript and trying to understand the inner workings of bokehjs. It’s certainly possible to use the browser’s javascript console to poke around the internals of bokehjs, but observable gives an elegant interface. For example, in producing the plot we constructed a Figure object called P. The image below shows what Observable can reveal about this figure, and using the little triangles you can open up the object and probe its inner structure. (Note: it’s important to load the non-minified bokehjs package if you want to do this, or the class ID’s will be incomprehensible in this output.) 2. Observable is interactive! What’s really different, and interesting, about doing this in Observable is that it’s interactive. If I go up to the cell where the variable data is defined, and change the numbers, as soon as I enter the cell the graph gets updated: This is because Observable’s execution graph knows that the fruit plot depends on the data variable, and when that variable changes, the plot gets recomputed. Incidentally, another feature of Observable is that since the execution order isn’t tied to the physical ordering of the cells in the document, I was able to move the graph right up next to the data cell so I can see clearly what was going on. This is only a tiny taste of the level of interactivity that’s possible in Observable — it’s very easy, for example, to add widgets and even do animations right in the notebook. This post isn’t the place to get into that, but there are lots of beautiful examples on the Observable home page. In closing, I think it’s important to point out that there are more natural ways to plot in Observable than using Bokeh. In particular, there is a tightly integrated API for using Vega, and the very powerful D3 package is practically built in to Observable. But for someone like me, who is comfortable with the python interface to bokeh and wants to learn more about bokehjs — especially considering that, while the python API is extensively and meticulously documented, the bokehjs API is basically a black box — Observable offers a fun opportunity. There are lots more things to try and I look forward to further ventures beyond the orbit of Jupyter.
[ { "code": null, "e": 1162, "s": 172, "text": "The Bokeh visualization library has become one of my favorite tools for displaying data while working with python in the jupyter notebook. Bokeh is powerful, easy to use, has accessible interactive features, and produces beautiful graphs. As I’ve worked with Bokeh over the past months, however, and learned a bit more about its internals, I’ve come to realize that the python API for Bokeh in jupyter is just a small part of the entire Bokeh package. In addition to that API, Bokeh includes a server package and a javascript library called bokehjs. In fact, Bokeh’s python “plotting” package doesn’t do any plotting at all; rather, it is a language for describing plots that get serialized into a json package and passed to bokehjs for rendering in the browser. As I experimented with adding more interactivity to my plots, it gradually became clear to me that knowing some javascript — which I didn’t — and having a clearer understanding of bokehjs would let me do a lot more with Bokeh." }, { "code": null, "e": 2055, "s": 1162, "text": "Meanwhile, for entirely different reasons, I came across Observablehq. Observablehq is created by a team led by Mike Bostock, the developer of the javascript D3 visualization package. At first glance, it looks very much like a cloud-hosted jupyter notebook based on javascript. Given my goals of exploring bokehjs and learning some javascript, I naively thought Observablehq was the perfect tool for me. Well, it’s not so simple, because Observablehq isn’t just a javascript version of the jupyter notebook, it’s something quite different, and quite beautiful in its own way; and bokehjs isn’t a completely natural fit for the Observablehq world. Still, I learned a lot about both bokehjs and Observablehq in trying to bring these worlds together, and I see a lot of potential for further development. Here are a brief progress report and some tips if you’d like to take this journey as well." }, { "code": null, "e": 2186, "s": 2055, "text": "As I mentioned above, when I looked at the Observablehq user interface, my first reaction was this is just Jupyter for javascript!" }, { "code": null, "e": 2990, "s": 2186, "text": "As the little animation above shows, Observable has notebooks, with cells, and you enter javascript (or markdown) into the cells; hit shift-enter, and the cell gets evaluated. Sounds like Jupyter, right? But Observable notebooks are profoundly different — each cell has a value, and the cells are assembled together into a graph based on references. When the value of one cell changes, all cells that depend on that cell are re-evaluated. It’s sort of like a spreadsheet of little javascript programs. This design means that Observable notebooks support a high degree of interactivity in a natural way far beyond the ability of jupyter notebooks. If you’re intrigued, your best option is to read the excellent articles at the Observablehq site. Beyond the introductory articles, check out in particular:" }, { "code": null, "e": 3019, "s": 2990, "text": "Observable for jupyter users" }, { "code": null, "e": 3039, "s": 3019, "text": "How Observable runs" }, { "code": null, "e": 3313, "s": 3039, "text": "The first step in experimenting with the bokehjs in an observable notebook is to get the library loaded. For this step, I had help from Bryan Chen’s Hello, Bokehjs notebook. Putting the following code in an observable notebook cell, and hitting Shift-Enter, does the trick:" }, { "code": null, "e": 4055, "s": 3313, "text": "Without spending too much time on the details, it is worth pointing out that the code that loads Bokeh is enclosed in braces so that it gets executed as a unit. As I mentioned earlier, each cell in an observable notebook is like a self-contained javascript program, and the cells are executed and re-executed depending on the dependency graph among their references. The crucial require statements in this code act via side effects, rather than by returning a value. That means Observable doesn’t understand the dependencies among those statements; if put in separate cells, they could be executed in any order. More generally, Observable isn’t set up to deal with functions that act via side effects, and one needs to be careful using them." }, { "code": null, "e": 4332, "s": 4055, "text": "This particular cell is a viewof construct, and its effect is to assign the variable Bokeh the reference to window.Bokeh where the bokehjs javascript library is attached, while displaying the contents of the message variable which is an html string indicating what’s going on." }, { "code": null, "e": 4494, "s": 4332, "text": "You can save yourself some typing and, instead of including the code above, take advantage of Observable’s ability to import cells across notebooks and just use:" }, { "code": null, "e": 4546, "s": 4494, "text": "import {Bokeh} from \"@jeremy9959/bokeh-experiments\"" }, { "code": null, "e": 4685, "s": 4546, "text": "Now that we have the library loaded, let’s draw a plot. I’ll follow the example of a hierarchical bar chart from the bokehjs distribution." }, { "code": null, "e": 5017, "s": 4685, "text": "You can look directly at the observable notebook where I draw this plot. The first part of the notebook just sets up the data by creating cells corresponding to the fruits and years data, well as the corresponding year by year counts. For example, the year by year counts are stored in the variable data which is declared directly:" }, { "code": null, "e": 5138, "s": 5017, "text": "// help the parser out by putting {} in ()data = ({ 2015: [2,1,4,3,2,4] , 2016:[5,3,3,2,4,6], 2017: [ 3,2,4,4,5,3],})" }, { "code": null, "e": 5257, "s": 5138, "text": "Notice that the braces used in javascript explicit object creation need parentheses to help the observable parser out." }, { "code": null, "e": 5389, "s": 5257, "text": "The Bokeh code to create the plot is taken directly from the file in the bokehjs distribution (though I made the plot a bit wider):" }, { "code": null, "e": 5488, "s": 5389, "text": "Finally, we render the plot into a cell in the observable notebook using Bokehjs’s embed function." }, { "code": null, "e": 5529, "s": 5488, "text": "The result is the plot I’ve drawn above." }, { "code": null, "e": 5790, "s": 5529, "text": "So far, this is a bit underwhelming, since we could have drawn the same plot in a jupyter notebook using the python API with no trouble at all. To illustrate why this approach is interesting, let me point out two major benefits we get by working in observable." }, { "code": null, "e": 6524, "s": 5790, "text": "We can inspect the javascript objects. One of the reasons I was interested in Observable in the first place is because I’m trying to learn javascript and trying to understand the inner workings of bokehjs. It’s certainly possible to use the browser’s javascript console to poke around the internals of bokehjs, but observable gives an elegant interface. For example, in producing the plot we constructed a Figure object called P. The image below shows what Observable can reveal about this figure, and using the little triangles you can open up the object and probe its inner structure. (Note: it’s important to load the non-minified bokehjs package if you want to do this, or the class ID’s will be incomprehensible in this output.)" }, { "code": null, "e": 7258, "s": 6524, "text": "We can inspect the javascript objects. One of the reasons I was interested in Observable in the first place is because I’m trying to learn javascript and trying to understand the inner workings of bokehjs. It’s certainly possible to use the browser’s javascript console to poke around the internals of bokehjs, but observable gives an elegant interface. For example, in producing the plot we constructed a Figure object called P. The image below shows what Observable can reveal about this figure, and using the little triangles you can open up the object and probe its inner structure. (Note: it’s important to load the non-minified bokehjs package if you want to do this, or the class ID’s will be incomprehensible in this output.)" }, { "code": null, "e": 7522, "s": 7258, "text": "2. Observable is interactive! What’s really different, and interesting, about doing this in Observable is that it’s interactive. If I go up to the cell where the variable data is defined, and change the numbers, as soon as I enter the cell the graph gets updated:" }, { "code": null, "e": 7681, "s": 7522, "text": "This is because Observable’s execution graph knows that the fruit plot depends on the data variable, and when that variable changes, the plot gets recomputed." }, { "code": null, "e": 7925, "s": 7681, "text": "Incidentally, another feature of Observable is that since the execution order isn’t tied to the physical ordering of the cells in the document, I was able to move the graph right up next to the data cell so I can see clearly what was going on." }, { "code": null, "e": 8217, "s": 7925, "text": "This is only a tiny taste of the level of interactivity that’s possible in Observable — it’s very easy, for example, to add widgets and even do animations right in the notebook. This post isn’t the place to get into that, but there are lots of beautiful examples on the Observable home page." } ]
Primality Test | Set 1 (Introduction and School Method) - GeeksforGeeks
17 Mar, 2021 Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5, Examples : Input: n = 11 Output: true Input: n = 15 Output: false Input: n = 1 Output: false School Method A simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find any number that divides, we return false. Below is the implementation of this method. C++ Java Python3 C# PHP Javascript // A school method based C++ program to check if a// number is prime#include <bits/stdc++.h>using namespace std; bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i=2; i<n; i++) if (n%i == 0) return false; return true;} // Driver Program to test above functionint main(){ isPrime(11)? cout << " true\n": cout << " false\n"; isPrime(15)? cout << " true\n": cout << " false\n"; return 0;} // A school method based JAVA program// to check if a number is primeclass GFG { static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Driver Program public static void main(String args[]) { if(isPrime(11)) System.out.println(" true"); else System.out.println(" false"); if(isPrime(15)) System.out.println(" true"); else System.out.println(" false"); }} // This code is contributed// by Nikita Tiwari. # A school method based Python3# program to check if a number# is prime def isPrime(n): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False; return True # Driver Program to test above functionprint("true") if isPrime(11) else print("false")print("true") if isPrime(14) else print("false") # This code is contributed by Smitha Dinesh Semwal // A optimized school method based C#// program to check if a number is primeusing System; namespace prime{ public class GFG { public static bool isprime(int n) { // Corner cases if (n <= 1) return false; for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Driver program public static void Main() { if (isprime(11)) Console.WriteLine("true"); else Console.WriteLine("false"); if (isprime(15)) Console.WriteLine("true"); else Console.WriteLine("false"); } }} // This code is contributed by Sam007 <?php// A school method based PHP// program to check if a number// is prime function isPrime($n){ // Corner case if ($n <= 1) return false; // Check from 2 to n-1 for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false; return true;} // Driver Code$tet = isPrime(11) ? " true\n" : " false\n";echo $tet;$tet = isPrime(15) ? " true\n" : " false\n";echo $tet; // This code is contributed by m_kit?> <script> // A school method based Javascript program to check if a// number is primefunction isPrime(n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (let i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Driver Program to test above function isPrime(11)? document.write(" true" + "<br>"): document.write(" false" + "<br>"); isPrime(15)? document.write(" true" + "<br>"): document.write(" false" + "<br>"); // This code is contributed by Mayank Tyagi </script> Output : true false Time complexity of this solution is O(n)Optimized School Method We can do following optimizations: Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia) Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked. The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia) jit_t mayanktyagi1709 number-theory Prime Number Mathematical number-theory Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Print all possible combinations of r elements in a given array of size n Minimum number of jumps to reach end
[ { "code": null, "e": 24770, "s": 24742, "text": "\n17 Mar, 2021" }, { "code": null, "e": 24994, "s": 24770, "text": "Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5, Examples : " }, { "code": null, "e": 25081, "s": 24994, "text": "Input: n = 11\nOutput: true\n\nInput: n = 15\nOutput: false\n\nInput: n = 1\nOutput: false" }, { "code": null, "e": 25306, "s": 25083, "text": "School Method A simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find any number that divides, we return false. Below is the implementation of this method. " }, { "code": null, "e": 25310, "s": 25306, "text": "C++" }, { "code": null, "e": 25315, "s": 25310, "text": "Java" }, { "code": null, "e": 25323, "s": 25315, "text": "Python3" }, { "code": null, "e": 25326, "s": 25323, "text": "C#" }, { "code": null, "e": 25330, "s": 25326, "text": "PHP" }, { "code": null, "e": 25341, "s": 25330, "text": "Javascript" }, { "code": "// A school method based C++ program to check if a// number is prime#include <bits/stdc++.h>using namespace std; bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i=2; i<n; i++) if (n%i == 0) return false; return true;} // Driver Program to test above functionint main(){ isPrime(11)? cout << \" true\\n\": cout << \" false\\n\"; isPrime(15)? cout << \" true\\n\": cout << \" false\\n\"; return 0;}", "e": 25819, "s": 25341, "text": null }, { "code": "// A school method based JAVA program// to check if a number is primeclass GFG { static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Driver Program public static void main(String args[]) { if(isPrime(11)) System.out.println(\" true\"); else System.out.println(\" false\"); if(isPrime(15)) System.out.println(\" true\"); else System.out.println(\" false\"); }} // This code is contributed// by Nikita Tiwari.", "e": 26522, "s": 25819, "text": null }, { "code": "# A school method based Python3# program to check if a number# is prime def isPrime(n): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False; return True # Driver Program to test above functionprint(\"true\") if isPrime(11) else print(\"false\")print(\"true\") if isPrime(14) else print(\"false\") # This code is contributed by Smitha Dinesh Semwal", "e": 26963, "s": 26522, "text": null }, { "code": "// A optimized school method based C#// program to check if a number is primeusing System; namespace prime{ public class GFG { public static bool isprime(int n) { // Corner cases if (n <= 1) return false; for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Driver program public static void Main() { if (isprime(11)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); if (isprime(15)) Console.WriteLine(\"true\"); else Console.WriteLine(\"false\"); } }} // This code is contributed by Sam007", "e": 27701, "s": 26963, "text": null }, { "code": "<?php// A school method based PHP// program to check if a number// is prime function isPrime($n){ // Corner case if ($n <= 1) return false; // Check from 2 to n-1 for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false; return true;} // Driver Code$tet = isPrime(11) ? \" true\\n\" : \" false\\n\";echo $tet;$tet = isPrime(15) ? \" true\\n\" : \" false\\n\";echo $tet; // This code is contributed by m_kit?>", "e": 28175, "s": 27701, "text": null }, { "code": "<script> // A school method based Javascript program to check if a// number is primefunction isPrime(n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (let i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Driver Program to test above function isPrime(11)? document.write(\" true\" + \"<br>\"): document.write(\" false\" + \"<br>\"); isPrime(15)? document.write(\" true\" + \"<br>\"): document.write(\" false\" + \"<br>\"); // This code is contributed by Mayank Tyagi </script>", "e": 28715, "s": 28175, "text": null }, { "code": null, "e": 28726, "s": 28715, "text": "Output : " }, { "code": null, "e": 28737, "s": 28726, "text": "true\nfalse" }, { "code": null, "e": 28837, "s": 28737, "text": "Time complexity of this solution is O(n)Optimized School Method We can do following optimizations: " }, { "code": null, "e": 29420, "s": 28837, "text": "Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)" }, { "code": null, "e": 29566, "s": 29420, "text": "Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked." }, { "code": null, "e": 30004, "s": 29566, "text": "The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)" }, { "code": null, "e": 30010, "s": 30004, "text": "jit_t" }, { "code": null, "e": 30026, "s": 30010, "text": "mayanktyagi1709" }, { "code": null, "e": 30040, "s": 30026, "text": "number-theory" }, { "code": null, "e": 30053, "s": 30040, "text": "Prime Number" }, { "code": null, "e": 30066, "s": 30053, "text": "Mathematical" }, { "code": null, "e": 30080, "s": 30066, "text": "number-theory" }, { "code": null, "e": 30093, "s": 30080, "text": "Mathematical" }, { "code": null, "e": 30106, "s": 30093, "text": "Prime Number" }, { "code": null, "e": 30204, "s": 30106, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30228, "s": 30204, "text": "Merge two sorted arrays" }, { "code": null, "e": 30271, "s": 30228, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30320, "s": 30271, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30361, "s": 30320, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 30395, "s": 30361, "text": "Program for factorial of a number" }, { "code": null, "e": 30416, "s": 30395, "text": "Operators in C / C++" }, { "code": null, "e": 30459, "s": 30416, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 30512, "s": 30459, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 30585, "s": 30512, "text": "Print all possible combinations of r elements in a given array of size n" } ]
Node.js path.format() Method - GeeksforGeeks
08 Oct, 2021 The path.format() method is used to return a path string from the given path object. The method has some rules where one path property gets more priority over another: The “root” parameter of the path object is ignored if the “dir” parameter is provided. The “ext” and “name” parameter of the path object are ignored if the “base” parameter is provided. Syntax: path.format( pathObject ) Parameters: This function accepts single parameter pathObject that contains the details of the path. It has the following parameters: dir: It specifies the directory name of the path object. root: It specifies the root of the path object. base: It specifies the base of the path object. name: It specifies the file name of the path object. ext: It specifies the file extension of the path object. Return Value: It returns a path string from the provided path object. Below programs illustrate the path.format() method in Node.js: Example 1: On POSIX // Import the path moduleconst path = require('path'); // CASE 1// If "dir", "root" and "base" are all given,// "root" is ignored.let path1 = path.format({ root: "/ignored/root/", dir: "/home/user/personal", base: "details.txt",});console.log("Path 1:", path1); // CASE 2// If "dir" is not specified then "root" will be used // If only "root" is provided// platform separator will not be included.// "ext" will be ignored.let path2 = path.format({ root: "/", base: "game.dat", ext: ".noextension",});console.log("Path 2:", path2); // CASE 3// If "base" is not specified// "name" and "ext" will be used let path3 = path.format({ root: "/images/", name: "image", ext: ".jpg",});console.log("Path 3:", path3); Output: Path 1: /home/user/personal/details.txt Path 2: /game.dat Path 3: /images/image.jpg Example 2: On Windows // Import the path moduleconst path = require('path'); // CASE 1// If "dir", "root" and "base" are all given,// "root" is ignored.let path1 = path.format({ root: "C:\\ignored\\root", dir: "website\\dist", base: "index.html",});console.log("Path 1:", path1); // CASE 2// If "dir" is not specified then "root"// will be used // If only "root" is provided platform// separator will not be included.// "ext" will be ignored.let path2 = path.format({ root: "C:\\", base: "style.css", ext: ".ignored",});console.log("Path 2:", path2); // CASE 3// If "base" is not specified// "name" and "ext" will be used let path3 = path.format({ root: "website\\", name: "main", ext: ".js",});console.log("Path 3:", path3); Output: Path 1: website\dist\index.html Path 2: C:\style.css Path 3: website\main.js Reference: https://nodejs.org/api/path.html#path_path_format_pathobject Node.js-path-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFileSync() Method How to update Node.js and NPM to next version ? Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37256, "s": 37228, "text": "\n08 Oct, 2021" }, { "code": null, "e": 37424, "s": 37256, "text": "The path.format() method is used to return a path string from the given path object. The method has some rules where one path property gets more priority over another:" }, { "code": null, "e": 37511, "s": 37424, "text": "The “root” parameter of the path object is ignored if the “dir” parameter is provided." }, { "code": null, "e": 37610, "s": 37511, "text": "The “ext” and “name” parameter of the path object are ignored if the “base” parameter is provided." }, { "code": null, "e": 37618, "s": 37610, "text": "Syntax:" }, { "code": null, "e": 37644, "s": 37618, "text": "path.format( pathObject )" }, { "code": null, "e": 37778, "s": 37644, "text": "Parameters: This function accepts single parameter pathObject that contains the details of the path. It has the following parameters:" }, { "code": null, "e": 37835, "s": 37778, "text": "dir: It specifies the directory name of the path object." }, { "code": null, "e": 37883, "s": 37835, "text": "root: It specifies the root of the path object." }, { "code": null, "e": 37931, "s": 37883, "text": "base: It specifies the base of the path object." }, { "code": null, "e": 37984, "s": 37931, "text": "name: It specifies the file name of the path object." }, { "code": null, "e": 38041, "s": 37984, "text": "ext: It specifies the file extension of the path object." }, { "code": null, "e": 38111, "s": 38041, "text": "Return Value: It returns a path string from the provided path object." }, { "code": null, "e": 38174, "s": 38111, "text": "Below programs illustrate the path.format() method in Node.js:" }, { "code": null, "e": 38194, "s": 38174, "text": "Example 1: On POSIX" }, { "code": "// Import the path moduleconst path = require('path'); // CASE 1// If \"dir\", \"root\" and \"base\" are all given,// \"root\" is ignored.let path1 = path.format({ root: \"/ignored/root/\", dir: \"/home/user/personal\", base: \"details.txt\",});console.log(\"Path 1:\", path1); // CASE 2// If \"dir\" is not specified then \"root\" will be used // If only \"root\" is provided// platform separator will not be included.// \"ext\" will be ignored.let path2 = path.format({ root: \"/\", base: \"game.dat\", ext: \".noextension\",});console.log(\"Path 2:\", path2); // CASE 3// If \"base\" is not specified// \"name\" and \"ext\" will be used let path3 = path.format({ root: \"/images/\", name: \"image\", ext: \".jpg\",});console.log(\"Path 3:\", path3);", "e": 38931, "s": 38194, "text": null }, { "code": null, "e": 38939, "s": 38931, "text": "Output:" }, { "code": null, "e": 39023, "s": 38939, "text": "Path 1: /home/user/personal/details.txt\nPath 2: /game.dat\nPath 3: /images/image.jpg" }, { "code": null, "e": 39045, "s": 39023, "text": "Example 2: On Windows" }, { "code": "// Import the path moduleconst path = require('path'); // CASE 1// If \"dir\", \"root\" and \"base\" are all given,// \"root\" is ignored.let path1 = path.format({ root: \"C:\\\\ignored\\\\root\", dir: \"website\\\\dist\", base: \"index.html\",});console.log(\"Path 1:\", path1); // CASE 2// If \"dir\" is not specified then \"root\"// will be used // If only \"root\" is provided platform// separator will not be included.// \"ext\" will be ignored.let path2 = path.format({ root: \"C:\\\\\", base: \"style.css\", ext: \".ignored\",});console.log(\"Path 2:\", path2); // CASE 3// If \"base\" is not specified// \"name\" and \"ext\" will be used let path3 = path.format({ root: \"website\\\\\", name: \"main\", ext: \".js\",});console.log(\"Path 3:\", path3);", "e": 39779, "s": 39045, "text": null }, { "code": null, "e": 39787, "s": 39779, "text": "Output:" }, { "code": null, "e": 39864, "s": 39787, "text": "Path 1: website\\dist\\index.html\nPath 2: C:\\style.css\nPath 3: website\\main.js" }, { "code": null, "e": 39936, "s": 39864, "text": "Reference: https://nodejs.org/api/path.html#path_path_format_pathobject" }, { "code": null, "e": 39956, "s": 39936, "text": "Node.js-path-module" }, { "code": null, "e": 39964, "s": 39956, "text": "Node.js" }, { "code": null, "e": 39981, "s": 39964, "text": "Web Technologies" }, { "code": null, "e": 40079, "s": 39981, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40112, "s": 40079, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 40160, "s": 40112, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40190, "s": 40160, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 40210, "s": 40190, "text": "How to update NPM ?" }, { "code": null, "e": 40264, "s": 40210, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 40306, "s": 40264, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 40349, "s": 40306, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 40411, "s": 40349, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40456, "s": 40411, "text": "Convert a string to an integer in JavaScript" } ]
Jupyter Best Practices That Will Save You A Lot of Headaches | by Brunna Torino | Towards Data Science
Having been working with Jupyter almost daily for the past three years, I have experienced serious undesired situations that took me back days, or even weeks in my project completion time. These are simple things that I have learned to do to prevent serious data loss, time loss, and project phase confusion. If you have a 75MB file that takes 10–15 minutes to import to your working Jupyter Lab or Notebook, make sure to save it as a copy as soon as the import is done: import pandas as pdreally_large_file = pd.read_excel('largefile.xlsx')copy = really_large_file.copy() You can then choose to work on the copy of the original data frame or the original data frame (there’s no difference) but the important thing is that you will be able to go back to one of those original files if you make an irreparable mistake and only notice way down the line when it’s too late or too confusing to “undo cell operation”. If you have identified a rough number of significant phases of your project where you will change the dataset significantly, make sure to save it as another name by the of the operation, such as: def some_operation_to_my_data(df):# some operation return dfnew_df = some_operation_to_my_data(old_df) This way you can always go back to your old data frame before the big operation if you need to cross-check any details or discard the operation completely. There is an obvious trade-off here between saving copies and memory usage. If you find yourself with a heavy Jupyter file, always remember to delete those copies (as something called garbage collection) as you go along and validate them, and become certain that you won’t need them anymore. del old_dfdel really_large_file Instead of saving copies from your checkpoints, you can also save them as files, freeing memory from the current Jupyter session: def some_operation_to_my_data(df):# some operation return dfnew_df = some_operation_to_my_data(old_df)old _df.to_excel('checkpoint1.xlsx')del old_df One of the most annoying things that can happen is to spend hours and hours investigating and understanding your dataset, and arrive the next morning or the next week, and not understand anymore what you did or what you concluded. Even worse, if when another colleague has to take over, and you can’t explain your work anymore. Label parts of your Jupyter Notebook by creating a cell between them, where you will label what you are doing for this next phase. Also include a conclusion cell at the end, with a short summary of what you understood and any questions you have left. ## DATA VISUALIZATION PART : HIST, HEATMAP, CORRELATIONS...# CONCLUSIONS: NO SKEWDNESS, NORMAL DIST, MULTICOLLINERAITY... This tip goes along with the previous point, but it’s worth mentioning and emphasizing by itself. Sometimes, you want to do a quick operation on an earlier copy of your dataset, and you don’t think you will keep it in your file anyway — so you pick a random cell and write the code there. We have all been there, but try to form a habit of organizing cell operations chronologically and where they would be if you were to hand in the project today as it is, or had to explain what/how/why you wrote the code that way. It saves you time formating everything for submission later on. If you have a large folder containing dozens of files, it can be extremely tedious to import each one of them individually. What you can do instead, is transform that folder into a .zip file and open that in Jupyter: import zipfile as zffiles = zf.ZipFile("ZippedFolder.zip", 'r')files.extractall('directory to extract')files.close() In the same way, if you need to download several files from Jupyter you can also do it in one line: import shutilshutil.make_archive(output_filename_dont_add_.zip, 'zip', directory_to_download) Source for this code: Afshin Amiri Have you written a full algorithm and now you realized you actually have to change most of it or scrap it entirely? Open a draft file for every main file of your project, and copy-paste any unwanted code you wrote in there. It happens more often than not that you can use some of what you wrote previously on your new algorithm, or have to go back to see what didn’t work in your previous code. It occupies very little extra space and can save you a lot of time and confusion. Did you write a forever-looping algorithm by mistake? Do you suspect your current algorithm is not going to output what you expect? You don’t need to close everything or delete the cell. Look for the Interrupt Kernel button on the Jupyter menu bar and interrupt the currently running cell to save your project from data loss. Did you accidentally delete a cell, or made a mistake with your dataset? You can look for “Undo Cell Operation” in the Jupyter menu bar to bring back the cell you deleted, or undo the cell operation of your data. Jupyter will save checkpoints of your notebook from time to time, and if you realize you need to revert your whole file back to an earlier version, you can do that with the “Revert to Checkpoint” button. However, it is not the most reliable way of retrieving data and code as the checkpoint could have been three minutes ago or eight hours ago. I would always use the other tips aforementioned before this one, but it is good to know it exists. If you almost always use the same imports and packages in your projects, such as: import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport sklearn[...] You can save those repetitive imports as a Jupyter Notebook, and just click on Duplicate instead of opening a new, blank file. It saves you a little bit of time and proves to be very convenient in the long-run. This is a non-exhaustive list of best practices I found to increase my productivity, efficiency, and also professionalism while using Jupyter. For me, the most important benefit of implementing these is that I can always go back to an earlier version of my project (be it in older code I thought wouldn’t work, or earlier versions of a dataset) quickly and efficiently, which in turn makes me more willing (and less hesitant to) take risks, make mistakes and try new ways of achieving my goals. Do you have any other advice? Comment below and I will add them to the article!
[ { "code": null, "e": 481, "s": 172, "text": "Having been working with Jupyter almost daily for the past three years, I have experienced serious undesired situations that took me back days, or even weeks in my project completion time. These are simple things that I have learned to do to prevent serious data loss, time loss, and project phase confusion." }, { "code": null, "e": 643, "s": 481, "text": "If you have a 75MB file that takes 10–15 minutes to import to your working Jupyter Lab or Notebook, make sure to save it as a copy as soon as the import is done:" }, { "code": null, "e": 745, "s": 643, "text": "import pandas as pdreally_large_file = pd.read_excel('largefile.xlsx')copy = really_large_file.copy()" }, { "code": null, "e": 1085, "s": 745, "text": "You can then choose to work on the copy of the original data frame or the original data frame (there’s no difference) but the important thing is that you will be able to go back to one of those original files if you make an irreparable mistake and only notice way down the line when it’s too late or too confusing to “undo cell operation”." }, { "code": null, "e": 1281, "s": 1085, "text": "If you have identified a rough number of significant phases of your project where you will change the dataset significantly, make sure to save it as another name by the of the operation, such as:" }, { "code": null, "e": 1385, "s": 1281, "text": "def some_operation_to_my_data(df):# some operation return dfnew_df = some_operation_to_my_data(old_df)" }, { "code": null, "e": 1541, "s": 1385, "text": "This way you can always go back to your old data frame before the big operation if you need to cross-check any details or discard the operation completely." }, { "code": null, "e": 1832, "s": 1541, "text": "There is an obvious trade-off here between saving copies and memory usage. If you find yourself with a heavy Jupyter file, always remember to delete those copies (as something called garbage collection) as you go along and validate them, and become certain that you won’t need them anymore." }, { "code": null, "e": 1864, "s": 1832, "text": "del old_dfdel really_large_file" }, { "code": null, "e": 1994, "s": 1864, "text": "Instead of saving copies from your checkpoints, you can also save them as files, freeing memory from the current Jupyter session:" }, { "code": null, "e": 2144, "s": 1994, "text": "def some_operation_to_my_data(df):# some operation return dfnew_df = some_operation_to_my_data(old_df)old _df.to_excel('checkpoint1.xlsx')del old_df" }, { "code": null, "e": 2472, "s": 2144, "text": "One of the most annoying things that can happen is to spend hours and hours investigating and understanding your dataset, and arrive the next morning or the next week, and not understand anymore what you did or what you concluded. Even worse, if when another colleague has to take over, and you can’t explain your work anymore." }, { "code": null, "e": 2723, "s": 2472, "text": "Label parts of your Jupyter Notebook by creating a cell between them, where you will label what you are doing for this next phase. Also include a conclusion cell at the end, with a short summary of what you understood and any questions you have left." }, { "code": null, "e": 2845, "s": 2723, "text": "## DATA VISUALIZATION PART : HIST, HEATMAP, CORRELATIONS...# CONCLUSIONS: NO SKEWDNESS, NORMAL DIST, MULTICOLLINERAITY..." }, { "code": null, "e": 2943, "s": 2845, "text": "This tip goes along with the previous point, but it’s worth mentioning and emphasizing by itself." }, { "code": null, "e": 3363, "s": 2943, "text": "Sometimes, you want to do a quick operation on an earlier copy of your dataset, and you don’t think you will keep it in your file anyway — so you pick a random cell and write the code there. We have all been there, but try to form a habit of organizing cell operations chronologically and where they would be if you were to hand in the project today as it is, or had to explain what/how/why you wrote the code that way." }, { "code": null, "e": 3427, "s": 3363, "text": "It saves you time formating everything for submission later on." }, { "code": null, "e": 3644, "s": 3427, "text": "If you have a large folder containing dozens of files, it can be extremely tedious to import each one of them individually. What you can do instead, is transform that folder into a .zip file and open that in Jupyter:" }, { "code": null, "e": 3761, "s": 3644, "text": "import zipfile as zffiles = zf.ZipFile(\"ZippedFolder.zip\", 'r')files.extractall('directory to extract')files.close()" }, { "code": null, "e": 3861, "s": 3761, "text": "In the same way, if you need to download several files from Jupyter you can also do it in one line:" }, { "code": null, "e": 3955, "s": 3861, "text": "import shutilshutil.make_archive(output_filename_dont_add_.zip, 'zip', directory_to_download)" }, { "code": null, "e": 3990, "s": 3955, "text": "Source for this code: Afshin Amiri" }, { "code": null, "e": 4106, "s": 3990, "text": "Have you written a full algorithm and now you realized you actually have to change most of it or scrap it entirely?" }, { "code": null, "e": 4467, "s": 4106, "text": "Open a draft file for every main file of your project, and copy-paste any unwanted code you wrote in there. It happens more often than not that you can use some of what you wrote previously on your new algorithm, or have to go back to see what didn’t work in your previous code. It occupies very little extra space and can save you a lot of time and confusion." }, { "code": null, "e": 4793, "s": 4467, "text": "Did you write a forever-looping algorithm by mistake? Do you suspect your current algorithm is not going to output what you expect? You don’t need to close everything or delete the cell. Look for the Interrupt Kernel button on the Jupyter menu bar and interrupt the currently running cell to save your project from data loss." }, { "code": null, "e": 5006, "s": 4793, "text": "Did you accidentally delete a cell, or made a mistake with your dataset? You can look for “Undo Cell Operation” in the Jupyter menu bar to bring back the cell you deleted, or undo the cell operation of your data." }, { "code": null, "e": 5451, "s": 5006, "text": "Jupyter will save checkpoints of your notebook from time to time, and if you realize you need to revert your whole file back to an earlier version, you can do that with the “Revert to Checkpoint” button. However, it is not the most reliable way of retrieving data and code as the checkpoint could have been three minutes ago or eight hours ago. I would always use the other tips aforementioned before this one, but it is good to know it exists." }, { "code": null, "e": 5533, "s": 5451, "text": "If you almost always use the same imports and packages in your projects, such as:" }, { "code": null, "e": 5642, "s": 5533, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport sklearn[...]" }, { "code": null, "e": 5853, "s": 5642, "text": "You can save those repetitive imports as a Jupyter Notebook, and just click on Duplicate instead of opening a new, blank file. It saves you a little bit of time and proves to be very convenient in the long-run." }, { "code": null, "e": 6348, "s": 5853, "text": "This is a non-exhaustive list of best practices I found to increase my productivity, efficiency, and also professionalism while using Jupyter. For me, the most important benefit of implementing these is that I can always go back to an earlier version of my project (be it in older code I thought wouldn’t work, or earlier versions of a dataset) quickly and efficiently, which in turn makes me more willing (and less hesitant to) take risks, make mistakes and try new ways of achieving my goals." } ]
Baconian Cipher - GeeksforGeeks
21 May, 2018 Bacon’s cipher or the Baconian cipher is a method of steganography (a method of hiding a secret message as opposed to just a cipher) devised by Francis Bacon in 1605. A message is concealed in the presentation of text, rather than its content.The Baconian cipher is a substitution cipher in which each letter is replaced by a sequence of 5 characters. In the original cipher, these were sequences of ‘A’s and ‘B’s e.g. the letter ‘D’ was replaced by ‘aaabb’, the letter ‘O’ was replaced by ‘abbab’ etc. Each letter is assigned to a string of five binary digits. These could be the letters ‘A’ and ‘B’, the numbers 0 and 1 or whatever else you may desire.There are 2 kinds of Baconian ciphers – The 24 letter cipher: In which 2 pairs of letters (I, J) & (U, V) have same ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111I, Jabaaa01000Kabaab01001Lababa01010Mababb01011LetterCodeBinaryNabbaa01100Oabbab01101Pabbba01110Qabbbb01111Rbaaaa10000Sbaaab10001Tbaaba10010U, Vbaabb10011Wbabaa10100Xbabab10101Ybabba10110Zbabbb10111The 26 letter cipher: In which all letters have unique ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111Iabaaa01000Jabaab01001Kababa01010Lababb01011Mabbaa01100LetterCodeBinaryNabbab01101Oabbba01110Pabbbb01111Qbaaaa10000Rbaaab10001Sbaaba10010Tbaabb10011Ubabaa10100Vbabab10101Wbabba10110Xbabbb10111Ybbaaa11000Zbbaab11001 The 24 letter cipher: In which 2 pairs of letters (I, J) & (U, V) have same ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111I, Jabaaa01000Kabaab01001Lababa01010Mababb01011LetterCodeBinaryNabbaa01100Oabbab01101Pabbba01110Qabbbb01111Rbaaaa10000Sbaaab10001Tbaaba10010U, Vbaabb10011Wbabaa10100Xbabab10101Ybabba10110Zbabbb10111 The 26 letter cipher: In which all letters have unique ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111Iabaaa01000Jabaab01001Kababa01010Lababb01011Mabbaa01100LetterCodeBinaryNabbab01101Oabbba01110Pabbbb01111Qbaaaa10000Rbaaab10001Sbaaba10010Tbaabb10011Ubabaa10100Vbabab10101Wbabba10110Xbabbb10111Ybbaaa11000Zbbaab11001 Encryption We will extract a single character from the string and if its not a space then we will replace it with its corresponding ciphertext according to the cipher we are using else we will add a space and repeat it until we reach the end of the string. For example ‘A’ is replaced with ‘aaaaa’ Decryption We will extract every set of 5 characters from the encrypted string and check if the first character in that set of 5 characters is a space. If not we will lookup its corresponding plaintext letter from the cipher, replace it and increment the index of character by 5 (to get the set of next 5 characters) else if its a space we add a space and repeat a process by incrementing the current index of character by 1 Approach In Python, we can map key-value pairs using a data structure called a dictionary. We are going to use just one dictionary in which we will map the plaintext-ciphertext pairs as key-value pairs.For encryption we will simply lookup the corresponding ciphertext by accessing the value using the corresponding plaintext character as key.In decryption we will extract every 5 set of ciphertext characters and retrieve their keys from the dictionary using them as the corresponding value. For an accurate decryption we will use the 26 letter cipher. If you are not coding in python then you can come up with your own approach. # Python program to implement Baconian cipher '''This script uses a dictionary instead of 'chr()' & 'ord()' function''' '''Dictionary to map plaintext with ciphertext(key:value) => (plaintext:ciphertext)This script uses the 26 letter baconian cipherin which I, J & U, V have distinct patterns'''lookup = {'A':'aaaaa', 'B':'aaaab', 'C':'aaaba', 'D':'aaabb', 'E':'aabaa', 'F':'aabab', 'G':'aabba', 'H':'aabbb', 'I':'abaaa', 'J':'abaab', 'K':'ababa', 'L':'ababb', 'M':'abbaa', 'N':'abbab', 'O':'abbba', 'P':'abbbb', 'Q':'baaaa', 'R':'baaab', 'S':'baaba', 'T':'baabb', 'U':'babaa', 'V':'babab', 'W':'babba', 'X':'babbb', 'Y':'bbaaa', 'Z':'bbaab'} # Function to encrypt the string according to the cipher provideddef encrypt(message): cipher = '' for letter in message: # checks for space if(letter != ' '): # adds the ciphertext corresponding to the # plaintext from the dictionary cipher += lookup[letter] else: # adds space cipher += ' ' return cipher # Function to decrypt the string # according to the cipher provideddef decrypt(message): decipher = '' i = 0 # emulating a do-while loop while True : # condition to run decryption till # the last set of ciphertext if(i < len(message)-4): # extracting a set of ciphertext # from the message substr = message[i:i + 5] # checking for space as the first # character of the substring if(substr[0] != ' '): ''' This statement gets us the key(plaintext) using the values(ciphertext) Just the reverse of what we were doing in encrypt function ''' decipher += list(lookup.keys())[list(lookup.values()).index(substr)] i += 5 # to get the next set of ciphertext else: # adds space decipher += ' ' i += 1 # index next to the space else: break # emulating a do-while loop return decipher def main(): message = "Geeks for Geeks" result = encrypt(message.upper()) print (result) message = "AABAAABBABABAABABBBABBAAA" result = decrypt(message.lower()) print (result) #Executes the main functionif __name__ == '__main__': main() Output aabbaaabaaaabaaabababaaba aabababbbabaaab aabbaaabaaaabaaabababaaba ENJOY Analysis: This cipher offers very little communication security, as it is a substitution cipher. As such all the methods used to cryptanalyse substitution ciphers can be used to break Baconian ciphers. The main advantage of the cipher is that it allows hiding the fact that a secret message has been sent at all. References: Practical Cryptography This article is contributed by Palash Nigam . 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. cryptography secure-coding Strings Strings cryptography Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python program to check if a string is palindrome or not Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Check whether two strings are anagram of each other Length of the longest substring without repeating characters Reverse words in a given string Top 50 String Coding Problems for Interviews How to split a string in C/C++, Python and Java? Remove duplicates from a given string
[ { "code": null, "e": 24640, "s": 24612, "text": "\n21 May, 2018" }, { "code": null, "e": 25334, "s": 24640, "text": "Bacon’s cipher or the Baconian cipher is a method of steganography (a method of hiding a secret message as opposed to just a cipher) devised by Francis Bacon in 1605. A message is concealed in the presentation of text, rather than its content.The Baconian cipher is a substitution cipher in which each letter is replaced by a sequence of 5 characters. In the original cipher, these were sequences of ‘A’s and ‘B’s e.g. the letter ‘D’ was replaced by ‘aaabb’, the letter ‘O’ was replaced by ‘abbab’ etc. Each letter is assigned to a string of five binary digits. These could be the letters ‘A’ and ‘B’, the numbers 0 and 1 or whatever else you may desire.There are 2 kinds of Baconian ciphers –" }, { "code": null, "e": 26110, "s": 25334, "text": "The 24 letter cipher: In which 2 pairs of letters (I, J) & (U, V) have same ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111I, Jabaaa01000Kabaab01001Lababa01010Mababb01011LetterCodeBinaryNabbaa01100Oabbab01101Pabbba01110Qabbbb01111Rbaaaa10000Sbaaab10001Tbaaba10010U, Vbaabb10011Wbabaa10100Xbabab10101Ybabba10110Zbabbb10111The 26 letter cipher: In which all letters have unique ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111Iabaaa01000Jabaab01001Kababa01010Lababb01011Mabbaa01100LetterCodeBinaryNabbab01101Oabbba01110Pabbbb01111Qbaaaa10000Rbaaab10001Sbaaba10010Tbaabb10011Ubabaa10100Vbabab10101Wbabba10110Xbabbb10111Ybbaaa11000Zbbaab11001" }, { "code": null, "e": 26501, "s": 26110, "text": "The 24 letter cipher: In which 2 pairs of letters (I, J) & (U, V) have same ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111I, Jabaaa01000Kabaab01001Lababa01010Mababb01011LetterCodeBinaryNabbaa01100Oabbab01101Pabbba01110Qabbbb01111Rbaaaa10000Sbaaab10001Tbaaba10010U, Vbaabb10011Wbabaa10100Xbabab10101Ybabba10110Zbabbb10111" }, { "code": null, "e": 26887, "s": 26501, "text": "The 26 letter cipher: In which all letters have unique ciphertexts.LetterCodeBinaryAaaaaa00000Baaaab00001Caaaba00010Daaabb00011Eaabaa00100Faabab00101Gaabba00110Haabbb00111Iabaaa01000Jabaab01001Kababa01010Lababb01011Mabbaa01100LetterCodeBinaryNabbab01101Oabbba01110Pabbbb01111Qbaaaa10000Rbaaab10001Sbaaba10010Tbaabb10011Ubabaa10100Vbabab10101Wbabba10110Xbabbb10111Ybbaaa11000Zbbaab11001" }, { "code": null, "e": 26898, "s": 26887, "text": "Encryption" }, { "code": null, "e": 27185, "s": 26898, "text": "We will extract a single character from the string and if its not a space then we will replace it with its corresponding ciphertext according to the cipher we are using else we will add a space and repeat it until we reach the end of the string. For example ‘A’ is replaced with ‘aaaaa’" }, { "code": null, "e": 27196, "s": 27185, "text": "Decryption" }, { "code": null, "e": 27610, "s": 27196, "text": "We will extract every set of 5 characters from the encrypted string and check if the first character in that set of 5 characters is a space. If not we will lookup its corresponding plaintext letter from the cipher, replace it and increment the index of character by 5 (to get the set of next 5 characters) else if its a space we add a space and repeat a process by incrementing the current index of character by 1" }, { "code": null, "e": 27619, "s": 27610, "text": "Approach" }, { "code": null, "e": 28240, "s": 27619, "text": "In Python, we can map key-value pairs using a data structure called a dictionary. We are going to use just one dictionary in which we will map the plaintext-ciphertext pairs as key-value pairs.For encryption we will simply lookup the corresponding ciphertext by accessing the value using the corresponding plaintext character as key.In decryption we will extract every 5 set of ciphertext characters and retrieve their keys from the dictionary using them as the corresponding value. For an accurate decryption we will use the 26 letter cipher. If you are not coding in python then you can come up with your own approach." }, { "code": "# Python program to implement Baconian cipher '''This script uses a dictionary instead of 'chr()' & 'ord()' function''' '''Dictionary to map plaintext with ciphertext(key:value) => (plaintext:ciphertext)This script uses the 26 letter baconian cipherin which I, J & U, V have distinct patterns'''lookup = {'A':'aaaaa', 'B':'aaaab', 'C':'aaaba', 'D':'aaabb', 'E':'aabaa', 'F':'aabab', 'G':'aabba', 'H':'aabbb', 'I':'abaaa', 'J':'abaab', 'K':'ababa', 'L':'ababb', 'M':'abbaa', 'N':'abbab', 'O':'abbba', 'P':'abbbb', 'Q':'baaaa', 'R':'baaab', 'S':'baaba', 'T':'baabb', 'U':'babaa', 'V':'babab', 'W':'babba', 'X':'babbb', 'Y':'bbaaa', 'Z':'bbaab'} # Function to encrypt the string according to the cipher provideddef encrypt(message): cipher = '' for letter in message: # checks for space if(letter != ' '): # adds the ciphertext corresponding to the # plaintext from the dictionary cipher += lookup[letter] else: # adds space cipher += ' ' return cipher # Function to decrypt the string # according to the cipher provideddef decrypt(message): decipher = '' i = 0 # emulating a do-while loop while True : # condition to run decryption till # the last set of ciphertext if(i < len(message)-4): # extracting a set of ciphertext # from the message substr = message[i:i + 5] # checking for space as the first # character of the substring if(substr[0] != ' '): ''' This statement gets us the key(plaintext) using the values(ciphertext) Just the reverse of what we were doing in encrypt function ''' decipher += list(lookup.keys())[list(lookup.values()).index(substr)] i += 5 # to get the next set of ciphertext else: # adds space decipher += ' ' i += 1 # index next to the space else: break # emulating a do-while loop return decipher def main(): message = \"Geeks for Geeks\" result = encrypt(message.upper()) print (result) message = \"AABAAABBABABAABABBBABBAAA\" result = decrypt(message.lower()) print (result) #Executes the main functionif __name__ == '__main__': main()", "e": 30621, "s": 28240, "text": null }, { "code": null, "e": 30703, "s": 30621, "text": "Output\naabbaaabaaaabaaabababaaba aabababbbabaaab aabbaaabaaaabaaabababaaba\nENJOY\n" }, { "code": null, "e": 31016, "s": 30703, "text": "Analysis: This cipher offers very little communication security, as it is a substitution cipher. As such all the methods used to cryptanalyse substitution ciphers can be used to break Baconian ciphers. The main advantage of the cipher is that it allows hiding the fact that a secret message has been sent at all." }, { "code": null, "e": 31051, "s": 31016, "text": "References: Practical Cryptography" }, { "code": null, "e": 31352, "s": 31051, "text": "This article is contributed by Palash Nigam . 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": 31477, "s": 31352, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 31490, "s": 31477, "text": "cryptography" }, { "code": null, "e": 31504, "s": 31490, "text": "secure-coding" }, { "code": null, "e": 31512, "s": 31504, "text": "Strings" }, { "code": null, "e": 31520, "s": 31512, "text": "Strings" }, { "code": null, "e": 31533, "s": 31520, "text": "cryptography" }, { "code": null, "e": 31631, "s": 31533, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31688, "s": 31631, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 31724, "s": 31688, "text": "Convert string to char array in C++" }, { "code": null, "e": 31777, "s": 31724, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 31815, "s": 31777, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 31867, "s": 31815, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 31928, "s": 31867, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 31960, "s": 31928, "text": "Reverse words in a given string" }, { "code": null, "e": 32005, "s": 31960, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 32054, "s": 32005, "text": "How to split a string in C/C++, Python and Java?" } ]
AWT List Class
The List represents a list of text items. The list can be configured that user can choose either one item or multiple items. Following is the declaration for java.awt.List class: public class List extends Component implements ItemSelectable, Accessible List() Creates a new scrolling list. List(int rows) Creates a new scrolling list initialized with the specified number of visible lines. List(int rows, boolean multipleMode) Creates a new scrolling list initialized to display the specified number of rows. Returns an array of all the objects currently registered as FooListeners upon this List. void add(String item) Adds the specified item to the end of scrolling list. void add(String item, int index) Adds the specified item to the the scrolling list at the position indicated by the index. void addActionListener(ActionListener l) Adds the specified action listener to receive action events from this list. void addItem(String item) Deprecated. replaced by add(String). void addItem(String item, int index) Deprecated. replaced by add(String, int). void addItemListener(ItemListener l) Adds the specified item listener to receive item events from this list. void addNotify() Creates the peer for the list. boolean allowsMultipleSelections() Deprecated. As of JDK version 1.1, replaced by isMultipleMode(). void clear() Deprecated. As of JDK version 1.1, replaced by removeAll(). int countItems() Deprecated. As of JDK version 1.1, replaced by getItemCount(). void delItem(int position) Deprecated. replaced by remove(String) and remove(int). void delItems(int start, int end) Deprecated. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package private method. void deselect(int index) Deselects the item at the specified index. AccessibleContext getAccessibleContext() Gets the AccessibleContext associated with this List. ActionListener[] getActionListeners() Returns an array of all the action listeners registered on this list. String getItem(int index) Gets the item associated with the specified index. int getItemCount() Gets the number of items in the list. ItemListener[] getItemListeners() Returns an array of all the item listeners registered on this list. String[] getItems() Gets the items in the list. Dimension getMinimumSize() Determines the minimum size of this scrolling list. Dimension getMinimumSize(int rows) Gets the minumum dimensions for a list with the specified number of rows. Dimension getPreferredSize() Gets the preferred size of this scrolling list. Dimension getPreferredSize(int rows) Gets the preferred dimensions for a list with the specified number of rows. int getRows() Gets the number of visible lines in this list. int getSelectedIndex() Gets the index of the selected item on the list, int[] getSelectedIndexes() Gets the selected indexes on the list. String getSelectedItem() Gets the selected item on this scrolling list. String[] getSelectedItems() Gets the selected items on this scrolling list. Object[] getSelectedObjects() Gets the selected items on this scrolling list in an array of Objects. int getVisibleIndex() Gets the index of the item that was last made visible by the method makeVisible. boolean isIndexSelected(int index) Determines if the specified item in this scrolling list is selected. boolean isMultipleMode() Determines whether this list allows multiple selections. boolean isSelected(int index) Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int). void makeVisible(int index) Makes the item at the specified index visible. Dimension minimumSize() Deprecated. As of JDK version 1.1, replaced by getMinimumSize(). Dimension minimumSize(int rows) Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int). protected String paramString() Returns the parameter string representing the state of this scrolling list. Dimension preferredSize() Deprecated. As of JDK version 1.1, replaced by getPreferredSize(). Dimension preferredSize(int rows) Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int). protected void processActionEvent(ActionEvent e) Processes action events occurring on this component by dispatching them to any registered ActionListener objects. protected void processEvent(AWTEvent e) Processes events on this scrolling list. protected void processItemEvent(ItemEvent e) Processes item events occurring on this list by dispatching them to any registered ItemListener objects. void remove(int position) Removes the item at the specified position from this scrolling list. void remove(String item) Removes the first occurrence of an item from the list. void removeActionListener(ActionListener l) Removes the specified action listener so that it no longer receives action events from this list. void removeAll() Removes all items from this list. void removeItemListener(ItemListener l) Removes the specified item listener so that it no longer receives item events from this list. void removeNotify() Removes the peer for this list. void replaceItem(String newValue, int index) Replaces the item at the specified index in the scrolling list with the new string. void select(int index) Selects the item at the specified index in the scrolling list. void setMultipleMode(boolean b) Sets the flag that determines whether this list allows multiple selections. void setMultipleSelections(boolean b) Deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean). This class inherits methods from the following classes: java.awt.Component java.awt.Component java.lang.Object java.lang.Object Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui > package com.tutorialspoint.gui; import java.awt.*; import java.awt.event.*; public class AwtControlDemo { private Frame mainFrame; private Label headerLabel; private Label statusLabel; private Panel controlPanel; public AwtControlDemo(){ prepareGUI(); } public static void main(String[] args){ AwtControlDemo awtControlDemo = new AwtControlDemo(); awtControlDemo.showListDemo(); } private void prepareGUI(){ mainFrame = new Frame("Java AWT Examples"); mainFrame.setSize(400,400); mainFrame.setLayout(new GridLayout(3, 1)); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent){ System.exit(0); } }); headerLabel = new Label(); headerLabel.setAlignment(Label.CENTER); statusLabel = new Label(); statusLabel.setAlignment(Label.CENTER); statusLabel.setSize(350,100); controlPanel = new Panel(); controlPanel.setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(controlPanel); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showListDemo(){ headerLabel.setText("Control in action: List"); final List fruitList = new List(4,false); fruitList.add("Apple"); fruitList.add("Grapes"); fruitList.add("Mango"); fruitList.add("Peer"); final List vegetableList = new List(4,true); vegetableList.add("Lady Finger"); vegetableList.add("Onion"); vegetableList.add("Potato"); vegetableList.add("Tomato"); Button showButton = new Button("Show"); showButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String data = "Fruits Selected: " + fruitList.getItem(fruitList.getSelectedIndex()); data += ", Vegetables selected: "; for(String vegetable:vegetableList.getSelectedItems()){ data += vegetable + " "; } statusLabel.setText(data); } }); controlPanel.add(fruitList); controlPanel.add(vegetableList); controlPanel.add(showButton); mainFrame.setVisible(true); } } Compile the program using command prompt. Go to D:/ > AWT and type the following command. D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java If no error comes that means compilation is successful. Run the program using following command. D:\AWT>java com.tutorialspoint.gui.AwtControlDemo Verify the following output 13 Lectures 2 hours EduOLC Print Add Notes Bookmark this page
[ { "code": null, "e": 1872, "s": 1747, "text": "The List represents a list of text items. The list can be configured that user can choose either one item or multiple items." }, { "code": null, "e": 1926, "s": 1872, "text": "Following is the declaration for java.awt.List class:" }, { "code": null, "e": 2009, "s": 1926, "text": "public class List\n extends Component\n implements ItemSelectable, Accessible" }, { "code": null, "e": 2017, "s": 2009, "text": "List() " }, { "code": null, "e": 2047, "s": 2017, "text": "Creates a new scrolling list." }, { "code": null, "e": 2063, "s": 2047, "text": "List(int rows) " }, { "code": null, "e": 2148, "s": 2063, "text": "Creates a new scrolling list initialized with the specified number of visible lines." }, { "code": null, "e": 2186, "s": 2148, "text": "List(int rows, boolean multipleMode) " }, { "code": null, "e": 2268, "s": 2186, "text": "Creates a new scrolling list initialized to display the specified number of rows." }, { "code": null, "e": 2358, "s": 2268, "text": " Returns an array of all the objects currently registered as FooListeners upon this List." }, { "code": null, "e": 2381, "s": 2358, "text": "void add(String item) " }, { "code": null, "e": 2435, "s": 2381, "text": "Adds the specified item to the end of scrolling list." }, { "code": null, "e": 2469, "s": 2435, "text": "void add(String item, int index) " }, { "code": null, "e": 2559, "s": 2469, "text": "Adds the specified item to the the scrolling list at the position indicated by the index." }, { "code": null, "e": 2601, "s": 2559, "text": "void addActionListener(ActionListener l) " }, { "code": null, "e": 2677, "s": 2601, "text": "Adds the specified action listener to receive action events from this list." }, { "code": null, "e": 2704, "s": 2677, "text": "void addItem(String item) " }, { "code": null, "e": 2741, "s": 2704, "text": "Deprecated. replaced by add(String)." }, { "code": null, "e": 2778, "s": 2741, "text": "void addItem(String item, int index)" }, { "code": null, "e": 2820, "s": 2778, "text": "Deprecated. replaced by add(String, int)." }, { "code": null, "e": 2858, "s": 2820, "text": "void addItemListener(ItemListener l) " }, { "code": null, "e": 2930, "s": 2858, "text": "Adds the specified item listener to receive item events from this list." }, { "code": null, "e": 2948, "s": 2930, "text": "void addNotify() " }, { "code": null, "e": 2979, "s": 2948, "text": "Creates the peer for the list." }, { "code": null, "e": 3015, "s": 2979, "text": "boolean allowsMultipleSelections() " }, { "code": null, "e": 3081, "s": 3015, "text": " Deprecated. As of JDK version 1.1, replaced by isMultipleMode()." }, { "code": null, "e": 3095, "s": 3081, "text": "void clear() " }, { "code": null, "e": 3155, "s": 3095, "text": "Deprecated. As of JDK version 1.1, replaced by removeAll()." }, { "code": null, "e": 3173, "s": 3155, "text": "int countItems() " }, { "code": null, "e": 3236, "s": 3173, "text": "Deprecated. As of JDK version 1.1, replaced by getItemCount()." }, { "code": null, "e": 3263, "s": 3236, "text": "void delItem(int position)" }, { "code": null, "e": 3319, "s": 3263, "text": "Deprecated. replaced by remove(String) and remove(int)." }, { "code": null, "e": 3354, "s": 3319, "text": "void delItems(int start, int end) " }, { "code": null, "e": 3496, "s": 3354, "text": "Deprecated. As of JDK version 1.1, Not for public use in the future. This method is expected to be retained only as a package private method." }, { "code": null, "e": 3521, "s": 3496, "text": "void deselect(int index)" }, { "code": null, "e": 3564, "s": 3521, "text": "Deselects the item at the specified index." }, { "code": null, "e": 3605, "s": 3564, "text": "AccessibleContext getAccessibleContext()" }, { "code": null, "e": 3659, "s": 3605, "text": "Gets the AccessibleContext associated with this List." }, { "code": null, "e": 3698, "s": 3659, "text": "ActionListener[] getActionListeners() " }, { "code": null, "e": 3768, "s": 3698, "text": "Returns an array of all the action listeners registered on this list." }, { "code": null, "e": 3795, "s": 3768, "text": "String\tgetItem(int index) " }, { "code": null, "e": 3846, "s": 3795, "text": "Gets the item associated with the specified index." }, { "code": null, "e": 3866, "s": 3846, "text": "int getItemCount() " }, { "code": null, "e": 3904, "s": 3866, "text": "Gets the number of items in the list." }, { "code": null, "e": 3939, "s": 3904, "text": "ItemListener[]\tgetItemListeners() " }, { "code": null, "e": 4007, "s": 3939, "text": "Returns an array of all the item listeners registered on this list." }, { "code": null, "e": 4028, "s": 4007, "text": "String[] getItems() " }, { "code": null, "e": 4058, "s": 4028, "text": " Gets the items in the list." }, { "code": null, "e": 4086, "s": 4058, "text": "Dimension getMinimumSize() " }, { "code": null, "e": 4138, "s": 4086, "text": "Determines the minimum size of this scrolling list." }, { "code": null, "e": 4174, "s": 4138, "text": "Dimension getMinimumSize(int rows) " }, { "code": null, "e": 4248, "s": 4174, "text": "Gets the minumum dimensions for a list with the specified number of rows." }, { "code": null, "e": 4278, "s": 4248, "text": "Dimension getPreferredSize() " }, { "code": null, "e": 4326, "s": 4278, "text": "Gets the preferred size of this scrolling list." }, { "code": null, "e": 4364, "s": 4326, "text": "Dimension getPreferredSize(int rows) " }, { "code": null, "e": 4440, "s": 4364, "text": "Gets the preferred dimensions for a list with the specified number of rows." }, { "code": null, "e": 4455, "s": 4440, "text": "int getRows() " }, { "code": null, "e": 4502, "s": 4455, "text": "Gets the number of visible lines in this list." }, { "code": null, "e": 4526, "s": 4502, "text": "int getSelectedIndex() " }, { "code": null, "e": 4575, "s": 4526, "text": "Gets the index of the selected item on the list," }, { "code": null, "e": 4603, "s": 4575, "text": "int[] getSelectedIndexes() " }, { "code": null, "e": 4642, "s": 4603, "text": "Gets the selected indexes on the list." }, { "code": null, "e": 4668, "s": 4642, "text": "String getSelectedItem() " }, { "code": null, "e": 4715, "s": 4668, "text": "Gets the selected item on this scrolling list." }, { "code": null, "e": 4744, "s": 4715, "text": "String[] getSelectedItems() " }, { "code": null, "e": 4792, "s": 4744, "text": "Gets the selected items on this scrolling list." }, { "code": null, "e": 4823, "s": 4792, "text": "Object[] getSelectedObjects() " }, { "code": null, "e": 4894, "s": 4823, "text": "Gets the selected items on this scrolling list in an array of Objects." }, { "code": null, "e": 4917, "s": 4894, "text": "int getVisibleIndex() " }, { "code": null, "e": 4998, "s": 4917, "text": "Gets the index of the item that was last made visible by the method makeVisible." }, { "code": null, "e": 5034, "s": 4998, "text": "boolean isIndexSelected(int index) " }, { "code": null, "e": 5103, "s": 5034, "text": "Determines if the specified item in this scrolling list is selected." }, { "code": null, "e": 5129, "s": 5103, "text": "boolean isMultipleMode() " }, { "code": null, "e": 5186, "s": 5129, "text": "Determines whether this list allows multiple selections." }, { "code": null, "e": 5217, "s": 5186, "text": "boolean isSelected(int index) " }, { "code": null, "e": 5286, "s": 5217, "text": "Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int)." }, { "code": null, "e": 5315, "s": 5286, "text": "void makeVisible(int index) " }, { "code": null, "e": 5362, "s": 5315, "text": "Makes the item at the specified index visible." }, { "code": null, "e": 5387, "s": 5362, "text": "Dimension\tminimumSize() " }, { "code": null, "e": 5452, "s": 5387, "text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize()." }, { "code": null, "e": 5486, "s": 5452, "text": " Dimension\tminimumSize(int rows) " }, { "code": null, "e": 5554, "s": 5486, "text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int)." }, { "code": null, "e": 5586, "s": 5554, "text": "protected String paramString() " }, { "code": null, "e": 5662, "s": 5586, "text": "Returns the parameter string representing the state of this scrolling list." }, { "code": null, "e": 5689, "s": 5662, "text": "Dimension\tpreferredSize() " }, { "code": null, "e": 5756, "s": 5689, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize()." }, { "code": null, "e": 5791, "s": 5756, "text": "Dimension\tpreferredSize(int rows) " }, { "code": null, "e": 5861, "s": 5791, "text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int)." }, { "code": null, "e": 5912, "s": 5861, "text": "protected void processActionEvent(ActionEvent e) " }, { "code": null, "e": 6026, "s": 5912, "text": "Processes action events occurring on this component by dispatching them to any registered ActionListener objects." }, { "code": null, "e": 6068, "s": 6026, "text": "protected void processEvent(AWTEvent e) " }, { "code": null, "e": 6109, "s": 6068, "text": "Processes events on this scrolling list." }, { "code": null, "e": 6155, "s": 6109, "text": "protected void processItemEvent(ItemEvent e)" }, { "code": null, "e": 6260, "s": 6155, "text": "Processes item events occurring on this list by dispatching them to any registered ItemListener objects." }, { "code": null, "e": 6287, "s": 6260, "text": "void remove(int position) " }, { "code": null, "e": 6356, "s": 6287, "text": "Removes the item at the specified position from this scrolling list." }, { "code": null, "e": 6382, "s": 6356, "text": "void remove(String item) " }, { "code": null, "e": 6437, "s": 6382, "text": "Removes the first occurrence of an item from the list." }, { "code": null, "e": 6482, "s": 6437, "text": "void removeActionListener(ActionListener l) " }, { "code": null, "e": 6580, "s": 6482, "text": "Removes the specified action listener so that it no longer receives action events from this list." }, { "code": null, "e": 6598, "s": 6580, "text": "void removeAll() " }, { "code": null, "e": 6632, "s": 6598, "text": "Removes all items from this list." }, { "code": null, "e": 6673, "s": 6632, "text": "void removeItemListener(ItemListener l) " }, { "code": null, "e": 6767, "s": 6673, "text": "Removes the specified item listener so that it no longer receives item events from this list." }, { "code": null, "e": 6788, "s": 6767, "text": "void removeNotify() " }, { "code": null, "e": 6820, "s": 6788, "text": "Removes the peer for this list." }, { "code": null, "e": 6866, "s": 6820, "text": "void replaceItem(String newValue, int index) " }, { "code": null, "e": 6950, "s": 6866, "text": "Replaces the item at the specified index in the scrolling list with the new string." }, { "code": null, "e": 6974, "s": 6950, "text": "void select(int index) " }, { "code": null, "e": 7037, "s": 6974, "text": "Selects the item at the specified index in the scrolling list." }, { "code": null, "e": 7070, "s": 7037, "text": "void setMultipleMode(boolean b) " }, { "code": null, "e": 7146, "s": 7070, "text": "Sets the flag that determines whether this list allows multiple selections." }, { "code": null, "e": 7185, "s": 7146, "text": "void setMultipleSelections(boolean b) " }, { "code": null, "e": 7258, "s": 7185, "text": "Deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean)." }, { "code": null, "e": 7314, "s": 7258, "text": "This class inherits methods from the following classes:" }, { "code": null, "e": 7333, "s": 7314, "text": "java.awt.Component" }, { "code": null, "e": 7352, "s": 7333, "text": "java.awt.Component" }, { "code": null, "e": 7369, "s": 7352, "text": "java.lang.Object" }, { "code": null, "e": 7386, "s": 7369, "text": "java.lang.Object" }, { "code": null, "e": 7500, "s": 7386, "text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >" }, { "code": null, "e": 9862, "s": 7500, "text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtControlDemo {\n\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtControlDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtControlDemo awtControlDemo = new AwtControlDemo();\n awtControlDemo.showListDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showListDemo(){ \n\n headerLabel.setText(\"Control in action: List\"); \n final List fruitList = new List(4,false);\n\n fruitList.add(\"Apple\");\n fruitList.add(\"Grapes\");\n fruitList.add(\"Mango\");\n fruitList.add(\"Peer\");\n\n final List vegetableList = new List(4,true);\n \n vegetableList.add(\"Lady Finger\");\n vegetableList.add(\"Onion\");\n vegetableList.add(\"Potato\");\n vegetableList.add(\"Tomato\");\n\n Button showButton = new Button(\"Show\");\n\n showButton.addActionListener(new ActionListener() {\n\n public void actionPerformed(ActionEvent e) { \n String data = \"Fruits Selected: \" \n + fruitList.getItem(fruitList.getSelectedIndex());\n data += \", Vegetables selected: \";\n for(String vegetable:vegetableList.getSelectedItems()){\n data += vegetable + \" \";\n }\n statusLabel.setText(data);\n }\n }); \n\n controlPanel.add(fruitList);\n controlPanel.add(vegetableList);\n controlPanel.add(showButton);\n\n mainFrame.setVisible(true); \n }\n}" }, { "code": null, "e": 9953, "s": 9862, "text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command." }, { "code": null, "e": 10009, "s": 9953, "text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtControlDemo.java" }, { "code": null, "e": 10106, "s": 10009, "text": "If no error comes that means compilation is successful. Run the program using following command." }, { "code": null, "e": 10156, "s": 10106, "text": "D:\\AWT>java com.tutorialspoint.gui.AwtControlDemo" }, { "code": null, "e": 10184, "s": 10156, "text": "Verify the following output" }, { "code": null, "e": 10217, "s": 10184, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 10225, "s": 10217, "text": " EduOLC" }, { "code": null, "e": 10232, "s": 10225, "text": " Print" }, { "code": null, "e": 10243, "s": 10232, "text": " Add Notes" } ]
Inplace (Fixed space) M x N size matrix transpose | Updated - GeeksforGeeks
15 Nov, 2021 About four months of gap (missing GFG), a new post. Given an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it’s diagonal (try yourself). How to transpose an arbitrary size matrix inplace? See the following matrix, a b c a d g j d e f ==> b e h k g h i c f i l j k l As per 2D numbering in C/C++, corresponding location mapping looks like, Org element New 0 a 0 1 b 4 2 c 8 3 d 1 4 e 5 5 f 9 6 g 2 7 h 6 8 i 10 9 j 3 10 k 7 11 l 11 Note that the first and last elements stay in their original location. We can easily see the transformation forms few permutation cycles. 1->4->5->9->3->1 – Total 5 elements form the cycle 2->8->10->7->6->2 – Another 5 elements form the cycle 0 – Self cycle 11 – Self cycle From the above example, we can easily devise an algorithm to move the elements along these cycles. How can we generate permutation cycles? Number of elements in both the matrices are constant, given by N = R * C, where R is row count and C is column count. An element at location ol (old location in R x C matrix), moved to nl (new location in C x R matrix). We need to establish relation between ol, nl, R and C. Assume ol = A[or][oc]. In C/C++ we can calculate the element address as, ol = or x C + oc (ignore base reference for simplicity) It is to be moved to new location nl in the transposed matrix, say nl = A[nr][nc], or in C/C++ terms nl = nr x R + nc (R - column count, C is row count as the matrix is transposed) Observe, nr = oc and nc = or, so replacing these for nl, nl = oc x R + or -----> [eq 1] after solving for relation between ol and nl, we get ol = or x C + oc ol x R = or x C x R + oc x R = or x N + oc x R (from the fact R * C = N) = or x N + (nl - or) --- from [eq 1] = or x (N-1) + nl OR, nl = ol x R - or x (N-1) Note that the values of nl and ol never go beyond N-1, so considering modulo division on both the sides by (N-1), we get the following based on properties of congruence, nl mod (N-1) = (ol x R - or x (N-1)) mod (N-1) = (ol x R) mod (N-1) - or x (N-1) mod(N-1) = ol x R mod (N-1), since second term evaluates to zero nl = (ol x R) mod (N-1), since nl is always less than N-1 A curious reader might have observed the significance of above relation. Every location is scaled by a factor of R (row size). It is obvious from the matrix that every location is displaced by scaled factor of R. The actual multiplier depends on congruence class of (N-1), i.e. the multiplier can be both -ve and +ve value of the congruent class.Hence every location transformation is simple modulo division. These modulo divisions form cyclic permutations. We need some book keeping information to keep track of already moved elements. Here is code for inplace matrix transformation, C++ C // C++ program for in-place matrix transpose#include <bits/stdc++.h>#define HASH_SIZE 128 using namespace std; // A utility function to print a 2D array of size nr x nc and base address Avoid Print2DArray(int *A, int nr, int nc){ for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) { cout<<setw(4)<<*(A + r*nc + c); } cout<<endl; } cout<<endl;} // Non-square matrix transpose of matrix of size r x c and base address Avoid MatrixInplaceTranspose(int *A, int r, int c){ int size = r*c - 1; int t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%(N-1) next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && b[i]; i++) ; cout << endl; }} // Driver program to test above functionint main(){ int r = 5, c = 6; int size = r*c; int *A = new int[size]; for(int i = 0; i < size; i++) A[i] = i+1; Print2DArray(A, r, c); MatrixInplaceTranspose(A, r, c); Print2DArray(A, c, r); delete[] A; return 0;} // This code is contributed by rrrtnx. // Program for in-place matrix transpose#include <stdio.h>#include <iostream>#include <bitset>#define HASH_SIZE 128 using namespace std; // A utility function to print a 2D array of size nr x nc and base address Avoid Print2DArray(int *A, int nr, int nc){ for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) printf("%4d", *(A + r*nc + c)); printf("\n"); } printf("\n\n");} // Non-square matrix transpose of matrix of size r x c and base address Avoid MatrixInplaceTranspose(int *A, int r, int c){ int size = r*c - 1; int t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%(N-1) next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && b[i]; i++) ; cout << endl; }} // Driver program to test above functionint main(void){ int r = 5, c = 6; int size = r*c; int *A = new int[size]; for(int i = 0; i < size; i++) A[i] = i+1; Print2DArray(A, r, c); MatrixInplaceTranspose(A, r, c); Print2DArray(A, c, r); delete[] A; return 0;} 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 1 7 13 19 25 2 8 14 20 26 3 9 15 21 27 4 10 16 22 28 5 11 17 23 29 6 12 18 24 30 Output: 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 1 7 13 19 25 2 8 14 20 26 3 9 15 21 27 4 10 16 22 28 5 11 17 23 29 6 12 18 24 30 Extension: 17 – March – 2013 Some readers identified similarity between the matrix transpose and string transformation. Without much theory I am presenting the problem and solution. In given array of elements like [a1b2c3d4e5f6g7h8i9j1k2l3m4]. Convert it to [abcdefghijklm1234567891234]. The program should run inplace. What we need is an inplace transpose. Given below is code. C++ C #include <bits/stdc++.h>#define HASH_SIZE 128 using namespace std; typedef char data_t; void Print2DArray(char A[], int nr, int nc) { int size = nr*nc; for(int i = 0; i < size; i++) cout<<setw(4)<<*(A+i); cout<<endl;} void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) { int size = r*c - 1; data_t t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while( i < size ) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%size next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while( i != cycleBegin ); // Get Next Move (what about querying random location?) for(i = 1; i < size && b[i]; i++) ; cout << endl; }} void Fill(data_t buf[], int size) { // Fill abcd ... for(int i = 0; i < size; i++) buf[i] = 'a'+i; // Fill 0123 ... buf += size; for(int i = 0; i < size; i++) buf[i] = '0'+i;} void TestCase_01(void) { int r = 2, c = 10; int size = r*c; data_t *A = new data_t[size]; Fill(A, c); Print2DArray(A, r, c), cout << endl; MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r), cout << endl; delete[] A;} int main() { TestCase_01(); return 0;} // This code is contributed by rutvik_56. #include <stdio.h>#include <iostream>#include <bitset>#define HASH_SIZE 128 using namespace std; typedef char data_t; void Print2DArray(char A[], int nr, int nc) { int size = nr*nc; for(int i = 0; i < size; i++) printf("%4c", *(A + i)); printf("\n");} void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) { int size = r*c - 1; data_t t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while( i < size ) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%size next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while( i != cycleBegin ); // Get Next Move (what about querying random location?) for(i = 1; i < size && b[i]; i++) ; cout << endl; }} void Fill(data_t buf[], int size) { // Fill abcd ... for(int i = 0; i < size; i++) buf[i] = 'a'+i; // Fill 0123 ... buf += size; for(int i = 0; i < size; i++) buf[i] = '0'+i;} void TestCase_01(void) { int r = 2, c = 10; int size = r*c; data_t *A = new data_t[size]; Fill(A, c); Print2DArray(A, r, c), cout << endl; MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r), cout << endl; delete[] A;} int main() { TestCase_01(); return 0;} a b c d e f g h i j 0 1 2 3 4 5 6 7 8 9 a 0 b 1 c 2 d 3 e 4 f 5 g 6 h 7 i 8 j 9 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Update 09-July-2016: Notes on space complexity and storage order.After long time, it happened to review this post. Some readers pointed valid questions on how can it be in-place (?) when we are using bitset as marker (hash in code). Apologies for incorrect perception by looking at the article heading or content. While preparing the initial content, I was thinking of naive implementation using auxiliary space of atleast O(MN) needed to transpose rectangular matrix. The program presented above is using constant space as bitset size is fixed at compile time. However, to support arbitrary size of matrices we need bitset size atleast O(MN) size. One can use a HashMap (amortized O(1) complexity) for marking finished locations, yet HashMap’s worst case complexity can be O(N) or O(log N) based on implementation. HashMap space cost also increases based on items inserted. Please note that in-place was used w.r.t. matrix space.Also, it was assumed that the matrix will be stored in row major ordering (contigueous locations in memory). The reader can derive the formulae, if the matrix is represented in column major order by the programming language (e.g. Fortran/Julia).Thanks to the readers who pointed these two gaps.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++The post is incomplete without mentioning two links.1. Aashish covered good theory behind cycle leader algorithm. See his post on string transformation.2. As usual, Sambasiva demonstrated his exceptional skills in recursion to the problem. Ensure to understand his solution.— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. chhabradhanvi rrrtnx rutvik_56 Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Program to multiply two matrices Inplace rotate square matrix by 90 degrees | Set 1 Min Cost Path | DP-6 The Celebrity Problem Gold Mine Problem Rotate a matrix by 90 degree in clockwise direction without using any extra space Python program to multiply two matrices Multiplication of two Matrices in Single line using Numpy in Python
[ { "code": null, "e": 24625, "s": 24597, "text": "\n15 Nov, 2021" }, { "code": null, "e": 25017, "s": 24625, "text": "About four months of gap (missing GFG), a new post. Given an M x N matrix, transpose the matrix without auxiliary memory.It is easy to transpose matrix using an auxiliary array. If the matrix is symmetric in size, we can transpose the matrix inplace by mirroring the 2D array across it’s diagonal (try yourself). How to transpose an arbitrary size matrix inplace? See the following matrix, " }, { "code": null, "e": 25083, "s": 25017, "text": "a b c a d g j\nd e f ==> b e h k\ng h i c f i l\nj k l" }, { "code": null, "e": 25158, "s": 25083, "text": "As per 2D numbering in C/C++, corresponding location mapping looks like, " }, { "code": null, "e": 25354, "s": 25158, "text": "Org element New\n 0 a 0\n 1 b 4\n 2 c 8\n 3 d 1\n 4 e 5\n 5 f 9\n 6 g 2\n 7 h 6\n 8 i 10\n 9 j 3\n 10 k 7\n 11 l 11" }, { "code": null, "e": 25494, "s": 25354, "text": "Note that the first and last elements stay in their original location. We can easily see the transformation forms few permutation cycles. " }, { "code": null, "e": 25546, "s": 25494, "text": "1->4->5->9->3->1 – Total 5 elements form the cycle" }, { "code": null, "e": 25600, "s": 25546, "text": "2->8->10->7->6->2 – Another 5 elements form the cycle" }, { "code": null, "e": 25616, "s": 25600, "text": "0 – Self cycle" }, { "code": null, "e": 25632, "s": 25616, "text": "11 – Self cycle" }, { "code": null, "e": 26121, "s": 25632, "text": "From the above example, we can easily devise an algorithm to move the elements along these cycles. How can we generate permutation cycles? Number of elements in both the matrices are constant, given by N = R * C, where R is row count and C is column count. An element at location ol (old location in R x C matrix), moved to nl (new location in C x R matrix). We need to establish relation between ol, nl, R and C. Assume ol = A[or][oc]. In C/C++ we can calculate the element address as, " }, { "code": null, "e": 26177, "s": 26121, "text": "ol = or x C + oc (ignore base reference for simplicity)" }, { "code": null, "e": 26280, "s": 26177, "text": "It is to be moved to new location nl in the transposed matrix, say nl = A[nr][nc], or in C/C++ terms " }, { "code": null, "e": 26360, "s": 26280, "text": "nl = nr x R + nc (R - column count, C is row count as the matrix is transposed)" }, { "code": null, "e": 26419, "s": 26360, "text": "Observe, nr = oc and nc = or, so replacing these for nl, " }, { "code": null, "e": 26450, "s": 26419, "text": "nl = oc x R + or -----> [eq 1]" }, { "code": null, "e": 26505, "s": 26450, "text": "after solving for relation between ol and nl, we get " }, { "code": null, "e": 26690, "s": 26505, "text": "ol = or x C + oc\nol x R = or x C x R + oc x R\n = or x N + oc x R (from the fact R * C = N)\n = or x N + (nl - or) --- from [eq 1]\n = or x (N-1) + nl" }, { "code": null, "e": 26696, "s": 26690, "text": "OR, " }, { "code": null, "e": 26721, "s": 26696, "text": "nl = ol x R - or x (N-1)" }, { "code": null, "e": 26893, "s": 26721, "text": "Note that the values of nl and ol never go beyond N-1, so considering modulo division on both the sides by (N-1), we get the following based on properties of congruence, " }, { "code": null, "e": 27123, "s": 26893, "text": "nl mod (N-1) = (ol x R - or x (N-1)) mod (N-1)\n = (ol x R) mod (N-1) - or x (N-1) mod(N-1)\n = ol x R mod (N-1), since second term evaluates to zero\nnl = (ol x R) mod (N-1), since nl is always less than N-1" }, { "code": null, "e": 27709, "s": 27123, "text": "A curious reader might have observed the significance of above relation. Every location is scaled by a factor of R (row size). It is obvious from the matrix that every location is displaced by scaled factor of R. The actual multiplier depends on congruence class of (N-1), i.e. the multiplier can be both -ve and +ve value of the congruent class.Hence every location transformation is simple modulo division. These modulo divisions form cyclic permutations. We need some book keeping information to keep track of already moved elements. Here is code for inplace matrix transformation, " }, { "code": null, "e": 27713, "s": 27709, "text": "C++" }, { "code": null, "e": 27715, "s": 27713, "text": "C" }, { "code": "// C++ program for in-place matrix transpose#include <bits/stdc++.h>#define HASH_SIZE 128 using namespace std; // A utility function to print a 2D array of size nr x nc and base address Avoid Print2DArray(int *A, int nr, int nc){ for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) { cout<<setw(4)<<*(A + r*nc + c); } cout<<endl; } cout<<endl;} // Non-square matrix transpose of matrix of size r x c and base address Avoid MatrixInplaceTranspose(int *A, int r, int c){ int size = r*c - 1; int t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%(N-1) next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && b[i]; i++) ; cout << endl; }} // Driver program to test above functionint main(){ int r = 5, c = 6; int size = r*c; int *A = new int[size]; for(int i = 0; i < size; i++) A[i] = i+1; Print2DArray(A, r, c); MatrixInplaceTranspose(A, r, c); Print2DArray(A, c, r); delete[] A; return 0;} // This code is contributed by rrrtnx.", "e": 29404, "s": 27715, "text": null }, { "code": "// Program for in-place matrix transpose#include <stdio.h>#include <iostream>#include <bitset>#define HASH_SIZE 128 using namespace std; // A utility function to print a 2D array of size nr x nc and base address Avoid Print2DArray(int *A, int nr, int nc){ for(int r = 0; r < nr; r++) { for(int c = 0; c < nc; c++) printf(\"%4d\", *(A + r*nc + c)); printf(\"\\n\"); } printf(\"\\n\\n\");} // Non-square matrix transpose of matrix of size r x c and base address Avoid MatrixInplaceTranspose(int *A, int r, int c){ int size = r*c - 1; int t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while (i < size) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%(N-1) next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while (i != cycleBegin); // Get Next Move (what about querying random location?) for (i = 1; i < size && b[i]; i++) ; cout << endl; }} // Driver program to test above functionint main(void){ int r = 5, c = 6; int size = r*c; int *A = new int[size]; for(int i = 0; i < size; i++) A[i] = i+1; Print2DArray(A, r, c); MatrixInplaceTranspose(A, r, c); Print2DArray(A, c, r); delete[] A; return 0;}", "e": 31072, "s": 29404, "text": null }, { "code": null, "e": 31326, "s": 31072, "text": " 1 2 3 4 5 6\n 7 8 9 10 11 12\n 13 14 15 16 17 18\n 19 20 21 22 23 24\n 25 26 27 28 29 30\n\n\n\n 1 7 13 19 25\n 2 8 14 20 26\n 3 9 15 21 27\n 4 10 16 22 28\n 5 11 17 23 29\n 6 12 18 24 30" }, { "code": null, "e": 31336, "s": 31326, "text": "Output: " }, { "code": null, "e": 31588, "s": 31336, "text": " 1 2 3 4 5 6\n 7 8 9 10 11 12\n 13 14 15 16 17 18\n 19 20 21 22 23 24\n 25 26 27 28 29 30\n\n 1 7 13 19 25\n 2 8 14 20 26\n 3 9 15 21 27\n 4 10 16 22 28\n 5 11 17 23 29\n 6 12 18 24 30" }, { "code": null, "e": 31968, "s": 31588, "text": "Extension: 17 – March – 2013 Some readers identified similarity between the matrix transpose and string transformation. Without much theory I am presenting the problem and solution. In given array of elements like [a1b2c3d4e5f6g7h8i9j1k2l3m4]. Convert it to [abcdefghijklm1234567891234]. The program should run inplace. What we need is an inplace transpose. Given below is code. " }, { "code": null, "e": 31972, "s": 31968, "text": "C++" }, { "code": null, "e": 31974, "s": 31972, "text": "C" }, { "code": "#include <bits/stdc++.h>#define HASH_SIZE 128 using namespace std; typedef char data_t; void Print2DArray(char A[], int nr, int nc) { int size = nr*nc; for(int i = 0; i < size; i++) cout<<setw(4)<<*(A+i); cout<<endl;} void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) { int size = r*c - 1; data_t t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while( i < size ) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%size next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while( i != cycleBegin ); // Get Next Move (what about querying random location?) for(i = 1; i < size && b[i]; i++) ; cout << endl; }} void Fill(data_t buf[], int size) { // Fill abcd ... for(int i = 0; i < size; i++) buf[i] = 'a'+i; // Fill 0123 ... buf += size; for(int i = 0; i < size; i++) buf[i] = '0'+i;} void TestCase_01(void) { int r = 2, c = 10; int size = r*c; data_t *A = new data_t[size]; Fill(A, c); Print2DArray(A, r, c), cout << endl; MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r), cout << endl; delete[] A;} int main() { TestCase_01(); return 0;} // This code is contributed by rutvik_56.", "e": 33577, "s": 31974, "text": null }, { "code": "#include <stdio.h>#include <iostream>#include <bitset>#define HASH_SIZE 128 using namespace std; typedef char data_t; void Print2DArray(char A[], int nr, int nc) { int size = nr*nc; for(int i = 0; i < size; i++) printf(\"%4c\", *(A + i)); printf(\"\\n\");} void MatrixTransposeInplaceArrangement(data_t A[], int r, int c) { int size = r*c - 1; data_t t; // holds element to be replaced, eventually becomes next element to move int next; // location of 't' to be moved int cycleBegin; // holds start of cycle int i; // iterator bitset<HASH_SIZE> b; // hash to mark moved elements b.reset(); b[0] = b[size] = 1; i = 1; // Note that A[0] and A[size-1] won't move while( i < size ) { cycleBegin = i; t = A[i]; do { // Input matrix [r x c] // Output matrix // i_new = (i*r)%size next = (i*r)%size; swap(A[next], t); b[i] = 1; i = next; } while( i != cycleBegin ); // Get Next Move (what about querying random location?) for(i = 1; i < size && b[i]; i++) ; cout << endl; }} void Fill(data_t buf[], int size) { // Fill abcd ... for(int i = 0; i < size; i++) buf[i] = 'a'+i; // Fill 0123 ... buf += size; for(int i = 0; i < size; i++) buf[i] = '0'+i;} void TestCase_01(void) { int r = 2, c = 10; int size = r*c; data_t *A = new data_t[size]; Fill(A, c); Print2DArray(A, r, c), cout << endl; MatrixTransposeInplaceArrangement(A, r, c); Print2DArray(A, c, r), cout << endl; delete[] A;} int main() { TestCase_01(); return 0;}", "e": 35165, "s": 33577, "text": null }, { "code": null, "e": 35329, "s": 35165, "text": " a b c d e f g h i j 0 1 2 3 4 5 6 7 8 9\n\n\n a 0 b 1 c 2 d 3 e 4 f 5 g 6 h 7 i 8 j 9" }, { "code": null, "e": 37138, "s": 35329, "text": "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Update 09-July-2016: Notes on space complexity and storage order.After long time, it happened to review this post. Some readers pointed valid questions on how can it be in-place (?) when we are using bitset as marker (hash in code). Apologies for incorrect perception by looking at the article heading or content. While preparing the initial content, I was thinking of naive implementation using auxiliary space of atleast O(MN) needed to transpose rectangular matrix. The program presented above is using constant space as bitset size is fixed at compile time. However, to support arbitrary size of matrices we need bitset size atleast O(MN) size. One can use a HashMap (amortized O(1) complexity) for marking finished locations, yet HashMap’s worst case complexity can be O(N) or O(log N) based on implementation. HashMap space cost also increases based on items inserted. Please note that in-place was used w.r.t. matrix space.Also, it was assumed that the matrix will be stored in row major ordering (contigueous locations in memory). The reader can derive the formulae, if the matrix is represented in column major order by the programming language (e.g. Fortran/Julia).Thanks to the readers who pointed these two gaps.++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++The post is incomplete without mentioning two links.1. Aashish covered good theory behind cycle leader algorithm. See his post on string transformation.2. As usual, Sambasiva demonstrated his exceptional skills in recursion to the problem. Ensure to understand his solution.— Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37152, "s": 37138, "text": "chhabradhanvi" }, { "code": null, "e": 37159, "s": 37152, "text": "rrrtnx" }, { "code": null, "e": 37169, "s": 37159, "text": "rutvik_56" }, { "code": null, "e": 37176, "s": 37169, "text": "Matrix" }, { "code": null, "e": 37183, "s": 37176, "text": "Matrix" }, { "code": null, "e": 37281, "s": 37183, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37290, "s": 37281, "text": "Comments" }, { "code": null, "e": 37303, "s": 37290, "text": "Old Comments" }, { "code": null, "e": 37327, "s": 37303, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 37389, "s": 37327, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 37422, "s": 37389, "text": "Program to multiply two matrices" }, { "code": null, "e": 37473, "s": 37422, "text": "Inplace rotate square matrix by 90 degrees | Set 1" }, { "code": null, "e": 37494, "s": 37473, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 37516, "s": 37494, "text": "The Celebrity Problem" }, { "code": null, "e": 37534, "s": 37516, "text": "Gold Mine Problem" }, { "code": null, "e": 37616, "s": 37534, "text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space" }, { "code": null, "e": 37656, "s": 37616, "text": "Python program to multiply two matrices" } ]
Tryit Editor v3.7
Tryit: Border color with RGB values
[]
Python and AWS SSM Parameter Store | by billydharmawan | Towards Data Science
In any application, it is very common to have some secrets, which our application needs to be able to provide its intended functionalities. It is forbidden to put those secrets in our project folder and commit them to the Github repo. It is a big NO, NO. 🙅‍♂ There are a few alternatives to store the secrets securely, but, in this tutorial, I am going to show you how it can be done with the AWS Key Management Service (KMS) and Systems Manager’s Parameter Store (SSM). We are going to use Python 3.8 as the programming language and the official AWS Boto3 library to interact with AWS resources. At the end of this tutorial, you will be able to do the following exercises: create a key with KMS put a parameter/ secret as a SecureString into SSM retrieve and decrypt the SSM secret parameter The Github repo for this tutorial is available here. This tutorial assumes that you already have an AWS account and have access to it. This is required to do the KMS and SSM related exercises, in particular, creating the KMS key and putting a parameter into SSM. We are going to use aws-cli to do this. You can follow the AWS official documentation on how to install and set up the credentials. Alternatively, you can just do it directly on the AWS console. In this section, we will set up all the components required to do SSM parameter decryption. Let’s create a virtual environment to contain our project dependencies using virtualenv. From your terminal, run the following commands to create the virtual environment and activate it. $ ❯ mkdir -p ./demo/kms-ssm-decrypt$ ❯ cd ./demo/kms-ssm-decrypt$ ~/demo/kms-ssm-decrypt ❯ virtualenv ./venvUsing base prefix '/Library/Frameworks/Python.framework/Versions/3.8'New python executable in /Users/billyde/demo/kms-ssm-decrypt/venv/bin/python3.8Also creating executable in /Users/billyde/demo/kms-ssm-decrypt/venv/bin/pythonInstalling setuptools, pip, wheel...done.$ ~/demo/kms-ssm-decrypt ❯ source ./venv/bin/activate$ ~/demo/kms-ssm-decrypt (venv) ❯ The only library that is needed is Boto3. Let’s create a text file to keep project dependency and name it requirements.txt. The reason why we have this text file instead of installing the library straight away is so that we can commit it to a Github repo, instead of the whole venv to keep the repo size compact. Anyone can then clone the repo and install all the requirements on their machine via pip. Let’s go ahead and install this package from our terminal. $ ~/demo/kms-ssm-decrypt (venv) ❯ pip install -r requirements.txtCollecting boto3==1.11.0 Using cached boto3-1.11.0-py2.py3-none-any.whl (128 kB)Collecting s3transfer<0.4.0,>=0.3.0 Downloading s3transfer-0.3.2-py2.py3-none-any.whl (69 kB) |████████████████████████████████| 69 kB 1.5 MB/sCollecting botocore<1.15.0,>=1.14.0 Downloading botocore-1.14.9-py2.py3-none-any.whl (5.9 MB) |████████████████████████████████| 5.9 MB 4.6 MB/sCollecting jmespath<1.0.0,>=0.7.1 Using cached jmespath-0.9.4-py2.py3-none-any.whl (24 kB)Collecting urllib3<1.26,>=1.20 Using cached urllib3-1.25.8-py2.py3-none-any.whl (125 kB)Collecting python-dateutil<3.0.0,>=2.1 Using cached python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB)Collecting docutils<0.16,>=0.10 Using cached docutils-0.15.2-py3-none-any.whl (547 kB)Collecting six>=1.5 Using cached six-1.14.0-py2.py3-none-any.whl (10 kB)Installing collected packages: urllib3, six, python-dateutil, docutils, jmespath, botocore, s3transfer, boto3Successfully installed boto3-1.11.0 botocore-1.14.9 docutils-0.15.2 jmespath-0.9.4 python-dateutil-2.8.1 s3transfer-0.3.2 six-1.14.0 urllib3-1.25.8 Since we want to store secret/s, it is better to encrypt it at rest to provide extra layer of security. We are going to create a KMS key that will be used to encrypt and decrypt our secret parameter/s. From your terminal, run the following command, which will create a KMS key. $ ~/demo/kms-ssm-decrypt (venv) ❯ aws kms create-key --description "A key to encrypt-decrypt secrets"{ "KeyMetadata": { "AWSAccountId": "xxxxxxxxxxxx", "KeyId": "ca83c234-7e63-4d8d-1234-28603cb10123", "Arn": "arn:aws:kms:ap-southeast-2:xxxxxxxxxxxx:key/ca83c234-7e63-4d8d-1234-28603cb10123", "CreationDate": 1580217378.859, "Enabled": true, "Description": "A key to encrypt-decrypt secrets", "KeyUsage": "ENCRYPT_DECRYPT", "KeyState": "Enabled", "Origin": "AWS_KMS", "KeyManager": "CUSTOMER" }} Nice, the command outputs the key metadata onto the console if run successfully. We’re good to continue to the next step. We are going to store a secret parameter into the SSM parameter store as SecureString. SecureString parameter type simply indicates that the value of the parameter we are storing will be encrypted. To put a secret parameter, let’s execute the following command from the terminal. $ ~/demo/kms-ssm-decrypt (venv) ❯ aws ssm put-parameter --name "/demo/secret/parameter" --value "thisIsASecret" --type SecureString --key-id ca83c234-7e63-4d8d-1234-28603cb10123 --description "This is a secret parameter"{ "Version": 1, "Tier": "Standard"} The parameters for the command are self-explanatory, however, I just want to highlight a few of them: --name : is the name or path to the parameter you are storing, e.g. it could’ve just been a name like “somesecretpathname” instead of a path like above. --value : is the value of the parameter you are storing. --type : is the type of the parameter, which in this example is a SecureString to tell SSM to encrypt the value before storing it in the parameter store. If you are just storing a non-secret parameter, then the SSM parameter type would just be String. --key-id : is the id of the KMS key you want to use to encrypt the value of the parameter. This is the value of KeyId from the previous section where we generated the KMS key. --description : is the description of the parameter you are storing so you know what it’s for. Awesome. Now, we have our secret parameter stored in the SSM parameter store. Let’s see how we can programmatically retrieve and decrypt it. Now, it’s time to write the script that will retrieve the secret parameter we just stored in SSM parameter store and decrypt it so we can use it in our application. Let’s create a new Python file in the project directory and name it retrieve_and_decrypt_ssm_secret.py. Notice the get_parameter() function’s argument named WithDecryption. In this exercise, we specify it to be True because we want to get the secret value and use it in our application. You might ask, why don’t we specify the KeyId that was used to encrypt it? The answer is, the KeyId information is actually contained in the encrypted parameter and so, SSM knows which key to use to decrypt the secret with. The script is runnable from terminal and it accepts an argument, which is the parameter’s name or path. Go ahead and execute it from terminal like this. (Note that Boto3 will look for AWS Credentials in your environment) $ ~/demo/kms-ssm-decrypt (venv) ❯ python3 retrieve_and_decrypt_ssm_secret.py "/demo/secret/parameter"Secret isthisIsASecret=====Parameter details{'Parameter': {'Name': '/demo/secret/parameter', 'Type': 'SecureString', 'Value': 'thisIsASecret', 'Version': 1, 'LastModifiedDate': datetime.datetime(2020, 1, 30, 23, 26, 35, 169000, tzinfo=tzlocal()), 'ARN': 'arn:aws:ssm:ap-southeast-2:xxxxxxxxxxxx:parameter/demo/secret/parameter'}, 'ResponseMetadata': {'RequestId': '5ad11d35-axz6-42a0-90g5-0b7682a79321', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '5ad07d20-ama6-43c0-90a4-0b7682a11267', 'content-type': 'application/x-amz-json-1.1', 'content-length': '239', 'date': 'Thu, 30 Jan 2020 12:48:53 GMT'}, 'RetryAttempts': 0}} Tada! We got the secret parameter back — thisIsASecret. 🙂 By now, you will have gained the basic skills and knowledge on how to secure your application secret/s using AWS KMS and SSM parameter store. You have also learned how to programmatically retrieve the secret/s, so that, you can use it on your application. I hope this tutorial was useful and helps you understand one way to secure your application secret/s. Just a reminder that the Github repo is available here.
[ { "code": null, "e": 431, "s": 172, "text": "In any application, it is very common to have some secrets, which our application needs to be able to provide its intended functionalities. It is forbidden to put those secrets in our project folder and commit them to the Github repo. It is a big NO, NO. 🙅‍♂" }, { "code": null, "e": 769, "s": 431, "text": "There are a few alternatives to store the secrets securely, but, in this tutorial, I am going to show you how it can be done with the AWS Key Management Service (KMS) and Systems Manager’s Parameter Store (SSM). We are going to use Python 3.8 as the programming language and the official AWS Boto3 library to interact with AWS resources." }, { "code": null, "e": 846, "s": 769, "text": "At the end of this tutorial, you will be able to do the following exercises:" }, { "code": null, "e": 868, "s": 846, "text": "create a key with KMS" }, { "code": null, "e": 919, "s": 868, "text": "put a parameter/ secret as a SecureString into SSM" }, { "code": null, "e": 965, "s": 919, "text": "retrieve and decrypt the SSM secret parameter" }, { "code": null, "e": 1018, "s": 965, "text": "The Github repo for this tutorial is available here." }, { "code": null, "e": 1360, "s": 1018, "text": "This tutorial assumes that you already have an AWS account and have access to it. This is required to do the KMS and SSM related exercises, in particular, creating the KMS key and putting a parameter into SSM. We are going to use aws-cli to do this. You can follow the AWS official documentation on how to install and set up the credentials." }, { "code": null, "e": 1423, "s": 1360, "text": "Alternatively, you can just do it directly on the AWS console." }, { "code": null, "e": 1515, "s": 1423, "text": "In this section, we will set up all the components required to do SSM parameter decryption." }, { "code": null, "e": 1702, "s": 1515, "text": "Let’s create a virtual environment to contain our project dependencies using virtualenv. From your terminal, run the following commands to create the virtual environment and activate it." }, { "code": null, "e": 2165, "s": 1702, "text": "$ ❯ mkdir -p ./demo/kms-ssm-decrypt$ ❯ cd ./demo/kms-ssm-decrypt$ ~/demo/kms-ssm-decrypt ❯ virtualenv ./venvUsing base prefix '/Library/Frameworks/Python.framework/Versions/3.8'New python executable in /Users/billyde/demo/kms-ssm-decrypt/venv/bin/python3.8Also creating executable in /Users/billyde/demo/kms-ssm-decrypt/venv/bin/pythonInstalling setuptools, pip, wheel...done.$ ~/demo/kms-ssm-decrypt ❯ source ./venv/bin/activate$ ~/demo/kms-ssm-decrypt (venv) ❯" }, { "code": null, "e": 2289, "s": 2165, "text": "The only library that is needed is Boto3. Let’s create a text file to keep project dependency and name it requirements.txt." }, { "code": null, "e": 2568, "s": 2289, "text": "The reason why we have this text file instead of installing the library straight away is so that we can commit it to a Github repo, instead of the whole venv to keep the repo size compact. Anyone can then clone the repo and install all the requirements on their machine via pip." }, { "code": null, "e": 2627, "s": 2568, "text": "Let’s go ahead and install this package from our terminal." }, { "code": null, "e": 3771, "s": 2627, "text": "$ ~/demo/kms-ssm-decrypt (venv) ❯ pip install -r requirements.txtCollecting boto3==1.11.0 Using cached boto3-1.11.0-py2.py3-none-any.whl (128 kB)Collecting s3transfer<0.4.0,>=0.3.0 Downloading s3transfer-0.3.2-py2.py3-none-any.whl (69 kB) |████████████████████████████████| 69 kB 1.5 MB/sCollecting botocore<1.15.0,>=1.14.0 Downloading botocore-1.14.9-py2.py3-none-any.whl (5.9 MB) |████████████████████████████████| 5.9 MB 4.6 MB/sCollecting jmespath<1.0.0,>=0.7.1 Using cached jmespath-0.9.4-py2.py3-none-any.whl (24 kB)Collecting urllib3<1.26,>=1.20 Using cached urllib3-1.25.8-py2.py3-none-any.whl (125 kB)Collecting python-dateutil<3.0.0,>=2.1 Using cached python_dateutil-2.8.1-py2.py3-none-any.whl (227 kB)Collecting docutils<0.16,>=0.10 Using cached docutils-0.15.2-py3-none-any.whl (547 kB)Collecting six>=1.5 Using cached six-1.14.0-py2.py3-none-any.whl (10 kB)Installing collected packages: urllib3, six, python-dateutil, docutils, jmespath, botocore, s3transfer, boto3Successfully installed boto3-1.11.0 botocore-1.14.9 docutils-0.15.2 jmespath-0.9.4 python-dateutil-2.8.1 s3transfer-0.3.2 six-1.14.0 urllib3-1.25.8" }, { "code": null, "e": 3973, "s": 3771, "text": "Since we want to store secret/s, it is better to encrypt it at rest to provide extra layer of security. We are going to create a KMS key that will be used to encrypt and decrypt our secret parameter/s." }, { "code": null, "e": 4049, "s": 3973, "text": "From your terminal, run the following command, which will create a KMS key." }, { "code": null, "e": 4620, "s": 4049, "text": "$ ~/demo/kms-ssm-decrypt (venv) ❯ aws kms create-key --description \"A key to encrypt-decrypt secrets\"{ \"KeyMetadata\": { \"AWSAccountId\": \"xxxxxxxxxxxx\", \"KeyId\": \"ca83c234-7e63-4d8d-1234-28603cb10123\", \"Arn\": \"arn:aws:kms:ap-southeast-2:xxxxxxxxxxxx:key/ca83c234-7e63-4d8d-1234-28603cb10123\", \"CreationDate\": 1580217378.859, \"Enabled\": true, \"Description\": \"A key to encrypt-decrypt secrets\", \"KeyUsage\": \"ENCRYPT_DECRYPT\", \"KeyState\": \"Enabled\", \"Origin\": \"AWS_KMS\", \"KeyManager\": \"CUSTOMER\" }}" }, { "code": null, "e": 4742, "s": 4620, "text": "Nice, the command outputs the key metadata onto the console if run successfully. We’re good to continue to the next step." }, { "code": null, "e": 4940, "s": 4742, "text": "We are going to store a secret parameter into the SSM parameter store as SecureString. SecureString parameter type simply indicates that the value of the parameter we are storing will be encrypted." }, { "code": null, "e": 5022, "s": 4940, "text": "To put a secret parameter, let’s execute the following command from the terminal." }, { "code": null, "e": 5284, "s": 5022, "text": "$ ~/demo/kms-ssm-decrypt (venv) ❯ aws ssm put-parameter --name \"/demo/secret/parameter\" --value \"thisIsASecret\" --type SecureString --key-id ca83c234-7e63-4d8d-1234-28603cb10123 --description \"This is a secret parameter\"{ \"Version\": 1, \"Tier\": \"Standard\"}" }, { "code": null, "e": 5386, "s": 5284, "text": "The parameters for the command are self-explanatory, however, I just want to highlight a few of them:" }, { "code": null, "e": 5539, "s": 5386, "text": "--name : is the name or path to the parameter you are storing, e.g. it could’ve just been a name like “somesecretpathname” instead of a path like above." }, { "code": null, "e": 5596, "s": 5539, "text": "--value : is the value of the parameter you are storing." }, { "code": null, "e": 5848, "s": 5596, "text": "--type : is the type of the parameter, which in this example is a SecureString to tell SSM to encrypt the value before storing it in the parameter store. If you are just storing a non-secret parameter, then the SSM parameter type would just be String." }, { "code": null, "e": 6024, "s": 5848, "text": "--key-id : is the id of the KMS key you want to use to encrypt the value of the parameter. This is the value of KeyId from the previous section where we generated the KMS key." }, { "code": null, "e": 6119, "s": 6024, "text": "--description : is the description of the parameter you are storing so you know what it’s for." }, { "code": null, "e": 6260, "s": 6119, "text": "Awesome. Now, we have our secret parameter stored in the SSM parameter store. Let’s see how we can programmatically retrieve and decrypt it." }, { "code": null, "e": 6425, "s": 6260, "text": "Now, it’s time to write the script that will retrieve the secret parameter we just stored in SSM parameter store and decrypt it so we can use it in our application." }, { "code": null, "e": 6529, "s": 6425, "text": "Let’s create a new Python file in the project directory and name it retrieve_and_decrypt_ssm_secret.py." }, { "code": null, "e": 6936, "s": 6529, "text": "Notice the get_parameter() function’s argument named WithDecryption. In this exercise, we specify it to be True because we want to get the secret value and use it in our application. You might ask, why don’t we specify the KeyId that was used to encrypt it? The answer is, the KeyId information is actually contained in the encrypted parameter and so, SSM knows which key to use to decrypt the secret with." }, { "code": null, "e": 7157, "s": 6936, "text": "The script is runnable from terminal and it accepts an argument, which is the parameter’s name or path. Go ahead and execute it from terminal like this. (Note that Boto3 will look for AWS Credentials in your environment)" }, { "code": null, "e": 7895, "s": 7157, "text": "$ ~/demo/kms-ssm-decrypt (venv) ❯ python3 retrieve_and_decrypt_ssm_secret.py \"/demo/secret/parameter\"Secret isthisIsASecret=====Parameter details{'Parameter': {'Name': '/demo/secret/parameter', 'Type': 'SecureString', 'Value': 'thisIsASecret', 'Version': 1, 'LastModifiedDate': datetime.datetime(2020, 1, 30, 23, 26, 35, 169000, tzinfo=tzlocal()), 'ARN': 'arn:aws:ssm:ap-southeast-2:xxxxxxxxxxxx:parameter/demo/secret/parameter'}, 'ResponseMetadata': {'RequestId': '5ad11d35-axz6-42a0-90g5-0b7682a79321', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '5ad07d20-ama6-43c0-90a4-0b7682a11267', 'content-type': 'application/x-amz-json-1.1', 'content-length': '239', 'date': 'Thu, 30 Jan 2020 12:48:53 GMT'}, 'RetryAttempts': 0}}" }, { "code": null, "e": 7953, "s": 7895, "text": "Tada! We got the secret parameter back — thisIsASecret. 🙂" }, { "code": null, "e": 8209, "s": 7953, "text": "By now, you will have gained the basic skills and knowledge on how to secure your application secret/s using AWS KMS and SSM parameter store. You have also learned how to programmatically retrieve the secret/s, so that, you can use it on your application." }, { "code": null, "e": 8311, "s": 8209, "text": "I hope this tutorial was useful and helps you understand one way to secure your application secret/s." } ]
Python MySQL - GeeksforGeeks
01 Feb, 2022 Python MySQL Connector is a Python driver that helps to integrate Python and MySQL. This Python MySQL library allows the conversion between Python and MySQL data types. MySQL Connector API is implemented using pure Python and does not require any third-party library. This Python MySQL tutorial will help to learn how to use MySQL with Python from basics to advance, including all necessary functions and queries explained in detail with the help of good Python MySQL examples. So, let’s get started. To install the Python-mysql-connector module, one must have Python and PIP, preinstalled on their system. If Python and pip are already installed type the below command in the terminal. pip3 install mysql-connector-python Note: If Python is not present, go through How to install Python on Windows and Linux? and follow the instructions provided. We can connect to the MySQL server using the connect() method. Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password") print(dataBase) # Disconnecting from the serverdataBase.close() Output: <mysql.connector.connection_cext.CMySQLConnection object at 0x7f73f0191d00> Note: For more information, refer to Connect MySQL database using MySQL-Connector Python. After connecting to the MySQL server let’s see how to create a MySQL database using Python. For this, we will first create a cursor() object and will then pass the SQL command as a string to the execute() method. The SQL command to create a database is – CREATE DATABASE DATABASE_NAME Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password") # preparing a cursor objectcursorObject = dataBase.cursor() # creating databasecursorObject.execute("CREATE DATABASE gfg") Output: For creating tables we will follow the similar approach of writing the SQL commands as strings and then passing it to the execute() method of the cursor object. SQL command for creating a table is – CREATE TABLE ( column_name_1 column_Data_type, column_name_2 column_Data_type, : : column_name_n column_Data_type ); Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() # creating tablestudentRecord = """CREATE TABLE STUDENT ( NAME VARCHAR(20) NOT NULL, BRANCH VARCHAR(50), ROLL INT NOT NULL, SECTION VARCHAR(5), AGE INT )""" # table createdcursorObject.execute(studentRecord) # disconnecting from serverdataBase.close() Output: To insert data into the MySQL table Insert into query is used. Syntax: INSERT INTO table_name (column_names) VALUES (data) Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\VALUES (%s, %s, %s, %s, %s)"val = ("Ram", "CSE", "85", "B", "19") cursorObject.execute(sql, val)dataBase.commit() # disconnecting from serverdataBase.close() Output: To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method. Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() sql = "INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\VALUES (%s, %s, %s, %s, %s)"val = [("Nikhil", "CSE", "98", "A", "18"), ("Nisha", "CSE", "99", "A", "18"), ("Rohan", "MAE", "43", "B", "20"), ("Amit", "ECE", "24", "A", "21"), ("Anil", "MAE", "45", "B", "20"), ("Megha", "ECE", "55", "A", "22"), ("Sita", "CSE", "95", "A", "19")] cursorObject.executemany(sql, val)dataBase.commit() # disconnecting from serverdataBase.close() Output: We can use the select query on the MySQL tables in the following ways – In order to select particular attribute columns from a table, we write the attribute names. SELECT attr1, attr2 FROM table_name In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol. SELECT * FROM table_name Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query = "SELECT NAME, ROLL FROM STUDENT"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close() Output: Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause. Syntax: SELECT column1, column2, .... columnN FROM [TABLE NAME] WHERE [CONDITION]; Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query = "SELECT * FROM STUDENT where AGE >=20"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close() Output: ('Rohan', 'MAE', 43, 'B', 20) ('Amit', 'ECE', 24, 'A', 21) ('Anil', 'MAE', 45, 'B', 20) ('Megha', 'ECE', 55, 'A', 22) OrderBy is used to arrange the result set in either ascending or descending order. By default, it is always in ascending order unless “DESC” is mentioned, which arranges it in descending order. “ASC” can also be used to explicitly arrange it in ascending order. But, it is generally not done this way since default already does that. Syntax: SELECT column1, column2 FROM table_name ORDER BY column_name ASC|DESC; Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query = "SELECT * FROM STUDENT ORDER BY NAME DESC"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close() Output: The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of OFFSET keyword. OFFSET allows you to start from a custom row and get the required number of result rows. Syntax: SELECT * FROM tablename LIMIT limit; SELECT * FROM tablename LIMIT limit OFFSET offset; Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query = "SELECT * FROM STUDENT LIMIT 2 OFFSET 1"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close() Output: ('Nikhil', 'CSE', 98, 'A', 18) ('Nisha', 'CSE', 99, 'A', 18) The update query is used to change the existing values in a database. By using update a specific value can be corrected or updated. It only affects the data and not the structure of the table. The basic advantage provided by this command is that it keeps the table accurate. Syntax: UPDATE tablename SET ="new value" WHERE ="old value"; Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query = "UPDATE STUDENT SET AGE = 23 WHERE Name ='Ram'"cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close() Output: We can use the Delete query to delete data from the table in MySQL. Syntax: DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME = ATTRIBUTE_VALUE Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query = "DELETE FROM STUDENT WHERE NAME = 'Ram'"cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close() Output: Drop command affects the structure of the table and not data. It is used to delete an already existing table. For cases where you are not sure if the table to be dropped exists or not DROP TABLE IF EXISTS command is used. Both cases will be dealt with in the following examples. Syntax: DROP TABLE tablename; DROP TABLE IF EXISTS tablename; At first, let’s see the list of tables in our database. We can see that there are two tables for students, so let’s drop the second table. Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query ="DROP TABLE Student;" cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close() Output: Python3 # importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host ="localhost", user ="user", passwd ="password", database = "gfg") # preparing a cursor objectcursorObject = dataBase.cursor() query ="Drop Table if exists Employee;" cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close() The above example, will not create any error and output because we have used the Drop Table is exists query. If we will simply use the Drop table Employee then ProgrammingError: 1051 (42S02): Unknown table ‘gfg.Employee’ is raised. How to insert values into MySQL server table using Python? How to Show All Tables in MySQL using Python? How to Get the Size of a Table in MySQL using Python? How to Rename a MySQL Table in Python? How to Copy a Table in MySQL Using Python? How to Copy a Table Definition in MySQL Using Python? Get the id after INSERT into MySQL database using Python How to Use IF Statement in MySQL Using Python Deleting Element from Table in MySql using Python Grant MySQL table and column permissions using Python How to Count the Number of Rows in a MySQL Table in Python? Count SQL Table Column Using Python How to Add a Column to a MySQL Table in Python? How to Get the Minimum and maximum Value of a Column of a MySQL Table Using Python? How to Perform Arithmetic Across Columns of a MySQL Table Using Python? How to Concatenate Column Values of a MySQL Table Using Python? Add comment to column in MySQL using Python Grant MySQL table and column permissions using Python Create MySQL Database Login Page in Python using Tkinter Extract Data from Database using MySQL-Connector and XAMPP in Python rajeev0719singh nikhilaggarwal3 saurabh1990aror Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace()
[ { "code": null, "e": 41552, "s": 41524, "text": "\n01 Feb, 2022" }, { "code": null, "e": 41821, "s": 41552, "text": "Python MySQL Connector is a Python driver that helps to integrate Python and MySQL. This Python MySQL library allows the conversion between Python and MySQL data types. MySQL Connector API is implemented using pure Python and does not require any third-party library. " }, { "code": null, "e": 42054, "s": 41821, "text": "This Python MySQL tutorial will help to learn how to use MySQL with Python from basics to advance, including all necessary functions and queries explained in detail with the help of good Python MySQL examples. So, let’s get started." }, { "code": null, "e": 42240, "s": 42054, "text": "To install the Python-mysql-connector module, one must have Python and PIP, preinstalled on their system. If Python and pip are already installed type the below command in the terminal." }, { "code": null, "e": 42276, "s": 42240, "text": "pip3 install mysql-connector-python" }, { "code": null, "e": 42401, "s": 42276, "text": "Note: If Python is not present, go through How to install Python on Windows and Linux? and follow the instructions provided." }, { "code": null, "e": 42465, "s": 42401, "text": "We can connect to the MySQL server using the connect() method. " }, { "code": null, "e": 42473, "s": 42465, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\") print(dataBase) # Disconnecting from the serverdataBase.close()", "e": 42684, "s": 42473, "text": null }, { "code": null, "e": 42692, "s": 42684, "text": "Output:" }, { "code": null, "e": 42768, "s": 42692, "text": "<mysql.connector.connection_cext.CMySQLConnection object at 0x7f73f0191d00>" }, { "code": null, "e": 42858, "s": 42768, "text": "Note: For more information, refer to Connect MySQL database using MySQL-Connector Python." }, { "code": null, "e": 43114, "s": 42858, "text": "After connecting to the MySQL server let’s see how to create a MySQL database using Python. For this, we will first create a cursor() object and will then pass the SQL command as a string to the execute() method. The SQL command to create a database is – " }, { "code": null, "e": 43144, "s": 43114, "text": "CREATE DATABASE DATABASE_NAME" }, { "code": null, "e": 43152, "s": 43144, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\") # preparing a cursor objectcursorObject = dataBase.cursor() # creating databasecursorObject.execute(\"CREATE DATABASE gfg\")", "e": 43421, "s": 43152, "text": null }, { "code": null, "e": 43429, "s": 43421, "text": "Output:" }, { "code": null, "e": 43629, "s": 43429, "text": "For creating tables we will follow the similar approach of writing the SQL commands as strings and then passing it to the execute() method of the cursor object. SQL command for creating a table is – " }, { "code": null, "e": 43766, "s": 43629, "text": "CREATE TABLE\n(\n column_name_1 column_Data_type,\n column_name_2 column_Data_type,\n :\n :\n column_name_n column_Data_type\n);" }, { "code": null, "e": 43774, "s": 43766, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() # creating tablestudentRecord = \"\"\"CREATE TABLE STUDENT ( NAME VARCHAR(20) NOT NULL, BRANCH VARCHAR(50), ROLL INT NOT NULL, SECTION VARCHAR(5), AGE INT )\"\"\" # table createdcursorObject.execute(studentRecord) # disconnecting from serverdataBase.close()", "e": 44363, "s": 43774, "text": null }, { "code": null, "e": 44371, "s": 44363, "text": "Output:" }, { "code": null, "e": 44435, "s": 44371, "text": "To insert data into the MySQL table Insert into query is used. " }, { "code": null, "e": 44443, "s": 44435, "text": "Syntax:" }, { "code": null, "e": 44496, "s": 44443, "text": " INSERT INTO table_name (column_names) VALUES (data)" }, { "code": null, "e": 44504, "s": 44496, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() sql = \"INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\\VALUES (%s, %s, %s, %s, %s)\"val = (\"Ram\", \"CSE\", \"85\", \"B\", \"19\") cursorObject.execute(sql, val)dataBase.commit() # disconnecting from serverdataBase.close()", "e": 44954, "s": 44504, "text": null }, { "code": null, "e": 44962, "s": 44954, "text": "Output:" }, { "code": null, "e": 45137, "s": 44962, "text": "To insert multiple values at once, executemany() method is used. This method iterates through the sequence of parameters, passing the current parameter to the execute method." }, { "code": null, "e": 45145, "s": 45137, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() sql = \"INSERT INTO STUDENT (NAME, BRANCH, ROLL, SECTION, AGE)\\VALUES (%s, %s, %s, %s, %s)\"val = [(\"Nikhil\", \"CSE\", \"98\", \"A\", \"18\"), (\"Nisha\", \"CSE\", \"99\", \"A\", \"18\"), (\"Rohan\", \"MAE\", \"43\", \"B\", \"20\"), (\"Amit\", \"ECE\", \"24\", \"A\", \"21\"), (\"Anil\", \"MAE\", \"45\", \"B\", \"20\"), (\"Megha\", \"ECE\", \"55\", \"A\", \"22\"), (\"Sita\", \"CSE\", \"95\", \"A\", \"19\")] cursorObject.executemany(sql, val)dataBase.commit() # disconnecting from serverdataBase.close()", "e": 45847, "s": 45145, "text": null }, { "code": null, "e": 45855, "s": 45847, "text": "Output:" }, { "code": null, "e": 45927, "s": 45855, "text": "We can use the select query on the MySQL tables in the following ways –" }, { "code": null, "e": 46019, "s": 45927, "text": "In order to select particular attribute columns from a table, we write the attribute names." }, { "code": null, "e": 46055, "s": 46019, "text": "SELECT attr1, attr2 FROM table_name" }, { "code": null, "e": 46146, "s": 46055, "text": "In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol." }, { "code": null, "e": 46171, "s": 46146, "text": "SELECT * FROM table_name" }, { "code": null, "e": 46179, "s": 46171, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query = \"SELECT NAME, ROLL FROM STUDENT\"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()", "e": 46587, "s": 46179, "text": null }, { "code": null, "e": 46595, "s": 46587, "text": "Output:" }, { "code": null, "e": 46782, "s": 46595, "text": "Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause." }, { "code": null, "e": 46790, "s": 46782, "text": "Syntax:" }, { "code": null, "e": 46865, "s": 46790, "text": "SELECT column1, column2, .... columnN FROM [TABLE NAME] WHERE [CONDITION];" }, { "code": null, "e": 46873, "s": 46865, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query = \"SELECT * FROM STUDENT where AGE >=20\"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()", "e": 47287, "s": 46873, "text": null }, { "code": null, "e": 47295, "s": 47287, "text": "Output:" }, { "code": null, "e": 47413, "s": 47295, "text": "('Rohan', 'MAE', 43, 'B', 20)\n('Amit', 'ECE', 24, 'A', 21)\n('Anil', 'MAE', 45, 'B', 20)\n('Megha', 'ECE', 55, 'A', 22)" }, { "code": null, "e": 47747, "s": 47413, "text": "OrderBy is used to arrange the result set in either ascending or descending order. By default, it is always in ascending order unless “DESC” is mentioned, which arranges it in descending order. “ASC” can also be used to explicitly arrange it in ascending order. But, it is generally not done this way since default already does that." }, { "code": null, "e": 47755, "s": 47747, "text": "Syntax:" }, { "code": null, "e": 47826, "s": 47755, "text": "SELECT column1, column2\nFROM table_name\nORDER BY column_name ASC|DESC;" }, { "code": null, "e": 47834, "s": 47826, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query = \"SELECT * FROM STUDENT ORDER BY NAME DESC\"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()", "e": 48252, "s": 47834, "text": null }, { "code": null, "e": 48260, "s": 48252, "text": "Output:" }, { "code": null, "e": 48596, "s": 48260, "text": "The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of OFFSET keyword. OFFSET allows you to start from a custom row and get the required number of result rows." }, { "code": null, "e": 48604, "s": 48596, "text": "Syntax:" }, { "code": null, "e": 48692, "s": 48604, "text": "SELECT * FROM tablename LIMIT limit;\nSELECT * FROM tablename LIMIT limit OFFSET offset;" }, { "code": null, "e": 48700, "s": 48692, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query = \"SELECT * FROM STUDENT LIMIT 2 OFFSET 1\"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()", "e": 49116, "s": 48700, "text": null }, { "code": null, "e": 49124, "s": 49116, "text": "Output:" }, { "code": null, "e": 49185, "s": 49124, "text": "('Nikhil', 'CSE', 98, 'A', 18)\n('Nisha', 'CSE', 99, 'A', 18)" }, { "code": null, "e": 49460, "s": 49185, "text": "The update query is used to change the existing values in a database. By using update a specific value can be corrected or updated. It only affects the data and not the structure of the table. The basic advantage provided by this command is that it keeps the table accurate." }, { "code": null, "e": 49468, "s": 49460, "text": "Syntax:" }, { "code": null, "e": 49522, "s": 49468, "text": "UPDATE tablename\nSET =\"new value\"\nWHERE =\"old value\";" }, { "code": null, "e": 49530, "s": 49522, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query = \"UPDATE STUDENT SET AGE = 23 WHERE Name ='Ram'\"cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close()", "e": 49900, "s": 49530, "text": null }, { "code": null, "e": 49908, "s": 49900, "text": "Output:" }, { "code": null, "e": 49976, "s": 49908, "text": "We can use the Delete query to delete data from the table in MySQL." }, { "code": null, "e": 49984, "s": 49976, "text": "Syntax:" }, { "code": null, "e": 50046, "s": 49984, "text": "DELETE FROM TABLE_NAME WHERE ATTRIBUTE_NAME = ATTRIBUTE_VALUE" }, { "code": null, "e": 50054, "s": 50046, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query = \"DELETE FROM STUDENT WHERE NAME = 'Ram'\"cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close()", "e": 50417, "s": 50054, "text": null }, { "code": null, "e": 50425, "s": 50417, "text": "Output:" }, { "code": null, "e": 50704, "s": 50425, "text": "Drop command affects the structure of the table and not data. It is used to delete an already existing table. For cases where you are not sure if the table to be dropped exists or not DROP TABLE IF EXISTS command is used. Both cases will be dealt with in the following examples." }, { "code": null, "e": 50712, "s": 50704, "text": "Syntax:" }, { "code": null, "e": 50766, "s": 50712, "text": "DROP TABLE tablename;\nDROP TABLE IF EXISTS tablename;" }, { "code": null, "e": 50822, "s": 50766, "text": "At first, let’s see the list of tables in our database." }, { "code": null, "e": 50905, "s": 50822, "text": "We can see that there are two tables for students, so let’s drop the second table." }, { "code": null, "e": 50913, "s": 50905, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query =\"DROP TABLE Student;\" cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close()", "e": 51257, "s": 50913, "text": null }, { "code": null, "e": 51265, "s": 51257, "text": "Output:" }, { "code": null, "e": 51273, "s": 51265, "text": "Python3" }, { "code": "# importing required librariesimport mysql.connector dataBase = mysql.connector.connect( host =\"localhost\", user =\"user\", passwd =\"password\", database = \"gfg\") # preparing a cursor objectcursorObject = dataBase.cursor() query =\"Drop Table if exists Employee;\" cursorObject.execute(query)dataBase.commit() # disconnecting from serverdataBase.close()", "e": 51628, "s": 51273, "text": null }, { "code": null, "e": 51860, "s": 51628, "text": "The above example, will not create any error and output because we have used the Drop Table is exists query. If we will simply use the Drop table Employee then ProgrammingError: 1051 (42S02): Unknown table ‘gfg.Employee’ is raised." }, { "code": null, "e": 51919, "s": 51860, "text": "How to insert values into MySQL server table using Python?" }, { "code": null, "e": 51965, "s": 51919, "text": "How to Show All Tables in MySQL using Python?" }, { "code": null, "e": 52019, "s": 51965, "text": "How to Get the Size of a Table in MySQL using Python?" }, { "code": null, "e": 52058, "s": 52019, "text": "How to Rename a MySQL Table in Python?" }, { "code": null, "e": 52101, "s": 52058, "text": "How to Copy a Table in MySQL Using Python?" }, { "code": null, "e": 52155, "s": 52101, "text": "How to Copy a Table Definition in MySQL Using Python?" }, { "code": null, "e": 52212, "s": 52155, "text": "Get the id after INSERT into MySQL database using Python" }, { "code": null, "e": 52258, "s": 52212, "text": "How to Use IF Statement in MySQL Using Python" }, { "code": null, "e": 52308, "s": 52258, "text": "Deleting Element from Table in MySql using Python" }, { "code": null, "e": 52362, "s": 52308, "text": "Grant MySQL table and column permissions using Python" }, { "code": null, "e": 52422, "s": 52362, "text": "How to Count the Number of Rows in a MySQL Table in Python?" }, { "code": null, "e": 52458, "s": 52422, "text": "Count SQL Table Column Using Python" }, { "code": null, "e": 52506, "s": 52458, "text": "How to Add a Column to a MySQL Table in Python?" }, { "code": null, "e": 52590, "s": 52506, "text": "How to Get the Minimum and maximum Value of a Column of a MySQL Table Using Python?" }, { "code": null, "e": 52662, "s": 52590, "text": "How to Perform Arithmetic Across Columns of a MySQL Table Using Python?" }, { "code": null, "e": 52726, "s": 52662, "text": "How to Concatenate Column Values of a MySQL Table Using Python?" }, { "code": null, "e": 52770, "s": 52726, "text": "Add comment to column in MySQL using Python" }, { "code": null, "e": 52824, "s": 52770, "text": "Grant MySQL table and column permissions using Python" }, { "code": null, "e": 52881, "s": 52824, "text": "Create MySQL Database Login Page in Python using Tkinter" }, { "code": null, "e": 52950, "s": 52881, "text": "Extract Data from Database using MySQL-Connector and XAMPP in Python" }, { "code": null, "e": 52966, "s": 52950, "text": "rajeev0719singh" }, { "code": null, "e": 52982, "s": 52966, "text": "nikhilaggarwal3" }, { "code": null, "e": 52998, "s": 52982, "text": "saurabh1990aror" }, { "code": null, "e": 53005, "s": 52998, "text": "Python" }, { "code": null, "e": 53103, "s": 53005, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 53112, "s": 53103, "text": "Comments" }, { "code": null, "e": 53125, "s": 53112, "text": "Old Comments" }, { "code": null, "e": 53153, "s": 53125, "text": "Read JSON file using Python" }, { "code": null, "e": 53203, "s": 53153, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 53225, "s": 53203, "text": "Python map() function" }, { "code": null, "e": 53269, "s": 53225, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 53304, "s": 53269, "text": "Read a file line by line in Python" }, { "code": null, "e": 53336, "s": 53304, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 53358, "s": 53336, "text": "Enumerate() in Python" }, { "code": null, "e": 53388, "s": 53358, "text": "Iterate over a list in Python" }, { "code": null, "e": 53430, "s": 53388, "text": "Different ways to create Pandas Dataframe" } ]
Program to find sum of beauty of all substrings in Python
Suppose we have a string s. We have to find the sum of beauty of all of its substrings. The beauty of a string is actually the difference in frequencies between the most frequent and least frequent characters. So if the string is "abaacc", then its frequency is 3 - 1 = 2. So, if the input is like s = "xxyzy", then the output will be 5 because the substrings with non-zero beauty are ["xxy","xxyz","xxyzy","xyzy","yzy"], each has beauty value 1. To solve this, we will follow these steps − res:= 0 res:= 0 for i in range 0 to size of s - 1, dofor j in range i+2 to size of s - 1, doc:= a map containing characters frequency of substring of s from index i to jv:= list of all frequency values of cres := res +(maximum of v - minimum of v) for i in range 0 to size of s - 1, do for j in range i+2 to size of s - 1, doc:= a map containing characters frequency of substring of s from index i to jv:= list of all frequency values of cres := res +(maximum of v - minimum of v) for j in range i+2 to size of s - 1, do c:= a map containing characters frequency of substring of s from index i to j c:= a map containing characters frequency of substring of s from index i to j v:= list of all frequency values of c v:= list of all frequency values of c res := res +(maximum of v - minimum of v) res := res +(maximum of v - minimum of v) return res return res Let us see the following implementation to get better understanding − from collections import Counter def solve(s): res=0 for i in range(len(s)): for j in range(i+2,len(s)): c=Counter(s[i:j+1]) v=c.values() res+=(max(v)-min(v)) return res s = "xxyzy" print(solve(s)) "xxyzy" 5
[ { "code": null, "e": 1335, "s": 1062, "text": "Suppose we have a string s. We have to find the sum of beauty of all of its substrings. The beauty of a string is actually the difference in frequencies between the most frequent and least frequent characters. So if the string is \"abaacc\", then its frequency is 3 - 1 = 2." }, { "code": null, "e": 1509, "s": 1335, "text": "So, if the input is like s = \"xxyzy\", then the output will be 5 because the substrings with non-zero beauty are [\"xxy\",\"xxyz\",\"xxyzy\",\"xyzy\",\"yzy\"], each has beauty value 1." }, { "code": null, "e": 1553, "s": 1509, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1561, "s": 1553, "text": "res:= 0" }, { "code": null, "e": 1569, "s": 1561, "text": "res:= 0" }, { "code": null, "e": 1801, "s": 1569, "text": "for i in range 0 to size of s - 1, dofor j in range i+2 to size of s - 1, doc:= a map containing characters frequency of substring of s from index i to jv:= list of all frequency values of cres := res +(maximum of v - minimum of v)" }, { "code": null, "e": 1839, "s": 1801, "text": "for i in range 0 to size of s - 1, do" }, { "code": null, "e": 2034, "s": 1839, "text": "for j in range i+2 to size of s - 1, doc:= a map containing characters frequency of substring of s from index i to jv:= list of all frequency values of cres := res +(maximum of v - minimum of v)" }, { "code": null, "e": 2074, "s": 2034, "text": "for j in range i+2 to size of s - 1, do" }, { "code": null, "e": 2152, "s": 2074, "text": "c:= a map containing characters frequency of substring of s from index i to j" }, { "code": null, "e": 2230, "s": 2152, "text": "c:= a map containing characters frequency of substring of s from index i to j" }, { "code": null, "e": 2268, "s": 2230, "text": "v:= list of all frequency values of c" }, { "code": null, "e": 2306, "s": 2268, "text": "v:= list of all frequency values of c" }, { "code": null, "e": 2348, "s": 2306, "text": "res := res +(maximum of v - minimum of v)" }, { "code": null, "e": 2390, "s": 2348, "text": "res := res +(maximum of v - minimum of v)" }, { "code": null, "e": 2401, "s": 2390, "text": "return res" }, { "code": null, "e": 2412, "s": 2401, "text": "return res" }, { "code": null, "e": 2482, "s": 2412, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2723, "s": 2482, "text": "from collections import Counter\n\ndef solve(s):\n res=0\n for i in range(len(s)):\n for j in range(i+2,len(s)):\n c=Counter(s[i:j+1])\n v=c.values()\n res+=(max(v)-min(v))\n return res\n\ns = \"xxyzy\"\nprint(solve(s))" }, { "code": null, "e": 2732, "s": 2723, "text": "\"xxyzy\"\n" }, { "code": null, "e": 2734, "s": 2732, "text": "5" } ]
Geolocation getCurrentPosition() API
The getCurrentPosition method retrieves the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The location information is returned in a Position object. Here is the syntax of this method − getCurrentPosition(showLocation, ErrorHandler, options); Here is the detail of parameters − showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information. showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information. ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information. ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information. options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information. options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information. The getCurrentPosition method does not return a value. <!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> function showLocation(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; alert("Latitude : " + latitude + " Longitude: " + longitude); } function errorHandler(err) { if(err.code == 1) { alert("Error: Access is denied!"); } else if( err.code == 2) { alert("Error: Position is unavailable!"); } } function getLocation() { if(navigator.geolocation) { // timeout at 60000 milliseconds (60 seconds) var options = {timeout:60000}; navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options); } else { alert("Sorry, browser does not support geolocation!"); } } </script> </head> <body> <form> <input type = "button" onclick = "getLocation();" value = "Get Location"/> </form> </body> </html> 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2866, "s": 2608, "text": "The getCurrentPosition method retrieves the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The location information is returned in a Position object." }, { "code": null, "e": 2903, "s": 2866, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2961, "s": 2903, "text": "getCurrentPosition(showLocation, ErrorHandler, options);\n" }, { "code": null, "e": 2996, "s": 2961, "text": "Here is the detail of parameters −" }, { "code": null, "e": 3224, "s": 2996, "text": "showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information." }, { "code": null, "e": 3452, "s": 3224, "text": "showLocation − This specifies the callback method that retrieves the location information. This method is called asynchronously with an object corresponding to the Position object which stores the returned location information." }, { "code": null, "e": 3691, "s": 3452, "text": "ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information." }, { "code": null, "e": 3930, "s": 3691, "text": "ErrorHandler − This optional parameter specifies the callback method that is invoked when an error occurs in processing the asynchronous call. This method is called with the PositionError object that stores the returned error information." }, { "code": null, "e": 4194, "s": 3930, "text": "options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information." }, { "code": null, "e": 4458, "s": 4194, "text": "options − This optional parameter specifies a set of options for retrieving the location information. You can specify (a) Accuracy of the returned location information (b) Timeout for retrieving the location information and (c) Use of cached location information." }, { "code": null, "e": 4513, "s": 4458, "text": "The getCurrentPosition method does not return a value." }, { "code": null, "e": 5670, "s": 4513, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n\t\t\n function showLocation(position) {\n var latitude = position.coords.latitude;\n var longitude = position.coords.longitude;\n alert(\"Latitude : \" + latitude + \" Longitude: \" + longitude);\n }\n\n function errorHandler(err) {\n if(err.code == 1) {\n alert(\"Error: Access is denied!\");\n } else if( err.code == 2) {\n alert(\"Error: Position is unavailable!\");\n }\n }\n\t\t\t\n function getLocation() {\n\n if(navigator.geolocation) {\n \n // timeout at 60000 milliseconds (60 seconds)\n var options = {timeout:60000};\n navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);\n } else {\n alert(\"Sorry, browser does not support geolocation!\");\n }\n }\n\t\t\t\n </script>\n </head>\n <body>\n \n <form>\n <input type = \"button\" onclick = \"getLocation();\" value = \"Get Location\"/>\n </form>\n \n </body>\n</html>" }, { "code": null, "e": 5703, "s": 5670, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5717, "s": 5703, "text": " Anadi Sharma" }, { "code": null, "e": 5752, "s": 5717, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5766, "s": 5752, "text": " Anadi Sharma" }, { "code": null, "e": 5801, "s": 5766, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5818, "s": 5801, "text": " Frahaan Hussain" }, { "code": null, "e": 5853, "s": 5818, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5884, "s": 5853, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5917, "s": 5884, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 5948, "s": 5917, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5983, "s": 5948, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6014, "s": 5983, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 6021, "s": 6014, "text": " Print" }, { "code": null, "e": 6032, "s": 6021, "text": " Add Notes" } ]
How to underline a Hyperlink on Hover using jQuery?
To underline a hyperlink on hover using jQuery, use the jQuery css() property. The color text-decoration property is used. You can try to run the following code to learn how to underline a hyperlink on hover: Live Demo <html> <head> <title>jQuery Hyperlink Decoration</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $('a').hover( function () { $(this).css({"text-decoration":"underline"}); }); }); </script> <style> a { text-decoration: none; } </style> </head> <body> <a href="#">Demo text</a> </body> </html>
[ { "code": null, "e": 1186, "s": 1062, "text": "To underline a hyperlink on hover using jQuery, use the jQuery css() property. The color text-decoration property is used." }, { "code": null, "e": 1272, "s": 1186, "text": "You can try to run the following code to learn how to underline a hyperlink on hover:" }, { "code": null, "e": 1282, "s": 1272, "text": "Live Demo" }, { "code": null, "e": 1880, "s": 1282, "text": "<html>\n\n <head>\n <title>jQuery Hyperlink Decoration</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() {\n\n $('a').hover(\n \n function () {\n $(this).css({\"text-decoration\":\"underline\"});\n });\n \n });\n </script>\n <style>\n a {\n text-decoration: none;\n }\n </style>\n </head>\n \n <body>\n <a href=\"#\">Demo text</a>\n \n </body>\n \n</html>" } ]
C Program to find LCM of two numbers using Recursion - GeeksforGeeks
15 Dec, 2020 Given two integers N and M, the task is to find their LCM using recursion. Examples: Input: N = 2, M = 4Output: 4Explanation: LCM of 2, 4 is 4. Input: N = 3, M = 5Output: 15Explanation: LCM of 3, 5 is 15. Approach: The idea is to use the basic elementary method of finding LCM of two numbers. Follow the steps below to solve the problem: Define a recursive function LCM() with 3 integer parameters N, M, and K to find LCM of N and M. The following base conditions need to be considered:If N or M is equal to 1, return N * M.If N is equal to M, return N. If N or M is equal to 1, return N * M. If N is equal to M, return N. If K < min(N, M):If K divides both N and M, return K * LCM(N/K, M/K, 2).Otherwise, increment K by 1 and return LCM(N, M, K+1). If K divides both N and M, return K * LCM(N/K, M/K, 2). Otherwise, increment K by 1 and return LCM(N, M, K+1). Otherwise, return the product of N and M. Finally, print the result of the recursive function as the required LCM.Below is the implementation of the above approach:CC// C program for the above approach #include <stdio.h> // Function to return the// minimum of two numbersint Min(int Num1, int Num2){ return Num1 >= Num2 ? Num2 : Num1;} // Utility function to calculate LCM// of two numbers using recursionint LCMUtil(int Num1, int Num2, int K){ // If either of the two numbers // is 1, return their product if (Num1 == 1 || Num2 == 1) return Num1 * Num2; // If both the numbers are equal if (Num1 == Num2) return Num1; // If K is smaller than the // minimum of the two numbers if (K <= Min(Num1, Num2)) { // Checks if both numbers are // divisible by K or not if (Num1 % K == 0 && Num2 % K == 0) { // Recursively call LCM() function return K * LCMUtil( Num1 / K, Num2 / K, 2); } // Otherwise else return LCMUtil(Num1, Num2, K + 1); } // If K exceeds minimum else return Num1 * Num2;} // Function to calculate LCM// of two numbersvoid LCM(int N, int M){ // Stores LCM of two number int lcm = LCMUtil(N, M, 2); // Print LCM printf("%d", lcm);} // Driver Codeint main(){ // Given N & M int N = 2, M = 4; // Function Call LCM(N, M); return 0;}Output:4 Time Complexity: O(max(N, M))Auxiliary Space: O(1)My Personal Notes arrow_drop_upSave Below is the implementation of the above approach: C // C program for the above approach #include <stdio.h> // Function to return the// minimum of two numbersint Min(int Num1, int Num2){ return Num1 >= Num2 ? Num2 : Num1;} // Utility function to calculate LCM// of two numbers using recursionint LCMUtil(int Num1, int Num2, int K){ // If either of the two numbers // is 1, return their product if (Num1 == 1 || Num2 == 1) return Num1 * Num2; // If both the numbers are equal if (Num1 == Num2) return Num1; // If K is smaller than the // minimum of the two numbers if (K <= Min(Num1, Num2)) { // Checks if both numbers are // divisible by K or not if (Num1 % K == 0 && Num2 % K == 0) { // Recursively call LCM() function return K * LCMUtil( Num1 / K, Num2 / K, 2); } // Otherwise else return LCMUtil(Num1, Num2, K + 1); } // If K exceeds minimum else return Num1 * Num2;} // Function to calculate LCM// of two numbersvoid LCM(int N, int M){ // Stores LCM of two number int lcm = LCMUtil(N, M, 2); // Print LCM printf("%d", lcm);} // Driver Codeint main(){ // Given N & M int N = 2, M = 4; // Function Call LCM(N, M); return 0;} 4 Time Complexity: O(max(N, M))Auxiliary Space: O(1) LCM Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Modular multiplicative inverse Algorithm to solve Rubik's Cube Count ways to reach the n'th stair Program to multiply two matrices Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Program for Tower of Hanoi Recursion Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Backtracking | Introduction Program for Sum of the digits of a given number
[ { "code": null, "e": 24301, "s": 24273, "text": "\n15 Dec, 2020" }, { "code": null, "e": 24376, "s": 24301, "text": "Given two integers N and M, the task is to find their LCM using recursion." }, { "code": null, "e": 24386, "s": 24376, "text": "Examples:" }, { "code": null, "e": 24445, "s": 24386, "text": "Input: N = 2, M = 4Output: 4Explanation: LCM of 2, 4 is 4." }, { "code": null, "e": 24506, "s": 24445, "text": "Input: N = 3, M = 5Output: 15Explanation: LCM of 3, 5 is 15." }, { "code": null, "e": 24639, "s": 24506, "text": "Approach: The idea is to use the basic elementary method of finding LCM of two numbers. Follow the steps below to solve the problem:" }, { "code": null, "e": 24735, "s": 24639, "text": "Define a recursive function LCM() with 3 integer parameters N, M, and K to find LCM of N and M." }, { "code": null, "e": 24855, "s": 24735, "text": "The following base conditions need to be considered:If N or M is equal to 1, return N * M.If N is equal to M, return N." }, { "code": null, "e": 24894, "s": 24855, "text": "If N or M is equal to 1, return N * M." }, { "code": null, "e": 24924, "s": 24894, "text": "If N is equal to M, return N." }, { "code": null, "e": 25051, "s": 24924, "text": "If K < min(N, M):If K divides both N and M, return K * LCM(N/K, M/K, 2).Otherwise, increment K by 1 and return LCM(N, M, K+1)." }, { "code": null, "e": 25107, "s": 25051, "text": "If K divides both N and M, return K * LCM(N/K, M/K, 2)." }, { "code": null, "e": 25162, "s": 25107, "text": "Otherwise, increment K by 1 and return LCM(N, M, K+1)." }, { "code": null, "e": 25204, "s": 25162, "text": "Otherwise, return the product of N and M." }, { "code": null, "e": 26732, "s": 25204, "text": "Finally, print the result of the recursive function as the required LCM.Below is the implementation of the above approach:CC// C program for the above approach #include <stdio.h> // Function to return the// minimum of two numbersint Min(int Num1, int Num2){ return Num1 >= Num2 ? Num2 : Num1;} // Utility function to calculate LCM// of two numbers using recursionint LCMUtil(int Num1, int Num2, int K){ // If either of the two numbers // is 1, return their product if (Num1 == 1 || Num2 == 1) return Num1 * Num2; // If both the numbers are equal if (Num1 == Num2) return Num1; // If K is smaller than the // minimum of the two numbers if (K <= Min(Num1, Num2)) { // Checks if both numbers are // divisible by K or not if (Num1 % K == 0 && Num2 % K == 0) { // Recursively call LCM() function return K * LCMUtil( Num1 / K, Num2 / K, 2); } // Otherwise else return LCMUtil(Num1, Num2, K + 1); } // If K exceeds minimum else return Num1 * Num2;} // Function to calculate LCM// of two numbersvoid LCM(int N, int M){ // Stores LCM of two number int lcm = LCMUtil(N, M, 2); // Print LCM printf(\"%d\", lcm);} // Driver Codeint main(){ // Given N & M int N = 2, M = 4; // Function Call LCM(N, M); return 0;}Output:4\nTime Complexity: O(max(N, M))Auxiliary Space: O(1)My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 26783, "s": 26732, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26785, "s": 26783, "text": "C" }, { "code": "// C program for the above approach #include <stdio.h> // Function to return the// minimum of two numbersint Min(int Num1, int Num2){ return Num1 >= Num2 ? Num2 : Num1;} // Utility function to calculate LCM// of two numbers using recursionint LCMUtil(int Num1, int Num2, int K){ // If either of the two numbers // is 1, return their product if (Num1 == 1 || Num2 == 1) return Num1 * Num2; // If both the numbers are equal if (Num1 == Num2) return Num1; // If K is smaller than the // minimum of the two numbers if (K <= Min(Num1, Num2)) { // Checks if both numbers are // divisible by K or not if (Num1 % K == 0 && Num2 % K == 0) { // Recursively call LCM() function return K * LCMUtil( Num1 / K, Num2 / K, 2); } // Otherwise else return LCMUtil(Num1, Num2, K + 1); } // If K exceeds minimum else return Num1 * Num2;} // Function to calculate LCM// of two numbersvoid LCM(int N, int M){ // Stores LCM of two number int lcm = LCMUtil(N, M, 2); // Print LCM printf(\"%d\", lcm);} // Driver Codeint main(){ // Given N & M int N = 2, M = 4; // Function Call LCM(N, M); return 0;}", "e": 28095, "s": 26785, "text": null }, { "code": null, "e": 28098, "s": 28095, "text": "4\n" }, { "code": null, "e": 28149, "s": 28098, "text": "Time Complexity: O(max(N, M))Auxiliary Space: O(1)" }, { "code": null, "e": 28153, "s": 28149, "text": "LCM" }, { "code": null, "e": 28166, "s": 28153, "text": "Mathematical" }, { "code": null, "e": 28176, "s": 28166, "text": "Recursion" }, { "code": null, "e": 28189, "s": 28176, "text": "Mathematical" }, { "code": null, "e": 28199, "s": 28189, "text": "Recursion" }, { "code": null, "e": 28297, "s": 28199, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28306, "s": 28297, "text": "Comments" }, { "code": null, "e": 28319, "s": 28306, "text": "Old Comments" }, { "code": null, "e": 28350, "s": 28319, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28382, "s": 28350, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28417, "s": 28382, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 28450, "s": 28417, "text": "Program to multiply two matrices" }, { "code": null, "e": 28503, "s": 28450, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 28530, "s": 28503, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 28540, "s": 28530, "text": "Recursion" }, { "code": null, "e": 28625, "s": 28540, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 28653, "s": 28625, "text": "Backtracking | Introduction" } ]
Polymorphism in C++
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function. Consider the following example where a base class has been derived by other two classes − #include <iostream> using namespace std; class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0){ width = a; height = b; } int area() { cout << "Parent class area :" <<endl; return 0; } }; class Rectangle: public Shape { public: Rectangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << "Rectangle class area :" <<endl; return (width * height); } }; class Triangle: public Shape { public: Triangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << "Triangle class area :" <<endl; return (width * height / 2); } }; // Main function for the program int main() { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; } When the above code is compiled and executed, it produces the following result − Parent class area : Parent class area : The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program. But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this − class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0) { width = a; height = b; } virtual int area() { cout << "Parent class area :" <<endl; return 0; } }; After this slight modification, when the previous example code is compiled and executed, it produces the following result − Rectangle class area Triangle class area This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called. As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations. A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function. What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. We can change the virtual function area() in the base class to the following − class Shape { protected: int width, height; public: Shape(int a = 0, int b = 0) { width = a; height = b; } // pure virtual function virtual int area() = 0; }; The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function. 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2470, "s": 2318, "text": "The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance." }, { "code": null, "e": 2632, "s": 2470, "text": "C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function." }, { "code": null, "e": 2722, "s": 2632, "text": "Consider the following example where a base class has been derived by other two classes −" }, { "code": null, "e": 3801, "s": 2722, "text": "#include <iostream> \nusing namespace std;\n \nclass Shape {\n protected:\n int width, height;\n \n public:\n Shape( int a = 0, int b = 0){\n width = a;\n height = b;\n }\n int area() {\n cout << \"Parent class area :\" <<endl;\n return 0;\n }\n};\nclass Rectangle: public Shape {\n public:\n Rectangle( int a = 0, int b = 0):Shape(a, b) { }\n \n int area () { \n cout << \"Rectangle class area :\" <<endl;\n return (width * height); \n }\n};\n\nclass Triangle: public Shape {\n public:\n Triangle( int a = 0, int b = 0):Shape(a, b) { }\n \n int area () { \n cout << \"Triangle class area :\" <<endl;\n return (width * height / 2); \n }\n};\n\n// Main function for the program\nint main() {\n Shape *shape;\n Rectangle rec(10,7);\n Triangle tri(10,5);\n\n // store the address of Rectangle\n shape = &rec;\n \n // call rectangle area.\n shape->area();\n\n // store the address of Triangle\n shape = &tri;\n \n // call triangle area.\n shape->area();\n \n return 0;\n}" }, { "code": null, "e": 3882, "s": 3801, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3923, "s": 3882, "text": "Parent class area :\nParent class area :\n" }, { "code": null, "e": 4327, "s": 3923, "text": "The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program." }, { "code": null, "e": 4496, "s": 4327, "text": "But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this −" }, { "code": null, "e": 4758, "s": 4496, "text": "class Shape {\n protected:\n int width, height;\n \n public:\n Shape( int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n virtual int area() {\n cout << \"Parent class area :\" <<endl;\n return 0;\n }\n};\n" }, { "code": null, "e": 4882, "s": 4758, "text": "After this slight modification, when the previous example code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4924, "s": 4882, "text": "Rectangle class area\nTriangle class area\n" }, { "code": null, "e": 5127, "s": 4924, "text": "This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called." }, { "code": null, "e": 5395, "s": 5127, "text": "As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations." }, { "code": null, "e": 5651, "s": 5395, "text": "A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function." }, { "code": null, "e": 5881, "s": 5651, "text": "What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding." }, { "code": null, "e": 6132, "s": 5881, "text": "It is possible that you want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class." }, { "code": null, "e": 6211, "s": 6132, "text": "We can change the virtual function area() in the base class to the following −" }, { "code": null, "e": 6433, "s": 6211, "text": "class Shape {\n protected:\n int width, height;\n\n public:\n Shape(int a = 0, int b = 0) {\n width = a;\n height = b;\n }\n \n // pure virtual function\n virtual int area() = 0;\n};\n" }, { "code": null, "e": 6556, "s": 6433, "text": "The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function." }, { "code": null, "e": 6593, "s": 6556, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 6612, "s": 6593, "text": " Arnab Chakraborty" }, { "code": null, "e": 6644, "s": 6612, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 6667, "s": 6644, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 6703, "s": 6667, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 6720, "s": 6703, "text": " Frahaan Hussain" }, { "code": null, "e": 6755, "s": 6720, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6772, "s": 6755, "text": " Frahaan Hussain" }, { "code": null, "e": 6807, "s": 6772, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6824, "s": 6807, "text": " Frahaan Hussain" }, { "code": null, "e": 6859, "s": 6824, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6876, "s": 6859, "text": " Frahaan Hussain" }, { "code": null, "e": 6883, "s": 6876, "text": " Print" }, { "code": null, "e": 6894, "s": 6883, "text": " Add Notes" } ]
How to Design a Reinforcement Learning Reward Function for a Lunar Lander 🛸 | by Alina Zhang | Towards Data Science
Imagine aliens 👽 attacked and you were trying to land a Lander🛸 on the Moon, what factors would you consider to complete the mission successfully? Here are some considerations: Touch down on the landing pad vs Move away from the landing pad Land with a low velocity vs Crash at a high velocity Use as little fuel as possible vs Use lots of fuel Approach the target as fast as possible vs Hang in the air What to punish? What to reward? How to balance multiple constraints? And how to represent those ideas in our reward function? Reinforcement Learning (RL) is a branch in machine learning that leverages the trial and error problem-solving method in agent training. In our example, the agent will try to land the Lunar Lander for, let’s say, 10k times, to learn how to make better actions in different states. The Reward Function is an incentive mechanism that tells the agent what is correct and what is wrong using reward and punishment. The goal of agents in RL is to maximize the total rewards. Sometimes we need to sacrifice immediate rewards in order to maximize the total rewards. Some ideas of reward and punishment rules in lunar lander reward function could be: Give a high reward for landing on the right place with low enough velocity Give a penalty if lander landed outside of the landing pad Give a reward based on the percentage of remaining fuel Give a big penalty if the velocity is above threshold (crashed) when landed on the surface Give distance reward to encourage lander to approach the target As illustrated in the above image, variable fuel_conservation is a value between 0 and 1. When landed successfully at the landing pad, the reward received will be multiplied by fuel_conservation to encourage the lander to use as little fuel as possible. If the lander landed outside of the target spot, we give a small penalty of -10. If the lander crashed with a high velocity, we give a big penalty of -100. distance_reward = 1-(distance_to_goal / distance_max)**0.5 uses power of 0.5 to offer agents a smooth gradient of rewards as lander getting closer to the landing pad. # Encourage lander to use as little fuel as possible# i.e. 0.85, or 0.32fuel_conservation = fuel_remaining / total_fuelif distance_to_goal is decreasing: if speed < threshold: if position is on landing pad: # Land successfully; give a big reward landing_reward = 100 # Multiply percentage of remaining fuel reward = landing_reward * fuel_conservation else: # Landing outside of landing pad reward = -10 else: # Crashed reward = -100else: # Encourage agents to approach the surface instead of # hanging in the air distance_reward = 1 - (distance_to_goal / distance_max)**0.5 reward = distance_reward * fuel_conservation In this article, we use lunar lander as an example to demonstrate how to build an advanced reward function with reward and punishment rules. During the training of RL models, Reward Function guide agents to learn from the trials and errors that: What should I do? How to select between actions? What are better actions to maximize the total rewards? How to evaluate the goodness/badness of actions in different states? Happy Landing! Hopefully, aliens will come in PEACE. 👽☮️✌️🕊🛸 Youtube tutorial video about RL LunarLander-v2 by OpenAI
[ { "code": null, "e": 319, "s": 172, "text": "Imagine aliens 👽 attacked and you were trying to land a Lander🛸 on the Moon, what factors would you consider to complete the mission successfully?" }, { "code": null, "e": 349, "s": 319, "text": "Here are some considerations:" }, { "code": null, "e": 413, "s": 349, "text": "Touch down on the landing pad vs Move away from the landing pad" }, { "code": null, "e": 466, "s": 413, "text": "Land with a low velocity vs Crash at a high velocity" }, { "code": null, "e": 517, "s": 466, "text": "Use as little fuel as possible vs Use lots of fuel" }, { "code": null, "e": 576, "s": 517, "text": "Approach the target as fast as possible vs Hang in the air" }, { "code": null, "e": 702, "s": 576, "text": "What to punish? What to reward? How to balance multiple constraints? And how to represent those ideas in our reward function?" }, { "code": null, "e": 983, "s": 702, "text": "Reinforcement Learning (RL) is a branch in machine learning that leverages the trial and error problem-solving method in agent training. In our example, the agent will try to land the Lunar Lander for, let’s say, 10k times, to learn how to make better actions in different states." }, { "code": null, "e": 1261, "s": 983, "text": "The Reward Function is an incentive mechanism that tells the agent what is correct and what is wrong using reward and punishment. The goal of agents in RL is to maximize the total rewards. Sometimes we need to sacrifice immediate rewards in order to maximize the total rewards." }, { "code": null, "e": 1345, "s": 1261, "text": "Some ideas of reward and punishment rules in lunar lander reward function could be:" }, { "code": null, "e": 1420, "s": 1345, "text": "Give a high reward for landing on the right place with low enough velocity" }, { "code": null, "e": 1479, "s": 1420, "text": "Give a penalty if lander landed outside of the landing pad" }, { "code": null, "e": 1535, "s": 1479, "text": "Give a reward based on the percentage of remaining fuel" }, { "code": null, "e": 1626, "s": 1535, "text": "Give a big penalty if the velocity is above threshold (crashed) when landed on the surface" }, { "code": null, "e": 1690, "s": 1626, "text": "Give distance reward to encourage lander to approach the target" }, { "code": null, "e": 1944, "s": 1690, "text": "As illustrated in the above image, variable fuel_conservation is a value between 0 and 1. When landed successfully at the landing pad, the reward received will be multiplied by fuel_conservation to encourage the lander to use as little fuel as possible." }, { "code": null, "e": 2100, "s": 1944, "text": "If the lander landed outside of the target spot, we give a small penalty of -10. If the lander crashed with a high velocity, we give a big penalty of -100." }, { "code": null, "e": 2267, "s": 2100, "text": "distance_reward = 1-(distance_to_goal / distance_max)**0.5 uses power of 0.5 to offer agents a smooth gradient of rewards as lander getting closer to the landing pad." }, { "code": null, "e": 2998, "s": 2267, "text": "# Encourage lander to use as little fuel as possible# i.e. 0.85, or 0.32fuel_conservation = fuel_remaining / total_fuelif distance_to_goal is decreasing: if speed < threshold: if position is on landing pad: # Land successfully; give a big reward landing_reward = 100 # Multiply percentage of remaining fuel reward = landing_reward * fuel_conservation else: # Landing outside of landing pad reward = -10 else: # Crashed reward = -100else: # Encourage agents to approach the surface instead of # hanging in the air distance_reward = 1 - (distance_to_goal / distance_max)**0.5 reward = distance_reward * fuel_conservation" }, { "code": null, "e": 3139, "s": 2998, "text": "In this article, we use lunar lander as an example to demonstrate how to build an advanced reward function with reward and punishment rules." }, { "code": null, "e": 3244, "s": 3139, "text": "During the training of RL models, Reward Function guide agents to learn from the trials and errors that:" }, { "code": null, "e": 3293, "s": 3244, "text": "What should I do? How to select between actions?" }, { "code": null, "e": 3348, "s": 3293, "text": "What are better actions to maximize the total rewards?" }, { "code": null, "e": 3417, "s": 3348, "text": "How to evaluate the goodness/badness of actions in different states?" }, { "code": null, "e": 3478, "s": 3417, "text": "Happy Landing! Hopefully, aliens will come in PEACE. 👽☮️✌️🕊🛸" }, { "code": null, "e": 3510, "s": 3478, "text": "Youtube tutorial video about RL" } ]
C Program for subtraction of matrices
Given two matrices MAT1[row][column] and MAT2[row][column] we have to find the difference between two matrices and print the result obtained after subtraction of two matrices. Subtraction of two matrices are MAT1[n][m] – MAT2[n][m]. For subtraction the number of rows and columns of both matrices should be same. Input: MAT1[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}} MAT2[N][N] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1}} Output: -8 -6 -4 -2 0 2 4 6 8 Approach used below is as follows − We will iterate both matrix for every row and column and subtract the values of mat2[][] from mat1[][] and store the result in a result[][] where row and column remain same for all the matrices. In fucntion void subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N]) Step 1-> Declare 2 integers i, j Step 2-> Loop For i = 0 and i < N and i++ Loop For j = 0 and j < N and j++ Set RESULT[i][j] as MAT1[i][j] - MAT2[i][j] In function int main() Step 1-> Declare a matrix MAT1[N][N] and MAT2[N][N] Step 2-> Call function subtract(MAT1, MAT2, RESULT); Step 3-> Print the result Live Demo #include <stdio.h> #define N 3 // This function subtracts MAT2[][] from MAT1[][], and stores // the result in RESULT[][] void subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) RESULT[i][j] = MAT1[i][j] - MAT2[i][j]; } int main() { int MAT1[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int MAT2[N][N] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} }; int RESULT[N][N]; // To store result int i, j; subtract(MAT1, MAT2, RESULT); printf("Resultant matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", RESULT[i][j]); printf("\n"); } return 0; } If run the above code it will generate the following output − Resultant matrix is -8 -6 -4 -2 0 2 4 6 8
[ { "code": null, "e": 1295, "s": 1062, "text": "Given two matrices MAT1[row][column] and MAT2[row][column] we have to find the difference between two matrices and print the result obtained after subtraction of two matrices. Subtraction of two matrices are MAT1[n][m] – MAT2[n][m]." }, { "code": null, "e": 1375, "s": 1295, "text": "For subtraction the number of rows and columns of both matrices should be same." }, { "code": null, "e": 1520, "s": 1375, "text": "Input:\nMAT1[N][N] = { {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}}\nMAT2[N][N] = { {9, 8, 7},\n {6, 5, 4},\n {3, 2, 1}}\nOutput:\n-8 -6 -4\n-2 0 2\n4 6 8" }, { "code": null, "e": 1556, "s": 1520, "text": "Approach used below is as follows −" }, { "code": null, "e": 1751, "s": 1556, "text": "We will iterate both matrix for every row and column and subtract the values of mat2[][] from mat1[][] and store the result in a result[][] where row and column remain same for all the matrices." }, { "code": null, "e": 2157, "s": 1751, "text": "In fucntion void subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N])\n Step 1-> Declare 2 integers i, j\n Step 2-> Loop For i = 0 and i < N and i++\n Loop For j = 0 and j < N and j++\n Set RESULT[i][j] as MAT1[i][j] - MAT2[i][j]\nIn function int main()\n Step 1-> Declare a matrix MAT1[N][N] and MAT2[N][N]\n Step 2-> Call function subtract(MAT1, MAT2, RESULT);\n Step 3-> Print the result" }, { "code": null, "e": 2168, "s": 2157, "text": " Live Demo" }, { "code": null, "e": 2881, "s": 2168, "text": "#include <stdio.h>\n#define N 3\n// This function subtracts MAT2[][] from MAT1[][], and stores\n// the result in RESULT[][]\nvoid subtract(int MAT1[][N], int MAT2[][N], int RESULT[][N]) {\n int i, j;\n for (i = 0; i < N; i++)\n for (j = 0; j < N; j++)\n RESULT[i][j] = MAT1[i][j] - MAT2[i][j];\n}\nint main() {\n int MAT1[N][N] = { {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}\n };\n int MAT2[N][N] = { {9, 8, 7},\n {6, 5, 4},\n {3, 2, 1}\n };\n int RESULT[N][N]; // To store result\n int i, j;\n subtract(MAT1, MAT2, RESULT);\n printf(\"Resultant matrix is \\n\");\n for (i = 0; i < N; i++) {\n for (j = 0; j < N; j++)\n printf(\"%d \", RESULT[i][j]);\n printf(\"\\n\");\n }\n return 0;\n}" }, { "code": null, "e": 2943, "s": 2881, "text": "If run the above code it will generate the following output −" }, { "code": null, "e": 2990, "s": 2943, "text": "Resultant matrix is\n-8 -6 -4\n-2 0 2\n 4 6 8" } ]
AWS DynamoDB - Update Data in a Table - GeeksforGeeks
31 Mar, 2021 Amazon DynamoDB is a NoSQL managed database that supports semi-structured data i.e. key-value and document data. A DynamoDB table stores data in the form of an item. While creating a table in DynamoDB, a partition key needs to be defined which acts as the primary key for the table and no schema. Each item consists of attributes. By default, every item will have a partition key as one of the attributes. Every item can have a different number of attributes. An example of an item is given below: Example: { "Color": true, "Director": "Christopher Nolan", "MovieID": 1, "Name": "Inception", "Rating": 8.7, "Year": 2010 } We will be doing the following operations in this article: Create a table in DynamoDB, say, Movies.Add items or data into the table.Update attribute of an item in the table. Create a table in DynamoDB, say, Movies. Add items or data into the table. Update attribute of an item in the table. The above approach has been implemented below: Create a table named Movies with partition key as MoviesID. Add items to the table. A table has been already created for your reference. See the image below: There are two ways to update the attributes of an item. They are : AWS CLI – In this, update-item is used to update the value of an attribute using Amazon Command Line Interface (CLI). Amazon Management Console – To update the value of an attribute in items, navigate to the Items tab of a table and click on the MovieID to update the item. An edit item page will open to either add, update or delete a key-value pair. In the original table, the director column of MovieID=050 is empty. We are going to add ‘Christopher Nolan’ under the director attribute. See the below images: Edit MovieID 050 Updated Table We observe that the director column of MovieID=050 has been updated with the value ‘Christopher Nolan’. Similarly, we can select any partition key and edit the value of the attribute of an item. Cloud-Computing DynamoDB DynamoDB-Basics Picked Amazon Web Services DynamoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install Python3 on AWS EC2? How to Connect to Amazon Linux Instance from Windows Client Operating System using PUTTY? Amazon S3 - Cross Region Replication Amazon EC2 - Creating an Elastic Cloud Compute Instance AWS DynamoDB - PartiQL Insert Statement How to Mock AWS DynamoDB Services for Unit Testing? DynamoDB - Local Installation DynamoDB - Data Types AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX) AWS DynamoDB - Create a Global Secondary Index
[ { "code": null, "e": 24707, "s": 24679, "text": "\n31 Mar, 2021" }, { "code": null, "e": 25205, "s": 24707, "text": "Amazon DynamoDB is a NoSQL managed database that supports semi-structured data i.e. key-value and document data. A DynamoDB table stores data in the form of an item. While creating a table in DynamoDB, a partition key needs to be defined which acts as the primary key for the table and no schema. Each item consists of attributes. By default, every item will have a partition key as one of the attributes. Every item can have a different number of attributes. An example of an item is given below:" }, { "code": null, "e": 25341, "s": 25205, "text": "Example:\n{\n \"Color\": true,\n \"Director\": \"Christopher Nolan\",\n \"MovieID\": 1,\n \"Name\": \"Inception\",\n \"Rating\": 8.7,\n \"Year\": 2010\n}" }, { "code": null, "e": 25400, "s": 25341, "text": "We will be doing the following operations in this article:" }, { "code": null, "e": 25515, "s": 25400, "text": "Create a table in DynamoDB, say, Movies.Add items or data into the table.Update attribute of an item in the table." }, { "code": null, "e": 25556, "s": 25515, "text": "Create a table in DynamoDB, say, Movies." }, { "code": null, "e": 25590, "s": 25556, "text": "Add items or data into the table." }, { "code": null, "e": 25632, "s": 25590, "text": "Update attribute of an item in the table." }, { "code": null, "e": 25679, "s": 25632, "text": "The above approach has been implemented below:" }, { "code": null, "e": 25837, "s": 25679, "text": "Create a table named Movies with partition key as MoviesID. Add items to the table. A table has been already created for your reference. See the image below:" }, { "code": null, "e": 25905, "s": 25837, "text": " There are two ways to update the attributes of an item. They are :" }, { "code": null, "e": 26023, "s": 25905, "text": "AWS CLI – In this, update-item is used to update the value of an attribute using Amazon Command Line Interface (CLI)." }, { "code": null, "e": 26417, "s": 26023, "text": "Amazon Management Console – To update the value of an attribute in items, navigate to the Items tab of a table and click on the MovieID to update the item. An edit item page will open to either add, update or delete a key-value pair. In the original table, the director column of MovieID=050 is empty. We are going to add ‘Christopher Nolan’ under the director attribute. See the below images:" }, { "code": null, "e": 26434, "s": 26417, "text": "Edit MovieID 050" }, { "code": null, "e": 26449, "s": 26434, "text": "Updated Table " }, { "code": null, "e": 26644, "s": 26449, "text": "We observe that the director column of MovieID=050 has been updated with the value ‘Christopher Nolan’. Similarly, we can select any partition key and edit the value of the attribute of an item." }, { "code": null, "e": 26660, "s": 26644, "text": "Cloud-Computing" }, { "code": null, "e": 26669, "s": 26660, "text": "DynamoDB" }, { "code": null, "e": 26685, "s": 26669, "text": "DynamoDB-Basics" }, { "code": null, "e": 26692, "s": 26685, "text": "Picked" }, { "code": null, "e": 26712, "s": 26692, "text": "Amazon Web Services" }, { "code": null, "e": 26721, "s": 26712, "text": "DynamoDB" }, { "code": null, "e": 26819, "s": 26721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26828, "s": 26819, "text": "Comments" }, { "code": null, "e": 26841, "s": 26828, "text": "Old Comments" }, { "code": null, "e": 26876, "s": 26841, "text": "How to Install Python3 on AWS EC2?" }, { "code": null, "e": 26966, "s": 26876, "text": "How to Connect to Amazon Linux Instance from Windows Client Operating System using PUTTY?" }, { "code": null, "e": 27003, "s": 26966, "text": "Amazon S3 - Cross Region Replication" }, { "code": null, "e": 27059, "s": 27003, "text": "Amazon EC2 - Creating an Elastic Cloud Compute Instance" }, { "code": null, "e": 27099, "s": 27059, "text": "AWS DynamoDB - PartiQL Insert Statement" }, { "code": null, "e": 27151, "s": 27099, "text": "How to Mock AWS DynamoDB Services for Unit Testing?" }, { "code": null, "e": 27181, "s": 27151, "text": "DynamoDB - Local Installation" }, { "code": null, "e": 27203, "s": 27181, "text": "DynamoDB - Data Types" }, { "code": null, "e": 27261, "s": 27203, "text": "AWS DynamoDB - Introduction to DynamoDB Accelerator (DAX)" } ]
Bar Plot in Matplotlib - GeeksforGeeks
04 Mar, 2021 A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories. The matplotlib API in Python provides the bar() function which can be used in MATLAB style use or as an object-oriented API. The syntax of the bar() function to be used with the axes is as follows:- plt.bar(x, height, width, bottom, align) The function creates a bar plot bounded with a rectangle depending on the given parameters. Following is a simple example of the bar plot, which represents the number of students enrolled in different courses of an institute. Python3 import numpy as npimport matplotlib.pyplot as plt # creating the datasetdata = {'C':20, 'C++':15, 'Java':30, 'Python':35}courses = list(data.keys())values = list(data.values()) fig = plt.figure(figsize = (10, 5)) # creating the bar plotplt.bar(courses, values, color ='maroon', width = 0.4) plt.xlabel("Courses offered")plt.ylabel("No. of students enrolled")plt.title("Students enrolled in different courses")plt.show() Output- Here plt.bar(courses, values, color=’maroon’) is used to specify that the bar chart is to be plotted by using the courses column as the X-axis, and the values as the Y-axis. The color attribute is used to set the color of the bars(maroon in this case).plt.xlabel(“Courses offered”) and plt.ylabel(“students enrolled”) are used to label the corresponding axes.plt.title() is used to make a title for the graph.plt.show() is used to show the graph as output using the previous commands. Python3 import pandas as pdfrom matplotlib import pyplot as plt # Read CSV into pandasdata = pd.read_csv(r"cars.csv")data.head()df = pd.DataFrame(data) name = df['car'].head(12)price = df['price'].head(12) # Figure Sizefig = plt.figure(figsize =(10, 7)) # Horizontal Bar Plotplt.bar(name[0:10], price[0:10]) # Show Plotplt.show() Output: It is observed in the above bar graph that the X-axis ticks are overlapping each other thus it cannot be seen properly. Thus by rotating the X-axis ticks, it can be visible clearly. That is why customization in bar graphs is required. Python3 import pandas as pdfrom matplotlib import pyplot as plt # Read CSV into pandasdata = pd.read_csv(r"cars.csv")data.head()df = pd.DataFrame(data) name = df['car'].head(12)price = df['price'].head(12) # Figure Sizefig, ax = plt.subplots(figsize =(16, 9)) # Horizontal Bar Plotax.barh(name, price) # Remove axes splinesfor s in ['top', 'bottom', 'left', 'right']: ax.spines[s].set_visible(False) # Remove x, y Ticksax.xaxis.set_ticks_position('none')ax.yaxis.set_ticks_position('none') # Add padding between axes and labelsax.xaxis.set_tick_params(pad = 5)ax.yaxis.set_tick_params(pad = 10) # Add x, y gridlinesax.grid(b = True, color ='grey', linestyle ='-.', linewidth = 0.5, alpha = 0.2) # Show top valuesax.invert_yaxis() # Add annotation to barsfor i in ax.patches: plt.text(i.get_width()+0.2, i.get_y()+0.5, str(round((i.get_width()), 2)), fontsize = 10, fontweight ='bold', color ='grey') # Add Plot Titleax.set_title('Sports car and their price in crore', loc ='left', ) # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize = 12, color ='grey', ha ='right', va ='bottom', alpha = 0.7) # Show Plotplt.show() Output: There are many more Customizations available for bar plots. Multiple bar plots are used when comparison among the data set is to be done when one variable is changing. We can easily convert it as a stacked area bar chart, where each subgroup is displayed by one on top of the others. It can be plotted by varying the thickness and position of the bars. Following bar plot shows the number of students passed in the engineering branch: Python3 import numpy as npimport matplotlib.pyplot as plt # set width of barbarWidth = 0.25fig = plt.subplots(figsize =(12, 8)) # set height of barIT = [12, 30, 1, 8, 22]ECE = [28, 6, 16, 5, 10]CSE = [29, 3, 24, 25, 17] # Set position of bar on X axisbr1 = np.arange(len(IT))br2 = [x + barWidth for x in br1]br3 = [x + barWidth for x in br2] # Make the plotplt.bar(br1, IT, color ='r', width = barWidth, edgecolor ='grey', label ='IT')plt.bar(br2, ECE, color ='g', width = barWidth, edgecolor ='grey', label ='ECE')plt.bar(br3, CSE, color ='b', width = barWidth, edgecolor ='grey', label ='CSE') # Adding Xticksplt.xlabel('Branch', fontweight ='bold', fontsize = 15)plt.ylabel('Students passed', fontweight ='bold', fontsize = 15)plt.xticks([r + barWidth for r in range(len(IT))], ['2015', '2016', '2017', '2018', '2019']) plt.legend()plt.show() Output: Stacked bar plots represent different groups on top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It goes from the bottom to the value instead of going from zero to value. The following bar plot represents the contribution of boys and girls in the team. Python3 import numpy as npimport matplotlib.pyplot as plt N = 5 boys = (20, 35, 30, 35, 27)girls = (25, 32, 34, 20, 25)boyStd = (2, 3, 4, 1, 2)girlStd = (3, 5, 2, 3, 3)ind = np.arange(N) width = 0.35 fig = plt.subplots(figsize =(10, 7))p1 = plt.bar(ind, boys, width, yerr = boyStd)p2 = plt.bar(ind, girls, width, bottom = boys, yerr = girlStd) plt.ylabel('Contribution')plt.title('Contribution by the teams')plt.xticks(ind, ('T1', 'T2', 'T3', 'T4', 'T5'))plt.yticks(np.arange(0, 81, 10))plt.legend((p1[0], p2[0]), ('boys', 'girls')) plt.show() Output- greeshmanalla Python-matplotlib 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 Python Dictionary Taking input in Python Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python
[ { "code": null, "e": 30424, "s": 30396, "text": "\n04 Mar, 2021" }, { "code": null, "e": 30895, "s": 30424, "text": "A bar plot or bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories. " }, { "code": null, "e": 31094, "s": 30895, "text": "The matplotlib API in Python provides the bar() function which can be used in MATLAB style use or as an object-oriented API. The syntax of the bar() function to be used with the axes is as follows:-" }, { "code": null, "e": 31135, "s": 31094, "text": "plt.bar(x, height, width, bottom, align)" }, { "code": null, "e": 31363, "s": 31135, "text": "The function creates a bar plot bounded with a rectangle depending on the given parameters. Following is a simple example of the bar plot, which represents the number of students enrolled in different courses of an institute. " }, { "code": null, "e": 31371, "s": 31363, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt # creating the datasetdata = {'C':20, 'C++':15, 'Java':30, 'Python':35}courses = list(data.keys())values = list(data.values()) fig = plt.figure(figsize = (10, 5)) # creating the bar plotplt.bar(courses, values, color ='maroon', width = 0.4) plt.xlabel(\"Courses offered\")plt.ylabel(\"No. of students enrolled\")plt.title(\"Students enrolled in different courses\")plt.show()", "e": 31808, "s": 31371, "text": null }, { "code": null, "e": 31818, "s": 31808, "text": "Output- " }, { "code": null, "e": 32304, "s": 31818, "text": "Here plt.bar(courses, values, color=’maroon’) is used to specify that the bar chart is to be plotted by using the courses column as the X-axis, and the values as the Y-axis. The color attribute is used to set the color of the bars(maroon in this case).plt.xlabel(“Courses offered”) and plt.ylabel(“students enrolled”) are used to label the corresponding axes.plt.title() is used to make a title for the graph.plt.show() is used to show the graph as output using the previous commands. " }, { "code": null, "e": 32312, "s": 32304, "text": "Python3" }, { "code": "import pandas as pdfrom matplotlib import pyplot as plt # Read CSV into pandasdata = pd.read_csv(r\"cars.csv\")data.head()df = pd.DataFrame(data) name = df['car'].head(12)price = df['price'].head(12) # Figure Sizefig = plt.figure(figsize =(10, 7)) # Horizontal Bar Plotplt.bar(name[0:10], price[0:10]) # Show Plotplt.show()", "e": 32634, "s": 32312, "text": null }, { "code": null, "e": 32643, "s": 32634, "text": "Output: " }, { "code": null, "e": 32878, "s": 32643, "text": "It is observed in the above bar graph that the X-axis ticks are overlapping each other thus it cannot be seen properly. Thus by rotating the X-axis ticks, it can be visible clearly. That is why customization in bar graphs is required." }, { "code": null, "e": 32886, "s": 32878, "text": "Python3" }, { "code": "import pandas as pdfrom matplotlib import pyplot as plt # Read CSV into pandasdata = pd.read_csv(r\"cars.csv\")data.head()df = pd.DataFrame(data) name = df['car'].head(12)price = df['price'].head(12) # Figure Sizefig, ax = plt.subplots(figsize =(16, 9)) # Horizontal Bar Plotax.barh(name, price) # Remove axes splinesfor s in ['top', 'bottom', 'left', 'right']: ax.spines[s].set_visible(False) # Remove x, y Ticksax.xaxis.set_ticks_position('none')ax.yaxis.set_ticks_position('none') # Add padding between axes and labelsax.xaxis.set_tick_params(pad = 5)ax.yaxis.set_tick_params(pad = 10) # Add x, y gridlinesax.grid(b = True, color ='grey', linestyle ='-.', linewidth = 0.5, alpha = 0.2) # Show top valuesax.invert_yaxis() # Add annotation to barsfor i in ax.patches: plt.text(i.get_width()+0.2, i.get_y()+0.5, str(round((i.get_width()), 2)), fontsize = 10, fontweight ='bold', color ='grey') # Add Plot Titleax.set_title('Sports car and their price in crore', loc ='left', ) # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30', fontsize = 12, color ='grey', ha ='right', va ='bottom', alpha = 0.7) # Show Plotplt.show()", "e": 34097, "s": 32886, "text": null }, { "code": null, "e": 34106, "s": 34097, "text": "Output: " }, { "code": null, "e": 34167, "s": 34106, "text": "There are many more Customizations available for bar plots. " }, { "code": null, "e": 34542, "s": 34167, "text": "Multiple bar plots are used when comparison among the data set is to be done when one variable is changing. We can easily convert it as a stacked area bar chart, where each subgroup is displayed by one on top of the others. It can be plotted by varying the thickness and position of the bars. Following bar plot shows the number of students passed in the engineering branch:" }, { "code": null, "e": 34550, "s": 34542, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt # set width of barbarWidth = 0.25fig = plt.subplots(figsize =(12, 8)) # set height of barIT = [12, 30, 1, 8, 22]ECE = [28, 6, 16, 5, 10]CSE = [29, 3, 24, 25, 17] # Set position of bar on X axisbr1 = np.arange(len(IT))br2 = [x + barWidth for x in br1]br3 = [x + barWidth for x in br2] # Make the plotplt.bar(br1, IT, color ='r', width = barWidth, edgecolor ='grey', label ='IT')plt.bar(br2, ECE, color ='g', width = barWidth, edgecolor ='grey', label ='ECE')plt.bar(br3, CSE, color ='b', width = barWidth, edgecolor ='grey', label ='CSE') # Adding Xticksplt.xlabel('Branch', fontweight ='bold', fontsize = 15)plt.ylabel('Students passed', fontweight ='bold', fontsize = 15)plt.xticks([r + barWidth for r in range(len(IT))], ['2015', '2016', '2017', '2018', '2019']) plt.legend()plt.show()", "e": 35416, "s": 34550, "text": null }, { "code": null, "e": 35425, "s": 35416, "text": "Output: " }, { "code": null, "e": 35755, "s": 35427, "text": "Stacked bar plots represent different groups on top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It goes from the bottom to the value instead of going from zero to value. The following bar plot represents the contribution of boys and girls in the team. " }, { "code": null, "e": 35763, "s": 35755, "text": "Python3" }, { "code": "import numpy as npimport matplotlib.pyplot as plt N = 5 boys = (20, 35, 30, 35, 27)girls = (25, 32, 34, 20, 25)boyStd = (2, 3, 4, 1, 2)girlStd = (3, 5, 2, 3, 3)ind = np.arange(N) width = 0.35 fig = plt.subplots(figsize =(10, 7))p1 = plt.bar(ind, boys, width, yerr = boyStd)p2 = plt.bar(ind, girls, width, bottom = boys, yerr = girlStd) plt.ylabel('Contribution')plt.title('Contribution by the teams')plt.xticks(ind, ('T1', 'T2', 'T3', 'T4', 'T5'))plt.yticks(np.arange(0, 81, 10))plt.legend((p1[0], p2[0]), ('boys', 'girls')) plt.show()", "e": 36313, "s": 35763, "text": null }, { "code": null, "e": 36323, "s": 36313, "text": "Output- " }, { "code": null, "e": 36339, "s": 36325, "text": "greeshmanalla" }, { "code": null, "e": 36357, "s": 36339, "text": "Python-matplotlib" }, { "code": null, "e": 36364, "s": 36357, "text": "Python" }, { "code": null, "e": 36462, "s": 36364, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36490, "s": 36462, "text": "Read JSON file using Python" }, { "code": null, "e": 36540, "s": 36490, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 36562, "s": 36540, "text": "Python map() function" }, { "code": null, "e": 36606, "s": 36562, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 36624, "s": 36606, "text": "Python Dictionary" }, { "code": null, "e": 36647, "s": 36624, "text": "Taking input in Python" }, { "code": null, "e": 36682, "s": 36647, "text": "Read a file line by line in Python" }, { "code": null, "e": 36714, "s": 36682, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 36756, "s": 36714, "text": "Different ways to create Pandas Dataframe" } ]
Smallest odd number with even sum of digits from the given number N - GeeksforGeeks
30 Jan, 2022 Given a large number in form of string str. The task is to find the smallest odd number whose sum of digits is even by removing zero or more characters from the given string str, where the digits can be rearranged. Examples Input: str = “15470” Output: 15 Explanation: Two smallest odd digits are 1 & 5. Hence the required number is 15. Input: str = “124” Output: -1 Explanation: There is no smallest odd digit other than 1. Hence the required number can’t be form. Approach: On observing closely, by intuition, it can be understood that the number of digits in the smallest odd number possible is 2. And every digit in this number is odd because the sum of two odd digits is always even. Therefore, the idea to solve this problem is to iterate through the given string and store every odd number in an array. This array can be sorted and the first two digits together form the smallest odd number whose sum of its digits is even. Below is the implementation of the above approach. C++ Java Python C# Javascript // C++ program to find the smallest odd number// with even sum of digits from the given number N#include<bits/stdc++.h>using namespace std; // Function to find the smallest odd number// whose sum of digits is even from the given stringint smallest(string s){ // Converting the given string // to a list of digits vector<int> a(s.length()); for(int i = 0; i < s.length(); i++) a[i] = s[i]-'0'; // An empty array to store the digits vector<int> b; // For loop to iterate through each digit for(int i = 0; i < a.size(); i++) { // If the given digit is odd then // the digit is appended to the array b if((a[i]) % 2 != 0) b.push_back(a[i]); } // Sorting the list of digits sort(b.begin(),b.end()); // If the size of the list is greater than 1 // then a 2 digit smallest odd number is returned // Since the sum of two odd digits is always even if(b.size() > 1) return (b[0])*10 + (b[1]); // Else, -1 is returned return -1;} // Driver codeint main(){ cout << (smallest("15470"));} // This code is contributed by Surendra_Gangwar // Java program to find the smallest// odd number with even sum of digits// from the given number Nimport java.util.*;class GFG{ // Function to find the smallest// odd number whose sum of digits// is even from the given stringpublic static int smallest(String s){ // Converting the given string // to a list of digits int[] a = new int[s.length()]; for(int i = 0; i < s.length(); i++) a[i] = s.charAt(i) - '0'; // An empty array to store the digits Vector<Integer> b = new Vector<Integer>(); // For loop to iterate through each digit for(int i = 0; i < a.length; i++) { // If the given digit is odd // then the digit is appended // to the array b if(a[i] % 2 != 0) b.add(a[i]); } // Sorting the list of digits Collections.sort(b); // If the size of the list is greater // than 1 then a 2 digit smallest odd // number is returned. Since the sum // of two odd digits is always even if(b.size() > 1) return (b.get(0)) * 10 + (b.get(1)); // Else, -1 is returned return -1;} // Driver codepublic static void main(String[] args){ System.out.print(smallest("15470"));}} // This code is contributed by divyeshrabadiya07 # Python program to find the smallest odd number# with even sum of digits from the given number N # Function to find the smallest odd number# whose sum of digits is even from the given stringdef smallest(s): # Converting the given string # to a list of digits a = list(s) # An empty array to store the digits b = [] # For loop to iterate through each digit for i in range(len(a)): # If the given digit is odd then # the digit is appended to the array b if(int(a[i])%2 != 0): b.append(a[i]) # Sorting the list of digits b = sorted(b) # If the size of the list is greater than 1 # then a 2 digit smallest odd number is returned # Since the sum of two odd digits is always even if(len(b)>1): return int(b[0])*10 + int(b[1]) # Else, -1 is returned return -1 # Driver codeif __name__ == "__main__": print(smallest("15470")) // C# program to find the smallest// odd number with even sum of digits// from the given number Nusing System;using System.Collections; class GFG{ // Function to find the smallest// odd number whose sum of digits// is even from the given stringpublic static int smallest(string s){ // Converting the given string // to a list of digits int[] a = new int[s.Length]; for(int i = 0; i < s.Length; i++) a[i] = (int)(s[i] - '0'); // An empty array to store the digits ArrayList b = new ArrayList(); // For loop to iterate through each digit for(int i = 0; i < a.Length; i++) { // If the given digit is odd // then the digit is appended // to the array b if (a[i] % 2 != 0) b.Add(a[i]); } // Sorting the list of digits b.Sort(); // If the size of the list is greater // than 1 then a 2 digit smallest odd // number is returned. Since the sum // of two odd digits is always even if (b.Count > 1) return ((int)b[0] * 10 + (int)b[1]); // Else, -1 is returned return -1;} // Driver codepublic static void Main(string[] args){ Console.Write(smallest("15470"));}} // This code is contributed by rutvik_56 <script> // Javascript program to find the// smallest odd number with even// sum of digits from the given number N // Function to find the smallest odd// number whose sum of digits is even// from the given stringfunction smallest(s){ // Converting the given string // to a list of digits var a = Array(s.length); for(var i = 0; i < s.length; i++) a[i] = s[i].charCodeAt(0) - '0'.charCodeAt(0); // An empty array to store the digits var b = []; // For loop to iterate through each digit for(var i = 0; i < a.length; i++) { // If the given digit is odd then // the digit is appended to the array b if ((a[i]) % 2 != 0) b.push(a[i]); } // Sorting the list of digits b.sort((a, b) => a - b); // If the size of the list is greater // than 1 then a 2 digit smallest odd // number is returned. Since the sum // of two odd digits is always even if (b.length > 1) return (b[0]) * 10 + (b[1]); // Else, -1 is returned return -1;} // Driver codedocument.write(smallest("15470")); // This code is contributed by importantly </script> 15 Time Complexity: O(N) where N = length of string. Auxiliary Space: O(N) SURENDRA_GANGWAR divyeshrabadiya07 rutvik_56 importantly subhammahato348 number-digits Technical Scripter 2019 Mathematical Strings Technical Scripter Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not
[ { "code": null, "e": 26267, "s": 26239, "text": "\n30 Jan, 2022" }, { "code": null, "e": 26482, "s": 26267, "text": "Given a large number in form of string str. The task is to find the smallest odd number whose sum of digits is even by removing zero or more characters from the given string str, where the digits can be rearranged." }, { "code": null, "e": 26491, "s": 26482, "text": "Examples" }, { "code": null, "e": 26604, "s": 26491, "text": "Input: str = “15470” Output: 15 Explanation: Two smallest odd digits are 1 & 5. Hence the required number is 15." }, { "code": null, "e": 26733, "s": 26604, "text": "Input: str = “124” Output: -1 Explanation: There is no smallest odd digit other than 1. Hence the required number can’t be form." }, { "code": null, "e": 27199, "s": 26733, "text": "Approach: On observing closely, by intuition, it can be understood that the number of digits in the smallest odd number possible is 2. And every digit in this number is odd because the sum of two odd digits is always even. Therefore, the idea to solve this problem is to iterate through the given string and store every odd number in an array. This array can be sorted and the first two digits together form the smallest odd number whose sum of its digits is even. " }, { "code": null, "e": 27250, "s": 27199, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27254, "s": 27250, "text": "C++" }, { "code": null, "e": 27259, "s": 27254, "text": "Java" }, { "code": null, "e": 27266, "s": 27259, "text": "Python" }, { "code": null, "e": 27269, "s": 27266, "text": "C#" }, { "code": null, "e": 27280, "s": 27269, "text": "Javascript" }, { "code": "// C++ program to find the smallest odd number// with even sum of digits from the given number N#include<bits/stdc++.h>using namespace std; // Function to find the smallest odd number// whose sum of digits is even from the given stringint smallest(string s){ // Converting the given string // to a list of digits vector<int> a(s.length()); for(int i = 0; i < s.length(); i++) a[i] = s[i]-'0'; // An empty array to store the digits vector<int> b; // For loop to iterate through each digit for(int i = 0; i < a.size(); i++) { // If the given digit is odd then // the digit is appended to the array b if((a[i]) % 2 != 0) b.push_back(a[i]); } // Sorting the list of digits sort(b.begin(),b.end()); // If the size of the list is greater than 1 // then a 2 digit smallest odd number is returned // Since the sum of two odd digits is always even if(b.size() > 1) return (b[0])*10 + (b[1]); // Else, -1 is returned return -1;} // Driver codeint main(){ cout << (smallest(\"15470\"));} // This code is contributed by Surendra_Gangwar", "e": 28452, "s": 27280, "text": null }, { "code": "// Java program to find the smallest// odd number with even sum of digits// from the given number Nimport java.util.*;class GFG{ // Function to find the smallest// odd number whose sum of digits// is even from the given stringpublic static int smallest(String s){ // Converting the given string // to a list of digits int[] a = new int[s.length()]; for(int i = 0; i < s.length(); i++) a[i] = s.charAt(i) - '0'; // An empty array to store the digits Vector<Integer> b = new Vector<Integer>(); // For loop to iterate through each digit for(int i = 0; i < a.length; i++) { // If the given digit is odd // then the digit is appended // to the array b if(a[i] % 2 != 0) b.add(a[i]); } // Sorting the list of digits Collections.sort(b); // If the size of the list is greater // than 1 then a 2 digit smallest odd // number is returned. Since the sum // of two odd digits is always even if(b.size() > 1) return (b.get(0)) * 10 + (b.get(1)); // Else, -1 is returned return -1;} // Driver codepublic static void main(String[] args){ System.out.print(smallest(\"15470\"));}} // This code is contributed by divyeshrabadiya07", "e": 29728, "s": 28452, "text": null }, { "code": "# Python program to find the smallest odd number# with even sum of digits from the given number N # Function to find the smallest odd number# whose sum of digits is even from the given stringdef smallest(s): # Converting the given string # to a list of digits a = list(s) # An empty array to store the digits b = [] # For loop to iterate through each digit for i in range(len(a)): # If the given digit is odd then # the digit is appended to the array b if(int(a[i])%2 != 0): b.append(a[i]) # Sorting the list of digits b = sorted(b) # If the size of the list is greater than 1 # then a 2 digit smallest odd number is returned # Since the sum of two odd digits is always even if(len(b)>1): return int(b[0])*10 + int(b[1]) # Else, -1 is returned return -1 # Driver codeif __name__ == \"__main__\": print(smallest(\"15470\"))", "e": 30685, "s": 29728, "text": null }, { "code": "// C# program to find the smallest// odd number with even sum of digits// from the given number Nusing System;using System.Collections; class GFG{ // Function to find the smallest// odd number whose sum of digits// is even from the given stringpublic static int smallest(string s){ // Converting the given string // to a list of digits int[] a = new int[s.Length]; for(int i = 0; i < s.Length; i++) a[i] = (int)(s[i] - '0'); // An empty array to store the digits ArrayList b = new ArrayList(); // For loop to iterate through each digit for(int i = 0; i < a.Length; i++) { // If the given digit is odd // then the digit is appended // to the array b if (a[i] % 2 != 0) b.Add(a[i]); } // Sorting the list of digits b.Sort(); // If the size of the list is greater // than 1 then a 2 digit smallest odd // number is returned. Since the sum // of two odd digits is always even if (b.Count > 1) return ((int)b[0] * 10 + (int)b[1]); // Else, -1 is returned return -1;} // Driver codepublic static void Main(string[] args){ Console.Write(smallest(\"15470\"));}} // This code is contributed by rutvik_56", "e": 31955, "s": 30685, "text": null }, { "code": "<script> // Javascript program to find the// smallest odd number with even// sum of digits from the given number N // Function to find the smallest odd// number whose sum of digits is even// from the given stringfunction smallest(s){ // Converting the given string // to a list of digits var a = Array(s.length); for(var i = 0; i < s.length; i++) a[i] = s[i].charCodeAt(0) - '0'.charCodeAt(0); // An empty array to store the digits var b = []; // For loop to iterate through each digit for(var i = 0; i < a.length; i++) { // If the given digit is odd then // the digit is appended to the array b if ((a[i]) % 2 != 0) b.push(a[i]); } // Sorting the list of digits b.sort((a, b) => a - b); // If the size of the list is greater // than 1 then a 2 digit smallest odd // number is returned. Since the sum // of two odd digits is always even if (b.length > 1) return (b[0]) * 10 + (b[1]); // Else, -1 is returned return -1;} // Driver codedocument.write(smallest(\"15470\")); // This code is contributed by importantly </script>", "e": 33146, "s": 31955, "text": null }, { "code": null, "e": 33149, "s": 33146, "text": "15" }, { "code": null, "e": 33199, "s": 33149, "text": "Time Complexity: O(N) where N = length of string." }, { "code": null, "e": 33222, "s": 33199, "text": "Auxiliary Space: O(N) " }, { "code": null, "e": 33239, "s": 33222, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 33257, "s": 33239, "text": "divyeshrabadiya07" }, { "code": null, "e": 33267, "s": 33257, "text": "rutvik_56" }, { "code": null, "e": 33279, "s": 33267, "text": "importantly" }, { "code": null, "e": 33295, "s": 33279, "text": "subhammahato348" }, { "code": null, "e": 33309, "s": 33295, "text": "number-digits" }, { "code": null, "e": 33333, "s": 33309, "text": "Technical Scripter 2019" }, { "code": null, "e": 33346, "s": 33333, "text": "Mathematical" }, { "code": null, "e": 33354, "s": 33346, "text": "Strings" }, { "code": null, "e": 33373, "s": 33354, "text": "Technical Scripter" }, { "code": null, "e": 33381, "s": 33373, "text": "Strings" }, { "code": null, "e": 33394, "s": 33381, "text": "Mathematical" }, { "code": null, "e": 33492, "s": 33394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33516, "s": 33492, "text": "Merge two sorted arrays" }, { "code": null, "e": 33559, "s": 33516, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33573, "s": 33559, "text": "Prime Numbers" }, { "code": null, "e": 33615, "s": 33573, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 33688, "s": 33615, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 33734, "s": 33688, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33759, "s": 33734, "text": "Reverse a string in Java" }, { "code": null, "e": 33793, "s": 33759, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33868, "s": 33793, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
C# | Structures | Set - 1 - GeeksforGeeks
27 Jun, 2021 Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. C# provide the ability to use pre-defined data types. However, sometimes the user might be in need to define its own data types which are also known as User-Defined Data Types. Although it comes under the value type, the user can modify it according to requirements and that’s why it is also termed as the user-defined data type.Defining Structure: In C#, structure is defined using struct keyword. Using struct keyword one can define the structure consisting of different data types in it. A structure can also contain constructors, constants, fields, methods, properties, indexers and events etc. Syntax: Access_Modifier struct structure_name { // Fields // Parameterized constructor // Constants // Properties // Indexers // Events // Methods etc. } Example: CSHARP // C# program to illustrate the// Declaration of structureusing System;namespace ConsoleApplication { // Defining structurepublic struct Person{ // Declaring different data types public string Name; public int Age; public int Weight; } class Geeks { // Main Method static void Main(string[] args) { // Declare P1 of type Person Person P1; // P1's data P1.Name = "Keshav Gupta"; P1.Age = 21; P1.Weight = 80; // Displaying the values Console.WriteLine("Data Stored in P1 is " + P1.Name + ", age is " + P1.Age + " and weight is " + P1.Weight); }}} Data Stored in P1 is Keshav Gupta, age is 21 and weight is 80 Explanation: In the above code, a structure with name “Person” is created with data members Name, Age and Weight.In the main method, P1 of structure type Person is created. Now, P1 can access its data members with the help of .( dot ) Operator. Copy Structure: In C#, user can copy one structure object into another one using ‘=’ (Assignment) operator. Syntax: Structure_object_destination = structure_object_source; Example: CSHARP // C# program to illustrate copy the structureusing System;namespace ConsoleApplication { // Defining structurepublic struct Person{ // Declaring different data types public string Name; public int Age; public int Weight; } class Geeks { // Main Method static void Main(string[] args) { // Declare P1 of type Person Person P1; // P1's data P1.Name = "Keshav Gupta"; P1.Age = 21; P1.Weight = 80; // Declare P2 of type Person Person P2; // Copying the values of P1 into P2 P2 = P1; // Displaying the values of P1 Console.WriteLine("Values Stored in P1"); Console.WriteLine("Name: " +P1.Name); Console.WriteLine("Age: " +P1.Age); Console.WriteLine("Weight: " +P1.Weight); Console.WriteLine(""); // Displaying the values of P2 Console.WriteLine("Values Stored in P2"); Console.WriteLine("Name: " +P2.Name); Console.WriteLine("Age: " +P2.Age); Console.WriteLine("Weight: " +P2.Weight); }}} Values Stored in P1 Name: Keshav Gupta Age: 21 Weight: 80 Values Stored in P2 Name: Keshav Gupta Age: 21 Weight: 80 Explanation: The data members of struct Person is initialized with the help of P1 and the values of data members can be copy to P2 by P1 using ‘='(assignment operator). Nesting of Structures: C# allows the declaration of one structure into another structure and this concept is termed as the nesting of the structure. Example: CSHARP // C# program to illustrate Nesting of structuresusing System;namespace ConsoleApplication { // first structure defined// with public modifierpublic struct Address{ // data member of Address structure public string City; public string State;} // Another structurestruct Person{ // data member of Person structure public string Name; public int Age; // Nesting of Address structure // by creating A1 of type Address public Address A1;} class Geeks { // Main method static void Main(string[] args) { // Declare p1 of type Person Person p1; // Assigning values to the variables p1.Name = "Raman"; p1.Age = 12; // Assigning values to the nested // structure data members p1.A1.City = "ABC_City"; p1.A1.State = "XYZ_State"; Console.WriteLine("Values Stored in p1"); Console.WriteLine("Name: " +p1.Name); Console.WriteLine("Age: " +p1.Age); Console.WriteLine("City: " +p1.A1.City); Console.WriteLine("State: " +p1.A1.State); }}} Values Stored in p1 Name: Raman Age: 12 City: ABC_City State: XYZ_State Important Points about Structures: Once the structures go out of scope, it gets automatically deallocated. Created much more easily and quickly than heap types. Using structure it become easy to copy the variable’s values onto stack. A struct is a value type, whereas a class is a reference type. Difference Between Structures and Class : simranarora5sos C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Delegates Introduction to .NET Framework Difference between Ref and Out keywords in C# Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework HashSet in C# with Examples Partial Classes in C# Top 50 C# Interview Questions & Answers
[ { "code": null, "e": 23704, "s": 23676, "text": "\n27 Jun, 2021" }, { "code": null, "e": 24526, "s": 23704, "text": "Structure is a value type and a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. C# provide the ability to use pre-defined data types. However, sometimes the user might be in need to define its own data types which are also known as User-Defined Data Types. Although it comes under the value type, the user can modify it according to requirements and that’s why it is also termed as the user-defined data type.Defining Structure: In C#, structure is defined using struct keyword. Using struct keyword one can define the structure consisting of different data types in it. A structure can also contain constructors, constants, fields, methods, properties, indexers and events etc. " }, { "code": null, "e": 24535, "s": 24526, "text": "Syntax: " }, { "code": null, "e": 24713, "s": 24535, "text": "Access_Modifier struct structure_name\n{\n\n // Fields \n // Parameterized constructor \n // Constants \n // Properties \n // Indexers \n // Events \n // Methods etc.\n \n}" }, { "code": null, "e": 24724, "s": 24713, "text": "Example: " }, { "code": null, "e": 24731, "s": 24724, "text": "CSHARP" }, { "code": "// C# program to illustrate the// Declaration of structureusing System;namespace ConsoleApplication { // Defining structurepublic struct Person{ // Declaring different data types public string Name; public int Age; public int Weight; } class Geeks { // Main Method static void Main(string[] args) { // Declare P1 of type Person Person P1; // P1's data P1.Name = \"Keshav Gupta\"; P1.Age = 21; P1.Weight = 80; // Displaying the values Console.WriteLine(\"Data Stored in P1 is \" + P1.Name + \", age is \" + P1.Age + \" and weight is \" + P1.Weight); }}}", "e": 25443, "s": 24731, "text": null }, { "code": null, "e": 25507, "s": 25445, "text": "Data Stored in P1 is Keshav Gupta, age is 21 and weight is 80" }, { "code": null, "e": 25756, "s": 25509, "text": "Explanation: In the above code, a structure with name “Person” is created with data members Name, Age and Weight.In the main method, P1 of structure type Person is created. Now, P1 can access its data members with the help of .( dot ) Operator. " }, { "code": null, "e": 25865, "s": 25756, "text": "Copy Structure: In C#, user can copy one structure object into another one using ‘=’ (Assignment) operator. " }, { "code": null, "e": 25874, "s": 25865, "text": "Syntax: " }, { "code": null, "e": 25930, "s": 25874, "text": "Structure_object_destination = structure_object_source;" }, { "code": null, "e": 25940, "s": 25930, "text": "Example: " }, { "code": null, "e": 25947, "s": 25940, "text": "CSHARP" }, { "code": "// C# program to illustrate copy the structureusing System;namespace ConsoleApplication { // Defining structurepublic struct Person{ // Declaring different data types public string Name; public int Age; public int Weight; } class Geeks { // Main Method static void Main(string[] args) { // Declare P1 of type Person Person P1; // P1's data P1.Name = \"Keshav Gupta\"; P1.Age = 21; P1.Weight = 80; // Declare P2 of type Person Person P2; // Copying the values of P1 into P2 P2 = P1; // Displaying the values of P1 Console.WriteLine(\"Values Stored in P1\"); Console.WriteLine(\"Name: \" +P1.Name); Console.WriteLine(\"Age: \" +P1.Age); Console.WriteLine(\"Weight: \" +P1.Weight); Console.WriteLine(\"\"); // Displaying the values of P2 Console.WriteLine(\"Values Stored in P2\"); Console.WriteLine(\"Name: \" +P2.Name); Console.WriteLine(\"Age: \" +P2.Age); Console.WriteLine(\"Weight: \" +P2.Weight); }}}", "e": 27067, "s": 25947, "text": null }, { "code": null, "e": 27186, "s": 27069, "text": "Values Stored in P1\nName: Keshav Gupta\nAge: 21\nWeight: 80\n\nValues Stored in P2\nName: Keshav Gupta\nAge: 21\nWeight: 80" }, { "code": null, "e": 27357, "s": 27188, "text": "Explanation: The data members of struct Person is initialized with the help of P1 and the values of data members can be copy to P2 by P1 using ‘='(assignment operator)." }, { "code": null, "e": 27507, "s": 27357, "text": "Nesting of Structures: C# allows the declaration of one structure into another structure and this concept is termed as the nesting of the structure. " }, { "code": null, "e": 27517, "s": 27507, "text": "Example: " }, { "code": null, "e": 27524, "s": 27517, "text": "CSHARP" }, { "code": "// C# program to illustrate Nesting of structuresusing System;namespace ConsoleApplication { // first structure defined// with public modifierpublic struct Address{ // data member of Address structure public string City; public string State;} // Another structurestruct Person{ // data member of Person structure public string Name; public int Age; // Nesting of Address structure // by creating A1 of type Address public Address A1;} class Geeks { // Main method static void Main(string[] args) { // Declare p1 of type Person Person p1; // Assigning values to the variables p1.Name = \"Raman\"; p1.Age = 12; // Assigning values to the nested // structure data members p1.A1.City = \"ABC_City\"; p1.A1.State = \"XYZ_State\"; Console.WriteLine(\"Values Stored in p1\"); Console.WriteLine(\"Name: \" +p1.Name); Console.WriteLine(\"Age: \" +p1.Age); Console.WriteLine(\"City: \" +p1.A1.City); Console.WriteLine(\"State: \" +p1.A1.State); }}}", "e": 28626, "s": 27524, "text": null }, { "code": null, "e": 28700, "s": 28628, "text": "Values Stored in p1\nName: Raman\nAge: 12\nCity: ABC_City\nState: XYZ_State" }, { "code": null, "e": 28739, "s": 28702, "text": "Important Points about Structures: " }, { "code": null, "e": 28811, "s": 28739, "text": "Once the structures go out of scope, it gets automatically deallocated." }, { "code": null, "e": 28865, "s": 28811, "text": "Created much more easily and quickly than heap types." }, { "code": null, "e": 28938, "s": 28865, "text": "Using structure it become easy to copy the variable’s values onto stack." }, { "code": null, "e": 29001, "s": 28938, "text": "A struct is a value type, whereas a class is a reference type." }, { "code": null, "e": 29044, "s": 29001, "text": "Difference Between Structures and Class : " }, { "code": null, "e": 29064, "s": 29048, "text": "simranarora5sos" }, { "code": null, "e": 29067, "s": 29064, "text": "C#" }, { "code": null, "e": 29165, "s": 29067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29174, "s": 29165, "text": "Comments" }, { "code": null, "e": 29187, "s": 29174, "text": "Old Comments" }, { "code": null, "e": 29215, "s": 29187, "text": "C# Dictionary with examples" }, { "code": null, "e": 29255, "s": 29215, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 29278, "s": 29255, "text": "Extension Method in C#" }, { "code": null, "e": 29293, "s": 29278, "text": "C# | Delegates" }, { "code": null, "e": 29324, "s": 29293, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29370, "s": 29324, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29457, "s": 29370, "text": "Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework" }, { "code": null, "e": 29485, "s": 29457, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29507, "s": 29485, "text": "Partial Classes in C#" } ]
HTML maxlength Attribute - GeeksforGeeks
08 Dec, 2021 It specifies the maximum number of characters that have been allowed in the Element. It can be used on the following Elements: <input><textarea> <input> <textarea> Attribute Values: It contains a single value number that allows the maximum number of characters in the <input> element. Its default value is 524288. Examples: Example for <input> element: HTML <!DOCTYPE html><html> <body> <center> <h1 style="color:green;font-style:italic;"> GeeksForGeeks </h1> <h2 style="color:green;font-style:italic;"> maxlength attribute </h2> <form action=""> Username: <input type="text" name="usrname" maxlength="12"> <br> <br> Password: <input type="text" name="password" maxlength="10"> <br> <br> <input type="submit" value="Submit"> </form> </center></body> </html> Output: Example for <textarea> element: HTML <!DOCTYPE html><html> <body> <center> <h1 style="color:green;font-style:italic;"> GeeksforGeeks </h1> <h2 style="color:green;font-style:italic;"> maxlength attribute </h2> <textarea rows="4" cols="50" maxlength="6"> write here something that you want.... </textarea> </center></body> </html> Output: Supported Browsers: The browsers supported by maxlength attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. akshaysingh98088 hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? Hide or show elements in HTML using display property 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": 25643, "s": 25615, "text": "\n08 Dec, 2021" }, { "code": null, "e": 25771, "s": 25643, "text": "It specifies the maximum number of characters that have been allowed in the Element. It can be used on the following Elements: " }, { "code": null, "e": 25789, "s": 25771, "text": "<input><textarea>" }, { "code": null, "e": 25797, "s": 25789, "text": "<input>" }, { "code": null, "e": 25808, "s": 25797, "text": "<textarea>" }, { "code": null, "e": 25958, "s": 25808, "text": "Attribute Values: It contains a single value number that allows the maximum number of characters in the <input> element. Its default value is 524288." }, { "code": null, "e": 25970, "s": 25958, "text": "Examples: " }, { "code": null, "e": 25999, "s": 25970, "text": "Example for <input> element:" }, { "code": null, "e": 26004, "s": 25999, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green;font-style:italic;\"> GeeksForGeeks </h1> <h2 style=\"color:green;font-style:italic;\"> maxlength attribute </h2> <form action=\"\"> Username: <input type=\"text\" name=\"usrname\" maxlength=\"12\"> <br> <br> Password: <input type=\"text\" name=\"password\" maxlength=\"10\"> <br> <br> <input type=\"submit\" value=\"Submit\"> </form> </center></body> </html>", "e": 26569, "s": 26004, "text": null }, { "code": null, "e": 26578, "s": 26569, "text": "Output: " }, { "code": null, "e": 26610, "s": 26578, "text": "Example for <textarea> element:" }, { "code": null, "e": 26615, "s": 26610, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green;font-style:italic;\"> GeeksforGeeks </h1> <h2 style=\"color:green;font-style:italic;\"> maxlength attribute </h2> <textarea rows=\"4\" cols=\"50\" maxlength=\"6\"> write here something that you want.... </textarea> </center></body> </html>", "e": 26980, "s": 26615, "text": null }, { "code": null, "e": 26989, "s": 26980, "text": "Output: " }, { "code": null, "e": 27073, "s": 26989, "text": "Supported Browsers: The browsers supported by maxlength attribute are listed below:" }, { "code": null, "e": 27087, "s": 27073, "text": "Google Chrome" }, { "code": null, "e": 27105, "s": 27087, "text": "Internet Explorer" }, { "code": null, "e": 27113, "s": 27105, "text": "Firefox" }, { "code": null, "e": 27119, "s": 27113, "text": "Opera" }, { "code": null, "e": 27126, "s": 27119, "text": "Safari" }, { "code": null, "e": 27265, "s": 27128, "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": 27282, "s": 27265, "text": "akshaysingh98088" }, { "code": null, "e": 27302, "s": 27282, "text": "hritikbhatnagar2182" }, { "code": null, "e": 27318, "s": 27302, "text": "HTML-Attributes" }, { "code": null, "e": 27323, "s": 27318, "text": "HTML" }, { "code": null, "e": 27340, "s": 27323, "text": "Web Technologies" }, { "code": null, "e": 27345, "s": 27340, "text": "HTML" }, { "code": null, "e": 27443, "s": 27345, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27493, "s": 27443, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27555, "s": 27493, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27615, "s": 27555, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27663, "s": 27615, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27716, "s": 27663, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27756, "s": 27716, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27789, "s": 27756, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27834, "s": 27789, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27877, "s": 27834, "text": "How to fetch data from an API in ReactJS ?" } ]
C/C++ Program to Find the Number Occurring Odd Number of Times - GeeksforGeeks
08 Jan, 2021 Given an array arr[] consisting of positive integers that occur even number of times, except one number, which occurs odd number of times. The task is to find this odd number of times occurring number. Examples : Input : arr = {1, 2, 3, 2, 3, 1, 3} Output : 3 Input : arr = {5, 7, 2, 7, 5, 2, 5} Output : 5 Naive Approach: A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts the number of occurrences of the element picked by outer loop. C++ C // C++ program to find the element// occurring odd number of times#include <bits/stdc++.h>using namespace std; // Function to find the element// occurring odd number of timesint getOddOccurrence(int arr[], int arr_size){ for (int i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // driver codeint main(){ int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << getOddOccurrence(arr, n); return 0;} // C program to find the element// occurring odd number of times#include <stdio.h> // Function to find the element// occurring odd number of timesint getOddOccurrence(int arr[], int arr_size){ for(int i = 0; i < arr_size; i++) { int count = 0; for(int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // Driver codeint main(){ int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling printf("%d",getOddOccurrence(arr, n)); return 0;} // This code is contributed by rbbansal 5 Time complexity: O(N2) Auxiliary space: O(1) Better Approach: A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.Time complexity: O(N) Auxiliary space: O(N) Efficient Approach: The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x. Below is the implementation of the above approach. C++ C // C++ program to find the element// occurring odd number of times#include <bits/stdc++.h>using namespace std; // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(ar) / sizeof(ar[0]); // Function calling cout << getOddOccurrence(ar, n); return 0;} // C program to find the element// occurring odd number of times#include <stdio.h> // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(ar) / sizeof(ar[0]); // Function calling printf("%d", getOddOccurrence(ar, n)); return 0;} 5 Time complexity: O(N) Auxiliary space: O(1)Please refer complete article on Find the Number Occurring Odd Number of Times for more details! nidhi_biet shubham_singh rbbansal Bitwise-XOR Arrays C Programs C++ Programs Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Strings in C Arrow operator -> in C/C++ with Examples Header files in C/C++ and its uses C Program to read contents of Whole File Basics of File Handling in C
[ { "code": null, "e": 26066, "s": 26038, "text": "\n08 Jan, 2021" }, { "code": null, "e": 26268, "s": 26066, "text": "Given an array arr[] consisting of positive integers that occur even number of times, except one number, which occurs odd number of times. The task is to find this odd number of times occurring number." }, { "code": null, "e": 26281, "s": 26268, "text": "Examples : " }, { "code": null, "e": 26376, "s": 26281, "text": "Input : arr = {1, 2, 3, 2, 3, 1, 3}\nOutput : 3\n\nInput : arr = {5, 7, 2, 7, 5, 2, 5}\nOutput : 5" }, { "code": null, "e": 26569, "s": 26376, "text": "Naive Approach: A Simple Solution is to run two nested loops. The outer loop picks all elements one by one and inner loop counts the number of occurrences of the element picked by outer loop. " }, { "code": null, "e": 26573, "s": 26569, "text": "C++" }, { "code": null, "e": 26575, "s": 26573, "text": "C" }, { "code": "// C++ program to find the element// occurring odd number of times#include <bits/stdc++.h>using namespace std; // Function to find the element// occurring odd number of timesint getOddOccurrence(int arr[], int arr_size){ for (int i = 0; i < arr_size; i++) { int count = 0; for (int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // driver codeint main(){ int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling cout << getOddOccurrence(arr, n); return 0;}", "e": 27261, "s": 26575, "text": null }, { "code": "// C program to find the element// occurring odd number of times#include <stdio.h> // Function to find the element// occurring odd number of timesint getOddOccurrence(int arr[], int arr_size){ for(int i = 0; i < arr_size; i++) { int count = 0; for(int j = 0; j < arr_size; j++) { if (arr[i] == arr[j]) count++; } if (count % 2 != 0) return arr[i]; } return -1;} // Driver codeint main(){ int arr[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function calling printf(\"%d\",getOddOccurrence(arr, n)); return 0;} // This code is contributed by rbbansal", "e": 27975, "s": 27261, "text": null }, { "code": null, "e": 27977, "s": 27975, "text": "5" }, { "code": null, "e": 28024, "s": 27979, "text": "Time complexity: O(N2) Auxiliary space: O(1)" }, { "code": null, "e": 28348, "s": 28024, "text": "Better Approach: A Better Solution is to use Hashing. Use array elements as key and their counts as value. Create an empty hash table. One by one traverse the given array elements and store counts. Time complexity of this solution is O(n). But it requires extra space for hashing.Time complexity: O(N) Auxiliary space: O(N)" }, { "code": null, "e": 28583, "s": 28348, "text": "Efficient Approach: The Best Solution is to do bitwise XOR of all the elements. XOR of all elements gives us odd occurring element. Please note that XOR of two elements is 0 if both elements are same and XOR of a number x with 0 is x." }, { "code": null, "e": 28636, "s": 28583, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 28640, "s": 28636, "text": "C++" }, { "code": null, "e": 28642, "s": 28640, "text": "C" }, { "code": "// C++ program to find the element// occurring odd number of times#include <bits/stdc++.h>using namespace std; // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(ar) / sizeof(ar[0]); // Function calling cout << getOddOccurrence(ar, n); return 0;}", "e": 29212, "s": 28642, "text": null }, { "code": "// C program to find the element// occurring odd number of times#include <stdio.h> // Function to find element occurring// odd number of timesint getOddOccurrence(int ar[], int ar_size){ int res = 0; for (int i = 0; i < ar_size; i++) res = res ^ ar[i]; return res;} /* Driver function to test above function */int main(){ int ar[] = { 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2 }; int n = sizeof(ar) / sizeof(ar[0]); // Function calling printf(\"%d\", getOddOccurrence(ar, n)); return 0;}", "e": 29759, "s": 29212, "text": null }, { "code": null, "e": 29761, "s": 29759, "text": "5" }, { "code": null, "e": 29904, "s": 29763, "text": "Time complexity: O(N) Auxiliary space: O(1)Please refer complete article on Find the Number Occurring Odd Number of Times for more details! " }, { "code": null, "e": 29915, "s": 29904, "text": "nidhi_biet" }, { "code": null, "e": 29929, "s": 29915, "text": "shubham_singh" }, { "code": null, "e": 29938, "s": 29929, "text": "rbbansal" }, { "code": null, "e": 29950, "s": 29938, "text": "Bitwise-XOR" }, { "code": null, "e": 29957, "s": 29950, "text": "Arrays" }, { "code": null, "e": 29968, "s": 29957, "text": "C Programs" }, { "code": null, "e": 29981, "s": 29968, "text": "C++ Programs" }, { "code": null, "e": 29986, "s": 29981, "text": "Hash" }, { "code": null, "e": 29993, "s": 29986, "text": "Arrays" }, { "code": null, "e": 29998, "s": 29993, "text": "Hash" }, { "code": null, "e": 30096, "s": 29998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30127, "s": 30096, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 30152, "s": 30127, "text": "Window Sliding Technique" }, { "code": null, "e": 30190, "s": 30152, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30211, "s": 30190, "text": "Next Greater Element" }, { "code": null, "e": 30269, "s": 30211, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30282, "s": 30269, "text": "Strings in C" }, { "code": null, "e": 30323, "s": 30282, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 30358, "s": 30323, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30399, "s": 30358, "text": "C Program to read contents of Whole File" } ]
Angular CLI - ng generate Command
This chapter explains the syntax, argument and options of ng generate command along with an example. The syntax for ng generate command is as follows − ng generate <schematic> [options] ng g <schematic> [options] ng generate command generates and/or modifies files based on a schematic. The argument for ng help command is as follows − appShell appShell application application class class component component directive directive enum enum guard guard interceptor interceptor interface interface library library module module pipe pipe service service serviceWorker serviceWorker webWorker webWorker Options are optional parameters. When true,runs through and reports activity without writing out results. Default:false. Aliases: -d. When true,forces overwriting of existing files. Default:false. Aliases: -f. Shows a helpmessage for this command in the console. Default: false. First move to an angular project created using ng new command and then run the command. This chapter is available athttps://www.tutorialspoint.com/angular_cli/angular_cli_ng_new.htm. An example for ng generate command is given below − \>Node\>TutorialsPoint> ng generate component goals CREATE src/app/goals/goals.component.html (20 bytes) CREATE src/app/goals/goals.component.spec.ts (621 bytes) CREATE src/app/goals/goals.component.ts (271 bytes) CREATE src/app/goals/goals.component.css (0 bytes) UPDATE src/app/app.module.ts (471 bytes) Here, ng generate command has created a new component in our project TutorialsPoint and added this new component entry in app.module.ts. 16 Lectures 1.5 hours Anadi Sharma 28 Lectures 2.5 hours Anadi Sharma 11 Lectures 7.5 hours SHIVPRASAD KOIRALA 16 Lectures 2.5 hours Frahaan Hussain 69 Lectures 5 hours Senol Atac 53 Lectures 3.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2176, "s": 2075, "text": "This chapter explains the syntax, argument and options of ng generate command along with an example." }, { "code": null, "e": 2227, "s": 2176, "text": "The syntax for ng generate command is as follows −" }, { "code": null, "e": 2289, "s": 2227, "text": "ng generate <schematic> [options]\nng g <schematic> [options]\n" }, { "code": null, "e": 2363, "s": 2289, "text": "ng generate command generates and/or modifies files based on a schematic." }, { "code": null, "e": 2412, "s": 2363, "text": "The argument for ng help command is as follows −" }, { "code": null, "e": 2421, "s": 2412, "text": "appShell" }, { "code": null, "e": 2430, "s": 2421, "text": "appShell" }, { "code": null, "e": 2442, "s": 2430, "text": "application" }, { "code": null, "e": 2454, "s": 2442, "text": "application" }, { "code": null, "e": 2460, "s": 2454, "text": "class" }, { "code": null, "e": 2466, "s": 2460, "text": "class" }, { "code": null, "e": 2476, "s": 2466, "text": "component" }, { "code": null, "e": 2486, "s": 2476, "text": "component" }, { "code": null, "e": 2496, "s": 2486, "text": "directive" }, { "code": null, "e": 2506, "s": 2496, "text": "directive" }, { "code": null, "e": 2511, "s": 2506, "text": "enum" }, { "code": null, "e": 2516, "s": 2511, "text": "enum" }, { "code": null, "e": 2522, "s": 2516, "text": "guard" }, { "code": null, "e": 2528, "s": 2522, "text": "guard" }, { "code": null, "e": 2540, "s": 2528, "text": "interceptor" }, { "code": null, "e": 2552, "s": 2540, "text": "interceptor" }, { "code": null, "e": 2562, "s": 2552, "text": "interface" }, { "code": null, "e": 2572, "s": 2562, "text": "interface" }, { "code": null, "e": 2580, "s": 2572, "text": "library" }, { "code": null, "e": 2588, "s": 2580, "text": "library" }, { "code": null, "e": 2595, "s": 2588, "text": "module" }, { "code": null, "e": 2602, "s": 2595, "text": "module" }, { "code": null, "e": 2607, "s": 2602, "text": "pipe" }, { "code": null, "e": 2612, "s": 2607, "text": "pipe" }, { "code": null, "e": 2620, "s": 2612, "text": "service" }, { "code": null, "e": 2628, "s": 2620, "text": "service" }, { "code": null, "e": 2642, "s": 2628, "text": "serviceWorker" }, { "code": null, "e": 2656, "s": 2642, "text": "serviceWorker" }, { "code": null, "e": 2666, "s": 2656, "text": "webWorker" }, { "code": null, "e": 2676, "s": 2666, "text": "webWorker" }, { "code": null, "e": 2709, "s": 2676, "text": "Options are optional parameters." }, { "code": null, "e": 2782, "s": 2709, "text": "When true,runs through and reports activity without writing out results." }, { "code": null, "e": 2797, "s": 2782, "text": "Default:false." }, { "code": null, "e": 2810, "s": 2797, "text": "Aliases: -d." }, { "code": null, "e": 2858, "s": 2810, "text": "When true,forces overwriting of existing files." }, { "code": null, "e": 2873, "s": 2858, "text": "Default:false." }, { "code": null, "e": 2886, "s": 2873, "text": "Aliases: -f." }, { "code": null, "e": 2939, "s": 2886, "text": "Shows a helpmessage for this command in the console." }, { "code": null, "e": 2955, "s": 2939, "text": "Default: false." }, { "code": null, "e": 3138, "s": 2955, "text": "First move to an angular project created using ng new command and then run the\ncommand. This chapter is available athttps://www.tutorialspoint.com/angular_cli/angular_cli_ng_new.htm." }, { "code": null, "e": 3190, "s": 3138, "text": "An example for ng generate command is given below −" }, { "code": null, "e": 3497, "s": 3190, "text": "\\>Node\\>TutorialsPoint> ng generate component goals\nCREATE src/app/goals/goals.component.html (20 bytes)\nCREATE src/app/goals/goals.component.spec.ts (621 bytes)\nCREATE src/app/goals/goals.component.ts (271 bytes)\nCREATE src/app/goals/goals.component.css (0 bytes)\nUPDATE src/app/app.module.ts (471 bytes)\n" }, { "code": null, "e": 3634, "s": 3497, "text": "Here, ng generate command has created a new component in our project TutorialsPoint and added this new component entry in app.module.ts." }, { "code": null, "e": 3669, "s": 3634, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3683, "s": 3669, "text": " Anadi Sharma" }, { "code": null, "e": 3718, "s": 3683, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3732, "s": 3718, "text": " Anadi Sharma" }, { "code": null, "e": 3767, "s": 3732, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3787, "s": 3767, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 3822, "s": 3787, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3839, "s": 3822, "text": " Frahaan Hussain" }, { "code": null, "e": 3872, "s": 3839, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 3884, "s": 3872, "text": " Senol Atac" }, { "code": null, "e": 3919, "s": 3884, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3931, "s": 3919, "text": " Senol Atac" }, { "code": null, "e": 3938, "s": 3931, "text": " Print" }, { "code": null, "e": 3949, "s": 3938, "text": " Add Notes" } ]
Next.js SWR (Stale While Revalidate) Introduction - GeeksforGeeks
03 Nov, 2021 State While Revalidate is React Hooks library for remote data fetching, created by Zeit. It is used for Returns the data from cache (stale) Sends the fetch request (revalidate), and then Comes with the up-to-date data again. Google says about the concept of SWR: “It helps developers balance between immediacy—loading cached content right away—and freshness—ensuring updates to the cached content are used in the future. If you maintain a third-party web service or library that updates on a regular schedule, or your first-party assets tend to have short lifetimes, then stale-while-revalidate may be a useful addition to your existing caching policies.” A Cache-Control response header that contains stale-while-revalidate should also contain max-age, and the number of seconds specified via max-age is what determines staleness. Any cached response newer than max-age is considered fresh, and older cached responses are stale. Simply put, SWR automatically revalidates the data from the origin as soon as data is rendered from the cache, this will render the pages much faster and after rendering the page the data is updated with the latest one. Advantages of SWR: Apart from Custom API calls & REST API integration, what comes with Zeit’s SWR are described below. Focus Revalidation: When you re-focus a page or switch between tabs in the browser, SWR automatically revalidates data. Fast Navigation: SWR automatically revalidates the data from the origin as soon as data is rendered from the cache. Refetch on Interval: SWR will give you the option to automatically fetch data, where prefetching will only take place of the component associated with the hook is on the screen. Local Mutation: Applying changes to data locally, i.e. always updated to the most recent data. Dependent Fetching: SWR allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data, fetch to happen. Scalable: SWR scales extremely well because it requires very little effort to write applications that automatically and eventually converge to the most recent remote data. Disadvantages of SWR: A major disadvantage of using SWR is that it might lead the user looking at stale data, which can happen because of a lack of proper implementation of the API, error in updating the displayed information, and possibly many others. Apart from creating a bad user experience, this can also be the sole reason for the setback of a company! Imagine a well-established company in finance, can they afford to have their users looking at the stale data!? Nope, and that is why an accurate implementation and use of SWR is required. Introduction to Next.js: Next.js is a react based framework. It is based on react, webpack & babel. It is known for its automatic code-splitting, hot-code reloading (i.e. reloads as soon as the changes get saved) & most importantly, Server Side Rendering. This puts up this framework on top of the recommended toolchains suggested at React documentation. Steps taken to set up your next.js project, given that one has node & npm installed on their device. Step 1: Check the node & npm versions by running below command$node -v && npm -v $node -v && npm -v Step 2: Create a directory, and after reaching the targeted directory in terminal perform$ npm install --save next react react-dom $ npm install --save next react react-dom Step 3: Create a file in index.js in the pages folder (basically pages/index.js), add the following code, and run npm start to see it in action! javascript // The code for pages/index.js import React from'react'; import Link from'next/link'; export default class extends React.Component { render() { return ( { <div> <h1>Hello Geeks</h1> </div> ) } } Using Next.js with SWR to fetch an API: We’ll perform a data-fetch using SWR & isomorphic-unfetch with the powerful Next.js, the two dependencies that need to be installed (commands given in the code). javascript // The code for /pages/index.js /* Install by using the CLI - npm i swr */import useSWR from 'swr'; import fetch from '../libs/fetch'; function StateNameAN () { const { data, error } = useSWR('https://gist.githubusercontent.com/shubhamjain/35ed77154f577295707a/raw/7bc2a915cff003fb1f8ff49c6890576eee4f2f10/IndianStates.json', fetch); /* In case API fails */ if (error) return <div>failed to load</div> /* While result API loads */ if (!data) return <div>loading...</div> /* After response from the API is received */ return <div>Hello{' '}{data.AN}!</div> } export default function IndexPage() { return ( <div> <StateNameAN /> </div> );} javascript // The code for /libs/fetch.js /* Install by using the CLI - npm i isomorphic-unfetch */import fetch from 'isomorphic-unfetch'; export default async function (...args) { const res = await fetch(...args) return res.json()} Output: Hello Andaman and Nicobar Islands! Next.js ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to redirect to another page in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS setState() React-Router Hooks Re-rendering Components in ReactJS 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 insert spaces/tabs in text using HTML/CSS? Convert a string to an integer in JavaScript
[ { "code": null, "e": 24199, "s": 24171, "text": "\n03 Nov, 2021" }, { "code": null, "e": 24304, "s": 24199, "text": "State While Revalidate is React Hooks library for remote data fetching, created by Zeit. It is used for " }, { "code": null, "e": 24340, "s": 24304, "text": "Returns the data from cache (stale)" }, { "code": null, "e": 24387, "s": 24340, "text": "Sends the fetch request (revalidate), and then" }, { "code": null, "e": 24425, "s": 24387, "text": "Comes with the up-to-date data again." }, { "code": null, "e": 24464, "s": 24425, "text": "Google says about the concept of SWR: " }, { "code": null, "e": 24858, "s": 24464, "text": " “It helps developers balance between immediacy—loading cached content right away—and freshness—ensuring updates to the cached content are used in the future. If you maintain a third-party web service or library that updates on a regular schedule, or your first-party assets tend to have short lifetimes, then stale-while-revalidate may be a useful addition to your existing caching policies.”" }, { "code": null, "e": 25353, "s": 24858, "text": "A Cache-Control response header that contains stale-while-revalidate should also contain max-age, and the number of seconds specified via max-age is what determines staleness. Any cached response newer than max-age is considered fresh, and older cached responses are stale. Simply put, SWR automatically revalidates the data from the origin as soon as data is rendered from the cache, this will render the pages much faster and after rendering the page the data is updated with the latest one. " }, { "code": null, "e": 25472, "s": 25353, "text": "Advantages of SWR: Apart from Custom API calls & REST API integration, what comes with Zeit’s SWR are described below." }, { "code": null, "e": 25592, "s": 25472, "text": "Focus Revalidation: When you re-focus a page or switch between tabs in the browser, SWR automatically revalidates data." }, { "code": null, "e": 25708, "s": 25592, "text": "Fast Navigation: SWR automatically revalidates the data from the origin as soon as data is rendered from the cache." }, { "code": null, "e": 25886, "s": 25708, "text": "Refetch on Interval: SWR will give you the option to automatically fetch data, where prefetching will only take place of the component associated with the hook is on the screen." }, { "code": null, "e": 25981, "s": 25886, "text": "Local Mutation: Applying changes to data locally, i.e. always updated to the most recent data." }, { "code": null, "e": 26229, "s": 25981, "text": "Dependent Fetching: SWR allows you to fetch data that depends on other data. It ensures the maximum possible parallelism (avoiding waterfalls), as well as serial fetching when a piece of dynamic data is required for the next data, fetch to happen." }, { "code": null, "e": 26402, "s": 26229, "text": "Scalable: SWR scales extremely well because it requires very little effort to write applications that automatically and eventually converge to the most recent remote data. " }, { "code": null, "e": 26425, "s": 26402, "text": "Disadvantages of SWR: " }, { "code": null, "e": 26656, "s": 26425, "text": "A major disadvantage of using SWR is that it might lead the user looking at stale data, which can happen because of a lack of proper implementation of the API, error in updating the displayed information, and possibly many others." }, { "code": null, "e": 26950, "s": 26656, "text": "Apart from creating a bad user experience, this can also be the sole reason for the setback of a company! Imagine a well-established company in finance, can they afford to have their users looking at the stale data!? Nope, and that is why an accurate implementation and use of SWR is required." }, { "code": null, "e": 26975, "s": 26950, "text": "Introduction to Next.js:" }, { "code": null, "e": 27305, "s": 26975, "text": "Next.js is a react based framework. It is based on react, webpack & babel. It is known for its automatic code-splitting, hot-code reloading (i.e. reloads as soon as the changes get saved) & most importantly, Server Side Rendering. This puts up this framework on top of the recommended toolchains suggested at React documentation." }, { "code": null, "e": 27407, "s": 27305, "text": "Steps taken to set up your next.js project, given that one has node & npm installed on their device. " }, { "code": null, "e": 27488, "s": 27407, "text": "Step 1: Check the node & npm versions by running below command$node -v && npm -v" }, { "code": null, "e": 27507, "s": 27488, "text": "$node -v && npm -v" }, { "code": null, "e": 27638, "s": 27507, "text": "Step 2: Create a directory, and after reaching the targeted directory in terminal perform$ npm install --save next react react-dom" }, { "code": null, "e": 27680, "s": 27638, "text": "$ npm install --save next react react-dom" }, { "code": null, "e": 27827, "s": 27680, "text": "Step 3: Create a file in index.js in the pages folder (basically pages/index.js), add the following code, and run npm start to see it in action! " }, { "code": null, "e": 27838, "s": 27827, "text": "javascript" }, { "code": "// The code for pages/index.js import React from'react'; import Link from'next/link'; export default class extends React.Component { render() { return ( { <div> <h1>Hello Geeks</h1> </div> ) } } ", "e": 28090, "s": 27838, "text": null }, { "code": null, "e": 28131, "s": 28090, "text": "Using Next.js with SWR to fetch an API: " }, { "code": null, "e": 28294, "s": 28131, "text": " We’ll perform a data-fetch using SWR & isomorphic-unfetch with the powerful Next.js, the two dependencies that need to be installed (commands given in the code)." }, { "code": null, "e": 28305, "s": 28294, "text": "javascript" }, { "code": "// The code for /pages/index.js /* Install by using the CLI - npm i swr */import useSWR from 'swr'; import fetch from '../libs/fetch'; function StateNameAN () { const { data, error } = useSWR('https://gist.githubusercontent.com/shubhamjain/35ed77154f577295707a/raw/7bc2a915cff003fb1f8ff49c6890576eee4f2f10/IndianStates.json', fetch); /* In case API fails */ if (error) return <div>failed to load</div> /* While result API loads */ if (!data) return <div>loading...</div> /* After response from the API is received */ return <div>Hello{' '}{data.AN}!</div> } export default function IndexPage() { return ( <div> <StateNameAN /> </div> );}", "e": 28976, "s": 28305, "text": null }, { "code": null, "e": 28987, "s": 28976, "text": "javascript" }, { "code": "// The code for /libs/fetch.js /* Install by using the CLI - npm i isomorphic-unfetch */import fetch from 'isomorphic-unfetch'; export default async function (...args) { const res = await fetch(...args) return res.json()}", "e": 29214, "s": 28987, "text": null }, { "code": null, "e": 29222, "s": 29214, "text": "Output:" }, { "code": null, "e": 29258, "s": 29222, "text": "Hello Andaman and Nicobar Islands! " }, { "code": null, "e": 29268, "s": 29260, "text": "Next.js" }, { "code": null, "e": 29276, "s": 29268, "text": "ReactJS" }, { "code": null, "e": 29293, "s": 29276, "text": "Web Technologies" }, { "code": null, "e": 29391, "s": 29293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29400, "s": 29391, "text": "Comments" }, { "code": null, "e": 29413, "s": 29400, "text": "Old Comments" }, { "code": null, "e": 29458, "s": 29413, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 29526, "s": 29458, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 29545, "s": 29526, "text": "ReactJS setState()" }, { "code": null, "e": 29564, "s": 29545, "text": "React-Router Hooks" }, { "code": null, "e": 29599, "s": 29564, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 29641, "s": 29599, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29674, "s": 29641, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29736, "s": 29674, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29786, "s": 29736, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Grouped Barplots in Python with Seaborn - GeeksforGeeks
02 Dec, 2020 Prerequisites: Seaborn In this article, we will discuss ways to make grouped barplots using Seaborn in Python. Before that, there are some concepts one must be familiar with: Barcharts: Barcharts are great when you have two variables one is numerical and therefore the other may be a categorical variable. A barplot can reveal the relationship between them. Grouped Barplot: A Grouped barplot is beneficial when you have a multiple categorical variable. Python’s Seaborn plotting library makes it easy to form grouped barplots. Groupby: Pandas dataframe.groupby() function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names. Import Libraries. Load or create data. Perform groupby with an aggregate function. Plot the barplot with grouped attributes. Following are implementation to explain the same: Example 1: Python3 # importing packagesimport seaborn as sb # load datasetdf = sb.load_dataset('tips') # perform groupbydf = df.groupby(['size', 'sex']).agg(mean_total_bill=("total_bill", 'mean'))df = df.reset_index() # plot barplotsb.barplot(x="size", y="mean_total_bill", hue="sex", data=df) Output: Example 2: Python3 # importing packagesimport seaborn as sb # load datasetdf = sb.load_dataset('tips') # perform groupbydf = df.groupby(['size', 'day']).agg(mean_total_bill=("total_bill", 'mean'))df = df.reset_index() # plot barplotsb.barplot(x="size", y="mean_total_bill", hue="day", data=df) Output: Example 3: Python3 # importing packagesimport seaborn as sb # load datasetdf = sb.load_dataset('anagrams') # perform groupbydf = df.groupby(['num1', 'attnr']).agg(mean_num3=("num3", 'mean'))df = df.reset_index() # plot barplotsb.barplot(x="num1", y="mean_num3", hue="attnr", data=df) Output: Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Get unique values from a list Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25665, "s": 25637, "text": "\n02 Dec, 2020" }, { "code": null, "e": 25688, "s": 25665, "text": "Prerequisites: Seaborn" }, { "code": null, "e": 25840, "s": 25688, "text": "In this article, we will discuss ways to make grouped barplots using Seaborn in Python. Before that, there are some concepts one must be familiar with:" }, { "code": null, "e": 26023, "s": 25840, "text": "Barcharts: Barcharts are great when you have two variables one is numerical and therefore the other may be a categorical variable. A barplot can reveal the relationship between them." }, { "code": null, "e": 26193, "s": 26023, "text": "Grouped Barplot: A Grouped barplot is beneficial when you have a multiple categorical variable. Python’s Seaborn plotting library makes it easy to form grouped barplots." }, { "code": null, "e": 26436, "s": 26193, "text": "Groupby: Pandas dataframe.groupby() function is used to split the data into groups based on some criteria. Pandas objects can be split on any of their axes. The abstract definition of grouping is to provide a mapping of labels to group names." }, { "code": null, "e": 26454, "s": 26436, "text": "Import Libraries." }, { "code": null, "e": 26475, "s": 26454, "text": "Load or create data." }, { "code": null, "e": 26519, "s": 26475, "text": "Perform groupby with an aggregate function." }, { "code": null, "e": 26561, "s": 26519, "text": "Plot the barplot with grouped attributes." }, { "code": null, "e": 26612, "s": 26561, "text": "Following are implementation to explain the same: " }, { "code": null, "e": 26623, "s": 26612, "text": "Example 1:" }, { "code": null, "e": 26631, "s": 26623, "text": "Python3" }, { "code": "# importing packagesimport seaborn as sb # load datasetdf = sb.load_dataset('tips') # perform groupbydf = df.groupby(['size', 'sex']).agg(mean_total_bill=(\"total_bill\", 'mean'))df = df.reset_index() # plot barplotsb.barplot(x=\"size\", y=\"mean_total_bill\", hue=\"sex\", data=df)", "e": 26939, "s": 26631, "text": null }, { "code": null, "e": 26947, "s": 26939, "text": "Output:" }, { "code": null, "e": 26958, "s": 26947, "text": "Example 2:" }, { "code": null, "e": 26966, "s": 26958, "text": "Python3" }, { "code": "# importing packagesimport seaborn as sb # load datasetdf = sb.load_dataset('tips') # perform groupbydf = df.groupby(['size', 'day']).agg(mean_total_bill=(\"total_bill\", 'mean'))df = df.reset_index() # plot barplotsb.barplot(x=\"size\", y=\"mean_total_bill\", hue=\"day\", data=df)", "e": 27274, "s": 26966, "text": null }, { "code": null, "e": 27282, "s": 27274, "text": "Output:" }, { "code": null, "e": 27293, "s": 27282, "text": "Example 3:" }, { "code": null, "e": 27301, "s": 27293, "text": "Python3" }, { "code": "# importing packagesimport seaborn as sb # load datasetdf = sb.load_dataset('anagrams') # perform groupbydf = df.groupby(['num1', 'attnr']).agg(mean_num3=(\"num3\", 'mean'))df = df.reset_index() # plot barplotsb.barplot(x=\"num1\", y=\"mean_num3\", hue=\"attnr\", data=df)", "e": 27599, "s": 27301, "text": null }, { "code": null, "e": 27607, "s": 27599, "text": "Output:" }, { "code": null, "e": 27622, "s": 27607, "text": "Python-Seaborn" }, { "code": null, "e": 27629, "s": 27622, "text": "Python" }, { "code": null, "e": 27727, "s": 27629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27759, "s": 27727, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27801, "s": 27759, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27843, "s": 27801, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27899, "s": 27843, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27926, "s": 27899, "text": "Python Classes and Objects" }, { "code": null, "e": 27957, "s": 27926, "text": "Python | os.path.join() method" }, { "code": null, "e": 27986, "s": 27957, "text": "Create a directory in Python" }, { "code": null, "e": 28008, "s": 27986, "text": "Defaultdict in Python" }, { "code": null, "e": 28047, "s": 28008, "text": "Python | Get unique values from a list" } ]
Node.js fs.lstatSync() Method - GeeksforGeeks
11 Oct, 2021 The fs.lstatSync() method is used to synchronously return information about the symbolic link that is being used to refer to a file or directory. The fs.Stat object returns several fields and methods to get more details about the file. Syntax: fs.lstatSync( path, options ) Parameters: This method accept two parameters as mentioned above and described below: path: It is a String, Buffer or URL that holds the path of the symbolic link. options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false. Returns: It returns a fs.Stats object which contains the details of the symbolic link. Below examples illustrate the fs.lstatSync() method in Node.js: Example 1: This example uses fs.lstatSync() method to get the details of a symbolic link to a file. // Node.js program to demonstrate the// fs.lstatSync() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + "\\example_file.txt", "symlinkToFile", 'file'); console.log("Symlink to file created") statsObj = fs.lstatSync("symlinkToFile"); console.log("Stat of symlinkToFile")console.log(statsObj); Output: Symlink to file created Stat of symlinkToFile Stats { dev: 3229478529, mode: 41398, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 281474976780954, size: 49, blocks: 0, atimeMs: 1585207963423.2476, mtimeMs: 1585207963423.2476, ctimeMs: 1585207963423.2476, birthtimeMs: 1585207963423.2476, atime: 2020-03-26T07:32:43.423Z, mtime: 2020-03-26T07:32:43.423Z, ctime: 2020-03-26T07:32:43.423Z, birthtime: 2020-03-26T07:32:43.423Z } Example 2: This example uses fs.lstatSync() method to get the details of a symbolic link to a folder. // Node.js program to demonstrate the// fs.lstatSync() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + "\\example_directory", "symlinkToDir", 'dir'); console.log("Symlink to directory created") statsObj = fs.lstatSync("symlinkToDir");console.log("Stat of symlinkToDir")console.log(statsObj); Output: Stat of symlinkToDir Stats { dev: 3229478529, mode: 41398, nlink: 1, uid: 0, gid: 0, rdev: 0, blksize: 4096, ino: 281474976780955, size: 50, blocks: 0, atimeMs: 1585208001112.3284, mtimeMs: 1585208001112.3284, ctimeMs: 1585208001112.3284, birthtimeMs: 1585208001112.3284, atime: 2020-03-26T07:33:21.112Z, mtime: 2020-03-26T07:33:21.112Z, ctime: 2020-03-26T07:33:21.112Z, birthtime: 2020-03-26T07:33:21.112Z } Reference: https://nodejs.org/api/fs.html#fs_fs_lstatsync_path_options Node.js-fs-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between dependencies, devDependencies and peerDependencies Node.js Export Module Mongoose Populate() Method How to connect Node.js with React.js ? Mongoose find() Function Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26842, "s": 26814, "text": "\n11 Oct, 2021" }, { "code": null, "e": 27078, "s": 26842, "text": "The fs.lstatSync() method is used to synchronously return information about the symbolic link that is being used to refer to a file or directory. The fs.Stat object returns several fields and methods to get more details about the file." }, { "code": null, "e": 27086, "s": 27078, "text": "Syntax:" }, { "code": null, "e": 27116, "s": 27086, "text": "fs.lstatSync( path, options )" }, { "code": null, "e": 27202, "s": 27116, "text": "Parameters: This method accept two parameters as mentioned above and described below:" }, { "code": null, "e": 27280, "s": 27202, "text": "path: It is a String, Buffer or URL that holds the path of the symbolic link." }, { "code": null, "e": 27552, "s": 27280, "text": "options: It is an object that can be used to specify optional parameters that will affect the output. It has one optional parameter:bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 27692, "s": 27552, "text": "bigint: It is a boolean value which specifies if the numeric values returned in the fs.Stats object are bigint. The default value is false." }, { "code": null, "e": 27779, "s": 27692, "text": "Returns: It returns a fs.Stats object which contains the details of the symbolic link." }, { "code": null, "e": 27843, "s": 27779, "text": "Below examples illustrate the fs.lstatSync() method in Node.js:" }, { "code": null, "e": 27943, "s": 27843, "text": "Example 1: This example uses fs.lstatSync() method to get the details of a symbolic link to a file." }, { "code": "// Node.js program to demonstrate the// fs.lstatSync() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + \"\\\\example_file.txt\", \"symlinkToFile\", 'file'); console.log(\"Symlink to file created\") statsObj = fs.lstatSync(\"symlinkToFile\"); console.log(\"Stat of symlinkToFile\")console.log(statsObj);", "e": 28304, "s": 27943, "text": null }, { "code": null, "e": 28312, "s": 28304, "text": "Output:" }, { "code": null, "e": 28783, "s": 28312, "text": "Symlink to file created\nStat of symlinkToFile\nStats {\n dev: 3229478529,\n mode: 41398,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 281474976780954,\n size: 49,\n blocks: 0,\n atimeMs: 1585207963423.2476,\n mtimeMs: 1585207963423.2476,\n ctimeMs: 1585207963423.2476,\n birthtimeMs: 1585207963423.2476,\n atime: 2020-03-26T07:32:43.423Z,\n mtime: 2020-03-26T07:32:43.423Z,\n ctime: 2020-03-26T07:32:43.423Z,\n birthtime: 2020-03-26T07:32:43.423Z\n}\n" }, { "code": null, "e": 28885, "s": 28783, "text": "Example 2: This example uses fs.lstatSync() method to get the details of a symbolic link to a folder." }, { "code": "// Node.js program to demonstrate the// fs.lstatSync() method // Import the filesystem moduleconst fs = require('fs'); fs.symlinkSync(__dirname + \"\\\\example_directory\", \"symlinkToDir\", 'dir'); console.log(\"Symlink to directory created\") statsObj = fs.lstatSync(\"symlinkToDir\");console.log(\"Stat of symlinkToDir\")console.log(statsObj);", "e": 29249, "s": 28885, "text": null }, { "code": null, "e": 29257, "s": 29249, "text": "Output:" }, { "code": null, "e": 29702, "s": 29257, "text": "Stat of symlinkToDir\nStats {\n dev: 3229478529,\n mode: 41398,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n blksize: 4096,\n ino: 281474976780955,\n size: 50,\n blocks: 0,\n atimeMs: 1585208001112.3284,\n mtimeMs: 1585208001112.3284,\n ctimeMs: 1585208001112.3284,\n birthtimeMs: 1585208001112.3284,\n atime: 2020-03-26T07:33:21.112Z,\n mtime: 2020-03-26T07:33:21.112Z,\n ctime: 2020-03-26T07:33:21.112Z,\n birthtime: 2020-03-26T07:33:21.112Z\n}" }, { "code": null, "e": 29773, "s": 29702, "text": "Reference: https://nodejs.org/api/fs.html#fs_fs_lstatsync_path_options" }, { "code": null, "e": 29791, "s": 29773, "text": "Node.js-fs-module" }, { "code": null, "e": 29799, "s": 29791, "text": "Node.js" }, { "code": null, "e": 29816, "s": 29799, "text": "Web Technologies" }, { "code": null, "e": 29914, "s": 29816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29984, "s": 29914, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 30006, "s": 29984, "text": "Node.js Export Module" }, { "code": null, "e": 30033, "s": 30006, "text": "Mongoose Populate() Method" }, { "code": null, "e": 30072, "s": 30033, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 30097, "s": 30072, "text": "Mongoose find() Function" }, { "code": null, "e": 30137, "s": 30097, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30182, "s": 30137, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30225, "s": 30182, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30275, "s": 30225, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Advanced Excel Statistical - LINEST Function
The LINEST function calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data, and then returns an array that describes the line. You can also combine LINEST with other functions to calculate the statistics for other types of models that are linear in the unknown parameters, including polynomial, logarithmic, exponential, and power series. Since this function returns an array of values, it must be entered as an array formula. LINEST (known_y's, [known_x's], [const], [stats]) The set of y-values that you already know in the relationship y = mx + b. If the range of known_y's is in a single column, each column of known_x's is interpreted as a separate variable. If the range of known_y's is contained in a single row, each row of known_x's is interpreted as a separate variable. A set of x-values that you may already know in the relationship y = mx + b. The range of known_x's can include one or more sets of variables. If only one variable is used, known_y's and known_x's can be ranges of any shape, as long as they have equal dimensions. If more than one variable is used, known_y's must be a vector (that is, a range with a height of one row or a width of one column). If known_x's is omitted, it is assumed to be the array {1,2,3,...} that is the same size as known_y's. A logical value specifying whether to force the constant b to equal 0. If const is TRUE or omitted, b is calculated normally. If const is FALSE, b is set equal to 0 and the m-values are adjusted to fit y = mx. A logical value specifying whether to return additional regression statistics. If stats is TRUE, LINEST returns the additional regression statistics. As a result, the returned array is {mn, mn-1 ,..., m1, b; sen ,sen-1, ..., se1, seb; r2, sey; F, df; ssreg, ssresid}. If stats is FALSE or omitted, LINEST returns only the mcoefficients and the constant b. The additional regression statistics are as given in the Table below. se1,se2,...,sen The standard error values for the coefficients m1,m2,...,mn. seb The standard error value for the constant b (seb = #N/A when const is FALSE). r2 The coefficient of determination. Compares estimated and actual yvalues, and ranges in value from 0 to 1. If it is 1, there is a perfect correlation in the sample — there is no difference between the estimated y-value and the actual y-value. At the other extreme, if the coefficient of determination is 0, the regression equation is not helpful in predicting a y-value. For information about how r2 is calculated, see Notes below. sey The standard error for the y estimate. F The F statistic, or the F-observed value. Use the F statistic to determine whether the observed relationship between the dependent and independent variables occurs by chance. df The degrees of freedom. Use the degrees of freedom to help you find F-critical values in a statistical table. Compare the values you find in the table to the F statistic returned by LINEST to determine a confidence level for the model. For information about how df is calculated, see Notes below. ssreg The regression sum of squares. ssreg The residual sum of squares. For information about how ssreg and ssresid are calculated, see Notes below. The equation for the line is − y = mx + b or y = m1x1 + m2x2 + ... + b The equation for the line is − y = mx + b or y = m1x1 + m2x2 + ... + b If there are multiple ranges of x-values, where the dependent y-values are a function of the independent x-values, then − The m-values are coefficients corresponding to each x-value, and b is a constant value. Note that y, x, and m can be vectors. If there are multiple ranges of x-values, where the dependent y-values are a function of the independent x-values, then − The m-values are coefficients corresponding to each x-value, and b is a constant value. The m-values are coefficients corresponding to each x-value, and b is a constant value. Note that y, x, and m can be vectors. Note that y, x, and m can be vectors. The array that the LINEST Function returns is {mn, mn-1... m1, b}. The array that the LINEST Function returns is {mn, mn-1... m1, b}. LINEST can also return additional regression statistics LINEST can also return additional regression statistics You can describe any straight line with the slope and the y-intercept − Slope(m) − To find the slope of a line, often written as m, take two points on the line, (x1,y1) and (x2,y2). The slope is equal to (–2 - y1)/(–2 - x1). Y-intercept(b) − The y-intercept of a line, often written as b, is the value of y at the point where the line crosses the y-axis. You can describe any straight line with the slope and the y-intercept − Slope(m) − To find the slope of a line, often written as m, take two points on the line, (x1,y1) and (x2,y2). The slope is equal to (–2 - y1)/(–2 - x1). Slope(m) − To find the slope of a line, often written as m, take two points on the line, (x1,y1) and (x2,y2). The slope is equal to (–2 - y1)/(–2 - x1). Y-intercept(b) − The y-intercept of a line, often written as b, is the value of y at the point where the line crosses the y-axis. Y-intercept(b) − The y-intercept of a line, often written as b, is the value of y at the point where the line crosses the y-axis. The equation of a straight line is y = mx + b. Once you know the values of m and b, you can calculate any point on the line by plugging the y- or x-value into that equation. You can also use the TREND Function. The equation of a straight line is y = mx + b. Once you know the values of m and b, you can calculate any point on the line by plugging the y- or x-value into that equation. You can also use the TREND Function. When you have only one independent x-variable, you can obtain the slope and yintercept values directly by using the following formulas − Slope − =INDEX (LINEST (known_y's,known_x's),1) Y-intercept − =INDEX (LINEST (known_y's,known_x's),2) When you have only one independent x-variable, you can obtain the slope and yintercept values directly by using the following formulas − Slope − =INDEX (LINEST (known_y's,known_x's),1) Slope − =INDEX (LINEST (known_y's,known_x's),1) Y-intercept − =INDEX (LINEST (known_y's,known_x's),2) Y-intercept − =INDEX (LINEST (known_y's,known_x's),2) The accuracy of the line calculated by the LINEST Function depends on the degree of scatter in your data. The more linear the data, the more accurate the LINEST model. The accuracy of the line calculated by the LINEST Function depends on the degree of scatter in your data. The more linear the data, the more accurate the LINEST model. LINEST uses the method of least squares for determining the best fit for the data. When you have only one independent x-variable, the calculations for m and b are based on the following formulas − $$m=\frac{\sum \left ( x-\bar{x} \right )\left ( y-\bar{y} \right )}{\sum \left ( x- \bar{x}\right )^2}$$ Where x and y are sample means. i.e. x = AVERAGE (known x's) y = AVERAGE (known_y's) LINEST uses the method of least squares for determining the best fit for the data. When you have only one independent x-variable, the calculations for m and b are based on the following formulas − $$m=\frac{\sum \left ( x-\bar{x} \right )\left ( y-\bar{y} \right )}{\sum \left ( x- \bar{x}\right )^2}$$ Where x and y are sample means. i.e. x = AVERAGE (known x's) y = AVERAGE (known_y's) The line and curve-fitting Functions LINEST and LOGEST can calculate the best straight line or exponential curve that fits your data. However, you have to decide which of the two results best fits your data. You can calculate TREND (known_y's,known_x's) for a straight line, or GROWTH(known_y's, known_x's) for an exponential curve. These Functions, without the known_x's argument omitted, return an array of y-values predicted along that line or curve at your actual data points. You can then compare the predicted values with the actual values. You may want to chart them both for a visual comparison. The line and curve-fitting Functions LINEST and LOGEST can calculate the best straight line or exponential curve that fits your data. However, you have to decide which of the two results best fits your data. You can calculate TREND (known_y's,known_x's) for a straight line, or GROWTH(known_y's, known_x's) for an exponential curve. These Functions, without the known_x's argument omitted, return an array of y-values predicted along that line or curve at your actual data points. You can then compare the predicted values with the actual values. You may want to chart them both for a visual comparison. In regression analysis, Excel calculates for each point the squared difference between the y-value estimated for that point and its actual y-value. The sum of these squared differences is called the residual sum of squares, ssresid. Excel then calculates the total sum of squares, sstotal. When the const argument = TRUE or is omitted, the total sum of squares is the sum of the squared differences between the actual y-values and the average of the y-values. In regression analysis, Excel calculates for each point the squared difference between the y-value estimated for that point and its actual y-value. The sum of these squared differences is called the residual sum of squares, ssresid. Excel then calculates the total sum of squares, sstotal. When the const argument = TRUE or is omitted, the total sum of squares is the sum of the squared differences between the actual y-values and the average of the y-values. When the const argument = FALSE, the total sum of squares is the sum of the squares of the actual y-values (without subtracting the average y-value from each individual y-value). Then regression sum of squares, ssreg, can be found from: ssreg = sstotal - ssresid. The smaller the residual sum of squares is, compared with the total sum of squares, the larger the value of the coefficient of determination, r2, which is an indicator of how well the equation resulting from the regression analysis explains the relationship among the variables. The value of r2 equals ssreg/sstotal. When the const argument = FALSE, the total sum of squares is the sum of the squares of the actual y-values (without subtracting the average y-value from each individual y-value). Then regression sum of squares, ssreg, can be found from: ssreg = sstotal - ssresid. The smaller the residual sum of squares is, compared with the total sum of squares, the larger the value of the coefficient of determination, r2, which is an indicator of how well the equation resulting from the regression analysis explains the relationship among the variables. The value of r2 equals ssreg/sstotal. In some cases, one or more of the X columns (assume that Y’s and X’s are in columns) may have no additional predictive value in the presence of the other X columns. i.e., eliminating one or more X columns might lead to predicted Y values that are equally accurate. In that case these redundant X columns should be omitted from the regression model. This phenomenon is called “collinearity” because any redundant X column can be expressed as a sum of multiples of the non-redundant X columns. In some cases, one or more of the X columns (assume that Y’s and X’s are in columns) may have no additional predictive value in the presence of the other X columns. i.e., eliminating one or more X columns might lead to predicted Y values that are equally accurate. In that case these redundant X columns should be omitted from the regression model. This phenomenon is called “collinearity” because any redundant X column can be expressed as a sum of multiples of the non-redundant X columns. The LINEST Function checks for collinearity and removes any redundant X columns from the regression model when it identifies them. Removed X columns can be recognized in LINEST output as having 0 coefficients in addition to 0 se values. If one or more columns are removed as redundant, df is affected because df depends on the number of X columns actually used for predictive purposes. The LINEST Function checks for collinearity and removes any redundant X columns from the regression model when it identifies them. Removed X columns can be recognized in LINEST output as having 0 coefficients in addition to 0 se values. If one or more columns are removed as redundant, df is affected because df depends on the number of X columns actually used for predictive purposes. If df is changed because redundant X columns are removed, values of sey and F are also affected. Collinearity should be relatively rare in practice. However, one case where it is more likely to arise is when some X columns contain only 0 and 1 values as indicators of whether a subject in an experiment is or is not a member of a particular group. If const = TRUE or is omitted, the LINEST function effectively inserts an additional X column of all 1 values to model the intercept If df is changed because redundant X columns are removed, values of sey and F are also affected. Collinearity should be relatively rare in practice. However, one case where it is more likely to arise is when some X columns contain only 0 and 1 values as indicators of whether a subject in an experiment is or is not a member of a particular group. If const = TRUE or is omitted, the LINEST function effectively inserts an additional X column of all 1 values to model the intercept The value of df is calculated as follows, when there are k columns of known_x’s and no X columns are removed from the model due to collinearity − If const = TRUE or is omitted, df = n – k – 1 If const = FALSE, df = n – k In both cases, each X column that was removed due to collinearity increases the value of df by 1. The value of df is calculated as follows, when there are k columns of known_x’s and no X columns are removed from the model due to collinearity − If const = TRUE or is omitted, df = n – k – 1 If const = TRUE or is omitted, df = n – k – 1 If const = FALSE, df = n – k If const = FALSE, df = n – k In both cases, each X column that was removed due to collinearity increases the value of df by 1. When entering an array constant (such as known_x's) as an argument, use commas to separate values that are contained in the same row and semicolons to separate rows. Separator characters may be different depending on your regional settings. When entering an array constant (such as known_x's) as an argument, use commas to separate values that are contained in the same row and semicolons to separate rows. Separator characters may be different depending on your regional settings. Note that the y-values predicted by the regression equation may not be valid if they are outside the range of the y-values you used to determine the equation. Note that the y-values predicted by the regression equation may not be valid if they are outside the range of the y-values you used to determine the equation. The underlying algorithm used in the LINEST function is different than the underlying algorithm used in the SLOPE and INTERCEPT functions. The difference between these algorithms can lead to different results when data is undetermined and collinear. The underlying algorithm used in the LINEST function is different than the underlying algorithm used in the SLOPE and INTERCEPT functions. The difference between these algorithms can lead to different results when data is undetermined and collinear. In addition to using LOGEST to calculate statistics for other regression types, you can use LINEST to calculate a range of other regression types by entering functions of the x and y variables as the x and y series for LINEST. For example, the following formula − =LINEST (yvalues, xvalues^COLUMN($A:$C)) Works when you have a single column of y-values and a single column of x-values to calculate the cubic (polynomial of order 3) approximation of the − y = m1*x + m2*x^2 + m3*x*3 + b You can adjust this formula to calculate other types of regression, but in some cases it requires the adjustment of the output values and other statistics. In addition to using LOGEST to calculate statistics for other regression types, you can use LINEST to calculate a range of other regression types by entering functions of the x and y variables as the x and y series for LINEST. For example, the following formula − =LINEST (yvalues, xvalues^COLUMN($A:$C)) Works when you have a single column of y-values and a single column of x-values to calculate the cubic (polynomial of order 3) approximation of the − y = m1*x + m2*x^2 + m3*x*3 + b You can adjust this formula to calculate other types of regression, but in some cases it requires the adjustment of the output values and other statistics. The F-test value that is returned by the LINEST Function differs from the F-test value that is returned by the FTEST Function. LINEST returns the F statistic, whereas FTEST returns the probability. The F-test value that is returned by the LINEST Function differs from the F-test value that is returned by the FTEST Function. LINEST returns the F statistic, whereas FTEST returns the probability. If the array of known_x's is not the same length as the array of known_y's, LINEST returns the #REF! error value. If the array of known_x's is not the same length as the array of known_y's, LINEST returns the #REF! error value. If any of the values in the supplied known_x's or known_y's arrays are not numeric (this may include text representations of numbers, as the LINEST Function does not recognize these as numbers), LINEST returns the #VALUE! error value. If any of the values in the supplied known_x's or known_y's arrays are not numeric (this may include text representations of numbers, as the LINEST Function does not recognize these as numbers), LINEST returns the #VALUE! error value. If either of the const or stats arguments cannot be evaluated to TRUE or FALSE, LINEST returns the #VALUE! error value. If either of the const or stats arguments cannot be evaluated to TRUE or FALSE, LINEST returns the #VALUE! error value. Excel 2007, Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2053, "s": 1854, "text": "The LINEST function calculates the statistics for a line by using the \"least squares\" method to calculate a straight line that best fits your data, and then returns an array that describes the line." }, { "code": null, "e": 2265, "s": 2053, "text": "You can also combine LINEST with other functions to calculate the statistics for other types of models that are linear in the unknown parameters, including polynomial, logarithmic, exponential, and power series." }, { "code": null, "e": 2354, "s": 2265, "text": "Since this function returns an array of values, it must be entered as an array formula. " }, { "code": null, "e": 2405, "s": 2354, "text": "LINEST (known_y's, [known_x's], [const], [stats])\n" }, { "code": null, "e": 2479, "s": 2405, "text": "The set of y-values that you already know in the relationship y = mx + b." }, { "code": null, "e": 2592, "s": 2479, "text": "If the range of known_y's is in a single column, each column of known_x's is interpreted as a separate variable." }, { "code": null, "e": 2709, "s": 2592, "text": "If the range of known_y's is contained in a single row, each row of known_x's is interpreted as a separate variable." }, { "code": null, "e": 2785, "s": 2709, "text": "A set of x-values that you may already know in the relationship y = mx + b." }, { "code": null, "e": 2851, "s": 2785, "text": "The range of known_x's can include one or more sets of variables." }, { "code": null, "e": 2972, "s": 2851, "text": "If only one variable is used, known_y's and known_x's can be ranges of any shape, as long as they have equal dimensions." }, { "code": null, "e": 3104, "s": 2972, "text": "If more than one variable is used, known_y's must be a vector (that is, a range with a height of one row or a width of one column)." }, { "code": null, "e": 3207, "s": 3104, "text": "If known_x's is omitted, it is assumed to be the array {1,2,3,...} that is the same size as known_y's." }, { "code": null, "e": 3278, "s": 3207, "text": "A logical value specifying whether to force the constant b to equal 0." }, { "code": null, "e": 3333, "s": 3278, "text": "If const is TRUE or omitted, b is calculated normally." }, { "code": null, "e": 3417, "s": 3333, "text": "If const is FALSE, b is set equal to 0 and the m-values are adjusted to fit y = mx." }, { "code": null, "e": 3496, "s": 3417, "text": "A logical value specifying whether to return additional regression statistics." }, { "code": null, "e": 3685, "s": 3496, "text": "If stats is TRUE, LINEST returns the additional regression statistics. As a result, the returned array is {mn, mn-1 ,..., m1, b; sen ,sen-1, ..., se1, seb; r2, sey; F, df; ssreg, ssresid}." }, { "code": null, "e": 3843, "s": 3685, "text": "If stats is FALSE or omitted, LINEST returns only the mcoefficients and the constant b. The additional regression statistics are as given in the Table below." }, { "code": null, "e": 3859, "s": 3843, "text": "se1,se2,...,sen" }, { "code": null, "e": 3920, "s": 3859, "text": "The standard error values for the coefficients m1,m2,...,mn." }, { "code": null, "e": 3924, "s": 3920, "text": "seb" }, { "code": null, "e": 4002, "s": 3924, "text": "The standard error value for the constant b (seb = #N/A when const is FALSE)." }, { "code": null, "e": 4005, "s": 4002, "text": "r2" }, { "code": null, "e": 4436, "s": 4005, "text": "The coefficient of determination. Compares estimated and actual yvalues, and ranges in value from 0 to 1. If it is 1, there is a perfect correlation in the sample — there is no difference between the estimated y-value and the actual y-value. At the other extreme, if the coefficient of determination is 0, the regression equation is not helpful in predicting a y-value. For information about how r2 is calculated, see Notes below." }, { "code": null, "e": 4440, "s": 4436, "text": "sey" }, { "code": null, "e": 4479, "s": 4440, "text": "The standard error for the y estimate." }, { "code": null, "e": 4481, "s": 4479, "text": "F" }, { "code": null, "e": 4656, "s": 4481, "text": "The F statistic, or the F-observed value. Use the F statistic to determine whether the observed relationship between the dependent and independent variables occurs by chance." }, { "code": null, "e": 4659, "s": 4656, "text": "df" }, { "code": null, "e": 4956, "s": 4659, "text": "The degrees of freedom. Use the degrees of freedom to help you find F-critical values in a statistical table. Compare the values you find in the table to the F statistic returned by LINEST to determine a confidence level for the model. For information about how df is calculated, see Notes below." }, { "code": null, "e": 4962, "s": 4956, "text": "ssreg" }, { "code": null, "e": 4993, "s": 4962, "text": "The regression sum of squares." }, { "code": null, "e": 4999, "s": 4993, "text": "ssreg" }, { "code": null, "e": 5105, "s": 4999, "text": "The residual sum of squares. For information about how ssreg and ssresid are calculated, see Notes below." }, { "code": null, "e": 5177, "s": 5105, "text": "The equation for the line is −\ny = mx + b\nor\ny = m1x1 + m2x2 + ... + b\n" }, { "code": null, "e": 5208, "s": 5177, "text": "The equation for the line is −" }, { "code": null, "e": 5219, "s": 5208, "text": "y = mx + b" }, { "code": null, "e": 5222, "s": 5219, "text": "or" }, { "code": null, "e": 5248, "s": 5222, "text": "y = m1x1 + m2x2 + ... + b" }, { "code": null, "e": 5499, "s": 5248, "text": "If there are multiple ranges of x-values, where the dependent y-values are a function of the independent x-values, then −\n\nThe m-values are coefficients corresponding to each x-value, and b is a constant value.\nNote that y, x, and m can be vectors.\n\n" }, { "code": null, "e": 5621, "s": 5499, "text": "If there are multiple ranges of x-values, where the dependent y-values are a function of the independent x-values, then −" }, { "code": null, "e": 5709, "s": 5621, "text": "The m-values are coefficients corresponding to each x-value, and b is a constant value." }, { "code": null, "e": 5797, "s": 5709, "text": "The m-values are coefficients corresponding to each x-value, and b is a constant value." }, { "code": null, "e": 5835, "s": 5797, "text": "Note that y, x, and m can be vectors." }, { "code": null, "e": 5873, "s": 5835, "text": "Note that y, x, and m can be vectors." }, { "code": null, "e": 5940, "s": 5873, "text": "The array that the LINEST Function returns is {mn, mn-1... m1, b}." }, { "code": null, "e": 6007, "s": 5940, "text": "The array that the LINEST Function returns is {mn, mn-1... m1, b}." }, { "code": null, "e": 6063, "s": 6007, "text": "LINEST can also return additional regression statistics" }, { "code": null, "e": 6119, "s": 6063, "text": "LINEST can also return additional regression statistics" }, { "code": null, "e": 6478, "s": 6119, "text": "You can describe any straight line with the slope and the y-intercept −\n\nSlope(m) −\nTo find the slope of a line, often written as m, take two points on the line, (x1,y1) and (x2,y2). The slope is equal to\n(–2 - y1)/(–2 - x1).\nY-intercept(b) −\nThe y-intercept of a line, often written as b, is the value of y at the point where the line crosses the y-axis.\n\n\n" }, { "code": null, "e": 6550, "s": 6478, "text": "You can describe any straight line with the slope and the y-intercept −" }, { "code": null, "e": 6703, "s": 6550, "text": "Slope(m) −\nTo find the slope of a line, often written as m, take two points on the line, (x1,y1) and (x2,y2). The slope is equal to\n(–2 - y1)/(–2 - x1)." }, { "code": null, "e": 6714, "s": 6703, "text": "Slope(m) −" }, { "code": null, "e": 6835, "s": 6714, "text": "To find the slope of a line, often written as m, take two points on the line, (x1,y1) and (x2,y2). The slope is equal to" }, { "code": null, "e": 6856, "s": 6835, "text": "(–2 - y1)/(–2 - x1)." }, { "code": null, "e": 6987, "s": 6856, "text": "Y-intercept(b) −\nThe y-intercept of a line, often written as b, is the value of y at the point where the line crosses the y-axis.\n" }, { "code": null, "e": 7004, "s": 6987, "text": "Y-intercept(b) −" }, { "code": null, "e": 7117, "s": 7004, "text": "The y-intercept of a line, often written as b, is the value of y at the point where the line crosses the y-axis." }, { "code": null, "e": 7328, "s": 7117, "text": "The equation of a straight line is y = mx + b. Once you know the values of m and b, you can calculate any point on the line by plugging the y- or x-value into that equation. You can also use the TREND Function." }, { "code": null, "e": 7539, "s": 7328, "text": "The equation of a straight line is y = mx + b. Once you know the values of m and b, you can calculate any point on the line by plugging the y- or x-value into that equation. You can also use the TREND Function." }, { "code": null, "e": 7782, "s": 7539, "text": "When you have only one independent x-variable, you can obtain the slope and yintercept values directly by using the following formulas −\n\nSlope −\n=INDEX (LINEST (known_y's,known_x's),1)\n\nY-intercept −\n=INDEX (LINEST (known_y's,known_x's),2)\n\n" }, { "code": null, "e": 7919, "s": 7782, "text": "When you have only one independent x-variable, you can obtain the slope and yintercept values directly by using the following formulas −" }, { "code": null, "e": 7968, "s": 7919, "text": "Slope −\n=INDEX (LINEST (known_y's,known_x's),1)\n" }, { "code": null, "e": 7976, "s": 7968, "text": "Slope −" }, { "code": null, "e": 8016, "s": 7976, "text": "=INDEX (LINEST (known_y's,known_x's),1)" }, { "code": null, "e": 8071, "s": 8016, "text": "Y-intercept −\n=INDEX (LINEST (known_y's,known_x's),2)\n" }, { "code": null, "e": 8085, "s": 8071, "text": "Y-intercept −" }, { "code": null, "e": 8125, "s": 8085, "text": "=INDEX (LINEST (known_y's,known_x's),2)" }, { "code": null, "e": 8293, "s": 8125, "text": "The accuracy of the line calculated by the LINEST Function depends on the degree of scatter in your data. The more linear the data, the more accurate the LINEST model." }, { "code": null, "e": 8461, "s": 8293, "text": "The accuracy of the line calculated by the LINEST Function depends on the degree of scatter in your data. The more linear the data, the more accurate the LINEST model." }, { "code": null, "e": 8850, "s": 8461, "text": "LINEST uses the method of least squares for determining the best fit for the data. When you have only one independent x-variable, the calculations for m and b are based on the following formulas −\n$$m=\\frac{\\sum \\left ( x-\\bar{x} \\right )\\left ( y-\\bar{y} \\right )}{\\sum \\left ( x- \\bar{x}\\right )^2}$$\nWhere x and y are sample means. i.e.\nx = AVERAGE (known x's)\ny = AVERAGE (known_y's)\n" }, { "code": null, "e": 9047, "s": 8850, "text": "LINEST uses the method of least squares for determining the best fit for the data. When you have only one independent x-variable, the calculations for m and b are based on the following formulas −" }, { "code": null, "e": 9153, "s": 9047, "text": "$$m=\\frac{\\sum \\left ( x-\\bar{x} \\right )\\left ( y-\\bar{y} \\right )}{\\sum \\left ( x- \\bar{x}\\right )^2}$$" }, { "code": null, "e": 9190, "s": 9153, "text": "Where x and y are sample means. i.e." }, { "code": null, "e": 9214, "s": 9190, "text": "x = AVERAGE (known x's)" }, { "code": null, "e": 9238, "s": 9214, "text": "y = AVERAGE (known_y's)" }, { "code": null, "e": 9842, "s": 9238, "text": "The line and curve-fitting Functions LINEST and LOGEST can calculate the best straight line or exponential curve that fits your data. However, you have to decide which of the two results best fits your data. You can calculate TREND (known_y's,known_x's) for a straight line, or GROWTH(known_y's, known_x's) for an exponential curve. These Functions, without the known_x's argument omitted, return an array of y-values predicted along that line or curve at your actual data points. You can then compare the predicted values with the actual values. You may want to chart them both for a visual comparison." }, { "code": null, "e": 10446, "s": 9842, "text": "The line and curve-fitting Functions LINEST and LOGEST can calculate the best straight line or exponential curve that fits your data. However, you have to decide which of the two results best fits your data. You can calculate TREND (known_y's,known_x's) for a straight line, or GROWTH(known_y's, known_x's) for an exponential curve. These Functions, without the known_x's argument omitted, return an array of y-values predicted along that line or curve at your actual data points. You can then compare the predicted values with the actual values. You may want to chart them both for a visual comparison." }, { "code": null, "e": 10906, "s": 10446, "text": "In regression analysis, Excel calculates for each point the squared difference between the y-value estimated for that point and its actual y-value. The sum of these squared differences is called the residual sum of squares, ssresid. Excel then calculates the total sum of squares, sstotal. When the const argument = TRUE or is omitted, the total sum of squares is the sum of the squared differences between the actual y-values and the average of the y-values." }, { "code": null, "e": 11366, "s": 10906, "text": "In regression analysis, Excel calculates for each point the squared difference between the y-value estimated for that point and its actual y-value. The sum of these squared differences is called the residual sum of squares, ssresid. Excel then calculates the total sum of squares, sstotal. When the const argument = TRUE or is omitted, the total sum of squares is the sum of the squared differences between the actual y-values and the average of the y-values." }, { "code": null, "e": 11947, "s": 11366, "text": "When the const argument = FALSE, the total sum of squares is the sum of the squares of the actual y-values (without subtracting the average y-value from each individual y-value). Then regression sum of squares, ssreg, can be found from: ssreg = sstotal - ssresid. The smaller the residual sum of squares is, compared with the total sum of squares, the larger the value of the coefficient of determination, r2, which is an indicator of how well the equation resulting from the regression analysis explains the relationship among the variables. The value of r2 equals ssreg/sstotal." }, { "code": null, "e": 12528, "s": 11947, "text": "When the const argument = FALSE, the total sum of squares is the sum of the squares of the actual y-values (without subtracting the average y-value from each individual y-value). Then regression sum of squares, ssreg, can be found from: ssreg = sstotal - ssresid. The smaller the residual sum of squares is, compared with the total sum of squares, the larger the value of the coefficient of determination, r2, which is an indicator of how well the equation resulting from the regression analysis explains the relationship among the variables. The value of r2 equals ssreg/sstotal." }, { "code": null, "e": 13020, "s": 12528, "text": "In some cases, one or more of the X columns (assume that Y’s and X’s are in columns) may have no additional predictive value in the presence of the other X columns. i.e., eliminating one or more X columns might lead to predicted Y values that are equally accurate. In that case these redundant X columns should be omitted from the regression model. This phenomenon is called “collinearity” because any redundant X column can be expressed as a sum of multiples of the non-redundant X columns." }, { "code": null, "e": 13512, "s": 13020, "text": "In some cases, one or more of the X columns (assume that Y’s and X’s are in columns) may have no additional predictive value in the presence of the other X columns. i.e., eliminating one or more X columns might lead to predicted Y values that are equally accurate. In that case these redundant X columns should be omitted from the regression model. This phenomenon is called “collinearity” because any redundant X column can be expressed as a sum of multiples of the non-redundant X columns." }, { "code": null, "e": 13898, "s": 13512, "text": "The LINEST Function checks for collinearity and removes any redundant X columns from the regression model when it identifies them. Removed X columns can be recognized in LINEST output as having 0 coefficients in addition to 0 se values. If one or more columns are removed as redundant, df is affected because df depends on the number of X columns actually used for predictive purposes." }, { "code": null, "e": 14284, "s": 13898, "text": "The LINEST Function checks for collinearity and removes any redundant X columns from the regression model when it identifies them. Removed X columns can be recognized in LINEST output as having 0 coefficients in addition to 0 se values. If one or more columns are removed as redundant, df is affected because df depends on the number of X columns actually used for predictive purposes." }, { "code": null, "e": 14765, "s": 14284, "text": "If df is changed because redundant X columns are removed, values of sey and F are also affected. Collinearity should be relatively rare in practice. However, one case where it is more likely to arise is when some X columns contain only 0 and 1 values as indicators of whether a subject in an experiment is or is not a member of a particular group. If const = TRUE or is omitted, the LINEST function effectively inserts an additional X column of all 1 values to model the intercept" }, { "code": null, "e": 15246, "s": 14765, "text": "If df is changed because redundant X columns are removed, values of sey and F are also affected. Collinearity should be relatively rare in practice. However, one case where it is more likely to arise is when some X columns contain only 0 and 1 values as indicators of whether a subject in an experiment is or is not a member of a particular group. If const = TRUE or is omitted, the LINEST function effectively inserts an additional X column of all 1 values to model the intercept" }, { "code": null, "e": 15568, "s": 15246, "text": "The value of df is calculated as follows, when there are k columns of known_x’s and no X columns are removed from the model due to collinearity −\n\nIf const = TRUE or is omitted, df = n – k – 1\nIf const = FALSE, df = n – k\n\nIn both cases, each X column that was removed due to collinearity increases the value of df by 1.\n" }, { "code": null, "e": 15714, "s": 15568, "text": "The value of df is calculated as follows, when there are k columns of known_x’s and no X columns are removed from the model due to collinearity −" }, { "code": null, "e": 15760, "s": 15714, "text": "If const = TRUE or is omitted, df = n – k – 1" }, { "code": null, "e": 15806, "s": 15760, "text": "If const = TRUE or is omitted, df = n – k – 1" }, { "code": null, "e": 15835, "s": 15806, "text": "If const = FALSE, df = n – k" }, { "code": null, "e": 15864, "s": 15835, "text": "If const = FALSE, df = n – k" }, { "code": null, "e": 15962, "s": 15864, "text": "In both cases, each X column that was removed due to collinearity increases the value of df by 1." }, { "code": null, "e": 16203, "s": 15962, "text": "When entering an array constant (such as known_x's) as an argument, use commas to separate values that are contained in the same row and semicolons to separate rows. Separator characters may be different depending on your regional settings." }, { "code": null, "e": 16444, "s": 16203, "text": "When entering an array constant (such as known_x's) as an argument, use commas to separate values that are contained in the same row and semicolons to separate rows. Separator characters may be different depending on your regional settings." }, { "code": null, "e": 16603, "s": 16444, "text": "Note that the y-values predicted by the regression equation may not be valid if they are outside the range of the y-values you used to determine the equation." }, { "code": null, "e": 16762, "s": 16603, "text": "Note that the y-values predicted by the regression equation may not be valid if they are outside the range of the y-values you used to determine the equation." }, { "code": null, "e": 17012, "s": 16762, "text": "The underlying algorithm used in the LINEST function is different than the underlying algorithm used in the SLOPE and INTERCEPT functions. The difference between these algorithms can lead to different results when data is undetermined and collinear." }, { "code": null, "e": 17262, "s": 17012, "text": "The underlying algorithm used in the LINEST function is different than the underlying algorithm used in the SLOPE and INTERCEPT functions. The difference between these algorithms can lead to different results when data is undetermined and collinear." }, { "code": null, "e": 17906, "s": 17262, "text": "In addition to using LOGEST to calculate statistics for other regression types, you can use LINEST to calculate a range of other regression types by entering functions of the x and y variables as the x and y series for LINEST. For example, the following formula −\n=LINEST (yvalues, xvalues^COLUMN($A:$C))\nWorks when you have a single column of y-values and a single column of x-values to calculate the cubic (polynomial of order 3) approximation of the −\ny = m1*x + m2*x^2 + m3*x*3 + b\nYou can adjust this formula to calculate other types of regression, but in some cases it requires the adjustment of the output values and other statistics.\n" }, { "code": null, "e": 18170, "s": 17906, "text": "In addition to using LOGEST to calculate statistics for other regression types, you can use LINEST to calculate a range of other regression types by entering functions of the x and y variables as the x and y series for LINEST. For example, the following formula −" }, { "code": null, "e": 18211, "s": 18170, "text": "=LINEST (yvalues, xvalues^COLUMN($A:$C))" }, { "code": null, "e": 18362, "s": 18211, "text": "Works when you have a single column of y-values and a single column of x-values to calculate the cubic (polynomial of order 3) approximation of the −" }, { "code": null, "e": 18393, "s": 18362, "text": "y = m1*x + m2*x^2 + m3*x*3 + b" }, { "code": null, "e": 18549, "s": 18393, "text": "You can adjust this formula to calculate other types of regression, but in some cases it requires the adjustment of the output values and other statistics." }, { "code": null, "e": 18747, "s": 18549, "text": "The F-test value that is returned by the LINEST Function differs from the F-test value that is returned by the FTEST Function. LINEST returns the F statistic, whereas FTEST returns the probability." }, { "code": null, "e": 18945, "s": 18747, "text": "The F-test value that is returned by the LINEST Function differs from the F-test value that is returned by the FTEST Function. LINEST returns the F statistic, whereas FTEST returns the probability." }, { "code": null, "e": 19059, "s": 18945, "text": "If the array of known_x's is not the same length as the array of known_y's, LINEST returns the #REF! error value." }, { "code": null, "e": 19173, "s": 19059, "text": "If the array of known_x's is not the same length as the array of known_y's, LINEST returns the #REF! error value." }, { "code": null, "e": 19408, "s": 19173, "text": "If any of the values in the supplied known_x's or known_y's arrays are not numeric (this may include text representations of numbers, as the LINEST Function does not recognize these as numbers), LINEST returns the #VALUE! error value." }, { "code": null, "e": 19643, "s": 19408, "text": "If any of the values in the supplied known_x's or known_y's arrays are not numeric (this may include text representations of numbers, as the LINEST Function does not recognize these as numbers), LINEST returns the #VALUE! error value." }, { "code": null, "e": 19763, "s": 19643, "text": "If either of the const or stats arguments cannot be evaluated to TRUE or FALSE, LINEST returns the #VALUE! error value." }, { "code": null, "e": 19883, "s": 19763, "text": "If either of the const or stats arguments cannot be evaluated to TRUE or FALSE, LINEST returns the #VALUE! error value." }, { "code": null, "e": 19930, "s": 19883, "text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 19966, "s": 19930, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 19980, "s": 19966, "text": " Arun Motoori" }, { "code": null, "e": 20015, "s": 19980, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 20030, "s": 20015, "text": " Pavan Lalwani" }, { "code": null, "e": 20066, "s": 20030, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 20075, "s": 20066, "text": " Inf Sid" }, { "code": null, "e": 20111, "s": 20075, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 20126, "s": 20111, "text": " Yoda Learning" }, { "code": null, "e": 20161, "s": 20126, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 20176, "s": 20161, "text": " William Fiset" }, { "code": null, "e": 20211, "s": 20176, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 20225, "s": 20211, "text": " Sasha Miller" }, { "code": null, "e": 20232, "s": 20225, "text": " Print" }, { "code": null, "e": 20243, "s": 20232, "text": " Add Notes" } ]
Best Data Visualization Project for beginners | Towards Data Science
People often tend to travel from one location to another location and explore new things, and in their journey, they need to know all the popular places around them so that they don’t miss out on any. So this application is for those people who need to know all the densely populated areas around them. Input to this model is your current location and the radius of the search for which you need the recommended places. We use FourSquare API, that gives all the popular places around a given location and python to visualize this stuff. To build this application we take the help of FourSquare API, so you need to have a developer account in the FourSquare Developer portal, don't worry it's free to use. Here is how you can get the FourSquare API credentials Visit the FourSquare Developer website.Create an account, it is free to use (you can find step by step guide here)So finally you will be having a CLIENT ID and CLIENT SECRET credentials with you, that will be used in further steps. Visit the FourSquare Developer website. Create an account, it is free to use (you can find step by step guide here) So finally you will be having a CLIENT ID and CLIENT SECRET credentials with you, that will be used in further steps. So to explore a location we use this URL provided by the FourSquare API https://api.foursquare.com/v2/venues/explore?client_id={CLIENT ID}&client_secret={CLIENT SECRET}&ll={Latitude},{Longitude}&v={VERSION}&radius={RADIUS}&limit={LIMIT} Client ID and Client Secret you will get it from your FourSquare Developer account.Latitude and Longitude are your current location coordinates, you can get these using python geopy library, which converts location to coordinates.Radius is one of the inputs given by the user.LIMIT is the number of results you want to fetch from API Client ID and Client Secret you will get it from your FourSquare Developer account. Latitude and Longitude are your current location coordinates, you can get these using python geopy library, which converts location to coordinates. Radius is one of the inputs given by the user. LIMIT is the number of results you want to fetch from API Now we are ready with our requirements so let's start coding... A raw data is fetched from FourSquare API as shown below finally! our data is ready to be visualized, have a look at it... Hurray! we made it, here is our final output which depicts Name of the locationWhat is the category, it is famous forAddress of the locationDistance from current location Name of the location What is the category, it is famous for Address of the location Distance from current location Note: Red marker shows the current location, whereas blue markers show the famous locations nearby We created a FourSquare API account and got our unique credentials.We converted the address provided by a user to the location coordinates.We fetched data from FourSquare API and converted it to a data frame.Finally visualized the data frame on the map. We created a FourSquare API account and got our unique credentials. We converted the address provided by a user to the location coordinates. We fetched data from FourSquare API and converted it to a data frame. Finally visualized the data frame on the map. This article shows the best and smart way to find all the popular locations near to you and this can be one of the best ways to start the data science projects for the beginners. you can get full source code here
[ { "code": null, "e": 475, "s": 172, "text": "People often tend to travel from one location to another location and explore new things, and in their journey, they need to know all the popular places around them so that they don’t miss out on any. So this application is for those people who need to know all the densely populated areas around them." }, { "code": null, "e": 709, "s": 475, "text": "Input to this model is your current location and the radius of the search for which you need the recommended places. We use FourSquare API, that gives all the popular places around a given location and python to visualize this stuff." }, { "code": null, "e": 877, "s": 709, "text": "To build this application we take the help of FourSquare API, so you need to have a developer account in the FourSquare Developer portal, don't worry it's free to use." }, { "code": null, "e": 932, "s": 877, "text": "Here is how you can get the FourSquare API credentials" }, { "code": null, "e": 1164, "s": 932, "text": "Visit the FourSquare Developer website.Create an account, it is free to use (you can find step by step guide here)So finally you will be having a CLIENT ID and CLIENT SECRET credentials with you, that will be used in further steps." }, { "code": null, "e": 1204, "s": 1164, "text": "Visit the FourSquare Developer website." }, { "code": null, "e": 1280, "s": 1204, "text": "Create an account, it is free to use (you can find step by step guide here)" }, { "code": null, "e": 1398, "s": 1280, "text": "So finally you will be having a CLIENT ID and CLIENT SECRET credentials with you, that will be used in further steps." }, { "code": null, "e": 1470, "s": 1398, "text": "So to explore a location we use this URL provided by the FourSquare API" }, { "code": null, "e": 1635, "s": 1470, "text": "https://api.foursquare.com/v2/venues/explore?client_id={CLIENT ID}&client_secret={CLIENT SECRET}&ll={Latitude},{Longitude}&v={VERSION}&radius={RADIUS}&limit={LIMIT}" }, { "code": null, "e": 1969, "s": 1635, "text": "Client ID and Client Secret you will get it from your FourSquare Developer account.Latitude and Longitude are your current location coordinates, you can get these using python geopy library, which converts location to coordinates.Radius is one of the inputs given by the user.LIMIT is the number of results you want to fetch from API" }, { "code": null, "e": 2053, "s": 1969, "text": "Client ID and Client Secret you will get it from your FourSquare Developer account." }, { "code": null, "e": 2201, "s": 2053, "text": "Latitude and Longitude are your current location coordinates, you can get these using python geopy library, which converts location to coordinates." }, { "code": null, "e": 2248, "s": 2201, "text": "Radius is one of the inputs given by the user." }, { "code": null, "e": 2306, "s": 2248, "text": "LIMIT is the number of results you want to fetch from API" }, { "code": null, "e": 2370, "s": 2306, "text": "Now we are ready with our requirements so let's start coding..." }, { "code": null, "e": 2427, "s": 2370, "text": "A raw data is fetched from FourSquare API as shown below" }, { "code": null, "e": 2493, "s": 2427, "text": "finally! our data is ready to be visualized, have a look at it..." }, { "code": null, "e": 2552, "s": 2493, "text": "Hurray! we made it, here is our final output which depicts" }, { "code": null, "e": 2664, "s": 2552, "text": "Name of the locationWhat is the category, it is famous forAddress of the locationDistance from current location" }, { "code": null, "e": 2685, "s": 2664, "text": "Name of the location" }, { "code": null, "e": 2724, "s": 2685, "text": "What is the category, it is famous for" }, { "code": null, "e": 2748, "s": 2724, "text": "Address of the location" }, { "code": null, "e": 2779, "s": 2748, "text": "Distance from current location" }, { "code": null, "e": 2878, "s": 2779, "text": "Note: Red marker shows the current location, whereas blue markers show the famous locations nearby" }, { "code": null, "e": 3132, "s": 2878, "text": "We created a FourSquare API account and got our unique credentials.We converted the address provided by a user to the location coordinates.We fetched data from FourSquare API and converted it to a data frame.Finally visualized the data frame on the map." }, { "code": null, "e": 3200, "s": 3132, "text": "We created a FourSquare API account and got our unique credentials." }, { "code": null, "e": 3273, "s": 3200, "text": "We converted the address provided by a user to the location coordinates." }, { "code": null, "e": 3343, "s": 3273, "text": "We fetched data from FourSquare API and converted it to a data frame." }, { "code": null, "e": 3389, "s": 3343, "text": "Finally visualized the data frame on the map." }, { "code": null, "e": 3568, "s": 3389, "text": "This article shows the best and smart way to find all the popular locations near to you and this can be one of the best ways to start the data science projects for the beginners." } ]
What is ternary operator (? X : Y) in C++?
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows − The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing. If the first operand evaluates to true (1), the second operand is evaluated. If the first operand evaluates to false (0), the third operand is evaluated. The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression. The evaluation of the conditional operator is very complex. The steps above were just a quick intro to it. Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third operands −If both operands are of the same type, the result is of that type.If both operands are of arithmetic or enumeration types, the usual arithmetic If both operands are of the same type, the result is of that type. If both operands are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Standard Conversions) are performed to convert them to a common type. If both operands are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type. If both operands are of reference types, reference conversions are performed to convert them to a common type. If both operands are of type void, the common type is type void. If both operands are of the same user-defined type, the common type is that type. If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.) #include <iostream> using namespace std; int main() { int i = 1, j = 2; cout << ( i > j ? i : j ) << " is greater." << endl; } This will give the output − 2 is greater.
[ { "code": null, "e": 1186, "s": 1062, "text": "The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows −" }, { "code": null, "e": 1307, "s": 1186, "text": "The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing." }, { "code": null, "e": 1384, "s": 1307, "text": "If the first operand evaluates to true (1), the second operand is evaluated." }, { "code": null, "e": 1461, "s": 1384, "text": "If the first operand evaluates to false (0), the third operand is evaluated." }, { "code": null, "e": 1872, "s": 1461, "text": "The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression. The evaluation of the conditional operator is very complex. The steps above were just a quick intro to it. Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. " }, { "code": null, "e": 2077, "s": 1872, "text": "The following rules apply to the second and third operands −If both operands are of the same type, the result is of that type.If both operands are of arithmetic or enumeration types, the usual arithmetic " }, { "code": null, "e": 2144, "s": 2077, "text": "If both operands are of the same type, the result is of that type." }, { "code": null, "e": 2223, "s": 2144, "text": "If both operands are of arithmetic or enumeration types, the usual arithmetic " }, { "code": null, "e": 2317, "s": 2223, "text": "conversions (covered in Standard Conversions) are performed to convert them to a common type." }, { "code": null, "e": 2511, "s": 2317, "text": "If both operands are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type." }, { "code": null, "e": 2622, "s": 2511, "text": "If both operands are of reference types, reference conversions are performed to convert them to a common type." }, { "code": null, "e": 2687, "s": 2622, "text": "If both operands are of type void, the common type is type void." }, { "code": null, "e": 2769, "s": 2687, "text": "If both operands are of the same user-defined type, the common type is that type." }, { "code": null, "e": 2945, "s": 2769, "text": "If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.)" }, { "code": null, "e": 3088, "s": 2945, "text": "#include <iostream> \nusing namespace std; \nint main() { \n int i = 1, j = 2; \n cout << ( i > j ? i : j ) << \" is greater.\" << endl; \n}" }, { "code": null, "e": 3116, "s": 3088, "text": "This will give the output −" }, { "code": null, "e": 3130, "s": 3116, "text": "2 is greater." } ]
Comparing dates in Python - GeeksforGeeks
24 May, 2018 Comparing dates is quite easy in Python. Dates can be easily compared using comparison operators (like <, >, <=, >=, != etc.). Let’s see how to compare dates with the help of datetime module using Python. Code #1 : Basic # Simple Python program to compare dates # importing datetime moduleimport datetime # date in yyyy/mm/dd formatd1 = datetime.datetime(2018, 5, 3)d2 = datetime.datetime(2018, 6, 1) # Comparing the dates will return# either True or Falseprint("d1 is greater than d2 : ", d1 > d2)print("d1 is less than d2 : ", d1 < d2)print("d1 is not equal to d2 : ", d1 != d2) Output : d1 is greater than d2 : False d1 is less than d2 : True d1 is not equal to d2 : True Code #2 : Sorting dates One of the best ways to sort a group of dates is to store them into a list and apply sort() method. This will sort all the dates which are available in the list. One can store the date class objects into the list using append() method. # Python program to sort the dates # importing datetime modulefrom datetime import * # create empty listgroup = [] # add today's dategroup.append(date.today()) # create some more datesd = date(2015, 6, 29)group.append(d) d = date(2011, 4, 7)group.append(d) # add 25 days to the date# and add to the listgroup.append(d + timedelta(days = 25)) # sort the listgroup.sort() # print the datesfor d in group: print(d) Output : 2011-04-07 2011-05-02 2015-06-29 2018-05-24 Code #3 : Comparing Dates Compare two date class objects, just like comparing two numbers. # importing datetime modulefrom datetime import * # Enter birth dates and store# into date class objectsd1, m1, y1 = [int(x) for x in input("Enter first" " person's date(DD/MM/YYYY) : ").split('/')] b1 = date(y1, m1, d1) # Input for second dated2, m2, y2 = [int(x) for x in input("Enter second" " person's date(DD/MM/YYYY) : ").split('/')] b2 = date(y2, m2, d2) # Check the datesif b1 == b2: print("Both persons are of equal age") elif b1 > b2: print("The second person is older") else: print("The first person is older") Output : Enter first person's date(DD/MM/YYYY) : 12/05/2017 Enter second person's date(DD/MM/YYYY) : 10/11/2015 The second person is older date-time-program python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs 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 sum() function in Python isupper(), islower(), lower(), upper() in Python and their applications
[ { "code": null, "e": 26103, "s": 26075, "text": "\n24 May, 2018" }, { "code": null, "e": 26308, "s": 26103, "text": "Comparing dates is quite easy in Python. Dates can be easily compared using comparison operators (like <, >, <=, >=, != etc.). Let’s see how to compare dates with the help of datetime module using Python." }, { "code": null, "e": 26324, "s": 26308, "text": "Code #1 : Basic" }, { "code": "# Simple Python program to compare dates # importing datetime moduleimport datetime # date in yyyy/mm/dd formatd1 = datetime.datetime(2018, 5, 3)d2 = datetime.datetime(2018, 6, 1) # Comparing the dates will return# either True or Falseprint(\"d1 is greater than d2 : \", d1 > d2)print(\"d1 is less than d2 : \", d1 < d2)print(\"d1 is not equal to d2 : \", d1 != d2)", "e": 26687, "s": 26324, "text": null }, { "code": null, "e": 26696, "s": 26687, "text": "Output :" }, { "code": null, "e": 26784, "s": 26696, "text": "d1 is greater than d2 : False\nd1 is less than d2 : True\nd1 is not equal to d2 : True" }, { "code": null, "e": 26809, "s": 26784, "text": " Code #2 : Sorting dates" }, { "code": null, "e": 27045, "s": 26809, "text": "One of the best ways to sort a group of dates is to store them into a list and apply sort() method. This will sort all the dates which are available in the list. One can store the date class objects into the list using append() method." }, { "code": "# Python program to sort the dates # importing datetime modulefrom datetime import * # create empty listgroup = [] # add today's dategroup.append(date.today()) # create some more datesd = date(2015, 6, 29)group.append(d) d = date(2011, 4, 7)group.append(d) # add 25 days to the date# and add to the listgroup.append(d + timedelta(days = 25)) # sort the listgroup.sort() # print the datesfor d in group: print(d) ", "e": 27473, "s": 27045, "text": null }, { "code": null, "e": 27482, "s": 27473, "text": "Output :" }, { "code": null, "e": 27526, "s": 27482, "text": "2011-04-07\n2011-05-02\n2015-06-29\n2018-05-24" }, { "code": null, "e": 27553, "s": 27526, "text": " Code #3 : Comparing Dates" }, { "code": null, "e": 27618, "s": 27553, "text": "Compare two date class objects, just like comparing two numbers." }, { "code": "# importing datetime modulefrom datetime import * # Enter birth dates and store# into date class objectsd1, m1, y1 = [int(x) for x in input(\"Enter first\" \" person's date(DD/MM/YYYY) : \").split('/')] b1 = date(y1, m1, d1) # Input for second dated2, m2, y2 = [int(x) for x in input(\"Enter second\" \" person's date(DD/MM/YYYY) : \").split('/')] b2 = date(y2, m2, d2) # Check the datesif b1 == b2: print(\"Both persons are of equal age\") elif b1 > b2: print(\"The second person is older\") else: print(\"The first person is older\")", "e": 28178, "s": 27618, "text": null }, { "code": null, "e": 28187, "s": 28178, "text": "Output :" }, { "code": null, "e": 28317, "s": 28187, "text": "Enter first person's date(DD/MM/YYYY) : 12/05/2017\nEnter second person's date(DD/MM/YYYY) : 10/11/2015\nThe second person is older" }, { "code": null, "e": 28335, "s": 28317, "text": "date-time-program" }, { "code": null, "e": 28350, "s": 28335, "text": "python-modules" }, { "code": null, "e": 28357, "s": 28350, "text": "Python" }, { "code": null, "e": 28455, "s": 28357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28487, "s": 28455, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28509, "s": 28487, "text": "Enumerate() in Python" }, { "code": null, "e": 28551, "s": 28509, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28580, "s": 28551, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28617, "s": 28580, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28659, "s": 28617, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28701, "s": 28659, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28737, "s": 28701, "text": "Convert integer to string in Python" }, { "code": null, "e": 28762, "s": 28737, "text": "sum() function in Python" } ]
Statistics - Continuous Uniform Distribution
The continuous uniform distribution is the probability distribution of random number selection from the continuous interval between a and b. Its density function is defined by the following. Here is a graph of the continuous uniform distribution with a = 1, b = 3. Problem Statement: Suppose you are leading a test and present an inquiry on the crowd of 20 contenders. The time permitted to answer the inquiry is 30 seconds. What number of persons is prone to react inside of 5 seconds? (Regularly, the contenders are required to click a catch of the right decision and the champ is picked on the premise of first snap). Solution: Step 1: The interval of the probability distribution in seconds is [0, 30]. ⇒ The probability density is = 1/30-0=1/30. Step 2: The requirement is how many will respond in 5 seconds. That is, the sub interval of the successful event is [0, 5]. Now the probability P (x < 5) is the proportion of the widths of these two interval. ⇒ 5/30=1/6. Subsequent to there are 20 contenders, the quantity of contenders prone to react in 5 seconds is (1/6) (20) =3. 40 Lectures 3.5 hours Madhu Bhatia 40 Lectures 2 hours Megha Aggarwal 66 Lectures 1.5 hours Mike West 22 Lectures 1 hours Mike West 60 Lectures 12 hours Michael Miller 65 Lectures 5 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 4588, "s": 4323, "text": "The continuous uniform distribution is the probability distribution of random number selection from the continuous interval between a and b. Its density function is defined by the following. Here is a graph of the continuous uniform distribution with a = 1, b = 3." }, { "code": null, "e": 4607, "s": 4588, "text": "Problem Statement:" }, { "code": null, "e": 4944, "s": 4607, "text": "Suppose you are leading a test and present an inquiry on the crowd of 20 contenders. The time permitted to answer the inquiry is 30 seconds. What number of persons is prone to react inside of 5 seconds? (Regularly, the contenders are required to click a catch of the right decision and the champ is picked on the premise of first snap)." }, { "code": null, "e": 4954, "s": 4944, "text": "Solution:" }, { "code": null, "e": 5030, "s": 4954, "text": "Step 1: The interval of the probability distribution in seconds is [0, 30]." }, { "code": null, "e": 5076, "s": 5030, "text": "⇒ The probability density is = 1/30-0=1/30. \n" }, { "code": null, "e": 5285, "s": 5076, "text": "Step 2: The requirement is how many will respond in 5 seconds. That is, the sub interval of the successful event is [0, 5]. Now the probability P (x < 5) is the proportion of the widths of these two interval." }, { "code": null, "e": 5299, "s": 5285, "text": "⇒ 5/30=1/6. \n" }, { "code": null, "e": 5411, "s": 5299, "text": "Subsequent to there are 20 contenders, the quantity of contenders prone to react in 5 seconds is (1/6) (20) =3." }, { "code": null, "e": 5446, "s": 5411, "text": "\n 40 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5460, "s": 5446, "text": " Madhu Bhatia" }, { "code": null, "e": 5493, "s": 5460, "text": "\n 40 Lectures \n 2 hours \n" }, { "code": null, "e": 5509, "s": 5493, "text": " Megha Aggarwal" }, { "code": null, "e": 5544, "s": 5509, "text": "\n 66 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5555, "s": 5544, "text": " Mike West" }, { "code": null, "e": 5588, "s": 5555, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 5599, "s": 5588, "text": " Mike West" }, { "code": null, "e": 5633, "s": 5599, "text": "\n 60 Lectures \n 12 hours \n" }, { "code": null, "e": 5649, "s": 5633, "text": " Michael Miller" }, { "code": null, "e": 5682, "s": 5649, "text": "\n 65 Lectures \n 5 hours \n" }, { "code": null, "e": 5699, "s": 5682, "text": " Abhilash Nelson" }, { "code": null, "e": 5706, "s": 5699, "text": " Print" }, { "code": null, "e": 5717, "s": 5706, "text": " Add Notes" } ]
How to Use SQL in Pandas. Add another relational database skill... | by Acusio Bivona | Towards Data Science
If you consider the structure of a Pandas DataFrame and the structure of a table from a SQL Database, they are structured very similarly. They both consist of data points, or values, with every row having a unique index and each column having a unique name. Because of this, SQL allows you to rapidly access the specific information you need for whatever project you are working on. But, very similar queries can be made using Pandas! In this blog post, I will show you how to do just that, along with explaining which library you’ll need to make it happen. When using SQL, obtaining the information we need is called querying the data. In Pandas, there is a built-in querying method that allows you to do the exact same thing, which is called .query(). This both saves time and makes your queries much more coherent in your code because you don’t have to use slicing syntax. For instance, a brief example to query data in Pandas using the .query() method would be: query_df = df.query("Col_1 > Col_2") Otherwise, if you didn’t use this method to obtain your data and used slicing syntax instead, it would look something like this: query_df = df[df[df['Col_1'] > df['Col_2']]] Like I said, the .query() method makes your code look more professional and more efficient. One important thing I want to note, is if/when you decide to use “and” or “or” in your Pandas query, you can’t actually use the words “and” or “or” — you have to use the symbols for “and” (&) and “or” (|) instead. Below is an example using “&” to help clarify: query_df = df.query("Col_1 > Col_2 & Col_2 <= Col_3") As is well known, the ability to use SQL and/or all of its varieties are some of the most in demand job skills on the market for data scientists — even during a pandemic. Luckily, there is a library in Python now called pandasql that allows you to write SQL-style syntax to gather data from Pandas DataFrames! This is great for both aspiring data scientists who want to practice their SQL skills and experienced data scientists who are comfortable gathering data using SQL-style syntax. To install it onto your computer, just use !pip install: !pip install pandasql Then, to import it into your notebook, you want to import a sqldf object from pandasql: from pandasql import sqldf After you’ve imported everything, it’s a good idea to write a quick lambda function that can make writing your queries easier. The reason for doing this is so that you don’t have to pass in global variables every time an object is used. Below is the lambda function that I was taught and have success with: pysqldf = lambda q: sqldf(q, globals()) Now, whenever you pass a query into pysqldf, the global variables will be passed along in the lambda so that you don’t have to do that over and over again for each object that’s used. Now that you have everything set up and ready to go, you can query data in your DataFrames using the same syntax as SQL! Here’s an example — this query will return the first 10 names from a df: q = """SELECT Name FROM df LIMIT 10;"""names = pysqldf(q)names The complexity of your queries is dependent on your needs and your skills as a data scientist. So if you’re comfortable using SQL-style syntax, or are looking to improve your SQL syntax skills, using pandasql can be a great way to continue organizing your data & practicing your skills. Thank you for reading!
[ { "code": null, "e": 730, "s": 172, "text": "If you consider the structure of a Pandas DataFrame and the structure of a table from a SQL Database, they are structured very similarly. They both consist of data points, or values, with every row having a unique index and each column having a unique name. Because of this, SQL allows you to rapidly access the specific information you need for whatever project you are working on. But, very similar queries can be made using Pandas! In this blog post, I will show you how to do just that, along with explaining which library you’ll need to make it happen." }, { "code": null, "e": 1138, "s": 730, "text": "When using SQL, obtaining the information we need is called querying the data. In Pandas, there is a built-in querying method that allows you to do the exact same thing, which is called .query(). This both saves time and makes your queries much more coherent in your code because you don’t have to use slicing syntax. For instance, a brief example to query data in Pandas using the .query() method would be:" }, { "code": null, "e": 1175, "s": 1138, "text": "query_df = df.query(\"Col_1 > Col_2\")" }, { "code": null, "e": 1304, "s": 1175, "text": "Otherwise, if you didn’t use this method to obtain your data and used slicing syntax instead, it would look something like this:" }, { "code": null, "e": 1349, "s": 1304, "text": "query_df = df[df[df['Col_1'] > df['Col_2']]]" }, { "code": null, "e": 1702, "s": 1349, "text": "Like I said, the .query() method makes your code look more professional and more efficient. One important thing I want to note, is if/when you decide to use “and” or “or” in your Pandas query, you can’t actually use the words “and” or “or” — you have to use the symbols for “and” (&) and “or” (|) instead. Below is an example using “&” to help clarify:" }, { "code": null, "e": 1756, "s": 1702, "text": "query_df = df.query(\"Col_1 > Col_2 & Col_2 <= Col_3\")" }, { "code": null, "e": 2300, "s": 1756, "text": "As is well known, the ability to use SQL and/or all of its varieties are some of the most in demand job skills on the market for data scientists — even during a pandemic. Luckily, there is a library in Python now called pandasql that allows you to write SQL-style syntax to gather data from Pandas DataFrames! This is great for both aspiring data scientists who want to practice their SQL skills and experienced data scientists who are comfortable gathering data using SQL-style syntax. To install it onto your computer, just use !pip install:" }, { "code": null, "e": 2322, "s": 2300, "text": "!pip install pandasql" }, { "code": null, "e": 2410, "s": 2322, "text": "Then, to import it into your notebook, you want to import a sqldf object from pandasql:" }, { "code": null, "e": 2437, "s": 2410, "text": "from pandasql import sqldf" }, { "code": null, "e": 2744, "s": 2437, "text": "After you’ve imported everything, it’s a good idea to write a quick lambda function that can make writing your queries easier. The reason for doing this is so that you don’t have to pass in global variables every time an object is used. Below is the lambda function that I was taught and have success with:" }, { "code": null, "e": 2784, "s": 2744, "text": "pysqldf = lambda q: sqldf(q, globals())" }, { "code": null, "e": 2968, "s": 2784, "text": "Now, whenever you pass a query into pysqldf, the global variables will be passed along in the lambda so that you don’t have to do that over and over again for each object that’s used." }, { "code": null, "e": 3162, "s": 2968, "text": "Now that you have everything set up and ready to go, you can query data in your DataFrames using the same syntax as SQL! Here’s an example — this query will return the first 10 names from a df:" }, { "code": null, "e": 3239, "s": 3162, "text": "q = \"\"\"SELECT Name FROM df LIMIT 10;\"\"\"names = pysqldf(q)names" } ]
How to make “spoiler” text in github wiki pages? - GeeksforGeeks
29 May, 2020 GitHub Wiki pages support GitHub Flavored Markdown. Read more about GitHub flavored markdown here: Mastering Markdown GitHub Flavored Markdown Spec However, there is no direct method to add a spoiler text in GitHub Flavored Markdown. But, there’s a workaround! Approach: Markdown Supports HTML Blocks in it. So, we can use HTML’s <details> and <summary> tag to create a spoiler text. The heading of the Spoiler Alert can be specified within the <summary> tag. The rest of the spoiler must be within the <details> tag. Only clicking on the “Spoiler Ahead” heading will reveal the spoiler. The text within the summary tag is the Spoiler Heading. Code, Images, Links, etc can be used following the GitHub flavored markdown, within the details tag. Example: html <!DOCTYPE html><head><head> <title> “spoiler” text in github wiki pages </title></head><body> <details> <summary>GeeksforGeeks</summary> A Computer Science Portal for Geeks </details> </body></html> Output: The <details> tag along with the <summary> tag creates the following output in markdown. Note: The Above Outputs has been directly generated from GitHub Wiki Pages markdown preview. Picked Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to execute PHP code using command line ? How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 26279, "s": 26251, "text": "\n29 May, 2020" }, { "code": null, "e": 26379, "s": 26279, "text": "GitHub Wiki pages support GitHub Flavored Markdown. Read more about GitHub flavored markdown here: " }, { "code": null, "e": 26398, "s": 26379, "text": "Mastering Markdown" }, { "code": null, "e": 26428, "s": 26398, "text": "GitHub Flavored Markdown Spec" }, { "code": null, "e": 26541, "s": 26428, "text": "However, there is no direct method to add a spoiler text in GitHub Flavored Markdown. But, there’s a workaround!" }, { "code": null, "e": 27025, "s": 26541, "text": "Approach: Markdown Supports HTML Blocks in it. So, we can use HTML’s <details> and <summary> tag to create a spoiler text. The heading of the Spoiler Alert can be specified within the <summary> tag. The rest of the spoiler must be within the <details> tag. Only clicking on the “Spoiler Ahead” heading will reveal the spoiler. The text within the summary tag is the Spoiler Heading. Code, Images, Links, etc can be used following the GitHub flavored markdown, within the details tag." }, { "code": null, "e": 27034, "s": 27025, "text": "Example:" }, { "code": null, "e": 27039, "s": 27034, "text": "html" }, { "code": "<!DOCTYPE html><head><head> <title> “spoiler” text in github wiki pages </title></head><body> <details> <summary>GeeksforGeeks</summary> A Computer Science Portal for Geeks </details> </body></html>", "e": 27280, "s": 27039, "text": null }, { "code": null, "e": 27377, "s": 27280, "text": "Output: The <details> tag along with the <summary> tag creates the following output in markdown." }, { "code": null, "e": 27470, "s": 27377, "text": "Note: The Above Outputs has been directly generated from GitHub Wiki Pages markdown preview." }, { "code": null, "e": 27477, "s": 27470, "text": "Picked" }, { "code": null, "e": 27494, "s": 27477, "text": "Web Technologies" }, { "code": null, "e": 27521, "s": 27494, "text": "Web technologies Questions" }, { "code": null, "e": 27619, "s": 27521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27659, "s": 27619, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27704, "s": 27659, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27747, "s": 27704, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27808, "s": 27747, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27880, "s": 27808, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27920, "s": 27880, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27965, "s": 27920, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 28015, "s": 27965, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28052, "s": 28015, "text": "Types of CSS (Cascading Style Sheet)" } ]
How to perform group-wise linear regression for a data frame in R?
The group−wise linear regression means creating regression model for group levels. For example, if we have a dependent variable y and the independent variable x also a grouping variable G that divides the combination of x and y into multiple groups then we can create a linear regression model for each of the group. In R, we can convert data frame to data.table object, this will help us to create the regression models easily. Live Demo Consider the below data frame − G1<−sample(LETTERS[1:4],20,replace=TRUE) x1<−rnorm(20,2,0.96) y1<−rnorm(20,5,1) df1<−data.frame(G1,x1,y1) df1 G1 x1 y1 1 C 1.2692290 3.994126 2 C 1.6317682 4.474443 3 D 1.3686734 5.444823 4 D 2.4969567 5.818360 5 C 2.3882221 3.766412 6 A 2.7568873 5.506297 7 A 2.1352764 4.548771 8 B 2.5232049 5.378314 9 A 2.8695959 4.735447 10 C −0.2317400 5.280478 11 A 1.1473469 5.064822 12 A 2.9099241 4.090654 13 A 2.4095434 6.538454 14 C 2.5310162 7.137598 15 A 2.4097431 4.778472 16 C 0.4945313 5.511772 17 C 1.3427334 5.030479 18 A 1.5200120 6.758618 19 A 2.4414779 5.854175 20 B −0.6968409 4.594522 Loading data.table package and converting data frame df1 to a data.table object − library(data.table) df1<−data.table(df1) Creating linear regression model groups defined in column G1 − df1[,as.list(coef(lm(y1 ~ x1))), by=G1] G1 (Intercept) x1 1: C 4.959098 0.05109642 2: D 4.991700 0.33106700 3: A 6.536957 -0.53189331 4: B 4.764140 0.24341026 Let’s have a look at another example − Class<−sample(c("I","II","III"),20,replace=TRUE) Ratings<−sample(1:10,20,replace=TRUE) Salary<−sample(20000:50000,20) df2<−data.frame(Class,Ratings,Salary) df2 Class Ratings Salary 1 I 4 28423 2 III 1 34728 3 II 1 26975 4 I 9 26777 5 II 6 29501 6 I 8 33061 7 II 4 43584 8 I 4 42525 9 II 9 30526 10 I 1 32872 11 I 7 21198 12 I 3 20971 13 III 9 49071 14 I 1 40314 15 III 1 36269 16 I 6 45482 17 II 1 48595 18 I 8 44054 19 I 1 25294 20 III 10 34944 df2<−data.table(df2) Creating regression models of Salary and Ratings for the three Classes − df2[,as.list(coef(lm(Salary~Ratings))),by=Class] Class (Intercept) Ratings 1: I 31894.13 194.9152 2: III 35270.10 663.4089 3: II 40405.42 -1087.9103
[ { "code": null, "e": 1491, "s": 1062, "text": "The group−wise linear regression means creating regression model for group levels. For example, if we have a dependent variable y and the independent variable x also a grouping variable G that divides the combination of x and y into multiple groups then we can create a linear regression model for each of the group. In R, we can convert data frame to data.table object, this will help us to create the regression models easily." }, { "code": null, "e": 1502, "s": 1491, "text": " Live Demo" }, { "code": null, "e": 1534, "s": 1502, "text": "Consider the below data frame −" }, { "code": null, "e": 1644, "s": 1534, "text": "G1<−sample(LETTERS[1:4],20,replace=TRUE)\nx1<−rnorm(20,2,0.96)\ny1<−rnorm(20,5,1)\ndf1<−data.frame(G1,x1,y1)\ndf1" }, { "code": null, "e": 2135, "s": 1644, "text": " G1 x1 y1\n1 C 1.2692290 3.994126\n2 C 1.6317682 4.474443\n3 D 1.3686734 5.444823\n4 D 2.4969567 5.818360\n5 C 2.3882221 3.766412\n6 A 2.7568873 5.506297\n7 A 2.1352764 4.548771\n8 B 2.5232049 5.378314\n9 A 2.8695959 4.735447\n10 C −0.2317400 5.280478\n11 A 1.1473469 5.064822\n12 A 2.9099241 4.090654\n13 A 2.4095434 6.538454\n14 C 2.5310162 7.137598\n15 A 2.4097431 4.778472\n16 C 0.4945313 5.511772\n17 C 1.3427334 5.030479\n18 A 1.5200120 6.758618\n19 A 2.4414779 5.854175\n20 B −0.6968409 4.594522" }, { "code": null, "e": 2217, "s": 2135, "text": "Loading data.table package and converting data frame df1 to a data.table object −" }, { "code": null, "e": 2258, "s": 2217, "text": "library(data.table)\ndf1<−data.table(df1)" }, { "code": null, "e": 2321, "s": 2258, "text": "Creating linear regression model groups defined in column G1 −" }, { "code": null, "e": 2361, "s": 2321, "text": "df1[,as.list(coef(lm(y1 ~ x1))), by=G1]" }, { "code": null, "e": 2483, "s": 2361, "text": " G1 (Intercept) x1\n1: C 4.959098 0.05109642\n2: D 4.991700 0.33106700\n3: A 6.536957 -0.53189331\n4: B 4.764140 0.24341026" }, { "code": null, "e": 2522, "s": 2483, "text": "Let’s have a look at another example −" }, { "code": null, "e": 2682, "s": 2522, "text": "Class<−sample(c(\"I\",\"II\",\"III\"),20,replace=TRUE)\nRatings<−sample(1:10,20,replace=TRUE)\nSalary<−sample(20000:50000,20)\ndf2<−data.frame(Class,Ratings,Salary)\ndf2" }, { "code": null, "e": 2989, "s": 2682, "text": "Class Ratings Salary\n1 I 4 28423\n2 III 1 34728\n3 II 1 26975\n4 I 9 26777\n5 II 6 29501\n6 I 8 33061\n7 II 4 43584\n8 I 4 42525\n9 II 9 30526\n10 I 1 32872\n11 I 7 21198\n12 I 3 20971\n13 III 9 49071\n14 I 1 40314\n15 III 1 36269\n16 I 6 45482\n17 II 1 48595\n18 I 8 44054\n19 I 1 25294\n20 III 10 34944\ndf2<−data.table(df2)" }, { "code": null, "e": 3062, "s": 2989, "text": "Creating regression models of Salary and Ratings for the three Classes −" }, { "code": null, "e": 3111, "s": 3062, "text": "df2[,as.list(coef(lm(Salary~Ratings))),by=Class]" }, { "code": null, "e": 3211, "s": 3111, "text": "Class (Intercept) Ratings\n1: I 31894.13 194.9152\n2: III 35270.10 663.4089\n3: II 40405.42 -1087.9103" } ]
Apply a Function over a Ragged Array in R Programming - tapply() Function - GeeksforGeeks
19 Jun, 2020 tapply() function in R Language is used to apply a function over a subset of vectors given by a combination of factors Syntax: tapply(vector, factor, fun) Parameters:vector: Created Vectorfactor: Created Factorfun: Function to be applied Example 1: # R Program to apply a function# over a data object # Creating Factorfac <- c(1, 1, 1, 1, 2, 2, 2, 3, 3) # Created Vectorvec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9) # Calling tapply() Functiontapply(vec, fac, sum) Output: 1 2 3 10 18 17 This is how above code works: Example 2: # R Program to apply a function# over a data object # Creating Factorfac <- c(1, 1, 1, 1, 2, 2, 2, 3, 3) # Created Vectorvec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9) # Calling tapply() Functiontapply(vec, fac, prod) Output: 1 2 3 24 210 72 R Array-Functions R Factor-Function R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? R - if statement How to filter R dataframe by multiple conditions? Plot mean and standard deviation using ggplot2 in R How to import an Excel File into R ?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n19 Jun, 2020" }, { "code": null, "e": 26606, "s": 26487, "text": "tapply() function in R Language is used to apply a function over a subset of vectors given by a combination of factors" }, { "code": null, "e": 26642, "s": 26606, "text": "Syntax: tapply(vector, factor, fun)" }, { "code": null, "e": 26725, "s": 26642, "text": "Parameters:vector: Created Vectorfactor: Created Factorfun: Function to be applied" }, { "code": null, "e": 26736, "s": 26725, "text": "Example 1:" }, { "code": "# R Program to apply a function# over a data object # Creating Factorfac <- c(1, 1, 1, 1, 2, 2, 2, 3, 3) # Created Vectorvec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9) # Calling tapply() Functiontapply(vec, fac, sum)", "e": 26946, "s": 26736, "text": null }, { "code": null, "e": 26954, "s": 26946, "text": "Output:" }, { "code": null, "e": 26975, "s": 26954, "text": " 1 2 3 \n10 18 17 \n" }, { "code": null, "e": 27016, "s": 26975, "text": "This is how above code works: Example 2:" }, { "code": "# R Program to apply a function# over a data object # Creating Factorfac <- c(1, 1, 1, 1, 2, 2, 2, 3, 3) # Created Vectorvec <- c(1, 2, 3, 4, 5, 6, 7, 8, 9) # Calling tapply() Functiontapply(vec, fac, prod)", "e": 27227, "s": 27016, "text": null }, { "code": null, "e": 27235, "s": 27227, "text": "Output:" }, { "code": null, "e": 27260, "s": 27235, "text": " 1 2 3 \n24 210 72 \n" }, { "code": null, "e": 27278, "s": 27260, "text": "R Array-Functions" }, { "code": null, "e": 27296, "s": 27278, "text": "R Factor-Function" }, { "code": null, "e": 27314, "s": 27296, "text": "R Vector-Function" }, { "code": null, "e": 27325, "s": 27314, "text": "R Language" }, { "code": null, "e": 27423, "s": 27325, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27475, "s": 27423, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27510, "s": 27475, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27548, "s": 27510, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27606, "s": 27548, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27649, "s": 27606, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27698, "s": 27649, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27715, "s": 27698, "text": "R - if statement" }, { "code": null, "e": 27765, "s": 27715, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27817, "s": 27765, "text": "Plot mean and standard deviation using ggplot2 in R" } ]
Fabric.js Textbox editable Property - GeeksforGeeks
20 Jan, 2021 In this article, we are going to see how to set the edit mode of a Textbox canvas using Fabric.js. The Textbox in Fabric.js is movable and can be stretched according to requirements. Further, the Textbox can be customized when it comes to initial stroke color, height, width, fill color, or stroke width. To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library using CDN, we will create a canvas block in the body tag which will contain the Textbox. After this, we will initialize instances of Canvas and Textbox provided by Fabric.js, set the edit mode by using the editable property, and render the Textbox on the Canvas as given in the example below. Syntax: fabric.Textbox('text', { editable: boolean }); Parameters: This property accepts a single parameter as mentioned above and described below: editable: It specifies the edit mode of the Textbox. A value of true makes the Textbox editable and a value of false disables editing. Example: This example uses Fabric.js to set the edit mode of the Textbox. HTML <html><head> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.0/fabric.min.js"> </script></head><body> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> Fabric.js | Textbox editable Property </h3> <canvas id="canvas" width="600" height="300" style="border:1px solid #000000"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas("canvas"); // Create new Textbox instances var textEditable = new fabric.Textbox( 'Editable Textbox', { width: 500, editable: true }); var textNonEditable = new fabric.Textbox( 'Non Editable Textbox', { width: 500, editable: false }); // Render the Textbox in canvas canvas.add(textEditable); canvas.add(textNonEditable); canvas.centerObject(textNonEditable); canvas.centerObjectH(textEditable); </script></body></html> Output: Fabric.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? How to remove duplicate elements from JavaScript Array ? How to get selected value in dropdown list using JavaScript ? 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": 25220, "s": 25192, "text": "\n20 Jan, 2021" }, { "code": null, "e": 25525, "s": 25220, "text": "In this article, we are going to see how to set the edit mode of a Textbox canvas using Fabric.js. The Textbox in Fabric.js is movable and can be stretched according to requirements. Further, the Textbox can be customized when it comes to initial stroke color, height, width, fill color, or stroke width." }, { "code": null, "e": 25925, "s": 25525, "text": "To make it possible we are going to use a JavaScript library called Fabric.js. After importing the library using CDN, we will create a canvas block in the body tag which will contain the Textbox. After this, we will initialize instances of Canvas and Textbox provided by Fabric.js, set the edit mode by using the editable property, and render the Textbox on the Canvas as given in the example below." }, { "code": null, "e": 25933, "s": 25925, "text": "Syntax:" }, { "code": null, "e": 25984, "s": 25933, "text": "fabric.Textbox('text', {\n editable: boolean\n});" }, { "code": null, "e": 26077, "s": 25984, "text": "Parameters: This property accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 26212, "s": 26077, "text": "editable: It specifies the edit mode of the Textbox. A value of true makes the Textbox editable and a value of false disables editing." }, { "code": null, "e": 26286, "s": 26212, "text": "Example: This example uses Fabric.js to set the edit mode of the Textbox." }, { "code": null, "e": 26291, "s": 26286, "text": "HTML" }, { "code": "<html><head> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.3.0/fabric.min.js\"> </script></head><body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> Fabric.js | Textbox editable Property </h3> <canvas id=\"canvas\" width=\"600\" height=\"300\" style=\"border:1px solid #000000\"> </canvas> <script> // Initiate a Canvas instance var canvas = new fabric.Canvas(\"canvas\"); // Create new Textbox instances var textEditable = new fabric.Textbox( 'Editable Textbox', { width: 500, editable: true }); var textNonEditable = new fabric.Textbox( 'Non Editable Textbox', { width: 500, editable: false }); // Render the Textbox in canvas canvas.add(textEditable); canvas.add(textNonEditable); canvas.centerObject(textNonEditable); canvas.centerObjectH(textEditable); </script></body></html>", "e": 27302, "s": 26291, "text": null }, { "code": null, "e": 27310, "s": 27302, "text": "Output:" }, { "code": null, "e": 27320, "s": 27310, "text": "Fabric.js" }, { "code": null, "e": 27331, "s": 27320, "text": "JavaScript" }, { "code": null, "e": 27348, "s": 27331, "text": "Web Technologies" }, { "code": null, "e": 27446, "s": 27348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27455, "s": 27446, "text": "Comments" }, { "code": null, "e": 27468, "s": 27455, "text": "Old Comments" }, { "code": null, "e": 27529, "s": 27468, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27570, "s": 27529, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27624, "s": 27570, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27681, "s": 27624, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 27743, "s": 27681, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 27785, "s": 27743, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27818, "s": 27785, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27880, "s": 27818, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27923, "s": 27880, "text": "How to fetch data from an API in ReactJS ?" } ]
Android - Enable Logging in OkHttp - GeeksforGeeks
19 Sep, 2021 Have you ever experienced a negative experience while doing an API request in your Android application? Or perhaps you encountered an error that rendered your API call ineffective. The first option would have been to try API requests through some client to figure out what was wrong. Or perhaps you would have tried something different. What if we told you that you could have selected something different that would not have forced you to test APIs through a client? Geek Tip: You may use interceptors in your Android code to obtain the logs when an issue occurs. Isn’t this a better solution? OkHttp is an interceptor that allows you to report API requests. So, in this case, an interceptor functions more like a manager for an API request, allowing you to monitor or execute certain actions on your API calls. Let us begin by including it into our project; in the build.gradle file, we will include the following: implementation "com.squareup.okhttp3:logging-interceptor:4.0.0" And then, in order to begin tracking your API calls, we must first perform an API request. Kotlin val geeksforgeeks = OkHttpClient.Builder()var demands = Request.Builder() .url(/*Your API key which you generated*/) .build() Now, In this section, we build an object for the request and define a variable client of OkHttpClient. Hence, in order to make an API request, we will need the following code: Kotlin geeksforgeeks.newCall(request).enqueue(object :Callback{ override fun onFailure(request: Request?, e: IOException?) { // The API Call Failed // Do something like changing // the UI to prompt user } override fun onResponse(response: Response?) { // Response returned from the API // So something from it. }}) We have just made our first API call. However, we would not see any logs because we have not installed any interceptors to log the calls. So, how can we record the call’s response? To begin logging, we must include interceptors in the OkHttpClient described earlier. And, as previously said, interceptors are used to monitor the API request and will publish the logs that are created in the console’s Logcat. To include an Interceptor: Kotlin val aLogger = HttpLoggingInterceptor()aLogger.level = (HttpLoggingInterceptor.Level.BASIC) And, in order to include this interceptor in the client we use: Kotlin val geeksforgeeks = OkHttpClient.Builder()geeksforgeeks.addInterceptor(logging) And now, when we access the API again, we’ll get logs in Logcat that look like this: --> POST /hello world/http/1.1 (6-byte body) <-- 600 OK (10ms, 4-byte body) Note #1: To add a custom TAG for your or logs, simply enter the following, Kotlin val aLogger = HttpLoggingInterceptor(object : Logger() { fun aLogger(textString: String) { Log.d("GEEKS FOR GEEKS", textString) }}) Note #2: You may also extend the Interceptor class to construct your own Interceptor. Kotlin class GeeksforGeeksInterceptor : Interceptor { override fun gfgInter(chain: Interceptor.Chain): Response { var geeksforgeeks = chain.request() geeksforgeeks = request.newBuilder() .build() return chain.proceed(request) }} Then add it to the client’s list by using: Kotlin val geeksforgeeks = OkHttpClient.Builder()geeksforgeeks.addInterceptor(CustomInterceptor()) In the above sample, redactHeader conceals the sensitive information of the Authorization and Cookie key. These are only created at the HEADERS and BODY levels. This is how we can track API calls performed in your Android app. Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example Fragment Lifecycle in Android Flutter - BoxShadow Widget How to Change the Background Color After Clicking the Button in Android?
[ { "code": null, "e": 26515, "s": 26487, "text": "\n19 Sep, 2021" }, { "code": null, "e": 26696, "s": 26515, "text": "Have you ever experienced a negative experience while doing an API request in your Android application? Or perhaps you encountered an error that rendered your API call ineffective." }, { "code": null, "e": 26983, "s": 26696, "text": "The first option would have been to try API requests through some client to figure out what was wrong. Or perhaps you would have tried something different. What if we told you that you could have selected something different that would not have forced you to test APIs through a client?" }, { "code": null, "e": 27110, "s": 26983, "text": "Geek Tip: You may use interceptors in your Android code to obtain the logs when an issue occurs. Isn’t this a better solution?" }, { "code": null, "e": 27432, "s": 27110, "text": "OkHttp is an interceptor that allows you to report API requests. So, in this case, an interceptor functions more like a manager for an API request, allowing you to monitor or execute certain actions on your API calls. Let us begin by including it into our project; in the build.gradle file, we will include the following:" }, { "code": null, "e": 27496, "s": 27432, "text": "implementation \"com.squareup.okhttp3:logging-interceptor:4.0.0\"" }, { "code": null, "e": 27587, "s": 27496, "text": "And then, in order to begin tracking your API calls, we must first perform an API request." }, { "code": null, "e": 27594, "s": 27587, "text": "Kotlin" }, { "code": "val geeksforgeeks = OkHttpClient.Builder()var demands = Request.Builder() .url(/*Your API key which you generated*/) .build()", "e": 27734, "s": 27594, "text": null }, { "code": null, "e": 27838, "s": 27734, "text": "Now, In this section, we build an object for the request and define a variable client of OkHttpClient. " }, { "code": null, "e": 27911, "s": 27838, "text": "Hence, in order to make an API request, we will need the following code:" }, { "code": null, "e": 27918, "s": 27911, "text": "Kotlin" }, { "code": "geeksforgeeks.newCall(request).enqueue(object :Callback{ override fun onFailure(request: Request?, e: IOException?) { // The API Call Failed // Do something like changing // the UI to prompt user } override fun onResponse(response: Response?) { // Response returned from the API // So something from it. }})", "e": 28279, "s": 27918, "text": null }, { "code": null, "e": 28460, "s": 28279, "text": "We have just made our first API call. However, we would not see any logs because we have not installed any interceptors to log the calls. So, how can we record the call’s response?" }, { "code": null, "e": 28546, "s": 28460, "text": "To begin logging, we must include interceptors in the OkHttpClient described earlier." }, { "code": null, "e": 28715, "s": 28546, "text": "And, as previously said, interceptors are used to monitor the API request and will publish the logs that are created in the console’s Logcat. To include an Interceptor:" }, { "code": null, "e": 28722, "s": 28715, "text": "Kotlin" }, { "code": "val aLogger = HttpLoggingInterceptor()aLogger.level = (HttpLoggingInterceptor.Level.BASIC)", "e": 28813, "s": 28722, "text": null }, { "code": null, "e": 28877, "s": 28813, "text": "And, in order to include this interceptor in the client we use:" }, { "code": null, "e": 28884, "s": 28877, "text": "Kotlin" }, { "code": "val geeksforgeeks = OkHttpClient.Builder()geeksforgeeks.addInterceptor(logging)", "e": 28964, "s": 28884, "text": null }, { "code": null, "e": 29049, "s": 28964, "text": "And now, when we access the API again, we’ll get logs in Logcat that look like this:" }, { "code": null, "e": 29126, "s": 29049, "text": "--> POST /hello world/http/1.1 (6-byte body)\n\n<-- 600 OK (10ms, 4-byte body)" }, { "code": null, "e": 29201, "s": 29126, "text": "Note #1: To add a custom TAG for your or logs, simply enter the following," }, { "code": null, "e": 29208, "s": 29201, "text": "Kotlin" }, { "code": "val aLogger = HttpLoggingInterceptor(object : Logger() { fun aLogger(textString: String) { Log.d(\"GEEKS FOR GEEKS\", textString) }})", "e": 29353, "s": 29208, "text": null }, { "code": null, "e": 29439, "s": 29353, "text": "Note #2: You may also extend the Interceptor class to construct your own Interceptor." }, { "code": null, "e": 29446, "s": 29439, "text": "Kotlin" }, { "code": "class GeeksforGeeksInterceptor : Interceptor { override fun gfgInter(chain: Interceptor.Chain): Response { var geeksforgeeks = chain.request() geeksforgeeks = request.newBuilder() .build() return chain.proceed(request) }}", "e": 29710, "s": 29446, "text": null }, { "code": null, "e": 29753, "s": 29710, "text": "Then add it to the client’s list by using:" }, { "code": null, "e": 29760, "s": 29753, "text": "Kotlin" }, { "code": "val geeksforgeeks = OkHttpClient.Builder()geeksforgeeks.addInterceptor(CustomInterceptor())", "e": 29852, "s": 29760, "text": null }, { "code": null, "e": 30079, "s": 29852, "text": "In the above sample, redactHeader conceals the sensitive information of the Authorization and Cookie key. These are only created at the HEADERS and BODY levels. This is how we can track API calls performed in your Android app." }, { "code": null, "e": 30086, "s": 30079, "text": "Picked" }, { "code": null, "e": 30094, "s": 30086, "text": "Android" }, { "code": null, "e": 30102, "s": 30094, "text": "Android" }, { "code": null, "e": 30200, "s": 30102, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30238, "s": 30200, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 30277, "s": 30238, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30327, "s": 30277, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30353, "s": 30327, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 30404, "s": 30353, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30446, "s": 30404, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30484, "s": 30446, "text": "Android Listview in Java with Example" }, { "code": null, "e": 30514, "s": 30484, "text": "Fragment Lifecycle in Android" }, { "code": null, "e": 30541, "s": 30514, "text": "Flutter - BoxShadow Widget" } ]
How to Pass Data to Destination using Safe Args in Android? - GeeksforGeeks
04 Feb, 2021 SafeArgs is a gradle plugin that allows you to Pass data to destination UI components. It generates simple object and builder classes for type-safe navigation and access to any associated arguments. Safe Args is strongly recommended for navigating and passing data because it ensures type-safety. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a new project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Add dependency Inside build.gradle (project) add the following code under dependencies. dependencies { classpath “androidx.navigation:navigation-safe-args-gradle-plugin:2.3.2” } Inside build.gradle (app) add the following code and click Sync now plugins { id ‘com.android.application’ id ‘kotlin-android’ id ‘kotlin-android-extensions’ id “androidx.navigation.safeargs.kotlin” } Step 3: Create two new Fragments In this article, we are going to send data from one fragment and receive it in another. So, First, create two Fragments. To create a new Fragment: Project Name (right click) -> new -> Fragment -> Fragment (Blank) A dialog box will open. In the Fragment Name write Registration and in fragment layout name write fragment_registration. In a similar way create another fragment with fragment name Detail and fragment layout name as fragment_detail. Step 4: Create an XML layout of both fragments Go to the Fragment_registration.xml file and refer to the following code. Below is the code for the Fragment_registration.xml file. This is for the basic layout used in the app. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".Registration"> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" android:layout_margin="20dp" android:ems="10" android:hint="Name" android:inputType="textPersonName" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <EditText android:id="@+id/et_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Email" android:layout_margin="20dp" android:inputType="textPersonName" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_name" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Password" android:layout_margin="20dp" android:inputType="textPersonName" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_email" /> <Button android:id="@+id/button_send" android:layout_width="276dp" android:layout_height="50dp" android:text="Send" android:layout_margin="20dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/et_password" /> </androidx.constraintlayout.widget.ConstraintLayout> Go to the Fragment_detail.xml file and refer to the following code. Below is the code for the Fragment_detail.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".Details"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name :" android:id="@+id/tv1" android:textSize="20sp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="50dp" android:layout_marginStart="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="@color/black" android:id="@+id/tv_name" app:layout_constraintLeft_toRightOf="@id/tv1" app:layout_constraintTop_toTopOf="@id/tv1" android:layout_marginStart="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Email :" android:id="@+id/tv2" android:textSize="20sp" app:layout_constraintTop_toBottomOf="@id/tv1" app:layout_constraintLeft_toLeftOf="parent" android:layout_marginTop="20dp" android:layout_marginStart="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="@color/black" android:id="@+id/tv_email" app:layout_constraintLeft_toRightOf="@id/tv2" app:layout_constraintTop_toTopOf="@id/tv2" android:layout_marginStart="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Password :" android:id="@+id/tv3" android:textSize="20sp" app:layout_constraintTop_toBottomOf="@id/tv2" app:layout_constraintLeft_toLeftOf="parent" android:layout_marginTop="20dp" android:layout_marginStart="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="@color/black" android:id="@+id/tv_password" app:layout_constraintLeft_toRightOf="@id/tv3" app:layout_constraintTop_toTopOf="@id/tv3" android:layout_marginStart="20dp" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 5: Create a new Kotlin class Create a new Class User.kt we will use data of custom generic “User” having a name, email, password to pass to another fragment. Kotlin import android.os.Parcelableimport kotlinx.android.parcel.Parcelize @Parcelizedata class User( val name : String ="", val email : String= "", val password : String ="" ) : Parcelable Step 6: Create a new Navigation graph res (right click) -> new -> Android resource file In the dialog write file name as nav_graph and choose Resource type as “Navigation“. and click Ok. Now open the just created nav_graph.xml file click on the new destination icon and choose both of the fragments. Make Fragment_registration as the home. Create action from fragment_registration to fragment_detail and pass the User argument in the arguments of Fragment_detail. Its XML code is given below. XML <?xml version="1.0" encoding="utf-8"?><navigation 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:id="@+id/nav_graph" app:startDestination="@id/registration"> <fragment android:id="@+id/registration" android:name="com.geeksforgeeks.navargsexample.Registration" android:label="fragment_registration" tools:layout="@layout/fragment_registration" > <action android:id="@+id/action_registration_to_details" app:destination="@id/details" /> </fragment> <fragment android:id="@+id/details" android:name="com.geeksforgeeks.navargsexample.Details" android:label="fragment_details" tools:layout="@layout/fragment_details" > <argument android:name="user" app:argType="com.geeksforgeeks.navargsexample.User" /> </fragment> </navigation> Step 7: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. This layout contains one Frame Layout and a fragment that will act as a host for the fragments that we created earlier. Notice the navGraph tag inside the fragment tag. XML <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <!--this fragmnet will act as the host for both fragments in the main activity--> <fragment android:id="@+id/nav_Host_Fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:navGraph="@navigation/nav_graph" /> </FrameLayout> </androidx.constraintlayout.widget.ConstraintLayout> Step 8: Working with Registration.kt file Go to the Registration.kt file and refer to the following code. Below is the code for the Registration.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.navigation.fragment.findNavControllerimport com.geeksforgeeks.navargsexample.databinding.FragmentRegistrationBinding class Registration : Fragment() { private var _binding: FragmentRegistrationBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRegistrationBinding.inflate(inflater, container, false) val view = binding.root // call onClick on the SendButton binding.buttonSend.setOnClickListener { val name = binding.etName.text.toString() val email = binding.etEmail.text.toString() val password = binding.etPassword.text.toString() // create user object and pass the // required arguments // that is name, email,and password val user = User(name,email, password) // create an action and pass the the required user object to it // If you can not find the RegistrationDirection try to "Build project" val action = RegistrationDirections.actionRegistrationToDetails(user) // this will navigate the current fragment i.e // Registration to the Detail fragment findNavController().navigate( action ) } return view } override fun onDestroyView() { super.onDestroyView() _binding = null }} Step 9: Working with the Details.kt file Go to the Details.kt file and refer to the following code. Below is the code for the Details.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.navigation.fragment.navArgsimport com.geeksforgeeks.navargsexample.databinding.FragmentDetailsBinding class Details : Fragment() { private var _binding: FragmentDetailsBinding? = null private val binding get() = _binding!! // get the arguments from the Registration fragment private val args : DetailsArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDetailsBinding.inflate(inflater, container, false) val view = binding.root // Receive the arguments in a variable val userDetails = args.user // set the values to respective textViews binding.tvName.text = userDetails.name binding.tvEmail.text = userDetails.email binding.tvPassword.text = userDetails.password return view } override fun onDestroyView() { super.onDestroyView() _binding = null }} Note: In this example, we don’t have to write any code inside ActivityMain.kt Github Repo here. android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Create and Add Data to SQLite Database in Android? Services in Android with Example Broadcast Receiver in Android With Example Content Providers in Android with Example Android RecyclerView in Kotlin Services in Android with Example Broadcast Receiver in Android With Example Content Providers in Android with Example Android RecyclerView in Kotlin Android UI Layouts
[ { "code": null, "e": 24006, "s": 23978, "text": "\n04 Feb, 2021" }, { "code": null, "e": 24472, "s": 24006, "text": "SafeArgs is a gradle plugin that allows you to Pass data to destination UI components. It generates simple object and builder classes for type-safe navigation and access to any associated arguments. Safe Args is strongly recommended for navigating and passing data because it ensures type-safety. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 24501, "s": 24472, "text": "Step 1: Create a new project" }, { "code": null, "e": 24665, "s": 24501, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 24688, "s": 24665, "text": "Step 2: Add dependency" }, { "code": null, "e": 24761, "s": 24688, "text": "Inside build.gradle (project) add the following code under dependencies." }, { "code": null, "e": 24777, "s": 24761, "text": " dependencies {" }, { "code": null, "e": 24854, "s": 24777, "text": " classpath “androidx.navigation:navigation-safe-args-gradle-plugin:2.3.2”" }, { "code": null, "e": 24856, "s": 24854, "text": "}" }, { "code": null, "e": 24924, "s": 24856, "text": "Inside build.gradle (app) add the following code and click Sync now" }, { "code": null, "e": 24934, "s": 24924, "text": "plugins {" }, { "code": null, "e": 24966, "s": 24934, "text": " id ‘com.android.application’" }, { "code": null, "e": 24989, "s": 24966, "text": " id ‘kotlin-android’" }, { "code": null, "e": 25023, "s": 24989, "text": " id ‘kotlin-android-extensions’" }, { "code": null, "e": 25067, "s": 25023, "text": " id “androidx.navigation.safeargs.kotlin”" }, { "code": null, "e": 25069, "s": 25067, "text": "}" }, { "code": null, "e": 25102, "s": 25069, "text": "Step 3: Create two new Fragments" }, { "code": null, "e": 25249, "s": 25102, "text": "In this article, we are going to send data from one fragment and receive it in another. So, First, create two Fragments. To create a new Fragment:" }, { "code": null, "e": 25315, "s": 25249, "text": "Project Name (right click) -> new -> Fragment -> Fragment (Blank)" }, { "code": null, "e": 25548, "s": 25315, "text": "A dialog box will open. In the Fragment Name write Registration and in fragment layout name write fragment_registration. In a similar way create another fragment with fragment name Detail and fragment layout name as fragment_detail." }, { "code": null, "e": 25595, "s": 25548, "text": "Step 4: Create an XML layout of both fragments" }, { "code": null, "e": 25773, "s": 25595, "text": "Go to the Fragment_registration.xml file and refer to the following code. Below is the code for the Fragment_registration.xml file. This is for the basic layout used in the app." }, { "code": null, "e": 25777, "s": 25773, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".Registration\"> <EditText android:id=\"@+id/et_name\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentEnd=\"true\" android:layout_margin=\"20dp\" android:ems=\"10\" android:hint=\"Name\" android:inputType=\"textPersonName\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <EditText android:id=\"@+id/et_email\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:ems=\"10\" android:hint=\"Email\" android:layout_margin=\"20dp\" android:inputType=\"textPersonName\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/et_name\" /> <EditText android:id=\"@+id/et_password\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:ems=\"10\" android:hint=\"Password\" android:layout_margin=\"20dp\" android:inputType=\"textPersonName\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/et_email\" /> <Button android:id=\"@+id/button_send\" android:layout_width=\"276dp\" android:layout_height=\"50dp\" android:text=\"Send\" android:layout_margin=\"20dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/et_password\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 27928, "s": 25777, "text": null }, { "code": null, "e": 28049, "s": 27928, "text": "Go to the Fragment_detail.xml file and refer to the following code. Below is the code for the Fragment_detail.xml file. " }, { "code": null, "e": 28053, "s": 28049, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout 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\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" tools:context=\".Details\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Name :\" android:id=\"@+id/tv1\" android:textSize=\"20sp\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" android:layout_marginTop=\"50dp\" android:layout_marginStart=\"30dp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"20sp\" android:textColor=\"@color/black\" android:id=\"@+id/tv_name\" app:layout_constraintLeft_toRightOf=\"@id/tv1\" app:layout_constraintTop_toTopOf=\"@id/tv1\" android:layout_marginStart=\"20dp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Email :\" android:id=\"@+id/tv2\" android:textSize=\"20sp\" app:layout_constraintTop_toBottomOf=\"@id/tv1\" app:layout_constraintLeft_toLeftOf=\"parent\" android:layout_marginTop=\"20dp\" android:layout_marginStart=\"30dp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"20sp\" android:textColor=\"@color/black\" android:id=\"@+id/tv_email\" app:layout_constraintLeft_toRightOf=\"@id/tv2\" app:layout_constraintTop_toTopOf=\"@id/tv2\" android:layout_marginStart=\"20dp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Password :\" android:id=\"@+id/tv3\" android:textSize=\"20sp\" app:layout_constraintTop_toBottomOf=\"@id/tv2\" app:layout_constraintLeft_toLeftOf=\"parent\" android:layout_marginTop=\"20dp\" android:layout_marginStart=\"30dp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"20sp\" android:textColor=\"@color/black\" android:id=\"@+id/tv_password\" app:layout_constraintLeft_toRightOf=\"@id/tv3\" app:layout_constraintTop_toTopOf=\"@id/tv3\" android:layout_marginStart=\"20dp\" /> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 30678, "s": 28053, "text": null }, { "code": null, "e": 30713, "s": 30678, "text": "Step 5: Create a new Kotlin class " }, { "code": null, "e": 30842, "s": 30713, "text": "Create a new Class User.kt we will use data of custom generic “User” having a name, email, password to pass to another fragment." }, { "code": null, "e": 30849, "s": 30842, "text": "Kotlin" }, { "code": "import android.os.Parcelableimport kotlinx.android.parcel.Parcelize @Parcelizedata class User( val name : String =\"\", val email : String= \"\", val password : String =\"\" ) : Parcelable", "e": 31043, "s": 30849, "text": null }, { "code": null, "e": 31081, "s": 31043, "text": "Step 6: Create a new Navigation graph" }, { "code": null, "e": 31132, "s": 31081, "text": "res (right click) -> new -> Android resource file " }, { "code": null, "e": 31537, "s": 31132, "text": "In the dialog write file name as nav_graph and choose Resource type as “Navigation“. and click Ok. Now open the just created nav_graph.xml file click on the new destination icon and choose both of the fragments. Make Fragment_registration as the home. Create action from fragment_registration to fragment_detail and pass the User argument in the arguments of Fragment_detail. Its XML code is given below." }, { "code": null, "e": 31541, "s": 31537, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><navigation 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:id=\"@+id/nav_graph\" app:startDestination=\"@id/registration\"> <fragment android:id=\"@+id/registration\" android:name=\"com.geeksforgeeks.navargsexample.Registration\" android:label=\"fragment_registration\" tools:layout=\"@layout/fragment_registration\" > <action android:id=\"@+id/action_registration_to_details\" app:destination=\"@id/details\" /> </fragment> <fragment android:id=\"@+id/details\" android:name=\"com.geeksforgeeks.navargsexample.Details\" android:label=\"fragment_details\" tools:layout=\"@layout/fragment_details\" > <argument android:name=\"user\" app:argType=\"com.geeksforgeeks.navargsexample.User\" /> </fragment> </navigation>", "e": 32532, "s": 31541, "text": null }, { "code": null, "e": 32580, "s": 32532, "text": "Step 7: Working with the activity_main.xml file" }, { "code": null, "e": 32865, "s": 32580, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. This layout contains one Frame Layout and a fragment that will act as a host for the fragments that we created earlier. Notice the navGraph tag inside the fragment tag." }, { "code": null, "e": 32869, "s": 32865, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <FrameLayout android:id=\"@+id/frameLayout\" android:layout_width=\"match_parent\" android:layout_height=\"0dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintHorizontal_bias=\"0.5\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <!--this fragmnet will act as the host for both fragments in the main activity--> <fragment android:id=\"@+id/nav_Host_Fragment\" android:name=\"androidx.navigation.fragment.NavHostFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:defaultNavHost=\"true\" app:navGraph=\"@navigation/nav_graph\" /> </FrameLayout> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 34087, "s": 32869, "text": null }, { "code": null, "e": 34129, "s": 34087, "text": "Step 8: Working with Registration.kt file" }, { "code": null, "e": 34315, "s": 34129, "text": "Go to the Registration.kt file and refer to the following code. Below is the code for the Registration.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 34322, "s": 34315, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.navigation.fragment.findNavControllerimport com.geeksforgeeks.navargsexample.databinding.FragmentRegistrationBinding class Registration : Fragment() { private var _binding: FragmentRegistrationBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRegistrationBinding.inflate(inflater, container, false) val view = binding.root // call onClick on the SendButton binding.buttonSend.setOnClickListener { val name = binding.etName.text.toString() val email = binding.etEmail.text.toString() val password = binding.etPassword.text.toString() // create user object and pass the // required arguments // that is name, email,and password val user = User(name,email, password) // create an action and pass the the required user object to it // If you can not find the RegistrationDirection try to \"Build project\" val action = RegistrationDirections.actionRegistrationToDetails(user) // this will navigate the current fragment i.e // Registration to the Detail fragment findNavController().navigate( action ) } return view } override fun onDestroyView() { super.onDestroyView() _binding = null }}", "e": 36024, "s": 34322, "text": null }, { "code": null, "e": 36065, "s": 36024, "text": "Step 9: Working with the Details.kt file" }, { "code": null, "e": 36241, "s": 36065, "text": "Go to the Details.kt file and refer to the following code. Below is the code for the Details.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 36248, "s": 36241, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.fragment.app.Fragmentimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport androidx.navigation.fragment.navArgsimport com.geeksforgeeks.navargsexample.databinding.FragmentDetailsBinding class Details : Fragment() { private var _binding: FragmentDetailsBinding? = null private val binding get() = _binding!! // get the arguments from the Registration fragment private val args : DetailsArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDetailsBinding.inflate(inflater, container, false) val view = binding.root // Receive the arguments in a variable val userDetails = args.user // set the values to respective textViews binding.tvName.text = userDetails.name binding.tvEmail.text = userDetails.email binding.tvPassword.text = userDetails.password return view } override fun onDestroyView() { super.onDestroyView() _binding = null }}", "e": 37400, "s": 36248, "text": null }, { "code": null, "e": 37478, "s": 37400, "text": "Note: In this example, we don’t have to write any code inside ActivityMain.kt" }, { "code": null, "e": 37496, "s": 37478, "text": "Github Repo here." }, { "code": null, "e": 37504, "s": 37496, "text": "android" }, { "code": null, "e": 37512, "s": 37504, "text": "Android" }, { "code": null, "e": 37519, "s": 37512, "text": "Kotlin" }, { "code": null, "e": 37527, "s": 37519, "text": "Android" }, { "code": null, "e": 37625, "s": 37527, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37634, "s": 37625, "text": "Comments" }, { "code": null, "e": 37647, "s": 37634, "text": "Old Comments" }, { "code": null, "e": 37705, "s": 37647, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 37738, "s": 37705, "text": "Services in Android with Example" }, { "code": null, "e": 37781, "s": 37738, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 37823, "s": 37781, "text": "Content Providers in Android with Example" }, { "code": null, "e": 37854, "s": 37823, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 37887, "s": 37854, "text": "Services in Android with Example" }, { "code": null, "e": 37930, "s": 37887, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 37972, "s": 37930, "text": "Content Providers in Android with Example" }, { "code": null, "e": 38003, "s": 37972, "text": "Android RecyclerView in Kotlin" } ]
C program to convert roman numbers to decimal numbers
Given below is an algorithm to convert roman numbers to decimal numbers in C language − Step 1 − Start Step 2 − Read the roman numeral at runtime Step 3 − length: = strlen(roman) Step 4 − for i = 0 to length-1 do Step 4.1 − switch(roman[i]) Step 4.1.1 − case ‘m’: Step 4.1.2 − case ‘M’: Step 4.1.2.1 − d[i]: =1000 Step 4.1.3 − case ‘d’: Step 4.1.4 − case ‘D’: Step 4.1.4.1 − d[i]: =500 Step 4.1.5 − case ‘c’: Step 4.1.6 − case ‘C’: Step 4.1.6.1 − d[i]: =100 Step 4.1.7 − case ‘l’: Step 4.1.8 − case ‘L’: Step 4.1.8.1 − d[i]: =50 Step 4.1.9 − case ‘x’: Step 4.1.10 − case ‘X’: Step 4.1.10.1 − d[i]: =10 Step 4.1.11 − case ‘v’: Step 4.1.12 − case ‘V’: Step 4.1.12.1 − d[i]: =5 Step 4.1.13 − case ‘i’: Step 4.1.14 − case ‘I’: Step 4.1.14.1 − d[i]: =1 Step 5 − for i =0 to length-1 do Step 5.1 − if (i==length-1) or (d[i]>=d[i+1]) then Step 5.1.1 − deci += d[i] Step 5.2 − else Step 5.2.1 − deci -= d[i] Step 6 − Print the decimal equivalent of roman numeral Step 7 − Stop Following is the C program to convert roman numbers to decimal numbers − #include <stdio.h> #include <conio.h> main(){ char roman[30]; int deci=0; int length,i,d[30]; printf("The Roman equivalent to decimal\n"); printf("Decimal:.........Roman\n"); printf("%5d............%3c\n",1,'I'); printf("%5d............%3c\n",5,'V'); printf("%5d............%3c\n",10,'X'); printf("%5d............%3c\n",50,'L'); printf("%5d............%3c\n",100,'C'); printf("%5d............%3c\n",500,'D'); printf("%5d............%3c\n",1000,'M'); printf("Enter a Roman numeral:"); scanf("%s",roman); length=strlen(roman); for(i=0;i<length;i++){ switch(roman[i]){ case 'm': case 'M': d[i]=1000; break; case 'd': case 'D': d[i]= 500; break; case 'c': case 'C': d[i]= 100; break; case 'l': case 'L': d[i]= 50; break; case 'x': case 'X': d[i]= 10; break;; case 'v': case 'V': d[i]= 5; break; case 'i': case 'I': d[i]= 1; } } for(i=0;i<length;i++){ if(i==length-1 || d[i]>=d[i+1]) deci += d[i]; else deci -= d[i]; } printf("The Decimal equivalent of Roman numeral %s is %d", roman, deci); } When the above program is executed, it produces the following result − The Roman equivalent to decimal Decimal:.........Roman 1............ I 5............ V 10............ X 50............ L 100............ C 500............ D 1000............ M Enter a Roman numeral: M The Decimal equivalent of Roman Numeral M is 1000
[ { "code": null, "e": 1150, "s": 1062, "text": "Given below is an algorithm to convert roman numbers to decimal numbers in C language −" }, { "code": null, "e": 1165, "s": 1150, "text": "Step 1 − Start" }, { "code": null, "e": 1208, "s": 1165, "text": "Step 2 − Read the roman numeral at runtime" }, { "code": null, "e": 1241, "s": 1208, "text": "Step 3 − length: = strlen(roman)" }, { "code": null, "e": 1275, "s": 1241, "text": "Step 4 − for i = 0 to length-1 do" }, { "code": null, "e": 1309, "s": 1275, "text": " Step 4.1 − switch(roman[i])" }, { "code": null, "e": 1342, "s": 1309, "text": " Step 4.1.1 − case ‘m’:" }, { "code": null, "e": 1375, "s": 1342, "text": " Step 4.1.2 − case ‘M’:" }, { "code": null, "e": 1417, "s": 1375, "text": " Step 4.1.2.1 − d[i]: =1000" }, { "code": null, "e": 1450, "s": 1417, "text": " Step 4.1.3 − case ‘d’:" }, { "code": null, "e": 1488, "s": 1450, "text": " Step 4.1.4 − case ‘D’:" }, { "code": null, "e": 1524, "s": 1488, "text": " Step 4.1.4.1 − d[i]: =500" }, { "code": null, "e": 1557, "s": 1524, "text": " Step 4.1.5 − case ‘c’:" }, { "code": null, "e": 1595, "s": 1557, "text": " Step 4.1.6 − case ‘C’:" }, { "code": null, "e": 1640, "s": 1595, "text": " Step 4.1.6.1 − d[i]: =100" }, { "code": null, "e": 1673, "s": 1640, "text": " Step 4.1.7 − case ‘l’:" }, { "code": null, "e": 1706, "s": 1673, "text": " Step 4.1.8 − case ‘L’:" }, { "code": null, "e": 1750, "s": 1706, "text": " Step 4.1.8.1 − d[i]: =50" }, { "code": null, "e": 1783, "s": 1750, "text": " Step 4.1.9 − case ‘x’:" }, { "code": null, "e": 1817, "s": 1783, "text": " Step 4.1.10 − case ‘X’:" }, { "code": null, "e": 1862, "s": 1817, "text": " Step 4.1.10.1 − d[i]: =10" }, { "code": null, "e": 1897, "s": 1862, "text": " Step 4.1.11 − case ‘v’:" }, { "code": null, "e": 1931, "s": 1897, "text": " Step 4.1.12 − case ‘V’:" }, { "code": null, "e": 1972, "s": 1931, "text": " Step 4.1.12.1 − d[i]: =5" }, { "code": null, "e": 2006, "s": 1972, "text": " Step 4.1.13 − case ‘i’:" }, { "code": null, "e": 2040, "s": 2006, "text": " Step 4.1.14 − case ‘I’:" }, { "code": null, "e": 2081, "s": 2040, "text": " Step 4.1.14.1 − d[i]: =1" }, { "code": null, "e": 2124, "s": 2081, "text": " Step 5 − for i =0 to length-1 do" }, { "code": null, "e": 2191, "s": 2124, "text": " Step 5.1 − if (i==length-1) or (d[i]>=d[i+1]) then" }, { "code": null, "e": 2239, "s": 2191, "text": " Step 5.1.1 − deci += d[i]" }, { "code": null, "e": 2265, "s": 2239, "text": " Step 5.2 − else" }, { "code": null, "e": 2305, "s": 2265, "text": " Step 5.2.1 − deci -= d[i]" }, { "code": null, "e": 2360, "s": 2305, "text": "Step 6 − Print the decimal equivalent of roman numeral" }, { "code": null, "e": 2374, "s": 2360, "text": "Step 7 − Stop" }, { "code": null, "e": 2447, "s": 2374, "text": "Following is the C program to convert roman numbers to decimal numbers −" }, { "code": null, "e": 3664, "s": 2447, "text": "#include <stdio.h>\n#include <conio.h>\nmain(){\n char roman[30];\n int deci=0;\n int length,i,d[30];\n printf(\"The Roman equivalent to decimal\\n\");\n printf(\"Decimal:.........Roman\\n\");\n printf(\"%5d............%3c\\n\",1,'I');\n printf(\"%5d............%3c\\n\",5,'V');\n printf(\"%5d............%3c\\n\",10,'X');\n printf(\"%5d............%3c\\n\",50,'L');\n printf(\"%5d............%3c\\n\",100,'C');\n printf(\"%5d............%3c\\n\",500,'D');\n printf(\"%5d............%3c\\n\",1000,'M');\n printf(\"Enter a Roman numeral:\");\n scanf(\"%s\",roman);\n length=strlen(roman);\n for(i=0;i<length;i++){\n switch(roman[i]){\n case 'm':\n case 'M': d[i]=1000; break;\n case 'd':\n case 'D': d[i]= 500; break;\n case 'c':\n case 'C': d[i]= 100; break;\n case 'l':\n case 'L': d[i]= 50; break;\n case 'x':\n case 'X': d[i]= 10; break;;\n case 'v':\n case 'V': d[i]= 5; break;\n case 'i':\n case 'I': d[i]= 1;\n }\n }\n for(i=0;i<length;i++){\n if(i==length-1 || d[i]>=d[i+1])\n deci += d[i];\n else\n deci -= d[i];\n }\n printf(\"The Decimal equivalent of Roman numeral %s is %d\", roman, deci);\n}" }, { "code": null, "e": 3735, "s": 3664, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3986, "s": 3735, "text": "The Roman equivalent to decimal\nDecimal:.........Roman\n1............ I\n5............ V\n10............ X\n50............ L\n100............ C\n500............ D\n1000............ M\nEnter a Roman numeral: M\nThe Decimal equivalent of Roman Numeral M is 1000" } ]
A R(API)D assessment of travel carbon emissions around the world | by Kyle Baranko | Towards Data Science
As a climate-conscious consumer, I’ve often wondered about the environmental impact of my routine travel from the East Coast to Salt Lake City and back. After seeing one of many recent headlines highlighting air travel’s surprisingly high rates of carbon emissions, I wondered: would taking a train, bus, or driving a car be better for the planet than flying? Thankfully, I stumbled across an easy-to-use API, built by London programmer Tobe-Nicol, that allows you to compare carbon footprints of various modes of travel. Prepared to put price, comfort, and convenience aside for the sake of the planet, I pulled from this API to compare my options and raised a host of questions about the energy intensity of travel along the way. What are the API parameters? I found this API on Twitter and was able to do some quick experimenting in a Jupyter Notebook thanks to the straightforward documentation. The API has the following parameters: Activity (required): this can be either the fuel consumption of a vehicle or the distance travelled in miles. Since we’re comparing different modes of transportation, I will set this parameter as “3,910” — the roundtrip length, in miles, of travel from New York to Salt Lake City. activityType: this parameter denotes the value of the integer entered above. mode: refers to the mode of transportation. There are several options to choose from: dieselCar, petrolCar, anyCar, taxi, economyFlight, businessFlight, firstclassFlight, anyFlight, motorbike, bus and transitRail. fuelType: this pairs with the modes listed above: motorGasoline (also known as petrol), diesel, aviationGasoline and jetFuel. I assumed that all commercial flights use jet fuel but paired the parameter “anyFlight” with aviation gasoline to see if there is a major difference in carbon footprint between the two fuel types. I also assigned “dieselCar”, “bus” and “transitRail” to diesel fuel; I assumed all other modes use gasoline. I began by putting these parameters into two lists of equal length, associating each mode of transportation with each fuel type. I also deleted “anyCar” from the list because it overlaps with “taxi” and “petrolCar” and seemed redundant. Here are the lists: list_of_modes = ['dieselCar', 'petrolCar', 'taxi', 'motorbike', 'bus', 'transitRail', 'economyFlight', 'businessFlight', 'firstclassFlight', 'anyFlight' ] list_of_fuels = ['diesel', 'motorGasoline', 'motorGasoline', 'motorGasoline', 'diesel', 'diesel', 'jetFuel', 'jetFuel','jetFuel', 'aviationGasoline'] Rather than manually enter each parameter into the system, I wrote a function to loop through both lists and output the API request as a dictionary. After importing the necessary packages, I defined the function, inserted the lists and packaged the output as a dictionary (for complete code, please see the jupyter notebook attached to this blog post). #import necessary packages import requestsimport jsonimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np%matplotlib inline #use carbon_slc_nyc function to create dictionary with mode of #transportation as keys and of carbon footprint as valuescarbon_footprint = {}carbon_footprint = carbon_slc_nyc(list_of_modes, list_of_fuels) With the output packaged as a dictionary, I turned it into a pandas dataframe, renamed the columns to more appropriate titles, and converted the ‘Carbon Footprint’ column data into floats in preparation for plotting. df = pd.DataFrame(list(carbon_footprint_ground.items()))df.rename(columns = {0 :'Type of Transport'}, inplace = True)df.rename(columns = {1 :'Carbon_Footprint'}, inplace = True)df['Carbon_Footprint'] = df['Carbon_Footprint'].astype('float64') With this DataFrame, I plotted a bar graph to visualize how much carbon each mode of transportation emits over the course of a 3,910-mile journey. plt.figure(figsize=(10,5))sns.barplot(x=df_ground['Type of Transport'], y=df_ground['Carbon_Footprint'])plt.xticks(rotation=45) Interesting. If I’m choosing a mode of transportation with average fuel consumption, taking a bus, train, or economy flight is my best bet. However, the results create a lot of questions. This data satisfies the logical explanation that driving your own car is less efficient than sharing a ride and spreading total emissions of a vehicle over many people, like on a plane, bus, or train. But why is getting a first-class ticket on a flight so much worse than an economy-ticket? And why does your average bus have the lowest carbon footprint for this trip? Besides electric or LNG-fueled municipal busses, I don’t think diesel-fueled Greyhound or Concord Coach busses are very climate-friendly. I thought this distribution would be unique to the U.S and used another parameter to compare average mode of transport carbon footprint between countries. The API calls for a ‘usa’, ‘gbr’, and ‘def’ input to compare footprints between the United States, United Kingdom, and global average. Although this new parameter only allowed me to compare with two other options, I wanted to see if travelling 3910 miles outside the US would change the bus’s climate dominance. The world averages are about the same as in the US, but in the UK, busses are significantly more polluting. All air travel is about the same, suggesting that this emissions calculator standardizes emissions globally, which makes sense given the international nature of the industry. In the UK, travelling via rail or economy flights are my best bet. How are the emissions calculated? After looking over these results, I checked the documentation further to find out how emissions are calculated. There are two methods. For the code above, the API used the average emissions factor for a vehicle in a given country and adjusted the result based on the distance travelled parameter. However, the API also offers a more specific calculation using the specific fuel efficiency of the vehicle. In this method, the API multiplies total fuel consumed by the emissions factor for that fuel. The emissions factor is usually provided by a government organization and is recommended by the IPCC. Total Emissions = Fuel Emission Factor * Fuel Usage To get a more accurate assessment of my travel options, I needed to know how much energy the engine of each mode of transportation consumes. I picked three top options from the first descriptive analysis and limited the output to results in the US. In the next API call, I incorporated the fuel efficiency of my mom’s Suburu (33 miles per gallon of gasoline), a typical Greyhound bus (6 miles per gallon of diesel fuel), and the miles per gallon, in jet fuel, of an Airbus A220 100. The Airbus fuel consumption was challenging because the official Wikipedia fuel economy data is listed in either kg/km or miles per seat gallon, meaning I either had to convert the kg/km to mpg or multiply the miles per seat gallon by the number of seats in an Airbus A220 100 (I assumed I’d have a full flight both ways — SLC and NYC are popular destinations). I wasn’t sure if the API’s carbon calculator automatically converts the fuel consumption parameter into miles per seat gallon for public transportation, so I called the data both ways, entering both miles per gallon and miles per seat gallon in fear of counting twice. It made for an interesting contrast anyways. From a quick Google search, I found that Airbus A220s can have between 120–160 seats. I went with 140 seats. #miles per seat gallon divided by seats on the plane A220_mpg_A = (85.6 / 140) suburu_mpg_A = 33 greyhound_mpg_A = 6A220_gal_A = 3910/A220_mpg_Asuburu_gal_A = 3910/suburu_mpg_Agreyhound_gal_A = 3910/greyhound_mpg_Alist_gallons_A = [suburu_gal_A, greyhound_gal_A, A220_gal_A]list_fuel_type_A = ['motorGasoline', 'diesel', 'jetFuel']#call API and create dataframe carbon_footprint_A = {}carbon_footprint_A = carbon_fuel(list_gallons_A, list_fuel_type_A) df_A = pd.DataFrame(list(carbon_footprint_A.items()))df_A.rename(columns = {0 :'Fuel_Type'}, inplace = True)df_A.rename(columns = {1 :'Carbon_Footprint'}, inplace = True)df_A['Carbon_Footprint'] = df_A['Carbon_Footprint'].astype('float64')#now adjust to miles per seat gallonA220_mpg_B = 85.6 suburu_mpg_B = 33 #adjusting to miles per seat gallon with 55 seatsgreyhound_mpg_B = 6 * 55 A220_gal_B = 3910/A220_mpg_Bsuburu_gal_B = 3910/suburu_mpg_Bgreyhound_gal_B = 3910/greyhound_mpg_Blist_gallons_B = [suburu_gal_B, greyhound_gal_B, A220_gal_B]list_fuel_type_B = ['motorGasoline', 'diesel', 'jetFuel']#call API and create dataframecarbon_footprint_B = {}carbon_footprint_B = carbon_fuel(list_gallons_B, list_fuel_type_B)df_B = pd.DataFrame(list(carbon_footprint_B.items()))df_B.rename(columns = {0 :'Fuel_Type'}, inplace = True)df_B.rename(columns = {1 :'Carbon_Footprint'}, inplace = True)df_B['Carbon_Footprint'] = df_B['Carbon_Footprint'].astype('float64') Here are the results: After plotting the results from the first API call, it is clear that flying my own plane from New York to Salt Lake City and back would have a high environmental impact, as would driving my own Greyhound bus. Driving my mom’s Suburu is obviously more efficient for one person because it is way smaller. However, when spreading the high MPG and carbon emissions across a plane or bus full of people, it is clear that again, the bus has the lowest carbon footprint. Although a plane carries more than twice as many people as the bus and moves from NYC to SLC much faster than any sort of road travel, the bus has the benefit of using a lower-polluting and less energy-dense fuel while still spreading the climate cost among 55 people. My mom’s Suburu, while having one of the most efficient engines on the gasoline-powered automobile market, can’t compare — even if I picked up two hitchhikers (I did the math). Conclusion If limiting carbon emissions on an individual basis is your top priority, don’t drive. Although it requires more energy (and more carbon) to move a bus or commercial airliner across the country, you’re spreading the climate cost across many more people when you elect to travel by train, bus, or air. This analysis could be improved with more nuance and a granular dataset, but it is clear that on a high-level, incentivizing more people to get from A to B in larger vehicles should play a role in formulating decarbonization strategy. Github link: https://github.com/kbaranko/SLC-to-NYC-Carbon-Costs
[ { "code": null, "e": 532, "s": 172, "text": "As a climate-conscious consumer, I’ve often wondered about the environmental impact of my routine travel from the East Coast to Salt Lake City and back. After seeing one of many recent headlines highlighting air travel’s surprisingly high rates of carbon emissions, I wondered: would taking a train, bus, or driving a car be better for the planet than flying?" }, { "code": null, "e": 904, "s": 532, "text": "Thankfully, I stumbled across an easy-to-use API, built by London programmer Tobe-Nicol, that allows you to compare carbon footprints of various modes of travel. Prepared to put price, comfort, and convenience aside for the sake of the planet, I pulled from this API to compare my options and raised a host of questions about the energy intensity of travel along the way." }, { "code": null, "e": 933, "s": 904, "text": "What are the API parameters?" }, { "code": null, "e": 1110, "s": 933, "text": "I found this API on Twitter and was able to do some quick experimenting in a Jupyter Notebook thanks to the straightforward documentation. The API has the following parameters:" }, { "code": null, "e": 1391, "s": 1110, "text": "Activity (required): this can be either the fuel consumption of a vehicle or the distance travelled in miles. Since we’re comparing different modes of transportation, I will set this parameter as “3,910” — the roundtrip length, in miles, of travel from New York to Salt Lake City." }, { "code": null, "e": 1468, "s": 1391, "text": "activityType: this parameter denotes the value of the integer entered above." }, { "code": null, "e": 1682, "s": 1468, "text": "mode: refers to the mode of transportation. There are several options to choose from: dieselCar, petrolCar, anyCar, taxi, economyFlight, businessFlight, firstclassFlight, anyFlight, motorbike, bus and transitRail." }, { "code": null, "e": 1808, "s": 1682, "text": "fuelType: this pairs with the modes listed above: motorGasoline (also known as petrol), diesel, aviationGasoline and jetFuel." }, { "code": null, "e": 2114, "s": 1808, "text": "I assumed that all commercial flights use jet fuel but paired the parameter “anyFlight” with aviation gasoline to see if there is a major difference in carbon footprint between the two fuel types. I also assigned “dieselCar”, “bus” and “transitRail” to diesel fuel; I assumed all other modes use gasoline." }, { "code": null, "e": 2371, "s": 2114, "text": "I began by putting these parameters into two lists of equal length, associating each mode of transportation with each fuel type. I also deleted “anyCar” from the list because it overlaps with “taxi” and “petrolCar” and seemed redundant. Here are the lists:" }, { "code": null, "e": 2685, "s": 2371, "text": "list_of_modes = ['dieselCar', 'petrolCar', 'taxi', 'motorbike', 'bus', 'transitRail', 'economyFlight', 'businessFlight', 'firstclassFlight', 'anyFlight' ] list_of_fuels = ['diesel', 'motorGasoline', 'motorGasoline', 'motorGasoline', 'diesel', 'diesel', 'jetFuel', 'jetFuel','jetFuel', 'aviationGasoline']" }, { "code": null, "e": 3038, "s": 2685, "text": "Rather than manually enter each parameter into the system, I wrote a function to loop through both lists and output the API request as a dictionary. After importing the necessary packages, I defined the function, inserted the lists and packaged the output as a dictionary (for complete code, please see the jupyter notebook attached to this blog post)." }, { "code": null, "e": 3404, "s": 3038, "text": "#import necessary packages import requestsimport jsonimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport numpy as np%matplotlib inline #use carbon_slc_nyc function to create dictionary with mode of #transportation as keys and of carbon footprint as valuescarbon_footprint = {}carbon_footprint = carbon_slc_nyc(list_of_modes, list_of_fuels)" }, { "code": null, "e": 3621, "s": 3404, "text": "With the output packaged as a dictionary, I turned it into a pandas dataframe, renamed the columns to more appropriate titles, and converted the ‘Carbon Footprint’ column data into floats in preparation for plotting." }, { "code": null, "e": 3864, "s": 3621, "text": "df = pd.DataFrame(list(carbon_footprint_ground.items()))df.rename(columns = {0 :'Type of Transport'}, inplace = True)df.rename(columns = {1 :'Carbon_Footprint'}, inplace = True)df['Carbon_Footprint'] = df['Carbon_Footprint'].astype('float64')" }, { "code": null, "e": 4011, "s": 3864, "text": "With this DataFrame, I plotted a bar graph to visualize how much carbon each mode of transportation emits over the course of a 3,910-mile journey." }, { "code": null, "e": 4139, "s": 4011, "text": "plt.figure(figsize=(10,5))sns.barplot(x=df_ground['Type of Transport'], y=df_ground['Carbon_Footprint'])plt.xticks(rotation=45)" }, { "code": null, "e": 4834, "s": 4139, "text": "Interesting. If I’m choosing a mode of transportation with average fuel consumption, taking a bus, train, or economy flight is my best bet. However, the results create a lot of questions. This data satisfies the logical explanation that driving your own car is less efficient than sharing a ride and spreading total emissions of a vehicle over many people, like on a plane, bus, or train. But why is getting a first-class ticket on a flight so much worse than an economy-ticket? And why does your average bus have the lowest carbon footprint for this trip? Besides electric or LNG-fueled municipal busses, I don’t think diesel-fueled Greyhound or Concord Coach busses are very climate-friendly." }, { "code": null, "e": 5301, "s": 4834, "text": "I thought this distribution would be unique to the U.S and used another parameter to compare average mode of transport carbon footprint between countries. The API calls for a ‘usa’, ‘gbr’, and ‘def’ input to compare footprints between the United States, United Kingdom, and global average. Although this new parameter only allowed me to compare with two other options, I wanted to see if travelling 3910 miles outside the US would change the bus’s climate dominance." }, { "code": null, "e": 5651, "s": 5301, "text": "The world averages are about the same as in the US, but in the UK, busses are significantly more polluting. All air travel is about the same, suggesting that this emissions calculator standardizes emissions globally, which makes sense given the international nature of the industry. In the UK, travelling via rail or economy flights are my best bet." }, { "code": null, "e": 5685, "s": 5651, "text": "How are the emissions calculated?" }, { "code": null, "e": 6286, "s": 5685, "text": "After looking over these results, I checked the documentation further to find out how emissions are calculated. There are two methods. For the code above, the API used the average emissions factor for a vehicle in a given country and adjusted the result based on the distance travelled parameter. However, the API also offers a more specific calculation using the specific fuel efficiency of the vehicle. In this method, the API multiplies total fuel consumed by the emissions factor for that fuel. The emissions factor is usually provided by a government organization and is recommended by the IPCC." }, { "code": null, "e": 6338, "s": 6286, "text": "Total Emissions = Fuel Emission Factor * Fuel Usage" }, { "code": null, "e": 6821, "s": 6338, "text": "To get a more accurate assessment of my travel options, I needed to know how much energy the engine of each mode of transportation consumes. I picked three top options from the first descriptive analysis and limited the output to results in the US. In the next API call, I incorporated the fuel efficiency of my mom’s Suburu (33 miles per gallon of gasoline), a typical Greyhound bus (6 miles per gallon of diesel fuel), and the miles per gallon, in jet fuel, of an Airbus A220 100." }, { "code": null, "e": 7497, "s": 6821, "text": "The Airbus fuel consumption was challenging because the official Wikipedia fuel economy data is listed in either kg/km or miles per seat gallon, meaning I either had to convert the kg/km to mpg or multiply the miles per seat gallon by the number of seats in an Airbus A220 100 (I assumed I’d have a full flight both ways — SLC and NYC are popular destinations). I wasn’t sure if the API’s carbon calculator automatically converts the fuel consumption parameter into miles per seat gallon for public transportation, so I called the data both ways, entering both miles per gallon and miles per seat gallon in fear of counting twice. It made for an interesting contrast anyways." }, { "code": null, "e": 7606, "s": 7497, "text": "From a quick Google search, I found that Airbus A220s can have between 120–160 seats. I went with 140 seats." }, { "code": null, "e": 9017, "s": 7606, "text": "#miles per seat gallon divided by seats on the plane A220_mpg_A = (85.6 / 140) suburu_mpg_A = 33 greyhound_mpg_A = 6A220_gal_A = 3910/A220_mpg_Asuburu_gal_A = 3910/suburu_mpg_Agreyhound_gal_A = 3910/greyhound_mpg_Alist_gallons_A = [suburu_gal_A, greyhound_gal_A, A220_gal_A]list_fuel_type_A = ['motorGasoline', 'diesel', 'jetFuel']#call API and create dataframe carbon_footprint_A = {}carbon_footprint_A = carbon_fuel(list_gallons_A, list_fuel_type_A) df_A = pd.DataFrame(list(carbon_footprint_A.items()))df_A.rename(columns = {0 :'Fuel_Type'}, inplace = True)df_A.rename(columns = {1 :'Carbon_Footprint'}, inplace = True)df_A['Carbon_Footprint'] = df_A['Carbon_Footprint'].astype('float64')#now adjust to miles per seat gallonA220_mpg_B = 85.6 suburu_mpg_B = 33 #adjusting to miles per seat gallon with 55 seatsgreyhound_mpg_B = 6 * 55 A220_gal_B = 3910/A220_mpg_Bsuburu_gal_B = 3910/suburu_mpg_Bgreyhound_gal_B = 3910/greyhound_mpg_Blist_gallons_B = [suburu_gal_B, greyhound_gal_B, A220_gal_B]list_fuel_type_B = ['motorGasoline', 'diesel', 'jetFuel']#call API and create dataframecarbon_footprint_B = {}carbon_footprint_B = carbon_fuel(list_gallons_B, list_fuel_type_B)df_B = pd.DataFrame(list(carbon_footprint_B.items()))df_B.rename(columns = {0 :'Fuel_Type'}, inplace = True)df_B.rename(columns = {1 :'Carbon_Footprint'}, inplace = True)df_B['Carbon_Footprint'] = df_B['Carbon_Footprint'].astype('float64')" }, { "code": null, "e": 9039, "s": 9017, "text": "Here are the results:" }, { "code": null, "e": 9342, "s": 9039, "text": "After plotting the results from the first API call, it is clear that flying my own plane from New York to Salt Lake City and back would have a high environmental impact, as would driving my own Greyhound bus. Driving my mom’s Suburu is obviously more efficient for one person because it is way smaller." }, { "code": null, "e": 9949, "s": 9342, "text": "However, when spreading the high MPG and carbon emissions across a plane or bus full of people, it is clear that again, the bus has the lowest carbon footprint. Although a plane carries more than twice as many people as the bus and moves from NYC to SLC much faster than any sort of road travel, the bus has the benefit of using a lower-polluting and less energy-dense fuel while still spreading the climate cost among 55 people. My mom’s Suburu, while having one of the most efficient engines on the gasoline-powered automobile market, can’t compare — even if I picked up two hitchhikers (I did the math)." }, { "code": null, "e": 9960, "s": 9949, "text": "Conclusion" }, { "code": null, "e": 10496, "s": 9960, "text": "If limiting carbon emissions on an individual basis is your top priority, don’t drive. Although it requires more energy (and more carbon) to move a bus or commercial airliner across the country, you’re spreading the climate cost across many more people when you elect to travel by train, bus, or air. This analysis could be improved with more nuance and a granular dataset, but it is clear that on a high-level, incentivizing more people to get from A to B in larger vehicles should play a role in formulating decarbonization strategy." } ]
Check whether the sum of prime elements of the array is prime or not - GeeksforGeeks
23 Apr, 2021 Given an array having N elements. The task is to check if the sum of prime elements of the array is prime or not.Examples: Input: arr[] = {1, 2, 3} Output: Yes As there are two primes in the array i.e. 2 and 3. So, the sum of prime is 2 + 3 = 5 and 5 is also prime. Input: arr[] = {2, 3, 2, 2} Output: No Approach: First find prime number up to 10^5 using Sieve. Then iterate over all elements of the array. If the number is prime then add it to sum. And finally, check whether the sum is prime or not. If prime then prints Yes otherwise No.Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the above approach#include <bits/stdc++.h>#define ll long long int#define MAX 100000using namespace std;bool prime[MAX]; // Sieve to find primevoid sieve(){ memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int i = 2; i < MAX; i++) if (prime[i]) for (int j = 2 * i; j < MAX; j += i) prime[j] = false; } // Function to check if the sum of// prime is prime or notbool checkArray(int arr[], int n){ // find sum of all prime number ll sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (prime[sum]) return true; return false;} // Driver codeint main(){ // array of elements int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); sieve(); if (checkArray(arr, n)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the above approachimport java.io.*; class GFG { static int MAX =100000; static boolean prime[] = new boolean[MAX]; // Sieve to find primestatic void sieve(){ for(int i=0;i<MAX;i++) { prime[i] =true; } prime[0] = prime[1] = false; for (int i = 2; i < MAX; i++) if (prime[i]) for (int j = 2 * i; j < MAX; j += i) prime[j] = false; } // Function to check if the sum of// prime is prime or notstatic boolean checkArray(int arr[], int n){ // find sum of all prime number int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (prime[sum]) return true; return false;} // Driver code public static void main (String[] args) { // array of elements int arr[] = { 1, 2, 3 }; int n = arr.length; sieve(); if (checkArray(arr, n)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by shs.. # Python3 implementation of above approachfrom math import gcd, sqrt MAX = 100000 prime = [True] * MAX # Sieve to find primedef sieve() : # 0 and 1 are not prime numbers prime[0] = False prime[1] = False for i in range(2, MAX) : if prime[i] : for j in range(2**i, MAX, i) : prime[j] = False # Function to check if the sum of# prime is prime or notdef checkArray(arr, n) : # find sum of all prime number sum = 0 for i in range(n) : if prime[arr[i]] : sum += arr[i] # if sum is prime # then return yes if prime[sum] : return True return False # Driver codeif __name__ == "__main__" : # list of elements arr = [1, 2, 3] n = len(arr) sieve() if checkArray(arr, n) : print("Yes") else : print("No") # This code is contributed by ANKITRAI1 // C# implementation of the above approachusing System; class GFG{static int MAX = 100000; static bool[] prime = new bool[MAX]; // Sieve to find primestatic void sieve(){ for(int i = 0; i < MAX; i++) { prime[i] = true; } prime[0] = prime[1] = false; for (int i = 2; i < MAX; i++) if (prime[i]) for (int j = 2 * i; j < MAX; j += i) prime[j] = false;} // Function to check if the sum of// prime is prime or notstatic bool checkArray(int[] arr, int n){ // find sum of all prime number int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (prime[sum]) return true; return false;} // Driver codepublic static void Main (){ // array of elements int[] arr = new int[] { 1, 2, 3 }; int n = arr.Length; sieve(); if (checkArray(arr, n)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by mits <?php// PHP implementation of the// above approach // Sieve to find primefunction sieve(){ $MAX = 100000; $prime = array($MAX); for($i = 0; $i < $MAX; $i++) { $prime[$i] = true; } $prime[0] = $prime[1] = false; for ($i = 2; $i < $MAX; $i++) if ($prime[$i]) for ($j = 2 * $i; $j < $MAX; $j += $i) $prime[$j] = false;} // Function to check if the sum of// prime is prime or notfunction checkArray($arr, $n){ $prime = array(100000); // find sum of all prime number $sum = 0; for ($i = 0; $i < $n; $i++) if ($prime[$arr[$i]]) $sum += $arr[$i]; // if sum is prime // then return yes if ($prime[$sum]) return true; return false;} // Driver code$arr= array(1, 2, 3);$n = sizeof($arr); sieve(); if (checkArray($arr, $n)) echo "Yes";else echo "No"; // This code is contributed// by Akanksha Rai?> <script> // JavaScript implementation of the// above approach // function check whether a number// is prime or notfunction isPrime(n){ // Corner case if (n <= 1) return 0; // Check from 2 to n-1 for (let i = 2; i < n; i++) if (n % i == 0) return 0; return 1;} var prime = new Array(5); // Sieve to find primefunction sieve(){ for(i = 0; i <=5; i++) { prime[i] = isPrime(i); }} // Function to check if the sum of// prime is prime or notfunction checkArray(arr, n){ // find sum of all prime number sum = 0; for (i = 0; i <= n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (sum) return 1; return 0;} var arr= [1, 2, 3];n = 3; sieve(); if (checkArray(arr, n)) document.write("Yes");else document.write("No"); </script> Yes Time Complexity: O(n * log(log n)) Auxiliary Space: O(MAX) Shashank12 Mithun Kumar ankthon Akanksha_Rai subhammahato348 akshitsaxenaa09 Prime Number sieve Arrays Mathematical Arrays Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Next Greater Element Window Sliding Technique Count pairs with given sum Program to find sum of elements in a given array Reversal algorithm for array rotation Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24405, "s": 24377, "text": "\n23 Apr, 2021" }, { "code": null, "e": 24529, "s": 24405, "text": "Given an array having N elements. The task is to check if the sum of prime elements of the array is prime or not.Examples: " }, { "code": null, "e": 24714, "s": 24529, "text": "Input: arr[] = {1, 2, 3}\nOutput: Yes\nAs there are two primes in the array i.e. 2 and 3. \nSo, the sum of prime is 2 + 3 = 5 and 5 is also prime. \n\nInput: arr[] = {2, 3, 2, 2}\nOutput: No" }, { "code": null, "e": 25003, "s": 24714, "text": "Approach: First find prime number up to 10^5 using Sieve. Then iterate over all elements of the array. If the number is prime then add it to sum. And finally, check whether the sum is prime or not. If prime then prints Yes otherwise No.Below is the implementation of the above approach: " }, { "code": null, "e": 25007, "s": 25003, "text": "C++" }, { "code": null, "e": 25012, "s": 25007, "text": "Java" }, { "code": null, "e": 25020, "s": 25012, "text": "Python3" }, { "code": null, "e": 25023, "s": 25020, "text": "C#" }, { "code": null, "e": 25027, "s": 25023, "text": "PHP" }, { "code": null, "e": 25038, "s": 25027, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>#define ll long long int#define MAX 100000using namespace std;bool prime[MAX]; // Sieve to find primevoid sieve(){ memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int i = 2; i < MAX; i++) if (prime[i]) for (int j = 2 * i; j < MAX; j += i) prime[j] = false; } // Function to check if the sum of// prime is prime or notbool checkArray(int arr[], int n){ // find sum of all prime number ll sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (prime[sum]) return true; return false;} // Driver codeint main(){ // array of elements int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); sieve(); if (checkArray(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 25996, "s": 25038, "text": null }, { "code": "// Java implementation of the above approachimport java.io.*; class GFG { static int MAX =100000; static boolean prime[] = new boolean[MAX]; // Sieve to find primestatic void sieve(){ for(int i=0;i<MAX;i++) { prime[i] =true; } prime[0] = prime[1] = false; for (int i = 2; i < MAX; i++) if (prime[i]) for (int j = 2 * i; j < MAX; j += i) prime[j] = false; } // Function to check if the sum of// prime is prime or notstatic boolean checkArray(int arr[], int n){ // find sum of all prime number int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (prime[sum]) return true; return false;} // Driver code public static void main (String[] args) { // array of elements int arr[] = { 1, 2, 3 }; int n = arr.length; sieve(); if (checkArray(arr, n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by shs..", "e": 27061, "s": 25996, "text": null }, { "code": "# Python3 implementation of above approachfrom math import gcd, sqrt MAX = 100000 prime = [True] * MAX # Sieve to find primedef sieve() : # 0 and 1 are not prime numbers prime[0] = False prime[1] = False for i in range(2, MAX) : if prime[i] : for j in range(2**i, MAX, i) : prime[j] = False # Function to check if the sum of# prime is prime or notdef checkArray(arr, n) : # find sum of all prime number sum = 0 for i in range(n) : if prime[arr[i]] : sum += arr[i] # if sum is prime # then return yes if prime[sum] : return True return False # Driver codeif __name__ == \"__main__\" : # list of elements arr = [1, 2, 3] n = len(arr) sieve() if checkArray(arr, n) : print(\"Yes\") else : print(\"No\") # This code is contributed by ANKITRAI1", "e": 27948, "s": 27061, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{static int MAX = 100000; static bool[] prime = new bool[MAX]; // Sieve to find primestatic void sieve(){ for(int i = 0; i < MAX; i++) { prime[i] = true; } prime[0] = prime[1] = false; for (int i = 2; i < MAX; i++) if (prime[i]) for (int j = 2 * i; j < MAX; j += i) prime[j] = false;} // Function to check if the sum of// prime is prime or notstatic bool checkArray(int[] arr, int n){ // find sum of all prime number int sum = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (prime[sum]) return true; return false;} // Driver codepublic static void Main (){ // array of elements int[] arr = new int[] { 1, 2, 3 }; int n = arr.Length; sieve(); if (checkArray(arr, n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by mits", "e": 28997, "s": 27948, "text": null }, { "code": "<?php// PHP implementation of the// above approach // Sieve to find primefunction sieve(){ $MAX = 100000; $prime = array($MAX); for($i = 0; $i < $MAX; $i++) { $prime[$i] = true; } $prime[0] = $prime[1] = false; for ($i = 2; $i < $MAX; $i++) if ($prime[$i]) for ($j = 2 * $i; $j < $MAX; $j += $i) $prime[$j] = false;} // Function to check if the sum of// prime is prime or notfunction checkArray($arr, $n){ $prime = array(100000); // find sum of all prime number $sum = 0; for ($i = 0; $i < $n; $i++) if ($prime[$arr[$i]]) $sum += $arr[$i]; // if sum is prime // then return yes if ($prime[$sum]) return true; return false;} // Driver code$arr= array(1, 2, 3);$n = sizeof($arr); sieve(); if (checkArray($arr, $n)) echo \"Yes\";else echo \"No\"; // This code is contributed// by Akanksha Rai?>", "e": 29924, "s": 28997, "text": null }, { "code": "<script> // JavaScript implementation of the// above approach // function check whether a number// is prime or notfunction isPrime(n){ // Corner case if (n <= 1) return 0; // Check from 2 to n-1 for (let i = 2; i < n; i++) if (n % i == 0) return 0; return 1;} var prime = new Array(5); // Sieve to find primefunction sieve(){ for(i = 0; i <=5; i++) { prime[i] = isPrime(i); }} // Function to check if the sum of// prime is prime or notfunction checkArray(arr, n){ // find sum of all prime number sum = 0; for (i = 0; i <= n; i++) if (prime[arr[i]]) sum += arr[i]; // if sum is prime // then return yes if (sum) return 1; return 0;} var arr= [1, 2, 3];n = 3; sieve(); if (checkArray(arr, n)) document.write(\"Yes\");else document.write(\"No\"); </script>", "e": 30803, "s": 29924, "text": null }, { "code": null, "e": 30807, "s": 30803, "text": "Yes" }, { "code": null, "e": 30844, "s": 30809, "text": "Time Complexity: O(n * log(log n))" }, { "code": null, "e": 30868, "s": 30844, "text": "Auxiliary Space: O(MAX)" }, { "code": null, "e": 30879, "s": 30868, "text": "Shashank12" }, { "code": null, "e": 30892, "s": 30879, "text": "Mithun Kumar" }, { "code": null, "e": 30900, "s": 30892, "text": "ankthon" }, { "code": null, "e": 30913, "s": 30900, "text": "Akanksha_Rai" }, { "code": null, "e": 30929, "s": 30913, "text": "subhammahato348" }, { "code": null, "e": 30945, "s": 30929, "text": "akshitsaxenaa09" }, { "code": null, "e": 30958, "s": 30945, "text": "Prime Number" }, { "code": null, "e": 30964, "s": 30958, "text": "sieve" }, { "code": null, "e": 30971, "s": 30964, "text": "Arrays" }, { "code": null, "e": 30984, "s": 30971, "text": "Mathematical" }, { "code": null, "e": 30991, "s": 30984, "text": "Arrays" }, { "code": null, "e": 31004, "s": 30991, "text": "Mathematical" }, { "code": null, "e": 31017, "s": 31004, "text": "Prime Number" }, { "code": null, "e": 31023, "s": 31017, "text": "sieve" }, { "code": null, "e": 31121, "s": 31023, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31130, "s": 31121, "text": "Comments" }, { "code": null, "e": 31143, "s": 31130, "text": "Old Comments" }, { "code": null, "e": 31164, "s": 31143, "text": "Next Greater Element" }, { "code": null, "e": 31189, "s": 31164, "text": "Window Sliding Technique" }, { "code": null, "e": 31216, "s": 31189, "text": "Count pairs with given sum" }, { "code": null, "e": 31265, "s": 31216, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 31303, "s": 31265, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31333, "s": 31303, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31393, "s": 31333, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31408, "s": 31393, "text": "C++ Data Types" }, { "code": null, "e": 31451, "s": 31408, "text": "Set in C++ Standard Template Library (STL)" } ]
ASP.NET - Validators
ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or contradictory data don't get stored. ASP.NET provides the following validation controls: RequiredFieldValidator RangeValidator CompareValidator RegularExpressionValidator CustomValidator ValidationSummary The validation control classes are inherited from the BaseValidator class hence they inherit its properties and methods. Therefore, it would help to take a look at the properties and the methods of this base class, which are common for all the validation controls: The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text box to force input into the text box. The syntax of the control is as given: <asp:RequiredFieldValidator ID="rfvcandidate" runat="server" ControlToValidate ="ddlcandidate" ErrorMessage="Please choose a candidate" InitialValue="Please choose a candidate"> </asp:RequiredFieldValidator> The RangeValidator control verifies that the input value falls within a predetermined range. It has three specific properties: The syntax of the control is as given: <asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass" ErrorMessage="Enter your class (6 - 12)" MaximumValue="12" MinimumValue="6" Type="Integer"> </asp:RangeValidator> The CompareValidator control compares a value in one control with a fixed value or a value in another control. It has the following specific properties: The basic syntax of the control is as follows: <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator"> </asp:CompareValidator> The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular expression. The regular expression is set in the ValidationExpression property. The following table summarizes the commonly used syntax constructs for regular expressions: Apart from single character match, a class of characters could be specified that can be matched, called the metacharacters. Quantifiers could be added to specify number of times a character could appear. The syntax of the control is as given: <asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string" ValidationExpression="string" ValidationGroup="string"> </asp:RegularExpressionValidator> The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation. The client side validation is accomplished through the ClientValidationFunction property. The client side validation routine should be written in a scripting language, such as JavaScript or VBScript, which the browser can understand. The server side validation routine must be called from the control's ServerValidate event handler. The server side validation routine should be written in any .Net language, like C# or VB.Net. The basic syntax for the control is as given: <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator"> </asp:CustomValidator> The ValidationSummary control does not perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation. The following two mutually inclusive properties list out the error message: ShowSummary : shows the error messages in specified format. ShowSummary : shows the error messages in specified format. ShowMessageBox : shows the error messages in a separate window. ShowMessageBox : shows the error messages in a separate window. The syntax for the control is as given: <asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" /> Complex pages have different groups of information provided in different panels. In such situation, a need might arise for performing validation separately for separate group. This kind of situation is handled using validation groups. To create a validation group, you should put the input controls and the validation controls into the same logical group by setting their ValidationGroup property. The following example describes a form to be filled up by all the students of a school, divided into four houses, for electing the school president. Here, we use the validation controls to validate the user input. This is the form in design view: The content file code is as given: <form id="form1" runat="server"> <table style="width: 66%;"> <tr> <td class="style1" colspan="3" align="center"> <asp:Label ID="lblmsg" Text="President Election Form : Choose your president" runat="server" /> </td> </tr> <tr> <td class="style3"> Candidate: </td> <td class="style2"> <asp:DropDownList ID="ddlcandidate" runat="server" style="width:239px"> <asp:ListItem>Please Choose a Candidate</asp:ListItem> <asp:ListItem>M H Kabir</asp:ListItem> <asp:ListItem>Steve Taylor</asp:ListItem> <asp:ListItem>John Abraham</asp:ListItem> <asp:ListItem>Venus Williams</asp:ListItem> </asp:DropDownList> </td> <td> <asp:RequiredFieldValidator ID="rfvcandidate" runat="server" ControlToValidate ="ddlcandidate" ErrorMessage="Please choose a candidate" InitialValue="Please choose a candidate"> </asp:RequiredFieldValidator> </td> </tr> <tr> <td class="style3"> House: </td> <td class="style2"> <asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow"> <asp:ListItem>Red</asp:ListItem> <asp:ListItem>Blue</asp:ListItem> <asp:ListItem>Yellow</asp:ListItem> <asp:ListItem>Green</asp:ListItem> </asp:RadioButtonList> </td> <td> <asp:RequiredFieldValidator ID="rfvhouse" runat="server" ControlToValidate="rblhouse" ErrorMessage="Enter your house name" > </asp:RequiredFieldValidator> <br /> </td> </tr> <tr> <td class="style3"> Class: </td> <td class="style2"> <asp:TextBox ID="txtclass" runat="server"></asp:TextBox> </td> <td> <asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass" ErrorMessage="Enter your class (6 - 12)" MaximumValue="12" MinimumValue="6" Type="Integer"> </asp:RangeValidator> </td> </tr> <tr> <td class="style3"> Email: </td> <td class="style2"> <asp:TextBox ID="txtemail" runat="server" style="width:250px"> </asp:TextBox> </td> <td> <asp:RegularExpressionValidator ID="remail" runat="server" ControlToValidate="txtemail" ErrorMessage="Enter your email" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator> </td> </tr> <tr> <td class="style3" align="center" colspan="3"> <asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click" style="text-align: center" Text="Submit" style="width:140px" /> </td> </tr> </table> <asp:ValidationSummary ID="ValidationSummary1" runat="server" DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" /> </form> The code behind the submit button: protected void btnsubmit_Click(object sender, EventArgs e) { if (Page.IsValid) { lblmsg.Text = "Thank You"; } else { lblmsg.Text = "Fill up all the fields"; } } 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2485, "s": 2347, "text": "ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or contradictory data don't get stored." }, { "code": null, "e": 2537, "s": 2485, "text": "ASP.NET provides the following validation controls:" }, { "code": null, "e": 2560, "s": 2537, "text": "RequiredFieldValidator" }, { "code": null, "e": 2575, "s": 2560, "text": "RangeValidator" }, { "code": null, "e": 2592, "s": 2575, "text": "CompareValidator" }, { "code": null, "e": 2619, "s": 2592, "text": "RegularExpressionValidator" }, { "code": null, "e": 2635, "s": 2619, "text": "CustomValidator" }, { "code": null, "e": 2653, "s": 2635, "text": "ValidationSummary" }, { "code": null, "e": 2918, "s": 2653, "text": "The validation control classes are inherited from the BaseValidator class hence they inherit its properties and methods. Therefore, it would help to take a look at the properties and the methods of this base class, which are common for all the validation controls:" }, { "code": null, "e": 3068, "s": 2918, "text": "The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text box to force input into the text box." }, { "code": null, "e": 3107, "s": 3068, "text": "The syntax of the control is as given:" }, { "code": null, "e": 3330, "s": 3107, "text": "<asp:RequiredFieldValidator ID=\"rfvcandidate\" \n runat=\"server\" ControlToValidate =\"ddlcandidate\"\n ErrorMessage=\"Please choose a candidate\" \n InitialValue=\"Please choose a candidate\">\n \n</asp:RequiredFieldValidator>" }, { "code": null, "e": 3423, "s": 3330, "text": "The RangeValidator control verifies that the input value falls within a predetermined range." }, { "code": null, "e": 3457, "s": 3423, "text": "It has three specific properties:" }, { "code": null, "e": 3496, "s": 3457, "text": "The syntax of the control is as given:" }, { "code": null, "e": 3699, "s": 3496, "text": "<asp:RangeValidator ID=\"rvclass\" runat=\"server\" ControlToValidate=\"txtclass\" \n ErrorMessage=\"Enter your class (6 - 12)\" MaximumValue=\"12\" \n MinimumValue=\"6\" Type=\"Integer\">\n \n</asp:RangeValidator>" }, { "code": null, "e": 3810, "s": 3699, "text": "The CompareValidator control compares a value in one control with a fixed value or a value in another control." }, { "code": null, "e": 3852, "s": 3810, "text": "It has the following specific properties:" }, { "code": null, "e": 3899, "s": 3852, "text": "The basic syntax of the control is as follows:" }, { "code": null, "e": 4024, "s": 3899, "text": "<asp:CompareValidator ID=\"CompareValidator1\" runat=\"server\" \n ErrorMessage=\"CompareValidator\">\n \n</asp:CompareValidator>" }, { "code": null, "e": 4211, "s": 4024, "text": "The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular expression. The regular expression is set in the ValidationExpression property." }, { "code": null, "e": 4303, "s": 4211, "text": "The following table summarizes the commonly used syntax constructs for regular expressions:" }, { "code": null, "e": 4427, "s": 4303, "text": "Apart from single character match, a class of characters could be specified that can be matched, called the metacharacters." }, { "code": null, "e": 4507, "s": 4427, "text": "Quantifiers could be added to specify number of times a character could appear." }, { "code": null, "e": 4546, "s": 4507, "text": "The syntax of the control is as given:" }, { "code": null, "e": 4724, "s": 4546, "text": "<asp:RegularExpressionValidator ID=\"string\" runat=\"server\" ErrorMessage=\"string\"\n ValidationExpression=\"string\" ValidationGroup=\"string\">\n \n</asp:RegularExpressionValidator>" }, { "code": null, "e": 4872, "s": 4724, "text": "The CustomValidator control allows writing application specific custom validation routines for both the client side and the server side validation." }, { "code": null, "e": 5106, "s": 4872, "text": "The client side validation is accomplished through the ClientValidationFunction property. The client side validation routine should be written in a scripting language, such as JavaScript or VBScript, which the browser can understand." }, { "code": null, "e": 5299, "s": 5106, "text": "The server side validation routine must be called from the control's ServerValidate event handler. The server side validation routine should be written in any .Net language, like C# or VB.Net." }, { "code": null, "e": 5345, "s": 5299, "text": "The basic syntax for the control is as given:" }, { "code": null, "e": 5502, "s": 5345, "text": "<asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" \n ClientValidationFunction=.cvf_func. ErrorMessage=\"CustomValidator\">\n \n</asp:CustomValidator>" }, { "code": null, "e": 5723, "s": 5502, "text": "The ValidationSummary control does not perform any validation but shows a summary of all errors in the page. The summary displays the values of the ErrorMessage property of all validation controls that failed validation." }, { "code": null, "e": 5799, "s": 5723, "text": "The following two mutually inclusive properties list out the error message:" }, { "code": null, "e": 5859, "s": 5799, "text": "ShowSummary : shows the error messages in specified format." }, { "code": null, "e": 5919, "s": 5859, "text": "ShowSummary : shows the error messages in specified format." }, { "code": null, "e": 5983, "s": 5919, "text": "ShowMessageBox : shows the error messages in a separate window." }, { "code": null, "e": 6047, "s": 5983, "text": "ShowMessageBox : shows the error messages in a separate window." }, { "code": null, "e": 6087, "s": 6047, "text": "The syntax for the control is as given:" }, { "code": null, "e": 6225, "s": 6087, "text": "<asp:ValidationSummary ID=\"ValidationSummary1\" runat=\"server\" \n DisplayMode = \"BulletList\" ShowSummary = \"true\" HeaderText=\"Errors:\" />" }, { "code": null, "e": 6460, "s": 6225, "text": "Complex pages have different groups of information provided in different panels. In such situation, a need might arise for performing validation separately for separate group. This kind of situation is handled using validation groups." }, { "code": null, "e": 6623, "s": 6460, "text": "To create a validation group, you should put the input controls and the validation controls into the same logical group by setting their ValidationGroup property." }, { "code": null, "e": 6837, "s": 6623, "text": "The following example describes a form to be filled up by all the students of a school, divided into four houses, for electing the school president. Here, we use the validation controls to validate the user input." }, { "code": null, "e": 6870, "s": 6837, "text": "This is the form in design view:" }, { "code": null, "e": 6905, "s": 6870, "text": "The content file code is as given:" }, { "code": null, "e": 10204, "s": 6905, "text": "<form id=\"form1\" runat=\"server\">\n\n <table style=\"width: 66%;\">\n \n <tr>\n <td class=\"style1\" colspan=\"3\" align=\"center\">\n <asp:Label ID=\"lblmsg\" \n Text=\"President Election Form : Choose your president\" \n runat=\"server\" />\n </td>\n </tr>\n\n <tr>\n <td class=\"style3\">\n Candidate:\n </td>\n\n <td class=\"style2\">\n <asp:DropDownList ID=\"ddlcandidate\" runat=\"server\" style=\"width:239px\">\n <asp:ListItem>Please Choose a Candidate</asp:ListItem>\n <asp:ListItem>M H Kabir</asp:ListItem>\n <asp:ListItem>Steve Taylor</asp:ListItem>\n <asp:ListItem>John Abraham</asp:ListItem>\n <asp:ListItem>Venus Williams</asp:ListItem>\n </asp:DropDownList>\n </td>\n\n <td>\n <asp:RequiredFieldValidator ID=\"rfvcandidate\" \n runat=\"server\" ControlToValidate =\"ddlcandidate\"\n ErrorMessage=\"Please choose a candidate\" \n InitialValue=\"Please choose a candidate\">\n </asp:RequiredFieldValidator>\n </td>\n </tr>\n\n <tr>\n <td class=\"style3\">\n House:\n </td>\n\n <td class=\"style2\">\n <asp:RadioButtonList ID=\"rblhouse\" runat=\"server\" RepeatLayout=\"Flow\">\n <asp:ListItem>Red</asp:ListItem>\n <asp:ListItem>Blue</asp:ListItem>\n <asp:ListItem>Yellow</asp:ListItem>\n <asp:ListItem>Green</asp:ListItem>\n </asp:RadioButtonList>\n </td>\n\n <td>\n <asp:RequiredFieldValidator ID=\"rfvhouse\" runat=\"server\" \n ControlToValidate=\"rblhouse\" ErrorMessage=\"Enter your house name\" >\n </asp:RequiredFieldValidator>\n <br />\n </td>\n </tr>\n\n <tr>\n <td class=\"style3\">\n Class:\n </td>\n\n <td class=\"style2\">\n <asp:TextBox ID=\"txtclass\" runat=\"server\"></asp:TextBox>\n </td>\n\n <td>\n <asp:RangeValidator ID=\"rvclass\" \n runat=\"server\" ControlToValidate=\"txtclass\" \n ErrorMessage=\"Enter your class (6 - 12)\" MaximumValue=\"12\" \n MinimumValue=\"6\" Type=\"Integer\">\n </asp:RangeValidator>\n </td>\n </tr>\n\n <tr>\n <td class=\"style3\">\n Email:\n </td>\n\n <td class=\"style2\">\n <asp:TextBox ID=\"txtemail\" runat=\"server\" style=\"width:250px\">\n </asp:TextBox>\n </td>\n\n <td>\n <asp:RegularExpressionValidator ID=\"remail\" runat=\"server\" \n ControlToValidate=\"txtemail\" ErrorMessage=\"Enter your email\" \n ValidationExpression=\"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\">\n </asp:RegularExpressionValidator>\n </td>\n </tr>\n\n <tr>\n <td class=\"style3\" align=\"center\" colspan=\"3\">\n <asp:Button ID=\"btnsubmit\" runat=\"server\" onclick=\"btnsubmit_Click\" \n style=\"text-align: center\" Text=\"Submit\" style=\"width:140px\" />\n </td>\n </tr>\n </table>\n <asp:ValidationSummary ID=\"ValidationSummary1\" runat=\"server\" \n DisplayMode =\"BulletList\" ShowSummary =\"true\" HeaderText=\"Errors:\" />\n</form>" }, { "code": null, "e": 10239, "s": 10204, "text": "The code behind the submit button:" }, { "code": null, "e": 10430, "s": 10239, "text": "protected void btnsubmit_Click(object sender, EventArgs e)\n{\n if (Page.IsValid)\n {\n lblmsg.Text = \"Thank You\";\n }\n else\n {\n lblmsg.Text = \"Fill up all the fields\";\n }\n}" }, { "code": null, "e": 10465, "s": 10430, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10479, "s": 10465, "text": " Anadi Sharma" }, { "code": null, "e": 10514, "s": 10479, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10537, "s": 10514, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 10571, "s": 10537, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 10591, "s": 10571, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 10626, "s": 10591, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 10643, "s": 10626, "text": " University Code" }, { "code": null, "e": 10678, "s": 10643, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10695, "s": 10678, "text": " University Code" }, { "code": null, "e": 10729, "s": 10695, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 10744, "s": 10729, "text": " Bhrugen Patel" }, { "code": null, "e": 10751, "s": 10744, "text": " Print" }, { "code": null, "e": 10762, "s": 10751, "text": " Add Notes" } ]
How to get the Position of mouse pointer in jQuery ? - GeeksforGeeks
31 Mar, 2021 In this article, we will see how to get the position of the mouse pointer using jQuery. To get the position of mouse pointer, event.pageX, and event.pageY property is used. The event.pageX property is used to find the position of the mouse pointer relative to the left edge of the document. The event.pageY property is used to find the position of the mouse pointer relative to the top edge of the document. Syntax: event.pageX event.pageY Here, we use on() method to attach one or more event handlers for the selected elements and the text() method to set or return the text content of the element Example: HTML <!DOCTYPE html><html> <head> <title> How to get the Position of mouse pointer in jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { $(document).on("mousemove", function (event) { $("#GFG").text("Mouse Position (" + event.pageX + ", " + event.pageY + ")"); }); }); </script> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to get the Position of mouse pointer in jQuery? </h3> <div id="GFG"></div></body> </html> Output: HTML-Tags jQuery-Questions JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method How to get the value in an input text box using jQuery ? Difference Between JavaScript and jQuery QR Code Generator using HTML, CSS and jQuery 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": 25675, "s": 25647, "text": "\n31 Mar, 2021" }, { "code": null, "e": 26083, "s": 25675, "text": "In this article, we will see how to get the position of the mouse pointer using jQuery. To get the position of mouse pointer, event.pageX, and event.pageY property is used. The event.pageX property is used to find the position of the mouse pointer relative to the left edge of the document. The event.pageY property is used to find the position of the mouse pointer relative to the top edge of the document." }, { "code": null, "e": 26091, "s": 26083, "text": "Syntax:" }, { "code": null, "e": 26115, "s": 26091, "text": "event.pageX\nevent.pageY" }, { "code": null, "e": 26274, "s": 26115, "text": "Here, we use on() method to attach one or more event handlers for the selected elements and the text() method to set or return the text content of the element" }, { "code": null, "e": 26283, "s": 26274, "text": "Example:" }, { "code": null, "e": 26288, "s": 26283, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to get the Position of mouse pointer in jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(document).on(\"mousemove\", function (event) { $(\"#GFG\").text(\"Mouse Position (\" + event.pageX + \", \" + event.pageY + \")\"); }); }); </script> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h3> How to get the Position of mouse pointer in jQuery? </h3> <div id=\"GFG\"></div></body> </html>", "e": 27058, "s": 26288, "text": null }, { "code": null, "e": 27066, "s": 27058, "text": "Output:" }, { "code": null, "e": 27076, "s": 27066, "text": "HTML-Tags" }, { "code": null, "e": 27093, "s": 27076, "text": "jQuery-Questions" }, { "code": null, "e": 27100, "s": 27093, "text": "JQuery" }, { "code": null, "e": 27117, "s": 27100, "text": "Web Technologies" }, { "code": null, "e": 27215, "s": 27117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27224, "s": 27215, "text": "Comments" }, { "code": null, "e": 27237, "s": 27224, "text": "Old Comments" }, { "code": null, "e": 27310, "s": 27237, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 27333, "s": 27310, "text": "jQuery | ajax() Method" }, { "code": null, "e": 27390, "s": 27333, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 27431, "s": 27390, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 27476, "s": 27431, "text": "QR Code Generator using HTML, CSS and jQuery" }, { "code": null, "e": 27518, "s": 27476, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27551, "s": 27518, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27613, "s": 27551, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27656, "s": 27613, "text": "How to fetch data from an API in ReactJS ?" } ]
Swift - Extensions
Functionality of an existing class, structure or enumeration type can be added with the help of extensions. Type functionality can be added with extensions but overriding the functionality is not possible with extensions. Swift Extension Functionalities − Adding computed properties and computed type properties Defining instance and type methods. Providing new initializers. Defining subscripts Defining and using new nested types Making an existing type conform to a protocol Extensions are declared with the keyword 'extension' extension SomeType { // new functionality can be added here } Existing type can also be added with extensions to make it as a protocol standard and its syntax is similar to that of classes or structures. extension SomeType: SomeProtocol, AnotherProtocol { // protocol requirements is described here } Computed 'instance' and 'type' properties can also be extended with the help of extensions. extension Int { var add: Int {return self + 100 } var sub: Int { return self - 10 } var mul: Int { return self * 10 } var div: Int { return self / 5 } } let addition = 3.add print("Addition is \(addition)") let subtraction = 120.sub print("Subtraction is \(subtraction)") let multiplication = 39.mul print("Multiplication is \(multiplication)") let division = 55.div print("Division is \(division)") let mix = 30.add + 34.sub print("Mixed Type is \(mix)") When we run the above program using playground, we get the following result − Addition is 103 Subtraction is 110 Multiplication is 390 Division is 11 Mixed Type is 154 Swift 4 provides the flexibility to add new initializers to an existing type by extensions. The user can add their own custom types to extend the types already defined and additional initialization options are also possible. Extensions supports only init(). deinit() is not supported by the extensions. struct sum { var num1 = 100, num2 = 200 } struct diff { var no1 = 200, no2 = 100 } struct mult { var a = sum() var b = diff() } let calc = mult() print ("Inside mult block \(calc.a.num1, calc.a.num2)") print("Inside mult block \(calc.b.no1, calc.b.no2)") let memcalc = mult(a: sum(num1: 300, num2: 500),b: diff(no1: 300, no2: 100)) print("Inside mult block \(memcalc.a.num1, memcalc.a.num2)") print("Inside mult block \(memcalc.b.no1, memcalc.b.no2)") extension mult { init(x: sum, y: diff) { let X = x.num1 + x.num2 let Y = y.no1 + y.no2 } } let a = sum(num1: 100, num2: 200) print("Inside Sum Block:\( a.num1, a.num2)") let b = diff(no1: 200, no2: 100) print("Inside Diff Block: \(b.no1, b.no2)") When we run the above program using playground, we get the following result − Inside mult block (100, 200) Inside mult block (200, 100) Inside mult block (300, 500) Inside mult block (300, 100) Inside Sum Block:(100, 200) Inside Diff Block: (200, 100) New instance methods and type methods can be added further to the subclass with the help of extensions. extension Int { func topics(summation: () -> ()) { for _ in 0..<self { summation() } } } 4.topics(summation: { print("Inside Extensions Block") }) 3.topics(summation: { print("Inside Type Casting Block") }) When we run the above program using playground, we get the following result − Inside Extensions Block Inside Extensions Block Inside Extensions Block Inside Extensions Block Inside Type Casting Block Inside Type Casting Block Inside Type Casting Block topics() function takes argument of type '(summation: () → ())' to indicate the function does not take any arguments and it won't return any values. To call that function multiple number of times, for block is initialized and call to the method with topic() is initialized. Instance methods can also be mutated when declared as extensions. Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation. extension Double { mutating func square() { let pi = 3.1415 self = pi * self * self } } var Trial1 = 3.3 Trial1.square() print("Area of circle is: \(Trial1)") var Trial2 = 5.8 Trial2.square() print("Area of circle is: \(Trial2)") var Trial3 = 120.3 Trial3.square() print("Area of circle is: \(Trial3)") When we run the above program using playground, we get the following result − Area of circle is: 34.210935 Area of circle is: 105.68006 Area of circle is: 45464.070735 Adding new subscripts to already declared instances can also be possible with extensions. extension Int { subscript(var multtable: Int) -> Int { var no1 = 1 while multtable > 0 { no1 *= 10 --multtable } return (self / no1) % 10 } } print(12[0]) print(7869[1]) print(786543[2]) When we run the above program using playground, we get the following result − 2 6 5 Nested types for class, structure and enumeration instances can also be extended with the help of extensions. extension Int { enum calc { case add case sub case mult case div case anything } var print: calc { switch self { case 0: return .add case 1: return .sub case 2: return .mult case 3: return .div default: return .anything } } } func result(numb: [Int]) { for i in numb { switch i.print { case .add: print(" 10 ") case .sub: print(" 20 ") case .mult: print(" 30 ") case .div: print(" 40 ") default: print(" 50 ") } } } result(numb: [0, 1, 2, 3, 4, 7]) When we run the above program using playground, we get the following result − 10 20 30 40 50 50 38 Lectures 1 hours Ashish Sharma 13 Lectures 2 hours Three Millennials 7 Lectures 1 hours Three Millennials 22 Lectures 1 hours Frahaan Hussain 12 Lectures 39 mins Devasena Rajendran 40 Lectures 2.5 hours Grant Klimaytys Print Add Notes Bookmark this page
[ { "code": null, "e": 2475, "s": 2253, "text": "Functionality of an existing class, structure or enumeration type can be added with the help of extensions. Type functionality can be added with extensions but overriding the functionality is not possible with extensions." }, { "code": null, "e": 2509, "s": 2475, "text": "Swift Extension Functionalities −" }, { "code": null, "e": 2565, "s": 2509, "text": "Adding computed properties and computed type properties" }, { "code": null, "e": 2601, "s": 2565, "text": "Defining instance and type methods." }, { "code": null, "e": 2629, "s": 2601, "text": "Providing new initializers." }, { "code": null, "e": 2649, "s": 2629, "text": "Defining subscripts" }, { "code": null, "e": 2685, "s": 2649, "text": "Defining and using new nested types" }, { "code": null, "e": 2731, "s": 2685, "text": "Making an existing type conform to a protocol" }, { "code": null, "e": 2784, "s": 2731, "text": "Extensions are declared with the keyword 'extension'" }, { "code": null, "e": 2850, "s": 2784, "text": "extension SomeType {\n // new functionality can be added here\n}\n" }, { "code": null, "e": 2992, "s": 2850, "text": "Existing type can also be added with extensions to make it as a protocol standard and its syntax is similar to that of classes or structures." }, { "code": null, "e": 3093, "s": 2992, "text": "extension SomeType: SomeProtocol, AnotherProtocol {\n // protocol requirements is described here\n}\n" }, { "code": null, "e": 3185, "s": 3093, "text": "Computed 'instance' and 'type' properties can also be extended with the help of extensions." }, { "code": null, "e": 3658, "s": 3185, "text": "extension Int {\n var add: Int {return self + 100 }\n var sub: Int { return self - 10 }\n var mul: Int { return self * 10 }\n var div: Int { return self / 5 }\n}\n\nlet addition = 3.add\nprint(\"Addition is \\(addition)\")\n\nlet subtraction = 120.sub\nprint(\"Subtraction is \\(subtraction)\")\n\nlet multiplication = 39.mul\nprint(\"Multiplication is \\(multiplication)\")\n\nlet division = 55.div\nprint(\"Division is \\(division)\")\n\nlet mix = 30.add + 34.sub\nprint(\"Mixed Type is \\(mix)\")" }, { "code": null, "e": 3736, "s": 3658, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 3827, "s": 3736, "text": "Addition is 103\nSubtraction is 110\nMultiplication is 390\nDivision is 11\nMixed Type is 154\n" }, { "code": null, "e": 4130, "s": 3827, "text": "Swift 4 provides the flexibility to add new initializers to an existing type by extensions. The user can add their own custom types to extend the types already defined and additional initialization options are also possible. Extensions supports only init(). deinit() is not supported by the extensions." }, { "code": null, "e": 4866, "s": 4130, "text": "struct sum {\n var num1 = 100, num2 = 200\n}\n\nstruct diff {\n var no1 = 200, no2 = 100\n}\n\nstruct mult {\n var a = sum()\n var b = diff()\n}\n\nlet calc = mult()\nprint (\"Inside mult block \\(calc.a.num1, calc.a.num2)\")\nprint(\"Inside mult block \\(calc.b.no1, calc.b.no2)\")\n\nlet memcalc = mult(a: sum(num1: 300, num2: 500),b: diff(no1: 300, no2: 100))\nprint(\"Inside mult block \\(memcalc.a.num1, memcalc.a.num2)\")\nprint(\"Inside mult block \\(memcalc.b.no1, memcalc.b.no2)\")\n\nextension mult {\n init(x: sum, y: diff) {\n let X = x.num1 + x.num2\n let Y = y.no1 + y.no2\n }\n}\n\nlet a = sum(num1: 100, num2: 200)\nprint(\"Inside Sum Block:\\( a.num1, a.num2)\")\n\nlet b = diff(no1: 200, no2: 100)\nprint(\"Inside Diff Block: \\(b.no1, b.no2)\")" }, { "code": null, "e": 4944, "s": 4866, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 5119, "s": 4944, "text": "Inside mult block (100, 200)\nInside mult block (200, 100)\nInside mult block (300, 500)\nInside mult block (300, 100)\nInside Sum Block:(100, 200)\nInside Diff Block: (200, 100)\n" }, { "code": null, "e": 5223, "s": 5119, "text": "New instance methods and type methods can be added further to the subclass with the help of extensions." }, { "code": null, "e": 5465, "s": 5223, "text": "extension Int {\n func topics(summation: () -> ()) {\n for _ in 0..<self {\n summation()\n }\n }\n}\n\n4.topics(summation: {\n print(\"Inside Extensions Block\")\n})\n\n3.topics(summation: {\n print(\"Inside Type Casting Block\")\n})" }, { "code": null, "e": 5543, "s": 5465, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 5718, "s": 5543, "text": "Inside Extensions Block\nInside Extensions Block\nInside Extensions Block\nInside Extensions Block\nInside Type Casting Block\nInside Type Casting Block\nInside Type Casting Block\n" }, { "code": null, "e": 5992, "s": 5718, "text": "topics() function takes argument of type '(summation: () → ())' to indicate the function does not take any arguments and it won't return any values. To call that function multiple number of times, for block is initialized and call to the method with topic() is initialized." }, { "code": null, "e": 6058, "s": 5992, "text": "Instance methods can also be mutated when declared as extensions." }, { "code": null, "e": 6230, "s": 6058, "text": "Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation." }, { "code": null, "e": 6554, "s": 6230, "text": "extension Double {\n mutating func square() {\n let pi = 3.1415\n self = pi * self * self\n }\n}\n\nvar Trial1 = 3.3\nTrial1.square()\nprint(\"Area of circle is: \\(Trial1)\")\n\nvar Trial2 = 5.8\nTrial2.square()\nprint(\"Area of circle is: \\(Trial2)\")\n\nvar Trial3 = 120.3\nTrial3.square()\nprint(\"Area of circle is: \\(Trial3)\")" }, { "code": null, "e": 6632, "s": 6554, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 6723, "s": 6632, "text": "Area of circle is: 34.210935\nArea of circle is: 105.68006\nArea of circle is: 45464.070735\n" }, { "code": null, "e": 6813, "s": 6723, "text": "Adding new subscripts to already declared instances can also be possible with extensions." }, { "code": null, "e": 7049, "s": 6813, "text": "extension Int {\n subscript(var multtable: Int) -> Int {\n var no1 = 1\n while multtable > 0 {\n no1 *= 10\n --multtable\n }\n return (self / no1) % 10\n }\n}\n\nprint(12[0])\nprint(7869[1])\nprint(786543[2])" }, { "code": null, "e": 7127, "s": 7049, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 7134, "s": 7127, "text": "2\n6\n5\n" }, { "code": null, "e": 7244, "s": 7134, "text": "Nested types for class, structure and enumeration instances can also be extended with the help of extensions." }, { "code": null, "e": 7976, "s": 7244, "text": "extension Int {\n enum calc {\n case add\n case sub\n case mult\n case div\n case anything\n }\n var print: calc {\n switch self {\n case 0:\n return .add\n case 1:\n return .sub\n case 2:\n return .mult\n case 3:\n return .div\n default:\n return .anything\n }\n }\n}\n\nfunc result(numb: [Int]) {\n for i in numb {\n switch i.print {\n case .add:\n print(\" 10 \")\n case .sub:\n print(\" 20 \")\n case .mult:\n print(\" 30 \")\n case .div:\n print(\" 40 \")\n default:\n print(\" 50 \")\n }\n }\n}\nresult(numb: [0, 1, 2, 3, 4, 7])" }, { "code": null, "e": 8054, "s": 7976, "text": "When we run the above program using playground, we get the following result −" }, { "code": null, "e": 8073, "s": 8054, "text": "10\n20\n30\n40\n50\n50\n" }, { "code": null, "e": 8106, "s": 8073, "text": "\n 38 Lectures \n 1 hours \n" }, { "code": null, "e": 8121, "s": 8106, "text": " Ashish Sharma" }, { "code": null, "e": 8154, "s": 8121, "text": "\n 13 Lectures \n 2 hours \n" }, { "code": null, "e": 8173, "s": 8154, "text": " Three Millennials" }, { "code": null, "e": 8205, "s": 8173, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 8224, "s": 8205, "text": " Three Millennials" }, { "code": null, "e": 8257, "s": 8224, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 8274, "s": 8257, "text": " Frahaan Hussain" }, { "code": null, "e": 8306, "s": 8274, "text": "\n 12 Lectures \n 39 mins\n" }, { "code": null, "e": 8326, "s": 8306, "text": " Devasena Rajendran" }, { "code": null, "e": 8361, "s": 8326, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8378, "s": 8361, "text": " Grant Klimaytys" }, { "code": null, "e": 8385, "s": 8378, "text": " Print" }, { "code": null, "e": 8396, "s": 8385, "text": " Add Notes" } ]
How to strike through and underline text in JavaFX?
In JavaFX, the text node is represented by the Javafx.scene.text.Text class. To insert/display text in JavaFx window you need to − Instantiate the Text class. Instantiate the Text class. Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor. Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor. Add the created node to the Group object. Add the created node to the Group object. The strikethrough property of the javafx.scene.text.Text class determines whether each line of the text should have a straight line passing through the middle of it. You can set the value to this property using the setStrikeThrough() method. It accepts a boolean value. You can strike though the text (node) by passing true as an argument to this method. The underline property of the javafx.scene.text.Text class determines whether each line of the text should have a straight line below it. You can set the value to this property using the setUnderline() method. It accepts a boolean value. You can have a line below the text (node) by passing true as an argument to this method. import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class Underline_StrikeThrough extends Application { public void start(Stage stage) throws FileNotFoundException { //Creating a text object String str = "Welcome to Tutorialspoint"; Text text = new Text(30.0, 80.0, str); //Setting the font Font font = Font.font("Brush Script MT", FontWeight.BOLD, FontPosture.REGULAR, 65); text.setFont(font); //Setting the color of the text text.setFill(Color.DARKCYAN); //Setting the width and color of the stroke text.setStrokeWidth(2); text.setStroke(Color.DARKSLATEGRAY); //Underlining the text text.setUnderline(true); //Striking through the text text.setStrikethrough(true); //Setting the stage Group root = new Group(text); Scene scene = new Scene(root, 595, 150, Color.BEIGE); stage.setTitle("Underline And Strike-through"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1193, "s": 1062, "text": "In JavaFX, the text node is represented by the Javafx.scene.text.Text class. To insert/display text in JavaFx window you need to −" }, { "code": null, "e": 1221, "s": 1193, "text": "Instantiate the Text class." }, { "code": null, "e": 1249, "s": 1221, "text": "Instantiate the Text class." }, { "code": null, "e": 1382, "s": 1249, "text": "Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor." }, { "code": null, "e": 1515, "s": 1382, "text": "Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor." }, { "code": null, "e": 1557, "s": 1515, "text": "Add the created node to the Group object." }, { "code": null, "e": 1599, "s": 1557, "text": "Add the created node to the Group object." }, { "code": null, "e": 1954, "s": 1599, "text": "The strikethrough property of the javafx.scene.text.Text class determines whether each line of the text should have a straight line passing through the middle of it. You can set the value to this property using the setStrikeThrough() method. It accepts a boolean value. You can strike though the text (node) by passing true as an argument to this method." }, { "code": null, "e": 2281, "s": 1954, "text": "The underline property of the javafx.scene.text.Text class determines whether each line of the text should have a straight line below it. You can set the value to this property using the setUnderline() method. It accepts a boolean value. You can have a line below the text (node) by passing true as an argument to this method." }, { "code": null, "e": 3624, "s": 2281, "text": "import java.io.FileNotFoundException;\nimport javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.scene.text.Text;\npublic class Underline_StrikeThrough extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //Creating a text object\n String str = \"Welcome to Tutorialspoint\";\n Text text = new Text(30.0, 80.0, str);\n //Setting the font\n Font font = Font.font(\"Brush Script MT\", FontWeight.BOLD, FontPosture.REGULAR, 65);\n text.setFont(font);\n //Setting the color of the text\n text.setFill(Color.DARKCYAN);\n //Setting the width and color of the stroke\n text.setStrokeWidth(2);\n text.setStroke(Color.DARKSLATEGRAY);\n //Underlining the text\n text.setUnderline(true);\n //Striking through the text\n text.setStrikethrough(true);\n //Setting the stage\n Group root = new Group(text);\n Scene scene = new Scene(root, 595, 150, Color.BEIGE);\n stage.setTitle(\"Underline And Strike-through\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
MongoDB - Update Document
MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method. The update() method updates the values in the existing document. The basic syntax of update() method is as follows − >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA) Consider the mycol collection has the following data. { "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} Following example will set the new title 'New MongoDB Tutorial' of the documents whose title is 'MongoDB Overview'. >db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} > By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter 'multi' to true. >db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}},{multi:true}) The save() method replaces the existing document with the new document passed in the save() method. The basic syntax of MongoDB save() method is shown below − >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA}) Following example will replace the document with the _id '5983548781331adf45ec5'. >db.mycol.save( { "_id" : ObjectId("507f191e810c19729de860ea"), "title":"Tutorials Point New Topic", "by":"Tutorials Point" } ) WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : ObjectId("507f191e810c19729de860ea") }) >db.mycol.find() { "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic", "by":"Tutorials Point"} { "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"} { "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"} > The findOneAndUpdate() method updates the values in the existing document. The basic syntax of findOneAndUpdate() method is as follows − >db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA) Assume we have created a collection named empDetails and inserted three documents in it as shown below − > db.empDetails.insertMany( [ { First_Name: "Radhika", Last_Name: "Sharma", Age: "26", e_mail: "radhika_sharma.123@gmail.com", phone: "9000012345" }, { First_Name: "Rachel", Last_Name: "Christopher", Age: "27", e_mail: "Rachel_Christopher.123@gmail.com", phone: "9000054321" }, { First_Name: "Fathima", Last_Name: "Sheik", Age: "24", e_mail: "Fathima_Sheik.123@gmail.com", phone: "9000054321" } ] ) Following example updates the age and email values of the document with name 'Radhika'. > db.empDetails.findOneAndUpdate( {First_Name: 'Radhika'}, { $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}} ) { "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" : "Sharma", "Age" : "30", "e_mail" : "radhika_newemail@gmail.com", "phone" : "9000012345" } This methods updates a single document which matches the given filter. The basic syntax of updateOne() method is as follows − >db.COLLECTION_NAME.updateOne(<filter>, <update>) > db.empDetails.updateOne( {First_Name: 'Radhika'}, { $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}} ) { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 } > The updateMany() method updates all the documents that matches the given filter. The basic syntax of updateMany() method is as follows − >db.COLLECTION_NAME.update(<filter>, <update>) > db.empDetails.updateMany( {Age:{ $gt: "25" }}, { $set: { Age: '00'}} ) { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 } You can see the updated values if you retrieve the contents of the document using the find method as shown below − > db.empDetails.find() { "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" : "Sharma", "Age" : "00", "e_mail" : "radhika_newemail@gmail.com", "phone" : "9000012345" } { "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" : "Rachel", "Last_Name" : "Christopher", "Age" : "00", "e_mail" : "Rachel_Christopher.123@gmail.com", "phone" : "9000054321" } { "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "Fathima_Sheik.123@gmail.com", "phone" : "9000054321" } > 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2800, "s": 2553, "text": "MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method." }, { "code": null, "e": 2865, "s": 2800, "text": "The update() method updates the values in the existing document." }, { "code": null, "e": 2917, "s": 2865, "text": "The basic syntax of update() method is as follows −" }, { "code": null, "e": 2979, "s": 2917, "text": ">db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)\n" }, { "code": null, "e": 3033, "s": 2979, "text": "Consider the mycol collection has the following data." }, { "code": null, "e": 3252, "s": 3033, "text": "{ \"_id\" : ObjectId(5983548781331adf45ec5), \"title\":\"MongoDB Overview\"}\n{ \"_id\" : ObjectId(5983548781331adf45ec6), \"title\":\"NoSQL Overview\"}\n{ \"_id\" : ObjectId(5983548781331adf45ec7), \"title\":\"Tutorials Point Overview\"}" }, { "code": null, "e": 3368, "s": 3252, "text": "Following example will set the new title 'New MongoDB Tutorial' of the documents whose title is 'MongoDB Overview'." }, { "code": null, "e": 3763, "s": 3368, "text": ">db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })\n>db.mycol.find()\n{ \"_id\" : ObjectId(5983548781331adf45ec5), \"title\":\"New MongoDB Tutorial\"}\n{ \"_id\" : ObjectId(5983548781331adf45ec6), \"title\":\"NoSQL Overview\"}\n{ \"_id\" : ObjectId(5983548781331adf45ec7), \"title\":\"Tutorials Point Overview\"}\n>" }, { "code": null, "e": 3894, "s": 3763, "text": "By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter 'multi' to true." }, { "code": null, "e": 3998, "s": 3894, "text": ">db.mycol.update({'title':'MongoDB Overview'},\n {$set:{'title':'New MongoDB Tutorial'}},{multi:true})" }, { "code": null, "e": 4098, "s": 3998, "text": "The save() method replaces the existing document with the new document passed in the save() method." }, { "code": null, "e": 4157, "s": 4098, "text": "The basic syntax of MongoDB save() method is shown below −" }, { "code": null, "e": 4210, "s": 4157, "text": ">db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})\n" }, { "code": null, "e": 4292, "s": 4210, "text": "Following example will replace the document with the _id '5983548781331adf45ec5'." }, { "code": null, "e": 4846, "s": 4292, "text": ">db.mycol.save(\n {\n \"_id\" : ObjectId(\"507f191e810c19729de860ea\"), \n\t\t\"title\":\"Tutorials Point New Topic\",\n \"by\":\"Tutorials Point\"\n }\n)\nWriteResult({\n\t\"nMatched\" : 0,\n\t\"nUpserted\" : 1,\n\t\"nModified\" : 0,\n\t\"_id\" : ObjectId(\"507f191e810c19729de860ea\")\n})\n>db.mycol.find()\n{ \"_id\" : ObjectId(\"507f191e810c19729de860e6\"), \"title\":\"Tutorials Point New Topic\",\n \"by\":\"Tutorials Point\"}\n{ \"_id\" : ObjectId(\"507f191e810c19729de860e6\"), \"title\":\"NoSQL Overview\"}\n{ \"_id\" : ObjectId(\"507f191e810c19729de860e6\"), \"title\":\"Tutorials Point Overview\"}\n>" }, { "code": null, "e": 4921, "s": 4846, "text": "The findOneAndUpdate() method updates the values in the existing document." }, { "code": null, "e": 4983, "s": 4921, "text": "The basic syntax of findOneAndUpdate() method is as follows −" }, { "code": null, "e": 5056, "s": 4983, "text": ">db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)\n" }, { "code": null, "e": 5161, "s": 5056, "text": "Assume we have created a collection named empDetails and inserted three documents in it as shown below −" }, { "code": null, "e": 5619, "s": 5161, "text": "> db.empDetails.insertMany(\n\t[\n\t\t{\n\t\t\tFirst_Name: \"Radhika\",\n\t\t\tLast_Name: \"Sharma\",\n\t\t\tAge: \"26\",\n\t\t\te_mail: \"radhika_sharma.123@gmail.com\",\n\t\t\tphone: \"9000012345\"\n\t\t},\n\t\t{\n\t\t\tFirst_Name: \"Rachel\",\n\t\t\tLast_Name: \"Christopher\",\n\t\t\tAge: \"27\",\n\t\t\te_mail: \"Rachel_Christopher.123@gmail.com\",\n\t\t\tphone: \"9000054321\"\n\t\t},\n\t\t{\n\t\t\tFirst_Name: \"Fathima\",\n\t\t\tLast_Name: \"Sheik\",\n\t\t\tAge: \"24\",\n\t\t\te_mail: \"Fathima_Sheik.123@gmail.com\",\n\t\t\tphone: \"9000054321\"\n\t\t}\n\t]\n)" }, { "code": null, "e": 5707, "s": 5619, "text": "Following example updates the age and email values of the document with name 'Radhika'." }, { "code": null, "e": 6013, "s": 5707, "text": "> db.empDetails.findOneAndUpdate(\n\t{First_Name: 'Radhika'},\n\t{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}\n)\n{\n\t\"_id\" : ObjectId(\"5dd6636870fb13eec3963bf5\"),\n\t\"First_Name\" : \"Radhika\",\n\t\"Last_Name\" : \"Sharma\",\n\t\"Age\" : \"30\",\n\t\"e_mail\" : \"radhika_newemail@gmail.com\",\n\t\"phone\" : \"9000012345\"\n}" }, { "code": null, "e": 6084, "s": 6013, "text": "This methods updates a single document which matches the given filter." }, { "code": null, "e": 6139, "s": 6084, "text": "The basic syntax of updateOne() method is as follows −" }, { "code": null, "e": 6189, "s": 6139, "text": ">db.COLLECTION_NAME.updateOne(<filter>, <update>)" }, { "code": null, "e": 6373, "s": 6189, "text": "> db.empDetails.updateOne(\n\t{First_Name: 'Radhika'},\n\t{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}\n)\n{ \"acknowledged\" : true, \"matchedCount\" : 1, \"modifiedCount\" : 0 }\n>" }, { "code": null, "e": 6454, "s": 6373, "text": "The updateMany() method updates all the documents that matches the given filter." }, { "code": null, "e": 6510, "s": 6454, "text": "The basic syntax of updateMany() method is as follows −" }, { "code": null, "e": 6557, "s": 6510, "text": ">db.COLLECTION_NAME.update(<filter>, <update>)" }, { "code": null, "e": 6699, "s": 6557, "text": "> db.empDetails.updateMany(\n\t{Age:{ $gt: \"25\" }},\n\t{ $set: { Age: '00'}}\n)\n{ \"acknowledged\" : true, \"matchedCount\" : 2, \"modifiedCount\" : 2 }" }, { "code": null, "e": 6814, "s": 6699, "text": "You can see the updated values if you retrieve the contents of the document using the find method as shown below −" }, { "code": null, "e": 7383, "s": 6814, "text": "> db.empDetails.find()\n{ \"_id\" : ObjectId(\"5dd6636870fb13eec3963bf5\"), \"First_Name\" : \"Radhika\", \"Last_Name\" : \"Sharma\", \"Age\" : \"00\", \"e_mail\" : \"radhika_newemail@gmail.com\", \"phone\" : \"9000012345\" }\n{ \"_id\" : ObjectId(\"5dd6636870fb13eec3963bf6\"), \"First_Name\" : \"Rachel\", \"Last_Name\" : \"Christopher\", \"Age\" : \"00\", \"e_mail\" : \"Rachel_Christopher.123@gmail.com\", \"phone\" : \"9000054321\" }\n{ \"_id\" : ObjectId(\"5dd6636870fb13eec3963bf7\"), \"First_Name\" : \"Fathima\", \"Last_Name\" : \"Sheik\", \"Age\" : \"24\", \"e_mail\" : \"Fathima_Sheik.123@gmail.com\", \"phone\" : \"9000054321\" }\n>" }, { "code": null, "e": 7416, "s": 7383, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 7435, "s": 7416, "text": " Arnab Chakraborty" }, { "code": null, "e": 7470, "s": 7435, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7498, "s": 7470, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7533, "s": 7498, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7556, "s": 7533, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 7591, "s": 7556, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7608, "s": 7591, "text": " University Code" }, { "code": null, "e": 7641, "s": 7608, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 7660, "s": 7641, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 7695, "s": 7660, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7715, "s": 7695, "text": " Skillbakerystudios" }, { "code": null, "e": 7722, "s": 7715, "text": " Print" }, { "code": null, "e": 7733, "s": 7722, "text": " Add Notes" } ]
Level up your code with Python decorators | by Alexander Bailey | Towards Data Science
There comes a point in every Python user’s life where you can level up from writing good code, to great code. Once you’ve mastered core Python functionality like list comprehensions and ternary operators, you should be ready to write more readable Python. Decorators are key to upgrading your code’s readability, and here we’ll cover the basics of them, as well as 3 ways to use them. In short, decorators are functions that wrap other functions. If there’s something that you want at the start and end of a function, then decorators are here to make your life a lot easier. Decorators can be spotted as an @ sign before a function definition. You might have spotted them in a flask app or a click CLI but the easiest way to explain how they work, is to work through a short example. So let’s say at the start of the function we want to print “Started’’ and at the end we want to print “Finished’’. To achieve this we could do the following: def circle_area(radius): print("Started: circle_area") area = 3.142 * radius ** 2 print("Finished") return areaarea = circle_area(2) This method works, but now our code is cluttered with print statements. The actual meat of the function could be written in just a single line but instead we’ve used three! So let’s make this clearer by making a new function that contains the main ingredient of our operation, and another containing just the print statements: def circle_area(radius): return 3.142 * radius ** 2def circle_area_and_print(radius): print("Started: circle_area_and_print") area = circle_area(radius) print("Ended") return areaarea = circle_area_and_print(2) At first glance you could argue this looks no clearer, as we have more code than before. At second glance you might notice that the code is much more readable from our additions. Our work here isn’t done however, what if we wanted to get more out of our code? Let’s say for example that we want to print before and after other functions too. As lazy data scientists, we don’t want to write the same line of code more than once, so let’s try to generalise the code we already have. We can do this with this new printer function. def printer(function): def new_function(*args): print(f"Started: {function.__name__}") output = function(*args) print("Finished") return output return new_functiondef circle_area(radius): return 3.142 * radius ** 2area = printer(circle_area)(2) So what does the printer function do here? The beauty of this function is that it constructs a new function by taking our original function and adding it to the print statements before and after the passed function is executed. Now printer returns the new function handle, allowing us to take any arbitrary function and return it with print statements. This is where the Python decorator really comes into it’s own. Now we’ve written the printer function to return a modified version of our original function, all we need to do is prepend the function definition with @printer : @printerdef circle_area(radius): return 3.142 * radius ** 2area = circle_area(2) Even in this simple example, when you compare the use of the printer decorator with the code we wrote at the beginning, our code is much more legible. There are a few nifty tricks of the trade for decorators that you can use to make your code easier to understand and read. We’ll take a look at: Logging (similar to the first example but somewhat more useful)Type checkingError handling Logging (similar to the first example but somewhat more useful) Type checking Error handling For the first example, we need to write a small function to set up logging in our script: import loggingdef setup_logging(name="logger", filepath=None, stream_log_level="DEBUG", file_log_level="DEBUG"): logger = logging.getLogger(name) logger.setLevel("DEBUG") formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) ch = logging.StreamHandler() ch.setLevel(getattr(logging, stream_log_level)) ch.setFormatter(formatter) logger.addHandler(ch) if filepath is not None: fh = logging.FileHandler(filepath) fh.setLevel(getattr(logging, file_log_level)) fh.setFormatter(formatter) logger.addHandler(fh) return loggerlogger = setup_logging(name="default_log",filepath="logger.log") Now we can write our new logging decorator: def log_decorator(log_name): def log_this(function): logger = logging.getLogger(log_name) def new_function(*args,**kwargs): logger.debug(f"{function.__name__} - {args} - {kwargs}") output = function(*args,**kwargs) logger.debug(f"{function.__name__} returned: {output}") return output return new_function return log_this This is slightly more complicated that the printer decorator we looked at before. This time, we wanted to build a decorator that can take an argument (the name of the logger). However the decorator function can only take one argument, so we wrap this function in another that can take many arguments. It takes a while to wrap your head around this inception-like function wrapping, but once you do it’s an invaluable tool in the data scientist’s tool-box. Now this is a controversial one, so hold on to your hats we could be in for a bumpy ride... Some will say that this decorator type checks a function’s inputs in a way that many would consider to be “un-Pythonic”. Python is a dynamically-typed language, so at the risk of ruffling too many feathers, it is important to note that in general when writing Python we should beg for forgiveness rather than ask permission. However if you’re willing to be a little bit cheeky with the laws of Python, then you’ll find this a really handy tool, especially when developing code. It makes it crystal clear when identifying wrong types that are being passed around. With that all in mind, here’s the code: def accepts(*types): def check_accepts(function): assert len(types) == function.__code__.co_argcount,\ "Number of typed inputs must match the function inputs" def new_function(*args, **kwargs): for (a, t) in zip(args, types): assert isinstance(a, t), \ "arg %r does not match %s" % (a,t) return function(*args, **kwargs) return new_function return check_accepts@accepts((int,float))def circle_area(radius): return 3.142 * radius ** 2 So now we’ve ensured that the inputs to the circle_area function will only accept type ints or floats, otherwise it will raise an AssertionError. For this example, let’s assume we’re trying to access data from an API but the API only allows for a given number of requests per minute. We can write a decorator that wraps the API call and will continue to try and get the data until it’s successful. import apiimport timeAPI_WAIT_TIME = 5 #minutesMAX_RETRIES = 10def error_handling(api_function): def trial(*args, num_retries=0, **kwargs): try: return api_function(*args, **kwargs) except api.error.RateLimitError: if num_retries > MAX_RETRIES: raise RuntimeError("Too many retries") else: msg = f"rate limit reached. Waiting {API_WAIT_TIME} minutes ..." time.sleep(API_WAIT_TIME * 60) return trial(*args, num_retries=num_retries + 1, **kwargs) return trial We can use this decorator each time we request data from the api module. The decorator will keep trying until it gets the data or it hits the maximum number of allowed retries, if that’s the case, a RuntimeError will be raised. Equally, a very similar version of this function could be used to arbitrarily catch different exceptions and deal with them in different ways. I’ll leave it up to the imagine of the reader to think about new ways to use this type of decorator. Hopefully you now have a better idea of what a Python decorator is and feel confident using it in your codebase (if not, then I’ve failed you...). The key take away here is that if you have a function that frequently occurs at the start and end of another function, then a decorator will be your new best friend. Decorators are going to help your code to be not only more readable, but also more modular and reusable.
[ { "code": null, "e": 281, "s": 171, "text": "There comes a point in every Python user’s life where you can level up from writing good code, to great code." }, { "code": null, "e": 556, "s": 281, "text": "Once you’ve mastered core Python functionality like list comprehensions and ternary operators, you should be ready to write more readable Python. Decorators are key to upgrading your code’s readability, and here we’ll cover the basics of them, as well as 3 ways to use them." }, { "code": null, "e": 746, "s": 556, "text": "In short, decorators are functions that wrap other functions. If there’s something that you want at the start and end of a function, then decorators are here to make your life a lot easier." }, { "code": null, "e": 955, "s": 746, "text": "Decorators can be spotted as an @ sign before a function definition. You might have spotted them in a flask app or a click CLI but the easiest way to explain how they work, is to work through a short example." }, { "code": null, "e": 1113, "s": 955, "text": "So let’s say at the start of the function we want to print “Started’’ and at the end we want to print “Finished’’. To achieve this we could do the following:" }, { "code": null, "e": 1258, "s": 1113, "text": "def circle_area(radius): print(\"Started: circle_area\") area = 3.142 * radius ** 2 print(\"Finished\") return areaarea = circle_area(2)" }, { "code": null, "e": 1585, "s": 1258, "text": "This method works, but now our code is cluttered with print statements. The actual meat of the function could be written in just a single line but instead we’ve used three! So let’s make this clearer by making a new function that contains the main ingredient of our operation, and another containing just the print statements:" }, { "code": null, "e": 1811, "s": 1585, "text": "def circle_area(radius): return 3.142 * radius ** 2def circle_area_and_print(radius): print(\"Started: circle_area_and_print\") area = circle_area(radius) print(\"Ended\") return areaarea = circle_area_and_print(2)" }, { "code": null, "e": 2071, "s": 1811, "text": "At first glance you could argue this looks no clearer, as we have more code than before. At second glance you might notice that the code is much more readable from our additions. Our work here isn’t done however, what if we wanted to get more out of our code?" }, { "code": null, "e": 2339, "s": 2071, "text": "Let’s say for example that we want to print before and after other functions too. As lazy data scientists, we don’t want to write the same line of code more than once, so let’s try to generalise the code we already have. We can do this with this new printer function." }, { "code": null, "e": 2621, "s": 2339, "text": "def printer(function): def new_function(*args): print(f\"Started: {function.__name__}\") output = function(*args) print(\"Finished\") return output return new_functiondef circle_area(radius): return 3.142 * radius ** 2area = printer(circle_area)(2)" }, { "code": null, "e": 2664, "s": 2621, "text": "So what does the printer function do here?" }, { "code": null, "e": 2974, "s": 2664, "text": "The beauty of this function is that it constructs a new function by taking our original function and adding it to the print statements before and after the passed function is executed. Now printer returns the new function handle, allowing us to take any arbitrary function and return it with print statements." }, { "code": null, "e": 3200, "s": 2974, "text": "This is where the Python decorator really comes into it’s own. Now we’ve written the printer function to return a modified version of our original function, all we need to do is prepend the function definition with @printer :" }, { "code": null, "e": 3284, "s": 3200, "text": "@printerdef circle_area(radius): return 3.142 * radius ** 2area = circle_area(2)" }, { "code": null, "e": 3435, "s": 3284, "text": "Even in this simple example, when you compare the use of the printer decorator with the code we wrote at the beginning, our code is much more legible." }, { "code": null, "e": 3558, "s": 3435, "text": "There are a few nifty tricks of the trade for decorators that you can use to make your code easier to understand and read." }, { "code": null, "e": 3580, "s": 3558, "text": "We’ll take a look at:" }, { "code": null, "e": 3671, "s": 3580, "text": "Logging (similar to the first example but somewhat more useful)Type checkingError handling" }, { "code": null, "e": 3735, "s": 3671, "text": "Logging (similar to the first example but somewhat more useful)" }, { "code": null, "e": 3749, "s": 3735, "text": "Type checking" }, { "code": null, "e": 3764, "s": 3749, "text": "Error handling" }, { "code": null, "e": 3854, "s": 3764, "text": "For the first example, we need to write a small function to set up logging in our script:" }, { "code": null, "e": 4592, "s": 3854, "text": "import loggingdef setup_logging(name=\"logger\", filepath=None, stream_log_level=\"DEBUG\", file_log_level=\"DEBUG\"): logger = logging.getLogger(name) logger.setLevel(\"DEBUG\") formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) ch = logging.StreamHandler() ch.setLevel(getattr(logging, stream_log_level)) ch.setFormatter(formatter) logger.addHandler(ch) if filepath is not None: fh = logging.FileHandler(filepath) fh.setLevel(getattr(logging, file_log_level)) fh.setFormatter(formatter) logger.addHandler(fh) return loggerlogger = setup_logging(name=\"default_log\",filepath=\"logger.log\")" }, { "code": null, "e": 4636, "s": 4592, "text": "Now we can write our new logging decorator:" }, { "code": null, "e": 5028, "s": 4636, "text": "def log_decorator(log_name): def log_this(function): logger = logging.getLogger(log_name) def new_function(*args,**kwargs): logger.debug(f\"{function.__name__} - {args} - {kwargs}\") output = function(*args,**kwargs) logger.debug(f\"{function.__name__} returned: {output}\") return output return new_function return log_this" }, { "code": null, "e": 5204, "s": 5028, "text": "This is slightly more complicated that the printer decorator we looked at before. This time, we wanted to build a decorator that can take an argument (the name of the logger)." }, { "code": null, "e": 5484, "s": 5204, "text": "However the decorator function can only take one argument, so we wrap this function in another that can take many arguments. It takes a while to wrap your head around this inception-like function wrapping, but once you do it’s an invaluable tool in the data scientist’s tool-box." }, { "code": null, "e": 5576, "s": 5484, "text": "Now this is a controversial one, so hold on to your hats we could be in for a bumpy ride..." }, { "code": null, "e": 5901, "s": 5576, "text": "Some will say that this decorator type checks a function’s inputs in a way that many would consider to be “un-Pythonic”. Python is a dynamically-typed language, so at the risk of ruffling too many feathers, it is important to note that in general when writing Python we should beg for forgiveness rather than ask permission." }, { "code": null, "e": 6139, "s": 5901, "text": "However if you’re willing to be a little bit cheeky with the laws of Python, then you’ll find this a really handy tool, especially when developing code. It makes it crystal clear when identifying wrong types that are being passed around." }, { "code": null, "e": 6179, "s": 6139, "text": "With that all in mind, here’s the code:" }, { "code": null, "e": 6713, "s": 6179, "text": "def accepts(*types): def check_accepts(function): assert len(types) == function.__code__.co_argcount,\\ \"Number of typed inputs must match the function inputs\" def new_function(*args, **kwargs): for (a, t) in zip(args, types): assert isinstance(a, t), \\ \"arg %r does not match %s\" % (a,t) return function(*args, **kwargs) return new_function return check_accepts@accepts((int,float))def circle_area(radius): return 3.142 * radius ** 2" }, { "code": null, "e": 6859, "s": 6713, "text": "So now we’ve ensured that the inputs to the circle_area function will only accept type ints or floats, otherwise it will raise an AssertionError." }, { "code": null, "e": 7111, "s": 6859, "text": "For this example, let’s assume we’re trying to access data from an API but the API only allows for a given number of requests per minute. We can write a decorator that wraps the API call and will continue to try and get the data until it’s successful." }, { "code": null, "e": 7682, "s": 7111, "text": "import apiimport timeAPI_WAIT_TIME = 5 #minutesMAX_RETRIES = 10def error_handling(api_function): def trial(*args, num_retries=0, **kwargs): try: return api_function(*args, **kwargs) except api.error.RateLimitError: if num_retries > MAX_RETRIES: raise RuntimeError(\"Too many retries\") else: msg = f\"rate limit reached. Waiting {API_WAIT_TIME} minutes ...\" time.sleep(API_WAIT_TIME * 60) return trial(*args, num_retries=num_retries + 1, **kwargs) return trial" }, { "code": null, "e": 7910, "s": 7682, "text": "We can use this decorator each time we request data from the api module. The decorator will keep trying until it gets the data or it hits the maximum number of allowed retries, if that’s the case, a RuntimeError will be raised." }, { "code": null, "e": 8154, "s": 7910, "text": "Equally, a very similar version of this function could be used to arbitrarily catch different exceptions and deal with them in different ways. I’ll leave it up to the imagine of the reader to think about new ways to use this type of decorator." }, { "code": null, "e": 8301, "s": 8154, "text": "Hopefully you now have a better idea of what a Python decorator is and feel confident using it in your codebase (if not, then I’ve failed you...)." } ]
Delete all records from a table in MySQL?
To delete all the records from a table in MySQL, use the TRUNCATE command. Let us fir see the syntax − TRUNCATE TABLE yourTableName. The above syntax will delete all the records from a table. Let us create a table to understand the above syntax − mysql> create table TruncateTableDemo −> ( −> BookId int −> , −> BookName varchar(200) −> ); Query OK, 0 rows affected (0.54 sec) Inserting records in the table with the help of insert command. The query to insert records in the table are as follows − mysql> insert into TruncateTableDemo values(1001,'C in Dept'); Query OK, 1 row affected (0.18 sec) mysql> insert into TruncateTableDemo values(1002,'The C++ Programming'); Query OK, 1 row affected (0.22 sec) mysql> insert into TruncateTableDemo values(1003,'Let us C'); Query OK, 1 row affected (0.16 sec) Now you can display all the records from the table with the help of a select statement. The query is as follows − mysql> select *from TruncateTableDemo; The following is the output − +--------+---------------------+ | BookId | BookName | +--------+---------------------+ | 1001 | C in Dept | | 1002 | The C++ Programming | | 1003 | Let us C | +--------+---------------------+ 3 rows in set (0.00 sec) Implement the above syntax to delete all the records from the table. The query is as follows − mysql> truncate table TruncateTableDemo; Query OK, 0 rows affected (0.93 sec) Now you can check all records have been deleted from the table or not. The following is the query − mysql> select *from TruncateTableDemo; Empty set (0.00 sec)
[ { "code": null, "e": 1165, "s": 1062, "text": "To delete all the records from a table in MySQL, use the TRUNCATE command. Let us fir see the syntax −" }, { "code": null, "e": 1195, "s": 1165, "text": "TRUNCATE TABLE yourTableName." }, { "code": null, "e": 1309, "s": 1195, "text": "The above syntax will delete all the records from a table. Let us create a table to understand the above syntax −" }, { "code": null, "e": 1448, "s": 1309, "text": "mysql> create table TruncateTableDemo\n−> (\n −> BookId int\n −> ,\n −> BookName varchar(200)\n−> );\nQuery OK, 0 rows affected (0.54 sec)" }, { "code": null, "e": 1570, "s": 1448, "text": "Inserting records in the table with the help of insert command. The query to insert records in the table are as follows −" }, { "code": null, "e": 1878, "s": 1570, "text": "mysql> insert into TruncateTableDemo values(1001,'C in Dept');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into TruncateTableDemo values(1002,'The C++ Programming');\nQuery OK, 1 row affected (0.22 sec)\n\nmysql> insert into TruncateTableDemo values(1003,'Let us C');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1992, "s": 1878, "text": "Now you can display all the records from the table with the help of a select statement. The query is as follows −" }, { "code": null, "e": 2031, "s": 1992, "text": "mysql> select *from TruncateTableDemo;" }, { "code": null, "e": 2061, "s": 2031, "text": "The following is the output −" }, { "code": null, "e": 2317, "s": 2061, "text": "+--------+---------------------+\n| BookId | BookName |\n+--------+---------------------+\n| 1001 | C in Dept |\n| 1002 | The C++ Programming |\n| 1003 | Let us C |\n+--------+---------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2412, "s": 2317, "text": "Implement the above syntax to delete all the records from the table. The query is as follows −" }, { "code": null, "e": 2490, "s": 2412, "text": "mysql> truncate table TruncateTableDemo;\nQuery OK, 0 rows affected (0.93 sec)" }, { "code": null, "e": 2561, "s": 2490, "text": "Now you can check all records have been deleted from the table or not." }, { "code": null, "e": 2590, "s": 2561, "text": "The following is the query −" }, { "code": null, "e": 2650, "s": 2590, "text": "mysql> select *from TruncateTableDemo;\nEmpty set (0.00 sec)" } ]
All Pandas cut() you should know for transforming numerical data into categorical data | by B. Chen | Towards Data Science
Numerical data is common in data analysis. Often you have numerical data that is continuous, very large scales, or highly skewed. Sometimes, it can be easier to bin those data into discrete intervals. This is helpful to perform descriptive statistics when values are divided into meaningful categories. For example, we can divide the exact age into Toddler, Child, Adult, and Elder. Pandas’ built-in cut() function is a great way to transform numerical data into categorical data. In this article, you’ll learn how to use it to deal with the following common tasks. Discretizing into equal-sized binsAdding custom binsAdding labels to binsConfiguring leftmost edge with right=FalseInclude the lowest value with include_lowest=TruePassing an IntervalIndex to binsReturning bins with retbins=TrueCreating unordered categories Discretizing into equal-sized bins Adding custom bins Adding labels to bins Configuring leftmost edge with right=False Include the lowest value with include_lowest=True Passing an IntervalIndex to bins Returning bins with retbins=True Creating unordered categories Please check out Notebook for the source code. The simplest usage of cut() must has a column and an integer as input. It is discretizing values into equal-sized bins. df = pd.DataFrame({'age': [2, 67, 40, 32, 4, 15, 82, 99, 26, 30]})df['age_group'] = pd.cut(df['age'], 3) Did you observe those intervals from the age_group column? Those interval values are having a round bracket at the start and a square bracket at the end, for example (1.903, 34.333]. It basically means any value on the side of the round bracket is not included in the interval and any value on the side of the square bracket is included (It is known as open and closed intervals in Math). Now, let's take a look at the new column age_group. df['age_group'] It shows dtype: category with 3 label values: (1.903, 34.333] , (34.333, 66.667] , and (66.667, 99.0]. Those label values are ordered as indicated with the symbol <. Behind the theme, an interval is calculated as follows in order to generate the equal-sized bins: interval = (max_value — min_value) / num_of_bins = (99 - 2) / 3 = 32.33333 (<--32.3333-->] < (<--32.3333-->] < (<--32.3333-->] (1.903, 34.333] < (34.333, 66.667] < (66.667, 99.0] Let’s divide the above age values into 4 custom groups i.e. 0–12, 12–19, 19–60, 61–100. To do that, we can simply pass those values in a list ([0, 12, 19, 61, 100]) to the argument bins. df['age_group'] = pd.cut(df['age'], bins=[0, 12, 19, 61, 100]) We added the group values for age in a new column age_group. By looking into the column df['age_group']0 (0, 12]1 (61, 100]2 (19, 61]3 (19, 61]4 (0, 12]5 (12, 19]6 (61, 100]7 (61, 100]8 (19, 61]9 (19, 61]Name: age_group, dtype: categoryCategories (4, interval[int64]): [(0, 12] < (12, 19] < (19, 61] < (61, 100]] We can see dtype: category with 4 ordered label values: (0, 12] < (12, 19] < (19, 61] < (61, 100]. Let’s sort the DataFrame by the column age_group: df.sort_values('age_group') Let’s count that how many values fall into each bin. df['age_group'].value_counts().sort_index()(0, 12] 2(12, 19] 1(19, 61] 4(61, 100] 3Name: age_group, dtype: int64 It is more descriptive to label these age_group values as ‘<12’, ‘Teen’, ‘Adult’, ‘Older’. To do that, we can simply pass those values in a list to the argument labels bins=[0, 12, 19, 61, 100]labels=['<12', 'Teen', 'Adult', 'Older']df['age_group'] = pd.cut(df['age'], bins, labels=labels) Now, when we looking into the column, it shows the label instead df['age_group']0 <121 Older2 Adult3 Adult4 <125 Teen6 Older7 Older8 Adult9 AdultName: age_group, dtype: categoryCategories (4, object): ['<12' < 'Teen' < 'Adult' < 'Older'] Similarly, it is showing label when sorting and counting df['age_group'].value_counts().sort_index()<12 2Teen 1Adult 4Older 3Name: age_group, dtype: int64 There is an argument right in Pandas cut() to configure whether bins include the rightmost edge or not. right defaults to True, which mean bins like[0, 12, 19, 61, 100] indicate (0,12], (12,19], (19,61],(61,100] . To include the leftmost edge, we can set right=False: pd.cut(df['age'], bins=[0, 12, 19, 61, 100], right=False)0 [0, 12)1 [61, 100)2 [19, 61)3 [19, 61)4 [0, 12)5 [12, 19)6 [61, 100)7 [61, 100)8 [19, 61)9 [19, 61)Name: age, dtype: categoryCategories (4, interval[int64]): [[0, 12) < [12, 19) < [19, 61) < [61, 100)] Suppose you would like to divide the above age values into 2–12, 12–19, 19–60, 61–100 instead. You will get a result contains NaN when setting the bins to [2, 12, 19, 61, 100]. df['age_group'] = pd.cut(df['age'], bins=[2, 12, 19, 61, 100]) We get a NaN because the value 2 is the leftmost edge of the first bin (2.0, 19.0] and is not included. To include the lowest value, we can set include_lowest=True. Alternatively, you can set the right to False to include the leftmost edge. df['age_group'] = pd.cut( df['age'], bins=[2, 12, 19, 61, 100], include_lowest=True) So far we have been passing an array to bins. Instead of an array, we can also pass an IntervalIndex. Let’s create an IntervalIndex with 3 bins (0, 12], (19, 61], (61, 100] : bins = pd.IntervalIndex.from_tuples([(0, 12), (19, 61), (61, 100)])IntervalIndex([(0, 12], (19, 61], (61, 100]], closed='right', dtype='interval[int64]') Next, let’s pass it to the argument bins df['age_group'] = pd.cut(df['age'], bins) Notice that value not covered by the IntervalIndex is set to NaN. Basically, passing an IntervalIndex for bins results in those categories exactly. There is an argument called retbin to return the bins. If it is set to True, the result will return the bins and it is useful when bins is passed as a single number value result, bins = pd.cut( df['age'], bins=4, # A single number value retbins=True)# Print out bins valuebinsarray([ 1.903, 26.25 , 50.5 , 74.75 , 99. ]) ordered=False will result in unordered categories when labels are passed. This parameter can be used to allow non-unique labels: pd.cut( df['age'], bins=[0, 12, 19, 61, 100], labels=['<12', 'Teen', 'Adult', 'Older'], ordered=False,)0 <121 Older2 Adult3 Adult4 <125 Teen6 Older7 Older8 Adult9 AdultName: age, dtype: categoryCategories (4, object): ['<12', 'Teen', 'Adult', 'Older'] Pandas cut() function is a quick and convenient way for transforming numerical data into categorical data. I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the cut() API and to know about other things you can do. Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning. A Practical Introduction to Pandas Series Using Pandas method chaining to improve code readability How to do a Custom Sort on Pandas DataFrame All the Pandas shift() you should know for data analysis When to use Pandas transform() function Pandas concat() tricks you should know Difference between apply() and transform() in Pandas All the Pandas merge() you should know Working with datetime in Pandas DataFrame Pandas read_csv() tricks you should know 4 tricks you should know to parse date columns with Pandas read_csv() More tutorials can be found on my Github
[ { "code": null, "e": 554, "s": 171, "text": "Numerical data is common in data analysis. Often you have numerical data that is continuous, very large scales, or highly skewed. Sometimes, it can be easier to bin those data into discrete intervals. This is helpful to perform descriptive statistics when values are divided into meaningful categories. For example, we can divide the exact age into Toddler, Child, Adult, and Elder." }, { "code": null, "e": 737, "s": 554, "text": "Pandas’ built-in cut() function is a great way to transform numerical data into categorical data. In this article, you’ll learn how to use it to deal with the following common tasks." }, { "code": null, "e": 995, "s": 737, "text": "Discretizing into equal-sized binsAdding custom binsAdding labels to binsConfiguring leftmost edge with right=FalseInclude the lowest value with include_lowest=TruePassing an IntervalIndex to binsReturning bins with retbins=TrueCreating unordered categories" }, { "code": null, "e": 1030, "s": 995, "text": "Discretizing into equal-sized bins" }, { "code": null, "e": 1049, "s": 1030, "text": "Adding custom bins" }, { "code": null, "e": 1071, "s": 1049, "text": "Adding labels to bins" }, { "code": null, "e": 1114, "s": 1071, "text": "Configuring leftmost edge with right=False" }, { "code": null, "e": 1164, "s": 1114, "text": "Include the lowest value with include_lowest=True" }, { "code": null, "e": 1197, "s": 1164, "text": "Passing an IntervalIndex to bins" }, { "code": null, "e": 1230, "s": 1197, "text": "Returning bins with retbins=True" }, { "code": null, "e": 1260, "s": 1230, "text": "Creating unordered categories" }, { "code": null, "e": 1307, "s": 1260, "text": "Please check out Notebook for the source code." }, { "code": null, "e": 1427, "s": 1307, "text": "The simplest usage of cut() must has a column and an integer as input. It is discretizing values into equal-sized bins." }, { "code": null, "e": 1532, "s": 1427, "text": "df = pd.DataFrame({'age': [2, 67, 40, 32, 4, 15, 82, 99, 26, 30]})df['age_group'] = pd.cut(df['age'], 3)" }, { "code": null, "e": 1921, "s": 1532, "text": "Did you observe those intervals from the age_group column? Those interval values are having a round bracket at the start and a square bracket at the end, for example (1.903, 34.333]. It basically means any value on the side of the round bracket is not included in the interval and any value on the side of the square bracket is included (It is known as open and closed intervals in Math)." }, { "code": null, "e": 1973, "s": 1921, "text": "Now, let's take a look at the new column age_group." }, { "code": null, "e": 1989, "s": 1973, "text": "df['age_group']" }, { "code": null, "e": 2253, "s": 1989, "text": "It shows dtype: category with 3 label values: (1.903, 34.333] , (34.333, 66.667] , and (66.667, 99.0]. Those label values are ordered as indicated with the symbol <. Behind the theme, an interval is calculated as follows in order to generate the equal-sized bins:" }, { "code": null, "e": 2462, "s": 2253, "text": "interval = (max_value — min_value) / num_of_bins = (99 - 2) / 3 = 32.33333 (<--32.3333-->] < (<--32.3333-->] < (<--32.3333-->] (1.903, 34.333] < (34.333, 66.667] < (66.667, 99.0]" }, { "code": null, "e": 2649, "s": 2462, "text": "Let’s divide the above age values into 4 custom groups i.e. 0–12, 12–19, 19–60, 61–100. To do that, we can simply pass those values in a list ([0, 12, 19, 61, 100]) to the argument bins." }, { "code": null, "e": 2712, "s": 2649, "text": "df['age_group'] = pd.cut(df['age'], bins=[0, 12, 19, 61, 100])" }, { "code": null, "e": 2800, "s": 2712, "text": "We added the group values for age in a new column age_group. By looking into the column" }, { "code": null, "e": 3064, "s": 2800, "text": "df['age_group']0 (0, 12]1 (61, 100]2 (19, 61]3 (19, 61]4 (0, 12]5 (12, 19]6 (61, 100]7 (61, 100]8 (19, 61]9 (19, 61]Name: age_group, dtype: categoryCategories (4, interval[int64]): [(0, 12] < (12, 19] < (19, 61] < (61, 100]]" }, { "code": null, "e": 3163, "s": 3064, "text": "We can see dtype: category with 4 ordered label values: (0, 12] < (12, 19] < (19, 61] < (61, 100]." }, { "code": null, "e": 3213, "s": 3163, "text": "Let’s sort the DataFrame by the column age_group:" }, { "code": null, "e": 3241, "s": 3213, "text": "df.sort_values('age_group')" }, { "code": null, "e": 3294, "s": 3241, "text": "Let’s count that how many values fall into each bin." }, { "code": null, "e": 3423, "s": 3294, "text": "df['age_group'].value_counts().sort_index()(0, 12] 2(12, 19] 1(19, 61] 4(61, 100] 3Name: age_group, dtype: int64" }, { "code": null, "e": 3591, "s": 3423, "text": "It is more descriptive to label these age_group values as ‘<12’, ‘Teen’, ‘Adult’, ‘Older’. To do that, we can simply pass those values in a list to the argument labels" }, { "code": null, "e": 3713, "s": 3591, "text": "bins=[0, 12, 19, 61, 100]labels=['<12', 'Teen', 'Adult', 'Older']df['age_group'] = pd.cut(df['age'], bins, labels=labels)" }, { "code": null, "e": 3778, "s": 3713, "text": "Now, when we looking into the column, it shows the label instead" }, { "code": null, "e": 3986, "s": 3778, "text": "df['age_group']0 <121 Older2 Adult3 Adult4 <125 Teen6 Older7 Older8 Adult9 AdultName: age_group, dtype: categoryCategories (4, object): ['<12' < 'Teen' < 'Adult' < 'Older']" }, { "code": null, "e": 4043, "s": 3986, "text": "Similarly, it is showing label when sorting and counting" }, { "code": null, "e": 4156, "s": 4043, "text": "df['age_group'].value_counts().sort_index()<12 2Teen 1Adult 4Older 3Name: age_group, dtype: int64" }, { "code": null, "e": 4424, "s": 4156, "text": "There is an argument right in Pandas cut() to configure whether bins include the rightmost edge or not. right defaults to True, which mean bins like[0, 12, 19, 61, 100] indicate (0,12], (12,19], (19,61],(61,100] . To include the leftmost edge, we can set right=False:" }, { "code": null, "e": 4724, "s": 4424, "text": "pd.cut(df['age'], bins=[0, 12, 19, 61, 100], right=False)0 [0, 12)1 [61, 100)2 [19, 61)3 [19, 61)4 [0, 12)5 [12, 19)6 [61, 100)7 [61, 100)8 [19, 61)9 [19, 61)Name: age, dtype: categoryCategories (4, interval[int64]): [[0, 12) < [12, 19) < [19, 61) < [61, 100)]" }, { "code": null, "e": 4901, "s": 4724, "text": "Suppose you would like to divide the above age values into 2–12, 12–19, 19–60, 61–100 instead. You will get a result contains NaN when setting the bins to [2, 12, 19, 61, 100]." }, { "code": null, "e": 4964, "s": 4901, "text": "df['age_group'] = pd.cut(df['age'], bins=[2, 12, 19, 61, 100])" }, { "code": null, "e": 5205, "s": 4964, "text": "We get a NaN because the value 2 is the leftmost edge of the first bin (2.0, 19.0] and is not included. To include the lowest value, we can set include_lowest=True. Alternatively, you can set the right to False to include the leftmost edge." }, { "code": null, "e": 5301, "s": 5205, "text": "df['age_group'] = pd.cut( df['age'], bins=[2, 12, 19, 61, 100], include_lowest=True)" }, { "code": null, "e": 5403, "s": 5301, "text": "So far we have been passing an array to bins. Instead of an array, we can also pass an IntervalIndex." }, { "code": null, "e": 5476, "s": 5403, "text": "Let’s create an IntervalIndex with 3 bins (0, 12], (19, 61], (61, 100] :" }, { "code": null, "e": 5656, "s": 5476, "text": "bins = pd.IntervalIndex.from_tuples([(0, 12), (19, 61), (61, 100)])IntervalIndex([(0, 12], (19, 61], (61, 100]], closed='right', dtype='interval[int64]')" }, { "code": null, "e": 5697, "s": 5656, "text": "Next, let’s pass it to the argument bins" }, { "code": null, "e": 5739, "s": 5697, "text": "df['age_group'] = pd.cut(df['age'], bins)" }, { "code": null, "e": 5887, "s": 5739, "text": "Notice that value not covered by the IntervalIndex is set to NaN. Basically, passing an IntervalIndex for bins results in those categories exactly." }, { "code": null, "e": 6058, "s": 5887, "text": "There is an argument called retbin to return the bins. If it is set to True, the result will return the bins and it is useful when bins is passed as a single number value" }, { "code": null, "e": 6232, "s": 6058, "text": "result, bins = pd.cut( df['age'], bins=4, # A single number value retbins=True)# Print out bins valuebinsarray([ 1.903, 26.25 , 50.5 , 74.75 , 99. ])" }, { "code": null, "e": 6361, "s": 6232, "text": "ordered=False will result in unordered categories when labels are passed. This parameter can be used to allow non-unique labels:" }, { "code": null, "e": 6663, "s": 6361, "text": "pd.cut( df['age'], bins=[0, 12, 19, 61, 100], labels=['<12', 'Teen', 'Adult', 'Older'], ordered=False,)0 <121 Older2 Adult3 Adult4 <125 Teen6 Older7 Older8 Adult9 AdultName: age, dtype: categoryCategories (4, object): ['<12', 'Teen', 'Adult', 'Older']" }, { "code": null, "e": 6770, "s": 6663, "text": "Pandas cut() function is a quick and convenient way for transforming numerical data into categorical data." }, { "code": null, "e": 6945, "s": 6770, "text": "I hope this article will help you to save time in learning Pandas. I recommend you to check out the documentation for the cut() API and to know about other things you can do." }, { "code": null, "e": 7097, "s": 6945, "text": "Thanks for reading. Please check out the notebook for the source code and stay tuned if you are interested in the practical aspect of machine learning." }, { "code": null, "e": 7139, "s": 7097, "text": "A Practical Introduction to Pandas Series" }, { "code": null, "e": 7196, "s": 7139, "text": "Using Pandas method chaining to improve code readability" }, { "code": null, "e": 7240, "s": 7196, "text": "How to do a Custom Sort on Pandas DataFrame" }, { "code": null, "e": 7297, "s": 7240, "text": "All the Pandas shift() you should know for data analysis" }, { "code": null, "e": 7337, "s": 7297, "text": "When to use Pandas transform() function" }, { "code": null, "e": 7376, "s": 7337, "text": "Pandas concat() tricks you should know" }, { "code": null, "e": 7429, "s": 7376, "text": "Difference between apply() and transform() in Pandas" }, { "code": null, "e": 7468, "s": 7429, "text": "All the Pandas merge() you should know" }, { "code": null, "e": 7510, "s": 7468, "text": "Working with datetime in Pandas DataFrame" }, { "code": null, "e": 7551, "s": 7510, "text": "Pandas read_csv() tricks you should know" }, { "code": null, "e": 7621, "s": 7551, "text": "4 tricks you should know to parse date columns with Pandas read_csv()" } ]
C++ Memory Library - static_pointer_cast
It allocates memory for an object of type T using alloc and constructs it passing args to its constructor. The function returns an object of type shared_ptr that owns and stores a pointer to the constructed object. Following is the declaration for std::static_pointer_cast. template <class T, class U> shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept; template <class T, class U> shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept; sp − Its a shared pointer. It returns a copy of sp of the proper type with its stored pointer casted statically from U* to T*. noexcep − It doesn't throw any exceptions. In below example explains about std::static_pointer_cast. #include <iostream> #include <memory> struct BaseClass {}; struct DerivedClass : BaseClass { void f() const { std::cout << "Sample word!\n"; } }; int main() { std::shared_ptr<BaseClass> ptr_to_base(std::make_shared<DerivedClass>()); std::static_pointer_cast<DerivedClass>(ptr_to_base)->f(); static_cast<DerivedClass*>(ptr_to_base.get())->f(); } Let us compile and run the above program, this will produce the following result − Sample word! Sample word! Print Add Notes Bookmark this page
[ { "code": null, "e": 2818, "s": 2603, "text": "It allocates memory for an object of type T using alloc and constructs it passing args to its constructor. The function returns an object of type shared_ptr that owns and stores a pointer to the constructed object." }, { "code": null, "e": 2877, "s": 2818, "text": "Following is the declaration for std::static_pointer_cast." }, { "code": null, "e": 2978, "s": 2877, "text": "template <class T, class U>\n shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept;" }, { "code": null, "e": 3079, "s": 2978, "text": "template <class T, class U>\n shared_ptr<T> static_pointer_cast (const shared_ptr<U>& sp) noexcept;" }, { "code": null, "e": 3106, "s": 3079, "text": "sp − Its a shared pointer." }, { "code": null, "e": 3206, "s": 3106, "text": "It returns a copy of sp of the proper type with its stored pointer casted statically from U* to T*." }, { "code": null, "e": 3249, "s": 3206, "text": "noexcep − It doesn't throw any exceptions." }, { "code": null, "e": 3307, "s": 3249, "text": "In below example explains about std::static_pointer_cast." }, { "code": null, "e": 3680, "s": 3307, "text": "#include <iostream>\n#include <memory>\n\nstruct BaseClass {};\n\nstruct DerivedClass : BaseClass {\n void f() const {\n std::cout << \"Sample word!\\n\";\n }\n};\n \nint main() {\n std::shared_ptr<BaseClass> ptr_to_base(std::make_shared<DerivedClass>());\n\n std::static_pointer_cast<DerivedClass>(ptr_to_base)->f();\n\n static_cast<DerivedClass*>(ptr_to_base.get())->f();\n\n}" }, { "code": null, "e": 3763, "s": 3680, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3790, "s": 3763, "text": "Sample word!\nSample word!\n" }, { "code": null, "e": 3797, "s": 3790, "text": " Print" }, { "code": null, "e": 3808, "s": 3797, "text": " Add Notes" } ]
How to create a movie trailer app in ReactJS ? - GeeksforGeeks
06 Aug, 2021 In this article, we are going to make a simple app that searches for any movie/web series trailers. We will use ‘movie-trailer’ npm package to find such URLs and display the content using another npm package called ‘react-player’. Prerequisites: The pre-requisites for this project are: React. React Hooks. JavaScript ES6. React Axios & API Functional Components Approach: Our app contains two sections i.e a section for taking the user input and the other for displaying the video. Whenever a user searches for a video, we will store that inside a state variable and whenever a user clicks on the search button we will call a function that will fetch the required video URL and store it in another state variable. Now we have the required URL, we will simply render that video using the ‘ReactPlayer’ component. Creating React app and installing module: Step 1: Create a react application by typing the following command in the terminal: npx create-react-app movie-app Step 2: Now, go to the project folder i.e movie-app by running the following command: cd movie-app Step 3: Let’s install some npm packages required for this project: movie-trailer: Fetch Youtube trailers for any movies/series. npm install --save movie-trailer react-player: A react component for playing a variety of URLs, including file paths, YouTube, etc. npm install react-player Project Structure: It should look like this: Example code: Edit src/App.js file: This file contains our app logic: Javascript import './App.css';import { useState } from 'react';import ReactPlayer from 'react-player';import movieTrailer from 'movie-trailer'; function App() { //Setting up the initial states using // react hook 'useState" const [video, setVideo] = useState("inception"); const [videoURL, setVideoURL] = useState("https://youtu.be/sa9l-dTv9Gk"); //A function to fetch the required URL // and storing it inside the // videoURL state variable function handleSearch() { movieTrailer(video).then((res) => { setVideoURL(res); }); } return ( <div className="App"> <div className="search-box"> <label> Search for any movies/shows:{ " " } </label> <input type="text" onChange= {(e) => { setVideo(e.target.value) }} /> <button onClick={()=>{handleSearch()}}> Search </button> </div> // Using 'ReactPlayer' component to // display the video <ReactPlayer url={videoURL} controls={true}/> </div> );} export default App; Edit src/App.css file: This file contains all the required styling for that app: CSS .App { display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; height: 100vh; width: 100%; font-size: 22px;} .search-box { height: 10vh;} .search-box>input,button { box-sizing: border-box; height: 25px; font-size: 20px;} Step to run application: Type the following command in the terminal: npm start Output: Now Open http://localhost:3000/ in your browser to see our working app. React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set background images in ReactJS ? How to navigate on path by button click in react router ? ReactJS useNavigate() Hook How to create a table in ReactJS ? Axios in React: A Guide for Beginners 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 insert spaces/tabs in text using HTML/CSS? Top 10 Angular Libraries For Web Developers
[ { "code": null, "e": 24708, "s": 24680, "text": "\n06 Aug, 2021" }, { "code": null, "e": 24940, "s": 24708, "text": "In this article, we are going to make a simple app that searches for any movie/web series trailers. We will use ‘movie-trailer’ npm package to find such URLs and display the content using another npm package called ‘react-player’. " }, { "code": null, "e": 24996, "s": 24940, "text": "Prerequisites: The pre-requisites for this project are:" }, { "code": null, "e": 25003, "s": 24996, "text": "React." }, { "code": null, "e": 25016, "s": 25003, "text": "React Hooks." }, { "code": null, "e": 25032, "s": 25016, "text": "JavaScript ES6." }, { "code": null, "e": 25050, "s": 25032, "text": "React Axios & API" }, { "code": null, "e": 25072, "s": 25050, "text": "Functional Components" }, { "code": null, "e": 25522, "s": 25072, "text": "Approach: Our app contains two sections i.e a section for taking the user input and the other for displaying the video. Whenever a user searches for a video, we will store that inside a state variable and whenever a user clicks on the search button we will call a function that will fetch the required video URL and store it in another state variable. Now we have the required URL, we will simply render that video using the ‘ReactPlayer’ component." }, { "code": null, "e": 25565, "s": 25522, "text": "Creating React app and installing module: " }, { "code": null, "e": 25649, "s": 25565, "text": "Step 1: Create a react application by typing the following command in the terminal:" }, { "code": null, "e": 25680, "s": 25649, "text": "npx create-react-app movie-app" }, { "code": null, "e": 25766, "s": 25680, "text": "Step 2: Now, go to the project folder i.e movie-app by running the following command:" }, { "code": null, "e": 25779, "s": 25766, "text": "cd movie-app" }, { "code": null, "e": 25846, "s": 25779, "text": "Step 3: Let’s install some npm packages required for this project:" }, { "code": null, "e": 25907, "s": 25846, "text": "movie-trailer: Fetch Youtube trailers for any movies/series." }, { "code": null, "e": 25940, "s": 25907, "text": "npm install --save movie-trailer" }, { "code": null, "e": 26039, "s": 25940, "text": "react-player: A react component for playing a variety of URLs, including file paths, YouTube, etc." }, { "code": null, "e": 26064, "s": 26039, "text": "npm install react-player" }, { "code": null, "e": 26109, "s": 26064, "text": "Project Structure: It should look like this:" }, { "code": null, "e": 26123, "s": 26109, "text": "Example code:" }, { "code": null, "e": 26179, "s": 26123, "text": "Edit src/App.js file: This file contains our app logic:" }, { "code": null, "e": 26190, "s": 26179, "text": "Javascript" }, { "code": "import './App.css';import { useState } from 'react';import ReactPlayer from 'react-player';import movieTrailer from 'movie-trailer'; function App() { //Setting up the initial states using // react hook 'useState\" const [video, setVideo] = useState(\"inception\"); const [videoURL, setVideoURL] = useState(\"https://youtu.be/sa9l-dTv9Gk\"); //A function to fetch the required URL // and storing it inside the // videoURL state variable function handleSearch() { movieTrailer(video).then((res) => { setVideoURL(res); }); } return ( <div className=\"App\"> <div className=\"search-box\"> <label> Search for any movies/shows:{ \" \" } </label> <input type=\"text\" onChange= {(e) => { setVideo(e.target.value) }} /> <button onClick={()=>{handleSearch()}}> Search </button> </div> // Using 'ReactPlayer' component to // display the video <ReactPlayer url={videoURL} controls={true}/> </div> );} export default App;", "e": 27230, "s": 26190, "text": null }, { "code": null, "e": 27311, "s": 27230, "text": "Edit src/App.css file: This file contains all the required styling for that app:" }, { "code": null, "e": 27315, "s": 27311, "text": "CSS" }, { "code": ".App { display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; height: 100vh; width: 100%; font-size: 22px;} .search-box { height: 10vh;} .search-box>input,button { box-sizing: border-box; height: 25px; font-size: 20px;}", "e": 27623, "s": 27315, "text": null }, { "code": null, "e": 27692, "s": 27623, "text": "Step to run application: Type the following command in the terminal:" }, { "code": null, "e": 27702, "s": 27692, "text": "npm start" }, { "code": null, "e": 27783, "s": 27702, "text": "Output: Now Open http://localhost:3000/ in your browser to see our working app." }, { "code": null, "e": 27799, "s": 27783, "text": "React-Questions" }, { "code": null, "e": 27807, "s": 27799, "text": "ReactJS" }, { "code": null, "e": 27824, "s": 27807, "text": "Web Technologies" }, { "code": null, "e": 27922, "s": 27824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27931, "s": 27922, "text": "Comments" }, { "code": null, "e": 27944, "s": 27931, "text": "Old Comments" }, { "code": null, "e": 27986, "s": 27944, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 28044, "s": 27986, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 28071, "s": 28044, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 28106, "s": 28071, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 28144, "s": 28106, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 28186, "s": 28144, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28219, "s": 28186, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28281, "s": 28219, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28331, "s": 28281, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Firebase - Github Authentication
In this chapter, we will show you how to authenticate users using the GitHub API. Open Firebase dashboard and click Auth from the side menu and then SIGN-IN-METHOD in tab bar. You need enable GitHub authentication and copy the Callback URL. You will need this in step 2. You can leave this tab open since you will need to add Client ID and Client Secret once you finish step 2. Follow this link to create the GitHub app. You need to copy the Callback URL from Firebase into the Authorization callback URL field. Once your app is created, you need to copy the Client Key and the Client Secret from the GitHub app to Firebase. We will add two buttons in the body tag. <button onclick = "githubSignin()">Github Signin</button> <button onclick = "githubSignout()">Github Signout</button> We will create functions for signin and signout inside the index.js file. var provider = new firebase.auth.GithubAuthProvider(); function githubSignin() { firebase.auth().signInWithPopup(provider) .then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(token) console.log(user) }).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; console.log(error.code) console.log(error.message) }); } function githubSignout(){ firebase.auth().signOut() .then(function() { console.log('Signout successful!') }, function(error) { console.log('Signout failed') }); } Now we can click on buttons to trigger authentication. Console will show that the authentication is successful. 60 Lectures 5 hours University Code 28 Lectures 2.5 hours Appeteria 85 Lectures 14.5 hours Appeteria 46 Lectures 2.5 hours Gautham Vijayan 13 Lectures 1.5 hours Nishant Kumar 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2248, "s": 2166, "text": "In this chapter, we will show you how to authenticate users using the GitHub API." }, { "code": null, "e": 2544, "s": 2248, "text": "Open Firebase dashboard and click Auth from the side menu and then SIGN-IN-METHOD in tab bar. You need enable GitHub authentication and copy the Callback URL. You will need this in step 2. You can leave this tab open since you will need to add Client ID and Client Secret once you finish step 2." }, { "code": null, "e": 2791, "s": 2544, "text": "Follow this link to create the GitHub app. You need to copy the Callback URL from Firebase into the Authorization callback URL field. Once your app is created, you need to copy the Client Key and the Client Secret from the GitHub app to Firebase." }, { "code": null, "e": 2832, "s": 2791, "text": "We will add two buttons in the body tag." }, { "code": null, "e": 2950, "s": 2832, "text": "<button onclick = \"githubSignin()\">Github Signin</button>\n<button onclick = \"githubSignout()\">Github Signout</button>" }, { "code": null, "e": 3024, "s": 2950, "text": "We will create functions for signin and signout inside the index.js file." }, { "code": null, "e": 3685, "s": 3024, "text": "var provider = new firebase.auth.GithubAuthProvider();\n\nfunction githubSignin() {\n firebase.auth().signInWithPopup(provider)\n \n .then(function(result) {\n var token = result.credential.accessToken;\n var user = result.user;\n\t\t\n console.log(token)\n console.log(user)\n }).catch(function(error) {\n var errorCode = error.code;\n var errorMessage = error.message;\n\t\t\n console.log(error.code)\n console.log(error.message)\n });\n}\n\nfunction githubSignout(){\n firebase.auth().signOut()\n \n .then(function() {\n console.log('Signout successful!')\n }, function(error) {\n console.log('Signout failed')\n });\n}" }, { "code": null, "e": 3797, "s": 3685, "text": "Now we can click on buttons to trigger authentication. Console will show that the authentication is successful." }, { "code": null, "e": 3830, "s": 3797, "text": "\n 60 Lectures \n 5 hours \n" }, { "code": null, "e": 3847, "s": 3830, "text": " University Code" }, { "code": null, "e": 3882, "s": 3847, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3893, "s": 3882, "text": " Appeteria" }, { "code": null, "e": 3929, "s": 3893, "text": "\n 85 Lectures \n 14.5 hours \n" }, { "code": null, "e": 3940, "s": 3929, "text": " Appeteria" }, { "code": null, "e": 3975, "s": 3940, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3992, "s": 3975, "text": " Gautham Vijayan" }, { "code": null, "e": 4027, "s": 3992, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4042, "s": 4027, "text": " Nishant Kumar" }, { "code": null, "e": 4078, "s": 4042, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 4093, "s": 4078, "text": " Rahul Agarwal" }, { "code": null, "e": 4100, "s": 4093, "text": " Print" }, { "code": null, "e": 4111, "s": 4100, "text": " Add Notes" } ]
Real Time Custom Object Detection: Part 2 | Towards Data Science
In this article we will test the Custom trained Darknet model from my previous article Citations: The video output feed is available on YouTube by Bloomberg Quicktake. Image of a window is a screenshot of my personal computer. The output image feed is taken from an open source dataset from Kaggle. Huge thanks to Shauryasikt Jena In my last article, we saw how to create a custom mask detector using darknet. It would be more fun to see it in action, wouldn't it ;) So let’s make it work and yeah, the steps are way easier than the one to train the model because you have already installed the required libraries if you have followed my previous article (Phew!). If you haven’t, Keep Calm :), you can check everything in detail by going on my article. Here’s my previous article — medium.com This entire code is executed using a CPU. If you are writing the video output, you don’t need a GPU, the video is written according to your preferred frames per second value. For writing a video file, check out step 10. Importing LibrariesGetting the generated files from trainingReading the netSome Preprocessing of input imagesConfidence scores, ClassId, Coordinates of Bounding BoxesNon Maximum Suppression (NMS)Drawing bounding boxesUsageWriting to a file(optional) Importing Libraries Getting the generated files from training Reading the net Some Preprocessing of input images Confidence scores, ClassId, Coordinates of Bounding Boxes Non Maximum Suppression (NMS) Drawing bounding boxes Usage Writing to a file(optional) Okay... let’s make it work! Please go through the entire article so that you don’t miss out anything. Thanks :) Please import these libraries. import tensorflow as tfimport numpy as npimport cv2import pandas as pdimport timeimport osimport matplotlib.pyplot as pltfrom PIL import Image Note: You also need ffmpeg==4.2.2+ to write the video output file. Please go through my previous article if you’re having any issues. Once you have ffmpeg make sure you are running everything in the same anaconda environment in which you have installed ffmpeg. That’s all you need, let’s go to the important next step! This is a very crucial step for our object detector to roll. I am listing these files down below, ensure you have these files. Custom .names fileCustom .cfg file Custom .names file Custom .cfg file Note: We created these files just before our training, so if you are missing any one of them, your model will give you a hard time. These two files are very specific to your custom object detector, my previous article will guide you what changes can be made. You can chill out! it just takes a minute to create these files, if followed every detail :) 3. Custom .weights file Okay... let’s pause here for a minute to understand exactly how you get it. This file is known as the weights file, it is generally a large file also depending on your training size(for me it was 256mb). You get this file when your training has completed. In my case, the file name which I used was yolov3_custom_train_3000.weights. Here, ‘3000’ means that the file was generated after completing 3000 epochs. If you have gone through the .cfg file, you’ll find the epochs set to be 6000. So why didn’t I go with ‘yolov3_custom_train_6000.weights’? This was because after some testing I found out that the weights file generated after 3000 epochs had the best accuracy among every weights file generated actually, not just the ‘6000’ one. Okay. So more epochs should mean more accuracy right? Not really :( More epochs can also mean overfitting which can drastically reduce the accuracy. My training data might have had some duplicate images, or I might have labelled some incorrectly (Yeah I know.. it was a tedious task so uh.. you know how the mind deviates right) which indeed had a direct impact on accuracy. Now.. the testing part starts. I will try my best to make it easy and simple to follow and obviously, understand side by side :) Luckily, cv2 has a built-in function. net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)ln = net.getLayerNames()ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()] These beautiful functions makes our day way easier by directly reading the network model stored in Darknet model files and setting them up to for our detector code(Yaaasss!!). For more info on the function — docs.opencv.org You also need to get the labels from the ‘yolo.names’ file.. LABELS = open(labelsPath).read().strip().split("\n") Note: configPath, weightsPath and labelsPath contain the paths to the respective files These are some steps we need to do for our model to get some preprocessed images. The preprocessing includes Mean Subtraction and Scaling. docs.opencv.org (H, W) = image.shape[:2]blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)net.setInput(blob)layerOutputs = net.forward(ln)# Initializing for getting box coordinates, confidences, classid boxes = []confidences = []classIDs = []threshold = 0.15 Yeah...literally after this step we will have some confidence about our code and better understanding about what we have done and what are we gonna do after this. for output in layerOutputs: for detection in output: scores = detection[5:] classID = np.argmax(scores) confidence = scores[classID] if confidence > threshold: box = detection[0:4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype("int") x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID) So what exactly is this code doing? layerOutputs contain a huge 2D array of float numbers from which we need the coordinates of our “to be” drawn bounding boxes, classid and the confidence scores of each prediction or we can say detection :) Oh yeah.. this step gave me a hard time initially when I was not providing the correct input data type to it. I also tried some pre-written functions of NMS, but my object detection was so slow... After hitting my head for some time (not literally..), I was able to get the correct input datatype by writing the code given in the previous step for this super-fast life-saving function. idxs = cv2.dnn.NMSBoxes(boxes, confidences, threshold, 0.1) You can find some info here — docs.opencv.org So what is NMS? The model returns more than one predictions, hence more than one boxes are present to a single object. We surely don’t want that. Thanks to NMS, it returns a single best bounding box for that object. To get a deep understanding of NMS and how it works — towardsdatascience.com Aahhaa.. the interesting part. Let’s get our detector running now mc = 0nmc = 0if len(idxs) > 0: for i in idxs.flatten(): (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) if LABELS[classIDs[i]] == 'OBJECT_NAME_1'): mc += 1 color = (0, 255, 0) cv2.rectangle(image, (x, y), (x + w, y + h), color, 1) text = "{}".format(LABELS[classIDs[i]]) cv2.putText(image, text, (x + w, y + h), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 1) if (LABELS[classIDs[i]] == 'OBJECT_NAME_2'): nmc += 1 color = (0, 0, 255) cv2.rectangle(image, (x, y), (x + w, y + h), color, 1) text = "{}".format(LABELS[classIDs[i]]) cv2.putText(image, text, (x + w, y + h), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 1)text1 = "No. of people wearing masks: " + str(mc)text2 = "No. of people not wearing masks: " + str(nmc)color1 = (0, 255, 0)color2 = (0, 0, 255)cv2.putText(image, text1, (2, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color1, 2)cv2.putText(image, text2, (2, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color2, 2) Done!! This code will give you an image/frame containing your bounding boxes Note: Be sure to change OBJECT_NAME_1 and OBJECT_NAME_2 according to your object name. This would make your understanding better about your code;) Tip: I would recommend you to create a function in which you pass an image because later you can use this function for video as well as for an image input ;) The above code can be used in two ways — Real Time, that is passing a video to the detector Real Time, that is passing a video to the detector This can be done by just reading the frame from a video, you can also resize it if you want so that your ‘cv2.imshow’ displays the output frames at a quicker rate that is frames per second. To read a video using cv2 — opencv-python-tutroals.readthedocs.io Note: You don’t need to convert the frames obtained to grey-scale. Now just pass the frame to the function (mentioned in the tip) and boom.. you have your real time object detector ready! Output Video — Note: The above video output is smooth because I have saved the frames by writing it to a .mp4 file at 20 Frames per Second(fps) 2. Image You can also test your object detector by just passing a single image. (Yeah.. less fun). To read an image using cv2 — opencv-python-tutroals.readthedocs.io Output Image — You might be wondering how I got the video output so smooth, right? Here’s a trick you can use to get your smooth video output... OpenCV has a function called as cv2.VideoWriter(), you can write your frames by specifying the file name, codecid, fps, and the same resolution as your input field. docs.opencv.org Define the variable out outside the while loop in which you are reading each frame of a video out = cv2.VideoWriter('file_name.mp4', -1, fps, (int(cap.get(3)),int(cap.get(4)))) Note: The second parameter ‘-1’ is the codecid to be given, but it worked fine for me on my computer. The codecid can be different on your computer. Please visit this site for debugging— stackoverflow.com The last parameter will help you to get the resolution of your input video. After this, put the code below in the while loop where your detector function is being called. while True: .... .... image = detector(frame) out.write(image) .... .... Note: Your detector function should return an ‘image’ Tip: You can also use ‘moviepy’ to write your frames into video... pypi.org So that’s it! I hope you have your own custom object detector by now. Cheers! Thank you for going through the entire article, hope you found it informative. If you have any feedbacks they are most welcome!
[ { "code": null, "e": 259, "s": 172, "text": "In this article we will test the Custom trained Darknet model from my previous article" }, { "code": null, "e": 503, "s": 259, "text": "Citations: The video output feed is available on YouTube by Bloomberg Quicktake. Image of a window is a screenshot of my personal computer. The output image feed is taken from an open source dataset from Kaggle. Huge thanks to Shauryasikt Jena" }, { "code": null, "e": 639, "s": 503, "text": "In my last article, we saw how to create a custom mask detector using darknet. It would be more fun to see it in action, wouldn't it ;)" }, { "code": null, "e": 836, "s": 639, "text": "So let’s make it work and yeah, the steps are way easier than the one to train the model because you have already installed the required libraries if you have followed my previous article (Phew!)." }, { "code": null, "e": 925, "s": 836, "text": "If you haven’t, Keep Calm :), you can check everything in detail by going on my article." }, { "code": null, "e": 954, "s": 925, "text": "Here’s my previous article —" }, { "code": null, "e": 965, "s": 954, "text": "medium.com" }, { "code": null, "e": 1185, "s": 965, "text": "This entire code is executed using a CPU. If you are writing the video output, you don’t need a GPU, the video is written according to your preferred frames per second value. For writing a video file, check out step 10." }, { "code": null, "e": 1435, "s": 1185, "text": "Importing LibrariesGetting the generated files from trainingReading the netSome Preprocessing of input imagesConfidence scores, ClassId, Coordinates of Bounding BoxesNon Maximum Suppression (NMS)Drawing bounding boxesUsageWriting to a file(optional)" }, { "code": null, "e": 1455, "s": 1435, "text": "Importing Libraries" }, { "code": null, "e": 1497, "s": 1455, "text": "Getting the generated files from training" }, { "code": null, "e": 1513, "s": 1497, "text": "Reading the net" }, { "code": null, "e": 1548, "s": 1513, "text": "Some Preprocessing of input images" }, { "code": null, "e": 1606, "s": 1548, "text": "Confidence scores, ClassId, Coordinates of Bounding Boxes" }, { "code": null, "e": 1636, "s": 1606, "text": "Non Maximum Suppression (NMS)" }, { "code": null, "e": 1659, "s": 1636, "text": "Drawing bounding boxes" }, { "code": null, "e": 1665, "s": 1659, "text": "Usage" }, { "code": null, "e": 1693, "s": 1665, "text": "Writing to a file(optional)" }, { "code": null, "e": 1805, "s": 1693, "text": "Okay... let’s make it work! Please go through the entire article so that you don’t miss out anything. Thanks :)" }, { "code": null, "e": 1836, "s": 1805, "text": "Please import these libraries." }, { "code": null, "e": 1979, "s": 1836, "text": "import tensorflow as tfimport numpy as npimport cv2import pandas as pdimport timeimport osimport matplotlib.pyplot as pltfrom PIL import Image" }, { "code": null, "e": 2240, "s": 1979, "text": "Note: You also need ffmpeg==4.2.2+ to write the video output file. Please go through my previous article if you’re having any issues. Once you have ffmpeg make sure you are running everything in the same anaconda environment in which you have installed ffmpeg." }, { "code": null, "e": 2298, "s": 2240, "text": "That’s all you need, let’s go to the important next step!" }, { "code": null, "e": 2425, "s": 2298, "text": "This is a very crucial step for our object detector to roll. I am listing these files down below, ensure you have these files." }, { "code": null, "e": 2460, "s": 2425, "text": "Custom .names fileCustom .cfg file" }, { "code": null, "e": 2479, "s": 2460, "text": "Custom .names file" }, { "code": null, "e": 2496, "s": 2479, "text": "Custom .cfg file" }, { "code": null, "e": 2848, "s": 2496, "text": "Note: We created these files just before our training, so if you are missing any one of them, your model will give you a hard time. These two files are very specific to your custom object detector, my previous article will guide you what changes can be made. You can chill out! it just takes a minute to create these files, if followed every detail :)" }, { "code": null, "e": 2872, "s": 2848, "text": "3. Custom .weights file" }, { "code": null, "e": 2948, "s": 2872, "text": "Okay... let’s pause here for a minute to understand exactly how you get it." }, { "code": null, "e": 3361, "s": 2948, "text": "This file is known as the weights file, it is generally a large file also depending on your training size(for me it was 256mb). You get this file when your training has completed. In my case, the file name which I used was yolov3_custom_train_3000.weights. Here, ‘3000’ means that the file was generated after completing 3000 epochs. If you have gone through the .cfg file, you’ll find the epochs set to be 6000." }, { "code": null, "e": 3421, "s": 3361, "text": "So why didn’t I go with ‘yolov3_custom_train_6000.weights’?" }, { "code": null, "e": 3611, "s": 3421, "text": "This was because after some testing I found out that the weights file generated after 3000 epochs had the best accuracy among every weights file generated actually, not just the ‘6000’ one." }, { "code": null, "e": 3665, "s": 3611, "text": "Okay. So more epochs should mean more accuracy right?" }, { "code": null, "e": 3679, "s": 3665, "text": "Not really :(" }, { "code": null, "e": 3986, "s": 3679, "text": "More epochs can also mean overfitting which can drastically reduce the accuracy. My training data might have had some duplicate images, or I might have labelled some incorrectly (Yeah I know.. it was a tedious task so uh.. you know how the mind deviates right) which indeed had a direct impact on accuracy." }, { "code": null, "e": 4115, "s": 3986, "text": "Now.. the testing part starts. I will try my best to make it easy and simple to follow and obviously, understand side by side :)" }, { "code": null, "e": 4153, "s": 4115, "text": "Luckily, cv2 has a built-in function." }, { "code": null, "e": 4293, "s": 4153, "text": "net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)ln = net.getLayerNames()ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]" }, { "code": null, "e": 4469, "s": 4293, "text": "These beautiful functions makes our day way easier by directly reading the network model stored in Darknet model files and setting them up to for our detector code(Yaaasss!!)." }, { "code": null, "e": 4501, "s": 4469, "text": "For more info on the function —" }, { "code": null, "e": 4517, "s": 4501, "text": "docs.opencv.org" }, { "code": null, "e": 4578, "s": 4517, "text": "You also need to get the labels from the ‘yolo.names’ file.." }, { "code": null, "e": 4631, "s": 4578, "text": "LABELS = open(labelsPath).read().strip().split(\"\\n\")" }, { "code": null, "e": 4718, "s": 4631, "text": "Note: configPath, weightsPath and labelsPath contain the paths to the respective files" }, { "code": null, "e": 4857, "s": 4718, "text": "These are some steps we need to do for our model to get some preprocessed images. The preprocessing includes Mean Subtraction and Scaling." }, { "code": null, "e": 4873, "s": 4857, "text": "docs.opencv.org" }, { "code": null, "e": 5155, "s": 4873, "text": "(H, W) = image.shape[:2]blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)net.setInput(blob)layerOutputs = net.forward(ln)# Initializing for getting box coordinates, confidences, classid boxes = []confidences = []classIDs = []threshold = 0.15" }, { "code": null, "e": 5318, "s": 5155, "text": "Yeah...literally after this step we will have some confidence about our code and better understanding about what we have done and what are we gonna do after this." }, { "code": null, "e": 5873, "s": 5318, "text": "for output in layerOutputs: for detection in output: scores = detection[5:] classID = np.argmax(scores) confidence = scores[classID] if confidence > threshold: box = detection[0:4] * np.array([W, H, W, H]) (centerX, centerY, width, height) = box.astype(\"int\") x = int(centerX - (width / 2)) y = int(centerY - (height / 2)) boxes.append([x, y, int(width), int(height)]) confidences.append(float(confidence)) classIDs.append(classID)" }, { "code": null, "e": 5909, "s": 5873, "text": "So what exactly is this code doing?" }, { "code": null, "e": 6115, "s": 5909, "text": "layerOutputs contain a huge 2D array of float numbers from which we need the coordinates of our “to be” drawn bounding boxes, classid and the confidence scores of each prediction or we can say detection :)" }, { "code": null, "e": 6312, "s": 6115, "text": "Oh yeah.. this step gave me a hard time initially when I was not providing the correct input data type to it. I also tried some pre-written functions of NMS, but my object detection was so slow..." }, { "code": null, "e": 6501, "s": 6312, "text": "After hitting my head for some time (not literally..), I was able to get the correct input datatype by writing the code given in the previous step for this super-fast life-saving function." }, { "code": null, "e": 6561, "s": 6501, "text": "idxs = cv2.dnn.NMSBoxes(boxes, confidences, threshold, 0.1)" }, { "code": null, "e": 6591, "s": 6561, "text": "You can find some info here —" }, { "code": null, "e": 6607, "s": 6591, "text": "docs.opencv.org" }, { "code": null, "e": 6623, "s": 6607, "text": "So what is NMS?" }, { "code": null, "e": 6823, "s": 6623, "text": "The model returns more than one predictions, hence more than one boxes are present to a single object. We surely don’t want that. Thanks to NMS, it returns a single best bounding box for that object." }, { "code": null, "e": 6877, "s": 6823, "text": "To get a deep understanding of NMS and how it works —" }, { "code": null, "e": 6900, "s": 6877, "text": "towardsdatascience.com" }, { "code": null, "e": 6966, "s": 6900, "text": "Aahhaa.. the interesting part. Let’s get our detector running now" }, { "code": null, "e": 8064, "s": 6966, "text": "mc = 0nmc = 0if len(idxs) > 0: for i in idxs.flatten(): (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) if LABELS[classIDs[i]] == 'OBJECT_NAME_1'): mc += 1 color = (0, 255, 0) cv2.rectangle(image, (x, y), (x + w, y + h), color, 1) text = \"{}\".format(LABELS[classIDs[i]]) cv2.putText(image, text, (x + w, y + h), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 1) if (LABELS[classIDs[i]] == 'OBJECT_NAME_2'): nmc += 1 color = (0, 0, 255) cv2.rectangle(image, (x, y), (x + w, y + h), color, 1) text = \"{}\".format(LABELS[classIDs[i]]) cv2.putText(image, text, (x + w, y + h), cv2.FONT_HERSHEY_SIMPLEX,0.5, color, 1)text1 = \"No. of people wearing masks: \" + str(mc)text2 = \"No. of people not wearing masks: \" + str(nmc)color1 = (0, 255, 0)color2 = (0, 0, 255)cv2.putText(image, text1, (2, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color1, 2)cv2.putText(image, text2, (2, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color2, 2)" }, { "code": null, "e": 8141, "s": 8064, "text": "Done!! This code will give you an image/frame containing your bounding boxes" }, { "code": null, "e": 8288, "s": 8141, "text": "Note: Be sure to change OBJECT_NAME_1 and OBJECT_NAME_2 according to your object name. This would make your understanding better about your code;)" }, { "code": null, "e": 8446, "s": 8288, "text": "Tip: I would recommend you to create a function in which you pass an image because later you can use this function for video as well as for an image input ;)" }, { "code": null, "e": 8487, "s": 8446, "text": "The above code can be used in two ways —" }, { "code": null, "e": 8538, "s": 8487, "text": "Real Time, that is passing a video to the detector" }, { "code": null, "e": 8589, "s": 8538, "text": "Real Time, that is passing a video to the detector" }, { "code": null, "e": 8807, "s": 8589, "text": "This can be done by just reading the frame from a video, you can also resize it if you want so that your ‘cv2.imshow’ displays the output frames at a quicker rate that is frames per second. To read a video using cv2 —" }, { "code": null, "e": 8845, "s": 8807, "text": "opencv-python-tutroals.readthedocs.io" }, { "code": null, "e": 8912, "s": 8845, "text": "Note: You don’t need to convert the frames obtained to grey-scale." }, { "code": null, "e": 9033, "s": 8912, "text": "Now just pass the frame to the function (mentioned in the tip) and boom.. you have your real time object detector ready!" }, { "code": null, "e": 9048, "s": 9033, "text": "Output Video —" }, { "code": null, "e": 9177, "s": 9048, "text": "Note: The above video output is smooth because I have saved the frames by writing it to a .mp4 file at 20 Frames per Second(fps)" }, { "code": null, "e": 9186, "s": 9177, "text": "2. Image" }, { "code": null, "e": 9305, "s": 9186, "text": "You can also test your object detector by just passing a single image. (Yeah.. less fun). To read an image using cv2 —" }, { "code": null, "e": 9343, "s": 9305, "text": "opencv-python-tutroals.readthedocs.io" }, { "code": null, "e": 9358, "s": 9343, "text": "Output Image —" }, { "code": null, "e": 9488, "s": 9358, "text": "You might be wondering how I got the video output so smooth, right? Here’s a trick you can use to get your smooth video output..." }, { "code": null, "e": 9653, "s": 9488, "text": "OpenCV has a function called as cv2.VideoWriter(), you can write your frames by specifying the file name, codecid, fps, and the same resolution as your input field." }, { "code": null, "e": 9669, "s": 9653, "text": "docs.opencv.org" }, { "code": null, "e": 9763, "s": 9669, "text": "Define the variable out outside the while loop in which you are reading each frame of a video" }, { "code": null, "e": 9858, "s": 9763, "text": "out = cv2.VideoWriter('file_name.mp4', -1, fps, (int(cap.get(3)),int(cap.get(4))))" }, { "code": null, "e": 10045, "s": 9858, "text": "Note: The second parameter ‘-1’ is the codecid to be given, but it worked fine for me on my computer. The codecid can be different on your computer. Please visit this site for debugging—" }, { "code": null, "e": 10063, "s": 10045, "text": "stackoverflow.com" }, { "code": null, "e": 10234, "s": 10063, "text": "The last parameter will help you to get the resolution of your input video. After this, put the code below in the while loop where your detector function is being called." }, { "code": null, "e": 10316, "s": 10234, "text": "while True: .... .... image = detector(frame) out.write(image) .... ...." }, { "code": null, "e": 10370, "s": 10316, "text": "Note: Your detector function should return an ‘image’" }, { "code": null, "e": 10437, "s": 10370, "text": "Tip: You can also use ‘moviepy’ to write your frames into video..." }, { "code": null, "e": 10446, "s": 10437, "text": "pypi.org" }, { "code": null, "e": 10524, "s": 10446, "text": "So that’s it! I hope you have your own custom object detector by now. Cheers!" } ]
Hexadecimal Arithmetic
Following are the characteristics of a hexadecimal number system. Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Also called base 16 number system. Also called base 16 number system. Each position in a hexadecimal number represents a 0 power of the base (16). Example − 160 Each position in a hexadecimal number represents a 0 power of the base (16). Example − 160 Last position in a hexadecimal number represents an x power of the base (16). Example − 16x where x represents the last position - 1. Last position in a hexadecimal number represents an x power of the base (16). Example − 16x where x represents the last position - 1. Hexadecimal Number − 19FDE16 Calculating Decimal Equivalent − Note − 19FDE16 is normally written as 19FDE. Following hexadecimal addition table will help you greatly to handle Hexadecimal addition. To use this table, simply follow the directions used in this example − Add A16 and 516. Locate A in the X column then locate the 5 in the Y column. The point in 'sum' area where these two columns intersect is the sum of two numbers. A16 + 516 = F16. The subtraction of hexadecimal numbers follow the same rules as the subtraction of numbers in any other number system. The only variation is in borrowed number. In the decimal system, you borrow a group of 1010. In the binary system, you borrow a group of 210. In the hexadecimal system you borrow a group of 1610. 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2037, "s": 1971, "text": "Following are the characteristics of a hexadecimal number system." }, { "code": null, "e": 2100, "s": 2037, "text": "Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F." }, { "code": null, "e": 2163, "s": 2100, "text": "Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F." }, { "code": null, "e": 2256, "s": 2163, "text": "Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15." }, { "code": null, "e": 2349, "s": 2256, "text": "Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15." }, { "code": null, "e": 2384, "s": 2349, "text": "Also called base 16 number system." }, { "code": null, "e": 2419, "s": 2384, "text": "Also called base 16 number system." }, { "code": null, "e": 2510, "s": 2419, "text": "Each position in a hexadecimal number represents a 0 power of the base (16). Example − 160" }, { "code": null, "e": 2601, "s": 2510, "text": "Each position in a hexadecimal number represents a 0 power of the base (16). Example − 160" }, { "code": null, "e": 2735, "s": 2601, "text": "Last position in a hexadecimal number represents an x power of the base (16). Example − 16x where x represents the last position - 1." }, { "code": null, "e": 2869, "s": 2735, "text": "Last position in a hexadecimal number represents an x power of the base (16). Example − 16x where x represents the last position - 1." }, { "code": null, "e": 2898, "s": 2869, "text": "Hexadecimal Number − 19FDE16" }, { "code": null, "e": 2931, "s": 2898, "text": "Calculating Decimal Equivalent −" }, { "code": null, "e": 2976, "s": 2931, "text": "Note − 19FDE16 is normally written as 19FDE." }, { "code": null, "e": 3067, "s": 2976, "text": "Following hexadecimal addition table will help you greatly to handle Hexadecimal addition." }, { "code": null, "e": 3300, "s": 3067, "text": "To use this table, simply follow the directions used in this example − Add A16 and 516. Locate A in the X column then locate the 5 in the Y column. The point in 'sum' area where these two columns intersect is the sum of two numbers." }, { "code": null, "e": 3318, "s": 3300, "text": "A16 + 516 = F16.\n" }, { "code": null, "e": 3633, "s": 3318, "text": "The subtraction of hexadecimal numbers follow the same rules as the subtraction of numbers in any other number system. The only variation is in borrowed number. In the decimal system, you borrow a group of 1010. In the binary system, you borrow a group of 210. In the hexadecimal system you borrow a group of 1610." }, { "code": null, "e": 3670, "s": 3633, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 3689, "s": 3670, "text": " Arnab Chakraborty" }, { "code": null, "e": 3723, "s": 3689, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 3742, "s": 3723, "text": " Arnab Chakraborty" }, { "code": null, "e": 3775, "s": 3742, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 3794, "s": 3775, "text": " Arnab Chakraborty" }, { "code": null, "e": 3829, "s": 3794, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3837, "s": 3829, "text": " Shweta" }, { "code": null, "e": 3870, "s": 3837, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 3887, "s": 3870, "text": " Abhilash Nelson" }, { "code": null, "e": 3920, "s": 3887, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 3942, "s": 3920, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 3949, "s": 3942, "text": " Print" }, { "code": null, "e": 3960, "s": 3949, "text": " Add Notes" } ]
Docker - Hub
Docker Hub is a registry service on the cloud that allows you to download Docker images that are built by other communities. You can also upload your own Docker built images to Docker hub. In this chapter, we will see how to download and the use the Jenkins Docker image from Docker hub. The official site for Docker hub is − https://www.docker.com/community-edition#/add_ons Step 1 − First you need to do a simple sign-up on Docker hub. Step 2 − Once you have signed up, you will be logged into Docker Hub. Step 3 − Next, let’s browse and find the Jenkins image. Step 4 − If you scroll down on the same page, you can see the Docker pull command. This will be used to download the Jenkins image onto the local Ubuntu server. Step 5 − Now, go to the Ubuntu server and run the following command − sudo docker pull jenkins To run Jenkins, you need to run the following command − sudo docker run -p 8080:8080 -p 50000:50000 jenkins Note the following points about the above sudo command − We are using the sudo command to ensure it runs with root access. We are using the sudo command to ensure it runs with root access. Here, jenkins is the name of the image we want to download from Docker hub and install on our Ubuntu machine. Here, jenkins is the name of the image we want to download from Docker hub and install on our Ubuntu machine. -p is used to map the port number of the internal Docker image to our main Ubuntu server so that we can access the container accordingly. -p is used to map the port number of the internal Docker image to our main Ubuntu server so that we can access the container accordingly. You will then have Jenkins successfully running as a container on the Ubuntu machine. 70 Lectures 12 hours Anshul Chauhan 41 Lectures 5 hours AR Shankar 31 Lectures 3 hours Abhilash Nelson 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 33 Lectures 4 hours Mumshad Mannambeth 13 Lectures 53 mins Musab Zayadneh Print Add Notes Bookmark this page
[ { "code": null, "e": 2629, "s": 2340, "text": "Docker Hub is a registry service on the cloud that allows you to download Docker images that are built by other communities. You can also upload your own Docker built images to Docker hub. In this chapter, we will see how to download and the use the Jenkins Docker image from Docker hub.\n" }, { "code": null, "e": 2717, "s": 2629, "text": "The official site for Docker hub is − https://www.docker.com/community-edition#/add_ons" }, { "code": null, "e": 2779, "s": 2717, "text": "Step 1 − First you need to do a simple sign-up on Docker hub." }, { "code": null, "e": 2849, "s": 2779, "text": "Step 2 − Once you have signed up, you will be logged into Docker Hub." }, { "code": null, "e": 2905, "s": 2849, "text": "Step 3 − Next, let’s browse and find the Jenkins image." }, { "code": null, "e": 3066, "s": 2905, "text": "Step 4 − If you scroll down on the same page, you can see the Docker pull command. This will be used to download the Jenkins image onto the local Ubuntu server." }, { "code": null, "e": 3136, "s": 3066, "text": "Step 5 − Now, go to the Ubuntu server and run the following command −" }, { "code": null, "e": 3163, "s": 3136, "text": "sudo docker pull jenkins \n" }, { "code": null, "e": 3219, "s": 3163, "text": "To run Jenkins, you need to run the following command −" }, { "code": null, "e": 3273, "s": 3219, "text": "sudo docker run -p 8080:8080 -p 50000:50000 jenkins \n" }, { "code": null, "e": 3330, "s": 3273, "text": "Note the following points about the above sudo command −" }, { "code": null, "e": 3396, "s": 3330, "text": "We are using the sudo command to ensure it runs with root access." }, { "code": null, "e": 3462, "s": 3396, "text": "We are using the sudo command to ensure it runs with root access." }, { "code": null, "e": 3572, "s": 3462, "text": "Here, jenkins is the name of the image we want to download from Docker hub and install on our Ubuntu machine." }, { "code": null, "e": 3682, "s": 3572, "text": "Here, jenkins is the name of the image we want to download from Docker hub and install on our Ubuntu machine." }, { "code": null, "e": 3820, "s": 3682, "text": "-p is used to map the port number of the internal Docker image to our main Ubuntu server so that we can access the container accordingly." }, { "code": null, "e": 3958, "s": 3820, "text": "-p is used to map the port number of the internal Docker image to our main Ubuntu server so that we can access the container accordingly." }, { "code": null, "e": 4044, "s": 3958, "text": "You will then have Jenkins successfully running as a container on the Ubuntu machine." }, { "code": null, "e": 4078, "s": 4044, "text": "\n 70 Lectures \n 12 hours \n" }, { "code": null, "e": 4094, "s": 4078, "text": " Anshul Chauhan" }, { "code": null, "e": 4127, "s": 4094, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 4139, "s": 4127, "text": " AR Shankar" }, { "code": null, "e": 4172, "s": 4139, "text": "\n 31 Lectures \n 3 hours \n" }, { "code": null, "e": 4189, "s": 4172, "text": " Abhilash Nelson" }, { "code": null, "e": 4222, "s": 4189, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 4262, "s": 4222, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 4295, "s": 4262, "text": "\n 33 Lectures \n 4 hours \n" }, { "code": null, "e": 4315, "s": 4295, "text": " Mumshad Mannambeth" }, { "code": null, "e": 4347, "s": 4315, "text": "\n 13 Lectures \n 53 mins\n" }, { "code": null, "e": 4363, "s": 4347, "text": " Musab Zayadneh" }, { "code": null, "e": 4370, "s": 4363, "text": " Print" }, { "code": null, "e": 4381, "s": 4370, "text": " Add Notes" } ]
Product of Primes | Practice | GeeksforGeeks
Given two numbers L and R (inclusive) find the product of primes within this range. Print the product modulo 109+7. If there are no primes in that range you must print 1. Example 1: Input: L = 1, R = 10 Output: 210 Explaination: The prime numbers are 2, 3, 5 and 7. Example 2: Input: L = 1, R = 20 Output: 9699690 Explaination: The primes are 2, 3, 5, 7, 11, 13, 17 and 19. Your Task: You do not need to read input or print anything. Your task is to complete the function primeProduct() which takes L and R and returns the product of the primes within the range. If there are no primes in that range then return 1. Expected Time Complexity: O((R-L)*(logR)) Expected Auxiliary Space: O(sqrt(R)) Constraints: 1 ≤ L ≤ R ≤ 109 0 ≤ L - R ≤ 106 +1 jaswanth17121 hour ago Best c++ efficient way #define ll long longclass Solution{public:bool check(ll n){ if(n==1) return false; if(n==2) return true; if(n%2==0) return false; for(int i=3;i*i<=n;i+=2){ if(n%i==0) return false; } return true; } long long primeProduct(long long L, long long R){ // code here ll ans=1; ll mod=1e9+7; for(ll i=L;i<=R;i++){ if(check(i)) ans=(ll)((ans*i)%(mod)); } return ans%mod; } 0 mayank20452 hours ago [Java] Memory efficient solution to find product of primes within a range given. class Solution{ static long primeProduct(long L, long R){ // code here long mod = 1000000007; int SIZE = (int) (R - L + 1); // By default value is false, which means that value is prime boolean primes[] = new boolean[SIZE]; for (long i = 2; i <= R / 2; ++i) { long start = L % i == 0 ? L : L + (i - (L % i)); //We are checking start is equal to i or not because when L is smaller than //i, then start will be equal to i as per code above but in this case start or i //is a prime, so we cannot mark primes[start] true (if it is false), so we will //increment start to its next value if (start == i) { start = start + i; } int index = 0; while (start <= R) { index = (int) (start - L); primes[index] = true; start += i; } } long product = 1; for (int i = 0; i < SIZE; ++i) { if (primes[i] == false) { product = (product * (L + i)) % mod; } } return product; } } 0 irejwanul3 hours ago The output is not succeeding for input: 34524465 34551428 +1 surjit200120013 hours ago C++ Solution Using segmented sieve class Solution{ const int MOD=1000000007; bool prime[1000001]; vector<int> p; void sieve(){ prime[0]=prime[1]=1; for(int i=2;1LL*i*i<1000001;i++){ if(!prime[i]){ for(int j=i*i;j<1000001;j+=i){ prime[j]=1; } } } for(int i=2;i<1000001;i++)if(!prime[i])p.push_back(i); } int seg(int L,int R){ if(L==1)L++; int max=(R-L+1),res=1; vector<bool> arr(max,false); for(auto &x:p){ if(1LL*x*x<=R){ long long i=(L/x)*x; if(i<L)i+=x; for(;i<=R;i+=x){ if(i!=x)arr[i-L]=1; } } } for(int i=L;i<=R;i++)if(!arr[i-L])res=1LL*res*i%MOD; return res; } public: long long primeProduct(long long L, long long R){ sieve(); return seg(L,R); } }; 0 aayush nigam3 hours ago My Solution: class Solution{ static long primeProduct(long L, long R){ // code here OptionalLong result = LongStream.rangeClosed(a, b).filter(i->isPrime(i)).reduce((x,y)->x*y); return result.getAsLong()%10000007; } private static boolean isPrime(long n){ if(n==1) return false; boolean result = LongStream.rangeClosed(2, n/2).noneMatch(i->n%i==0); return result; }} +3 ameyakannurkar3 hours ago class Solution{ bool isprime(long long n){ for(long long i=2;i*i<=n;i++) if(n%i == 0) return false; return true; }public: long long primeProduct(long long L, long long R){ // code here long long product=1; for(long long i=L;i<=R;i++) if(isprime(i)) product = (product*i) % 1000000007; return product; }}; 0 subhashishde083 hours ago bool isPrime(long long int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long long int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } long long primeProduct(long long L, long long R){ // code here long long int mod = pow(10,9) + 7; long long int result = 1; for(long long int i=L;i<=R;i++){ if(isPrime(i)){ result *= i; result = result % mod; } } return result%mod; } }; 0 rohankundu8594 hours ago //C++ Solution bool isprime(long long int n){ bool p=true; for(int i=2;i<=sqrt(n);i++) { if(n%i==0) { p=false; break; } } return p;} long long primeProduct(long long L, long long R) { // code here long long int x=1; for( long long int j=L;j<=R;j++) { if(isprime(j)) { x=(x*j)%1000000007; } } return x; } 0 choprakartik104 hours ago Code in JAVA(1.8) class Solution{ static long primeProduct(long L, long R){ long output = 1; for(long i=L;i<=R;i++){ if(isPrime(i)){ // System.out.println(i); output = (output*i)%1000000007; } } return output; } static boolean isPrime(long n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (long i = 3; i <= Math.sqrt(n); i =i+2) { if (n % i == 0) return false; } return true; } } 0 kunalbandooni14 hours ago Simple C++ solution:- Fastest in its kind :) class Solution{ bool isprime(long long n){ for(long long i=2;i*i<=n;i++) if(n%i == 0) return false; return true; } public: long long primeProduct(long long L, long long R){ long long product=1; for(long long i=L;i<=R;i++) if(isprime(i)) product = (product*i) % 1000000007; return product; } }; 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": 409, "s": 238, "text": "Given two numbers L and R (inclusive) find the product of primes within this range. Print the product modulo 109+7. If there are no primes in that range you must print 1." }, { "code": null, "e": 420, "s": 409, "text": "Example 1:" }, { "code": null, "e": 505, "s": 420, "text": "Input: L = 1, R = 10\nOutput: 210\nExplaination: The prime numbers are \n2, 3, 5 and 7." }, { "code": null, "e": 516, "s": 505, "text": "Example 2:" }, { "code": null, "e": 614, "s": 516, "text": "Input: L = 1, R = 20\nOutput: 9699690\nExplaination: The primes are 2, 3, \n5, 7, 11, 13, 17 and 19." }, { "code": null, "e": 855, "s": 614, "text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function primeProduct() which takes L and R and returns the product of the primes within the range. If there are no primes in that range then return 1." }, { "code": null, "e": 934, "s": 855, "text": "Expected Time Complexity: O((R-L)*(logR))\nExpected Auxiliary Space: O(sqrt(R))" }, { "code": null, "e": 981, "s": 934, "text": "Constraints:\n1 ≤ L ≤ R ≤ 109\n0 ≤ L - R ≤ 106 " }, { "code": null, "e": 984, "s": 981, "text": "+1" }, { "code": null, "e": 1007, "s": 984, "text": "jaswanth17121 hour ago" }, { "code": null, "e": 1030, "s": 1007, "text": "Best c++ efficient way" }, { "code": null, "e": 1503, "s": 1030, "text": "#define ll long longclass Solution{public:bool check(ll n){ if(n==1) return false; if(n==2) return true; if(n%2==0) return false; for(int i=3;i*i<=n;i+=2){ if(n%i==0) return false; } return true; } long long primeProduct(long long L, long long R){ // code here ll ans=1; ll mod=1e9+7; for(ll i=L;i<=R;i++){ if(check(i)) ans=(ll)((ans*i)%(mod)); } return ans%mod; }" }, { "code": null, "e": 1505, "s": 1503, "text": "0" }, { "code": null, "e": 1527, "s": 1505, "text": "mayank20452 hours ago" }, { "code": null, "e": 1608, "s": 1527, "text": "[Java] Memory efficient solution to find product of primes within a range given." }, { "code": null, "e": 2793, "s": 1608, "text": "class Solution{\n static long primeProduct(long L, long R){\n // code here\n long mod = 1000000007;\n int SIZE = (int) (R - L + 1);\n // By default value is false, which means that value is prime\n boolean primes[] = new boolean[SIZE];\n for (long i = 2; i <= R / 2; ++i) {\n long start = L % i == 0 ? L : L + (i - (L % i));\n //We are checking start is equal to i or not because when L is smaller than \n //i, then start will be equal to i as per code above but in this case start or i\n //is a prime, so we cannot mark primes[start] true (if it is false), so we will\n //increment start to its next value\n if (start == i) {\n start = start + i;\n }\n int index = 0;\n while (start <= R) {\n index = (int) (start - L);\n primes[index] = true;\n\n start += i;\n }\n }\n\n long product = 1;\n\n for (int i = 0; i < SIZE; ++i) {\n if (primes[i] == false) {\n product = (product * (L + i)) % mod;\n }\n }\n\n return product;\n }\n}" }, { "code": null, "e": 2795, "s": 2793, "text": "0" }, { "code": null, "e": 2816, "s": 2795, "text": "irejwanul3 hours ago" }, { "code": null, "e": 2874, "s": 2816, "text": "The output is not succeeding for input: 34524465 34551428" }, { "code": null, "e": 2877, "s": 2874, "text": "+1" }, { "code": null, "e": 2903, "s": 2877, "text": "surjit200120013 hours ago" }, { "code": null, "e": 2938, "s": 2903, "text": "C++ Solution Using segmented sieve" }, { "code": null, "e": 3882, "s": 2938, "text": "class Solution{\n const int MOD=1000000007;\n bool prime[1000001];\n vector<int> p;\n void sieve(){\n prime[0]=prime[1]=1;\n for(int i=2;1LL*i*i<1000001;i++){\n if(!prime[i]){\n for(int j=i*i;j<1000001;j+=i){\n prime[j]=1;\n }\n }\n }\n for(int i=2;i<1000001;i++)if(!prime[i])p.push_back(i);\n }\n int seg(int L,int R){\n if(L==1)L++;\n int max=(R-L+1),res=1;\n vector<bool> arr(max,false);\n for(auto &x:p){\n if(1LL*x*x<=R){\n long long i=(L/x)*x;\n if(i<L)i+=x;\n for(;i<=R;i+=x){\n if(i!=x)arr[i-L]=1;\n }\n }\n }\n for(int i=L;i<=R;i++)if(!arr[i-L])res=1LL*res*i%MOD;\n return res;\n }\npublic:\n long long primeProduct(long long L, long long R){\n sieve();\n return seg(L,R);\n }\n};" }, { "code": null, "e": 3884, "s": 3882, "text": "0" }, { "code": null, "e": 3908, "s": 3884, "text": "aayush nigam3 hours ago" }, { "code": null, "e": 3921, "s": 3908, "text": "My Solution:" }, { "code": null, "e": 4232, "s": 3921, "text": "class Solution{ static long primeProduct(long L, long R){ // code here OptionalLong result = LongStream.rangeClosed(a, b).filter(i->isPrime(i)).reduce((x,y)->x*y); return result.getAsLong()%10000007; } private static boolean isPrime(long n){ if(n==1) return false;" }, { "code": null, "e": 4337, "s": 4232, "text": " boolean result = LongStream.rangeClosed(2, n/2).noneMatch(i->n%i==0); return result; }}" }, { "code": null, "e": 4340, "s": 4337, "text": "+3" }, { "code": null, "e": 4366, "s": 4340, "text": "ameyakannurkar3 hours ago" }, { "code": null, "e": 4766, "s": 4366, "text": "class Solution{ bool isprime(long long n){ for(long long i=2;i*i<=n;i++) if(n%i == 0) return false; return true; }public: long long primeProduct(long long L, long long R){ // code here long long product=1; for(long long i=L;i<=R;i++) if(isprime(i)) product = (product*i) % 1000000007; return product; }};" }, { "code": null, "e": 4768, "s": 4766, "text": "0" }, { "code": null, "e": 4794, "s": 4768, "text": "subhashishde083 hours ago" }, { "code": null, "e": 5459, "s": 4794, "text": "bool isPrime(long long int n)\n{\n \n if (n <= 1)\n return false;\n if (n <= 3)\n return true;\n \n if (n % 2 == 0 || n % 3 == 0)\n return false;\n \n for (long long int i = 5; i * i <= n; i = i + 6)\n if (n % i == 0 || n % (i + 2) == 0)\n return false;\n \n return true;\n}\n long long primeProduct(long long L, long long R){\n // code here\n long long int mod = pow(10,9) + 7;\n long long int result = 1;\n for(long long int i=L;i<=R;i++){\n if(isPrime(i)){\n result *= i;\n result = result % mod;\n }\n }\n return result%mod;\n }\n};" }, { "code": null, "e": 5461, "s": 5459, "text": "0" }, { "code": null, "e": 5486, "s": 5461, "text": "rohankundu8594 hours ago" }, { "code": null, "e": 5502, "s": 5486, "text": "//C++ Solution " }, { "code": null, "e": 5926, "s": 5504, "text": "bool isprime(long long int n){ bool p=true; for(int i=2;i<=sqrt(n);i++) { if(n%i==0) { p=false; break; } } return p;} long long primeProduct(long long L, long long R) { // code here long long int x=1; for( long long int j=L;j<=R;j++) { if(isprime(j)) { x=(x*j)%1000000007; } } return x; }" }, { "code": null, "e": 5928, "s": 5926, "text": "0" }, { "code": null, "e": 5954, "s": 5928, "text": "choprakartik104 hours ago" }, { "code": null, "e": 6590, "s": 5954, "text": "Code in JAVA(1.8)\n\nclass Solution{\n static long primeProduct(long L, long R){\n long output = 1;\n for(long i=L;i<=R;i++){\n if(isPrime(i)){\n // System.out.println(i);\n output = (output*i)%1000000007;\n }\n }\n \n return output;\n }\n static boolean isPrime(long n)\n {\n if (n <= 1)\n return false;\n else if (n == 2)\n return true;\n else if (n % 2 == 0)\n return false;\n\n for (long i = 3; i <= Math.sqrt(n); i =i+2)\n {\n if (n % i == 0)\n return false;\n }\n return true;\n }\n}" }, { "code": null, "e": 6592, "s": 6590, "text": "0" }, { "code": null, "e": 6618, "s": 6592, "text": "kunalbandooni14 hours ago" }, { "code": null, "e": 6640, "s": 6618, "text": "Simple C++ solution:-" }, { "code": null, "e": 6663, "s": 6640, "text": "Fastest in its kind :)" }, { "code": null, "e": 7069, "s": 6663, "text": "class Solution{\n bool isprime(long long n){\n for(long long i=2;i*i<=n;i++)\n if(n%i == 0)\n return false;\n return true;\n }\npublic:\n long long primeProduct(long long L, long long R){\n long long product=1;\n for(long long i=L;i<=R;i++)\n if(isprime(i))\n product = (product*i) % 1000000007;\n return product;\n }\n};" }, { "code": null, "e": 7215, "s": 7069, "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": 7251, "s": 7215, "text": " Login to access your submissions. " }, { "code": null, "e": 7261, "s": 7251, "text": "\nProblem\n" }, { "code": null, "e": 7271, "s": 7261, "text": "\nContest\n" }, { "code": null, "e": 7334, "s": 7271, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7482, "s": 7334, "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": 7690, "s": 7482, "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": 7796, "s": 7690, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Add Image Recognition to your Chatbot with Google Dialogflow and Vision API | by Priyanka Vergadia | Towards Data Science
Conversational AI use cases are diverse. They include customer support, e-commerce, controlling IoT devices, enterprise productivity and much more. In very simplistic terms, these use cases involve a user asking a specific question (intent) and the conversational experience (or the chatbot) responding to the question by making calls to a backend system like a CRM, Database or an API. These “intents” are identified by utilizing Natural Language Processing (NLP) and the Machine Learning (ML). It turns out that some of these use cases can be enriched by allowing a user to upload an image. In such cases, you would want the conversation experience to take an action based on what exactly is in that image. Let’s imagine an e-commerce customer support example: If you are offering automated refunds, then you would ask the user to upload an image of the receipt, send the image to a pre-trained ML model, extract the text from the image, identify the purchase date from the text, see if it fits the refund window and then process the refund or deny it. Let’s image another support example: Your hardware product requires the customer to follow some setup steps and if they run into issues they turn to the chatbot, the chatbot asks them to upload the image of the device which in is sent to a pre-trained ML model which identifies what the problem can be and relays it back to the user via Chatbot. In this tutorial, you will learn how to integrate Dialogflow with Vision API to provide rich and dynamic ML based responses to user provided image inputs. You will create a simple chatbot application that will take an image as input, process it in Vision API and return the identified landmark to the user. See the image below. You will create a Dialogflow agent Implement a django front-end to upload a file Implement Dialogflow fulfillment to invoke vision API against the uploaded image. Just like the image below. Here is a video explaining the steps that follow. We are creating a conversation experience with a custom Django front-end and integrating it with Vision API. We will build the front-end with Django-framework, run and test it locally and then deploy it on Google App Engine. The front-end will look like this: The request flow will be: The user will send a request via this front-end.This will trigger a call to the Dialogflow DetectIntent API to map the user’s utterance to the right intent.Once the “Explore Landmark” intent is detected, Dialogflow fulfillment will then send a request to the Vision API, receive a response back and send it back to the user. The user will send a request via this front-end. This will trigger a call to the Dialogflow DetectIntent API to map the user’s utterance to the right intent. Once the “Explore Landmark” intent is detected, Dialogflow fulfillment will then send a request to the Vision API, receive a response back and send it back to the user. Overall architecture: Google cloud Vision API is a pre-trained Machine Learning model that helps derive insights from images. You can get insights including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. Here is the link to learn more specifically about the Vision API. Go to the Dialogflow Console.Sign-in, if you are a first time user, then use your email to sign upAccept the terms and conditions and you will be in the consoleCreate an Agent. To create, click on the dropdown menu in the left pane in order to see “Create new agent”Call this “VisionAPI”Dialogflow creates a Google Cloudproject for you to access logs, cloud functions etc. You can select an existing project as well.When you’re ready, click Create.Dialogflow creates two default intents as a part of the agent. Default Welcome intent helps greet your users. Default Fallback intent helps catch all the questions that your bot does not understand. Go to the Dialogflow Console. Sign-in, if you are a first time user, then use your email to sign up Accept the terms and conditions and you will be in the console Create an Agent. To create, click on the dropdown menu in the left pane in order to see “Create new agent” Call this “VisionAPI” Dialogflow creates a Google Cloudproject for you to access logs, cloud functions etc. You can select an existing project as well. When you’re ready, click Create. Dialogflow creates two default intents as a part of the agent. Default Welcome intent helps greet your users. Default Fallback intent helps catch all the questions that your bot does not understand. At this point, we have a functional bot that greets the users. But we need to update it slightly to let the user know that they can upload an image to explore landmarks. Click on “Default Welcome Intent”Update the “Response” to “Hi! You can upload a picture to explore landmarks.” Click on “Default Welcome Intent” Update the “Response” to “Hi! You can upload a picture to explore landmarks.” Click on “Entities”Create a new entity, name it “filename” and “save”. Click on “Entities” Create a new entity, name it “filename” and “save”. Click on “Intents” Name it “Explore uploaded image” Click on “Training phrases” and add “file is demo.jpg” and “file is taj.jpeg” with @filename as the entity. Click on “Responses” and add “Assessing file” as the Text Response Click on “Fulfillment” and toggle “Enable webhook call for this intent” Navigate to Dialogflow Agent “VisionAPI” and click on “Fulfillment” Enable inline code editor by toggling the switch. Update the index.js file with the following code and update YOUR-BUCKET-NAME with the name of your storage bucket. Click package.json and paste the following to replace its contents. Click Deploy at the bottom of the page. Clone this repository to your local machine: https://github.com/priyankavergadia/visionapi-dialogflow.git Change to the directory that contains the code/. Alternatively, you can download the sample as a zip and extract it. When deployed, your app uses the Cloud SQL Proxy that is built in to the App Engine environment to communicate with your Cloud SQL instance. However, to test your app locally, you must install and use a local copy of the Cloud SQL Proxy in your development environment. Learn more about the Cloud SQL Proxy here. To perform basic admin tasks on your Cloud SQL instance, you can use the MySQL client. Note: You must authenticate gcloud to use the proxy to connect from your local machine Download and install the Cloud SQL Proxy. The Cloud SQL Proxy is used to connect to your Cloud SQL instance when running locally. Download the proxy: curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.amd64 Make the proxy executable: chmod +x cloud_sql_proxy Create a Cloud SQL for MySQL Second Generation instance. Name the instance “polls-instance” or similar. It can take a few minutes for the instance to be ready. After the instance is ready, it should be visible in the instance list. Be sure to create a Second Generation instance. Now use the Cloud SDK to run the following command where [YOUR_INSTANCE_NAME] represents the name of your Cloud SQL instance. Make a note of the value shown for connectionName for the next step. The connectionName value is in the format [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME] gcloud sql instances describe [YOUR_INSTANCE_NAME] Alternatively, you can get the connection name from the console by clicking on the instance Start the Cloud SQL Proxy using the connectionName from the previous step. ./cloud_sql_proxy -instances=”[YOUR_INSTANCE_CONNECTION_NAME]”=tcp:3306 Replace [YOUR_INSTANCE_CONNECTION_NAME] with the value of connectionName that you recorded in the previous step. This step establishes a connection from your local computer to your Cloud SQL instance for local testing purposes. Keep the Cloud SQL Proxy running the entire time you test your app locally. Next, you create a new Cloud SQL user and database. Create a new database using the Google CloudConsole for your Cloud SQL instance polls-instance. For example, you can use the name polls. Create a new user using the Google CloudConsole for your Cloud SQL instance polls-instance. Open mysite/settings-changeme.py for editing. Rename the file to setting.py In two places, replace [YOUR-USERNAME] and [YOUR-PASSWORD] with the database username and password you created previously in the step “Create a Cloud SQL instance”. This helps set up the connection to the database for both App Engine deployment and local testing. In line ‘HOST’: ‘cloudsql/ [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]’ replace [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME] with your instance name acquired in previous step. Run the following command. Copy the outputted connectionName value for the next step. gcloud sql instances describe [YOUR_INSTANCE_NAME] Replace [YOUR-CONNECTION-NAME] with connectionName from the previous step Replace [YOUR-DATABASE] with the name you choose during the “Initialize your Cloud SQL instance” step and then, close and save settings.py # [START db_setup]if os.getenv(‘GAE_APPLICATION’, None):# Running on production App Engine, so connect to Google Cloud SQL using# the unix socket at /cloudsql/<your-cloudsql-connection string>DATABASES = {‘default’: {‘ENGINE’: ‘django.db.backends.mysql’,‘HOST’: ‘/cloudsql/[PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]’,‘USER’: ‘[YOUR-USERNAME]’,‘PASSWORD’: ‘[YOUR-PASSWORD]’,‘NAME’: ‘[YOUR-DATABASE]’,}}else:# Running locally so connect to either a local MySQL instance or connect to# Cloud SQL via the proxy. To start the proxy via command line:# $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306# See https://cloud.google.com/sql/docs/mysql-connect-proxyDATABASES = {‘default’: {‘ENGINE’: ‘django.db.backends.mysql’,‘HOST’: ‘127.0.0.1’,‘PORT’: ‘3306’,‘NAME’: ‘[YOUR-DATABASE]’,‘USER’: ‘[YOUR-USERNAME]’,‘PASSWORD’: ‘[YOUR-PASSWORD]’}}# [END db_setup] In Dialogflow’s console, go to settings ⚙ and under the general tab, you’ll see the Google Project section. Click on the service account. This will open the Google Cloud Console. In the Google Cloudconsole, the presented webpage will show the Dialogflow service account. Click on the 3 dots in the “Actions” section to the far right and then click “Create Key” A JSON file will be downloaded to your computer that you will need in the setup sections below. Inside chat folder, replace the key-sample.json with your own credentials json file and call it key.json. In views.py in chat folder, Change the GOOGLE_PROJECT_ID = “<YOUR_PROJECT_ID>” to your project ID Navigate to the Google CloudProject and click on Storage from the hamburger menu Click on “Create New Bucket” Provide a name — this has to be a globally unique name Choose where to store your data — Pick “Regional” and select the location that best suits your needs. Choose default storage class of your data as “Standard” Choose how to control access to objects as “Set permissions uniformly at bucket-level” and then continue to create the bucket. Once the bucket is created, click on the “Browser” and locate the bucket you just created. Click on the three dots on the right hand side corresponding to the bucket and click “Edit bucket permissions” In the presented side panel, click on “Add Members” and then add a new member “allUsers”, then click on “Select a role” to add “Storage Object Viewer” role. We do this to provide view access to the static front end files to allUsers. This is not an ideal security setting for the files but for the purpose of this particular lab it will work. Follow the same instructions and create a separate bucket to upload user images. Set permissions to “allUsers” and role “Storage Object Creator” and “Storage Object Viewer” Open mysite/setting.py Locate GCS_BUCKET variable and replace the “<YOUR-GCS-BUCKET-NAME>” with your GCS static bucket Locate GS_MEDIA_BUCKET_NAME variable and replace the “<YOUR-GCS-BUCKET-NAME-MEDIA>” with your GCS bucket name for the images. Locate GS_STATIC_BUCKET_NAME variable and replace the “<YOUR-GCS-BUCKET-NAME-STATIC>” with your GCS bucket name for the static files. Save the file. GCS_BUCKET = ‘<YOUR-GCS-BUCKET-NAME>’GS_MEDIA_BUCKET_NAME = ‘<YOUR-GCS-BUCKET-NAME-MEDIA>’GS_STATIC_BUCKET_NAME = ‘<YOUR-GCS-BUCKET-NAME-STATIC>’ Open chat -> templates -> home-changeme.html Rename it to home.html Look for <YOUR-GCS-BUCKET-NAME-MEDIA> and replace it with your bucket name for where you would like the user uploaded file to be saved. We do this so we don’t store the user uploaded file in the front-end and keep the static assets all in GCS bucket. The Vision API calls the GCS bucket to pick up the file and do the prediction. To run the Django app on your local computer, you’ll need to set up a Python development environment, including Python, pip, and virtualenv. For instructions, refer to Setting Up a Python Development Environment for Google Cloud Platform. Create an isolated Python environment, and install dependencies: virtualenv envsource env/bin/activatepip install -r requirements.txt Run the Django migrations to set up your models: python3 manage.py makemigrationspython3 manage.py makemigrations pollspython3 manage.py migrate Start a local web server: python3 manage.py runserver In your web browser, enter this address http://localhost:8000/ You should see a simple webpage with the text: “Dialogflow” a textbox and submit button. The sample app pages are delivered by the Django web server running on your computer. When you’re ready to move forward, press Ctrl+C to stop the local web server. Gather all the static content into one folder. This command moves all of the app’s static files into the folder specified by STATIC_ROOT in settings.py: python3 manage.py collectstatic Upload the app by running the following command from within the directory of the application where the app.yaml file is located: gcloud app deploy Wait for the message that notifies you that the update has been completed. In your web browser, enter this address: https://<your_project_id>.appspot.com This time, your request is served by a web server running in the App Engine standard environment. This command deploys the application as described in app.yaml and sets the newly deployed version as the default version, causing it to serve all new traffic. When you are ready to serve your content in production, in mysite/settings.py, change the DEBUG variable to False. Let’s test our chatbot with the following prompts User: “hi”Chatbot response: “Hi! You can upload a picture to explore landmarks.”User: uploads an image.Download an image with a landmark, name it “demo.jpg”Chatbot response: “file is being processed, here are the results: XXXX<whatever landmark is in your image>”Overall, it should look like this. User: “hi” Chatbot response: “Hi! You can upload a picture to explore landmarks.” User: uploads an image. Download an image with a landmark, name it “demo.jpg” Chatbot response: “file is being processed, here are the results: XXXX<whatever landmark is in your image>” Overall, it should look like this. Make sure to delete the Google Cloud project and the Dialogflow agent to avoid incurring any charges. Checkout my video series Deconstructing Chatbots, where I share how to get started and build conversational experiences using Dialogflow and Google Cloud tools. Dialogflow, Django app on Appengine, https://github.com/vkosuri/django-dialogflow
[ { "code": null, "e": 667, "s": 171, "text": "Conversational AI use cases are diverse. They include customer support, e-commerce, controlling IoT devices, enterprise productivity and much more. In very simplistic terms, these use cases involve a user asking a specific question (intent) and the conversational experience (or the chatbot) responding to the question by making calls to a backend system like a CRM, Database or an API. These “intents” are identified by utilizing Natural Language Processing (NLP) and the Machine Learning (ML)." }, { "code": null, "e": 880, "s": 667, "text": "It turns out that some of these use cases can be enriched by allowing a user to upload an image. In such cases, you would want the conversation experience to take an action based on what exactly is in that image." }, { "code": null, "e": 1226, "s": 880, "text": "Let’s imagine an e-commerce customer support example: If you are offering automated refunds, then you would ask the user to upload an image of the receipt, send the image to a pre-trained ML model, extract the text from the image, identify the purchase date from the text, see if it fits the refund window and then process the refund or deny it." }, { "code": null, "e": 1572, "s": 1226, "text": "Let’s image another support example: Your hardware product requires the customer to follow some setup steps and if they run into issues they turn to the chatbot, the chatbot asks them to upload the image of the device which in is sent to a pre-trained ML model which identifies what the problem can be and relays it back to the user via Chatbot." }, { "code": null, "e": 1900, "s": 1572, "text": "In this tutorial, you will learn how to integrate Dialogflow with Vision API to provide rich and dynamic ML based responses to user provided image inputs. You will create a simple chatbot application that will take an image as input, process it in Vision API and return the identified landmark to the user. See the image below." }, { "code": null, "e": 1935, "s": 1900, "text": "You will create a Dialogflow agent" }, { "code": null, "e": 1981, "s": 1935, "text": "Implement a django front-end to upload a file" }, { "code": null, "e": 2090, "s": 1981, "text": "Implement Dialogflow fulfillment to invoke vision API against the uploaded image. Just like the image below." }, { "code": null, "e": 2140, "s": 2090, "text": "Here is a video explaining the steps that follow." }, { "code": null, "e": 2400, "s": 2140, "text": "We are creating a conversation experience with a custom Django front-end and integrating it with Vision API. We will build the front-end with Django-framework, run and test it locally and then deploy it on Google App Engine. The front-end will look like this:" }, { "code": null, "e": 2426, "s": 2400, "text": "The request flow will be:" }, { "code": null, "e": 2751, "s": 2426, "text": "The user will send a request via this front-end.This will trigger a call to the Dialogflow DetectIntent API to map the user’s utterance to the right intent.Once the “Explore Landmark” intent is detected, Dialogflow fulfillment will then send a request to the Vision API, receive a response back and send it back to the user." }, { "code": null, "e": 2800, "s": 2751, "text": "The user will send a request via this front-end." }, { "code": null, "e": 2909, "s": 2800, "text": "This will trigger a call to the Dialogflow DetectIntent API to map the user’s utterance to the right intent." }, { "code": null, "e": 3078, "s": 2909, "text": "Once the “Explore Landmark” intent is detected, Dialogflow fulfillment will then send a request to the Vision API, receive a response back and send it back to the user." }, { "code": null, "e": 3100, "s": 3078, "text": "Overall architecture:" }, { "code": null, "e": 3416, "s": 3100, "text": "Google cloud Vision API is a pre-trained Machine Learning model that helps derive insights from images. You can get insights including image labeling, face and landmark detection, optical character recognition (OCR), and tagging of explicit content. Here is the link to learn more specifically about the Vision API." }, { "code": null, "e": 4063, "s": 3416, "text": "Go to the Dialogflow Console.Sign-in, if you are a first time user, then use your email to sign upAccept the terms and conditions and you will be in the consoleCreate an Agent. To create, click on the dropdown menu in the left pane in order to see “Create new agent”Call this “VisionAPI”Dialogflow creates a Google Cloudproject for you to access logs, cloud functions etc. You can select an existing project as well.When you’re ready, click Create.Dialogflow creates two default intents as a part of the agent. Default Welcome intent helps greet your users. Default Fallback intent helps catch all the questions that your bot does not understand." }, { "code": null, "e": 4093, "s": 4063, "text": "Go to the Dialogflow Console." }, { "code": null, "e": 4163, "s": 4093, "text": "Sign-in, if you are a first time user, then use your email to sign up" }, { "code": null, "e": 4226, "s": 4163, "text": "Accept the terms and conditions and you will be in the console" }, { "code": null, "e": 4333, "s": 4226, "text": "Create an Agent. To create, click on the dropdown menu in the left pane in order to see “Create new agent”" }, { "code": null, "e": 4355, "s": 4333, "text": "Call this “VisionAPI”" }, { "code": null, "e": 4485, "s": 4355, "text": "Dialogflow creates a Google Cloudproject for you to access logs, cloud functions etc. You can select an existing project as well." }, { "code": null, "e": 4518, "s": 4485, "text": "When you’re ready, click Create." }, { "code": null, "e": 4717, "s": 4518, "text": "Dialogflow creates two default intents as a part of the agent. Default Welcome intent helps greet your users. Default Fallback intent helps catch all the questions that your bot does not understand." }, { "code": null, "e": 4887, "s": 4717, "text": "At this point, we have a functional bot that greets the users. But we need to update it slightly to let the user know that they can upload an image to explore landmarks." }, { "code": null, "e": 4998, "s": 4887, "text": "Click on “Default Welcome Intent”Update the “Response” to “Hi! You can upload a picture to explore landmarks.”" }, { "code": null, "e": 5032, "s": 4998, "text": "Click on “Default Welcome Intent”" }, { "code": null, "e": 5110, "s": 5032, "text": "Update the “Response” to “Hi! You can upload a picture to explore landmarks.”" }, { "code": null, "e": 5181, "s": 5110, "text": "Click on “Entities”Create a new entity, name it “filename” and “save”." }, { "code": null, "e": 5201, "s": 5181, "text": "Click on “Entities”" }, { "code": null, "e": 5253, "s": 5201, "text": "Create a new entity, name it “filename” and “save”." }, { "code": null, "e": 5272, "s": 5253, "text": "Click on “Intents”" }, { "code": null, "e": 5305, "s": 5272, "text": "Name it “Explore uploaded image”" }, { "code": null, "e": 5413, "s": 5305, "text": "Click on “Training phrases” and add “file is demo.jpg” and “file is taj.jpeg” with @filename as the entity." }, { "code": null, "e": 5480, "s": 5413, "text": "Click on “Responses” and add “Assessing file” as the Text Response" }, { "code": null, "e": 5552, "s": 5480, "text": "Click on “Fulfillment” and toggle “Enable webhook call for this intent”" }, { "code": null, "e": 5620, "s": 5552, "text": "Navigate to Dialogflow Agent “VisionAPI” and click on “Fulfillment”" }, { "code": null, "e": 5670, "s": 5620, "text": "Enable inline code editor by toggling the switch." }, { "code": null, "e": 5785, "s": 5670, "text": "Update the index.js file with the following code and update YOUR-BUCKET-NAME with the name of your storage bucket." }, { "code": null, "e": 5853, "s": 5785, "text": "Click package.json and paste the following to replace its contents." }, { "code": null, "e": 5893, "s": 5853, "text": "Click Deploy at the bottom of the page." }, { "code": null, "e": 5999, "s": 5893, "text": "Clone this repository to your local machine: https://github.com/priyankavergadia/visionapi-dialogflow.git" }, { "code": null, "e": 6116, "s": 5999, "text": "Change to the directory that contains the code/. Alternatively, you can download the sample as a zip and extract it." }, { "code": null, "e": 6516, "s": 6116, "text": "When deployed, your app uses the Cloud SQL Proxy that is built in to the App Engine environment to communicate with your Cloud SQL instance. However, to test your app locally, you must install and use a local copy of the Cloud SQL Proxy in your development environment. Learn more about the Cloud SQL Proxy here. To perform basic admin tasks on your Cloud SQL instance, you can use the MySQL client." }, { "code": null, "e": 6603, "s": 6516, "text": "Note: You must authenticate gcloud to use the proxy to connect from your local machine" }, { "code": null, "e": 6733, "s": 6603, "text": "Download and install the Cloud SQL Proxy. The Cloud SQL Proxy is used to connect to your Cloud SQL instance when running locally." }, { "code": null, "e": 6753, "s": 6733, "text": "Download the proxy:" }, { "code": null, "e": 6837, "s": 6753, "text": "curl -o cloud_sql_proxy https://dl.google.com/cloudsql/cloud_sql_proxy.darwin.amd64" }, { "code": null, "e": 6864, "s": 6837, "text": "Make the proxy executable:" }, { "code": null, "e": 6889, "s": 6864, "text": "chmod +x cloud_sql_proxy" }, { "code": null, "e": 7169, "s": 6889, "text": "Create a Cloud SQL for MySQL Second Generation instance. Name the instance “polls-instance” or similar. It can take a few minutes for the instance to be ready. After the instance is ready, it should be visible in the instance list. Be sure to create a Second Generation instance." }, { "code": null, "e": 7451, "s": 7169, "text": "Now use the Cloud SDK to run the following command where [YOUR_INSTANCE_NAME] represents the name of your Cloud SQL instance. Make a note of the value shown for connectionName for the next step. The connectionName value is in the format [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]" }, { "code": null, "e": 7502, "s": 7451, "text": "gcloud sql instances describe [YOUR_INSTANCE_NAME]" }, { "code": null, "e": 7594, "s": 7502, "text": "Alternatively, you can get the connection name from the console by clicking on the instance" }, { "code": null, "e": 7669, "s": 7594, "text": "Start the Cloud SQL Proxy using the connectionName from the previous step." }, { "code": null, "e": 7741, "s": 7669, "text": "./cloud_sql_proxy -instances=”[YOUR_INSTANCE_CONNECTION_NAME]”=tcp:3306" }, { "code": null, "e": 7854, "s": 7741, "text": "Replace [YOUR_INSTANCE_CONNECTION_NAME] with the value of connectionName that you recorded in the previous step." }, { "code": null, "e": 8045, "s": 7854, "text": "This step establishes a connection from your local computer to your Cloud SQL instance for local testing purposes. Keep the Cloud SQL Proxy running the entire time you test your app locally." }, { "code": null, "e": 8097, "s": 8045, "text": "Next, you create a new Cloud SQL user and database." }, { "code": null, "e": 8234, "s": 8097, "text": "Create a new database using the Google CloudConsole for your Cloud SQL instance polls-instance. For example, you can use the name polls." }, { "code": null, "e": 8326, "s": 8234, "text": "Create a new user using the Google CloudConsole for your Cloud SQL instance polls-instance." }, { "code": null, "e": 8372, "s": 8326, "text": "Open mysite/settings-changeme.py for editing." }, { "code": null, "e": 8402, "s": 8372, "text": "Rename the file to setting.py" }, { "code": null, "e": 8666, "s": 8402, "text": "In two places, replace [YOUR-USERNAME] and [YOUR-PASSWORD] with the database username and password you created previously in the step “Create a Cloud SQL instance”. This helps set up the connection to the database for both App Engine deployment and local testing." }, { "code": null, "e": 8843, "s": 8666, "text": "In line ‘HOST’: ‘cloudsql/ [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]’ replace [PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME] with your instance name acquired in previous step." }, { "code": null, "e": 8929, "s": 8843, "text": "Run the following command. Copy the outputted connectionName value for the next step." }, { "code": null, "e": 8980, "s": 8929, "text": "gcloud sql instances describe [YOUR_INSTANCE_NAME]" }, { "code": null, "e": 9054, "s": 8980, "text": "Replace [YOUR-CONNECTION-NAME] with connectionName from the previous step" }, { "code": null, "e": 9193, "s": 9054, "text": "Replace [YOUR-DATABASE] with the name you choose during the “Initialize your Cloud SQL instance” step and then, close and save settings.py" }, { "code": null, "e": 10061, "s": 9193, "text": "# [START db_setup]if os.getenv(‘GAE_APPLICATION’, None):# Running on production App Engine, so connect to Google Cloud SQL using# the unix socket at /cloudsql/<your-cloudsql-connection string>DATABASES = {‘default’: {‘ENGINE’: ‘django.db.backends.mysql’,‘HOST’: ‘/cloudsql/[PROJECT_NAME]:[REGION_NAME]:[INSTANCE_NAME]’,‘USER’: ‘[YOUR-USERNAME]’,‘PASSWORD’: ‘[YOUR-PASSWORD]’,‘NAME’: ‘[YOUR-DATABASE]’,}}else:# Running locally so connect to either a local MySQL instance or connect to# Cloud SQL via the proxy. To start the proxy via command line:# $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306# See https://cloud.google.com/sql/docs/mysql-connect-proxyDATABASES = {‘default’: {‘ENGINE’: ‘django.db.backends.mysql’,‘HOST’: ‘127.0.0.1’,‘PORT’: ‘3306’,‘NAME’: ‘[YOUR-DATABASE]’,‘USER’: ‘[YOUR-USERNAME]’,‘PASSWORD’: ‘[YOUR-PASSWORD]’}}# [END db_setup]" }, { "code": null, "e": 10240, "s": 10061, "text": "In Dialogflow’s console, go to settings ⚙ and under the general tab, you’ll see the Google Project section. Click on the service account. This will open the Google Cloud Console." }, { "code": null, "e": 10422, "s": 10240, "text": "In the Google Cloudconsole, the presented webpage will show the Dialogflow service account. Click on the 3 dots in the “Actions” section to the far right and then click “Create Key”" }, { "code": null, "e": 10518, "s": 10422, "text": "A JSON file will be downloaded to your computer that you will need in the setup sections below." }, { "code": null, "e": 10624, "s": 10518, "text": "Inside chat folder, replace the key-sample.json with your own credentials json file and call it key.json." }, { "code": null, "e": 10722, "s": 10624, "text": "In views.py in chat folder, Change the GOOGLE_PROJECT_ID = “<YOUR_PROJECT_ID>” to your project ID" }, { "code": null, "e": 10803, "s": 10722, "text": "Navigate to the Google CloudProject and click on Storage from the hamburger menu" }, { "code": null, "e": 10832, "s": 10803, "text": "Click on “Create New Bucket”" }, { "code": null, "e": 10887, "s": 10832, "text": "Provide a name — this has to be a globally unique name" }, { "code": null, "e": 10989, "s": 10887, "text": "Choose where to store your data — Pick “Regional” and select the location that best suits your needs." }, { "code": null, "e": 11045, "s": 10989, "text": "Choose default storage class of your data as “Standard”" }, { "code": null, "e": 11172, "s": 11045, "text": "Choose how to control access to objects as “Set permissions uniformly at bucket-level” and then continue to create the bucket." }, { "code": null, "e": 11263, "s": 11172, "text": "Once the bucket is created, click on the “Browser” and locate the bucket you just created." }, { "code": null, "e": 11374, "s": 11263, "text": "Click on the three dots on the right hand side corresponding to the bucket and click “Edit bucket permissions”" }, { "code": null, "e": 11717, "s": 11374, "text": "In the presented side panel, click on “Add Members” and then add a new member “allUsers”, then click on “Select a role” to add “Storage Object Viewer” role. We do this to provide view access to the static front end files to allUsers. This is not an ideal security setting for the files but for the purpose of this particular lab it will work." }, { "code": null, "e": 11798, "s": 11717, "text": "Follow the same instructions and create a separate bucket to upload user images." }, { "code": null, "e": 11890, "s": 11798, "text": "Set permissions to “allUsers” and role “Storage Object Creator” and “Storage Object Viewer”" }, { "code": null, "e": 11913, "s": 11890, "text": "Open mysite/setting.py" }, { "code": null, "e": 12009, "s": 11913, "text": "Locate GCS_BUCKET variable and replace the “<YOUR-GCS-BUCKET-NAME>” with your GCS static bucket" }, { "code": null, "e": 12135, "s": 12009, "text": "Locate GS_MEDIA_BUCKET_NAME variable and replace the “<YOUR-GCS-BUCKET-NAME-MEDIA>” with your GCS bucket name for the images." }, { "code": null, "e": 12269, "s": 12135, "text": "Locate GS_STATIC_BUCKET_NAME variable and replace the “<YOUR-GCS-BUCKET-NAME-STATIC>” with your GCS bucket name for the static files." }, { "code": null, "e": 12284, "s": 12269, "text": "Save the file." }, { "code": null, "e": 12430, "s": 12284, "text": "GCS_BUCKET = ‘<YOUR-GCS-BUCKET-NAME>’GS_MEDIA_BUCKET_NAME = ‘<YOUR-GCS-BUCKET-NAME-MEDIA>’GS_STATIC_BUCKET_NAME = ‘<YOUR-GCS-BUCKET-NAME-STATIC>’" }, { "code": null, "e": 12475, "s": 12430, "text": "Open chat -> templates -> home-changeme.html" }, { "code": null, "e": 12498, "s": 12475, "text": "Rename it to home.html" }, { "code": null, "e": 12828, "s": 12498, "text": "Look for <YOUR-GCS-BUCKET-NAME-MEDIA> and replace it with your bucket name for where you would like the user uploaded file to be saved. We do this so we don’t store the user uploaded file in the front-end and keep the static assets all in GCS bucket. The Vision API calls the GCS bucket to pick up the file and do the prediction." }, { "code": null, "e": 13067, "s": 12828, "text": "To run the Django app on your local computer, you’ll need to set up a Python development environment, including Python, pip, and virtualenv. For instructions, refer to Setting Up a Python Development Environment for Google Cloud Platform." }, { "code": null, "e": 13132, "s": 13067, "text": "Create an isolated Python environment, and install dependencies:" }, { "code": null, "e": 13201, "s": 13132, "text": "virtualenv envsource env/bin/activatepip install -r requirements.txt" }, { "code": null, "e": 13250, "s": 13201, "text": "Run the Django migrations to set up your models:" }, { "code": null, "e": 13346, "s": 13250, "text": "python3 manage.py makemigrationspython3 manage.py makemigrations pollspython3 manage.py migrate" }, { "code": null, "e": 13372, "s": 13346, "text": "Start a local web server:" }, { "code": null, "e": 13400, "s": 13372, "text": "python3 manage.py runserver" }, { "code": null, "e": 13552, "s": 13400, "text": "In your web browser, enter this address http://localhost:8000/ You should see a simple webpage with the text: “Dialogflow” a textbox and submit button." }, { "code": null, "e": 13716, "s": 13552, "text": "The sample app pages are delivered by the Django web server running on your computer. When you’re ready to move forward, press Ctrl+C to stop the local web server." }, { "code": null, "e": 13869, "s": 13716, "text": "Gather all the static content into one folder. This command moves all of the app’s static files into the folder specified by STATIC_ROOT in settings.py:" }, { "code": null, "e": 13901, "s": 13869, "text": "python3 manage.py collectstatic" }, { "code": null, "e": 14030, "s": 13901, "text": "Upload the app by running the following command from within the directory of the application where the app.yaml file is located:" }, { "code": null, "e": 14048, "s": 14030, "text": "gcloud app deploy" }, { "code": null, "e": 14123, "s": 14048, "text": "Wait for the message that notifies you that the update has been completed." }, { "code": null, "e": 14164, "s": 14123, "text": "In your web browser, enter this address:" }, { "code": null, "e": 14202, "s": 14164, "text": "https://<your_project_id>.appspot.com" }, { "code": null, "e": 14300, "s": 14202, "text": "This time, your request is served by a web server running in the App Engine standard environment." }, { "code": null, "e": 14459, "s": 14300, "text": "This command deploys the application as described in app.yaml and sets the newly deployed version as the default version, causing it to serve all new traffic." }, { "code": null, "e": 14574, "s": 14459, "text": "When you are ready to serve your content in production, in mysite/settings.py, change the DEBUG variable to False." }, { "code": null, "e": 14624, "s": 14574, "text": "Let’s test our chatbot with the following prompts" }, { "code": null, "e": 14922, "s": 14624, "text": "User: “hi”Chatbot response: “Hi! You can upload a picture to explore landmarks.”User: uploads an image.Download an image with a landmark, name it “demo.jpg”Chatbot response: “file is being processed, here are the results: XXXX<whatever landmark is in your image>”Overall, it should look like this." }, { "code": null, "e": 14933, "s": 14922, "text": "User: “hi”" }, { "code": null, "e": 15004, "s": 14933, "text": "Chatbot response: “Hi! You can upload a picture to explore landmarks.”" }, { "code": null, "e": 15028, "s": 15004, "text": "User: uploads an image." }, { "code": null, "e": 15082, "s": 15028, "text": "Download an image with a landmark, name it “demo.jpg”" }, { "code": null, "e": 15190, "s": 15082, "text": "Chatbot response: “file is being processed, here are the results: XXXX<whatever landmark is in your image>”" }, { "code": null, "e": 15225, "s": 15190, "text": "Overall, it should look like this." }, { "code": null, "e": 15327, "s": 15225, "text": "Make sure to delete the Google Cloud project and the Dialogflow agent to avoid incurring any charges." }, { "code": null, "e": 15488, "s": 15327, "text": "Checkout my video series Deconstructing Chatbots, where I share how to get started and build conversational experiences using Dialogflow and Google Cloud tools." } ]
List all Files with Specific Extension in R - GeeksforGeeks
17 Jun, 2021 R programming language contains a wide variety of method to work with directory and its associated sub-directories. There are various inbuilt methods in R programming language which are used to return the file names with the required extensions. It can be used to efficiently locate the presence of a file. Directory in use: The list.files() method in R language is used to produce a character vector of the names of files or directories in the named directory. The regular expression is specified to match the files with the required file extension. The ‘$‘ symbol indicates the end-of-the-string, and the ‘\\‘ symbol before the ‘.’ is used to make sure that the files match the specified extension exactly. The pattern is case-sensitive, and any matches returned are strictly based on the specified characters of the pattern. The file names returned are sorted in alphabetical order. Syntax: list.files(path = “.”, pattern = NULL, full.names = FALSE, ignore.case = FALSE) Parameters : path – (Default : current working directory) A character vector of full path names pattern – regular expression to match the file names with full.names – If TRUE, returns the absolute path of the file locations ignore.case – Indicator of whether to ignore the case while searching for files. Example: R # list all the file names of the# specified patternfnames <- list.files(pattern = "\\.pdf$") print ("Names of files")print (fnames) Output [1] “Names of files” [1] “cubegfg.pdf” “maytravelform.pdf” The case of the file name can also be ignored by setting the attribute of ignore.case as the TRUE. Example: R # list all the file names of the # specified patternfnames <- list.files(pattern = "\\.pdf$", ignore.case = TRUE) print ("Names of files")print (fnames) Output [1] “Names of files” [1] “cubegfg.pdf” “maytravelform.pdf” “pdf2.pDf” The Sys.glob() method in R is used to extract the file names with the matched pattern. This method is used to expand wild cards, termed as “globbing” in file paths. The special character “*” is used to find matches for zero or more characters, in the retrieved string. Syntax: Sys.glob ( pattern) Parameters : pattern – character vector of patterns for relative or absolute file paths Example: R # list all the file names of # the specified patternfnames <- Sys.glob("*.png") print ("Names of files")print (fnames) Output [1] “Names of files” [1] “Screenshot 2021-06-03 at 4.35.54 PM.png” “cubegfg.png” [3] “gfg.png” Picked R directory-programs R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? Data Visualization in R Logistic Regression in R Programming Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? How to import an Excel File into R ? How to filter R DataFrame by values in a column?
[ { "code": null, "e": 25162, "s": 25134, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25470, "s": 25162, "text": "R programming language contains a wide variety of method to work with directory and its associated sub-directories. There are various inbuilt methods in R programming language which are used to return the file names with the required extensions. It can be used to efficiently locate the presence of a file. " }, { "code": null, "e": 25488, "s": 25470, "text": "Directory in use:" }, { "code": null, "e": 25992, "s": 25488, "text": "The list.files() method in R language is used to produce a character vector of the names of files or directories in the named directory. The regular expression is specified to match the files with the required file extension. The ‘$‘ symbol indicates the end-of-the-string, and the ‘\\\\‘ symbol before the ‘.’ is used to make sure that the files match the specified extension exactly. The pattern is case-sensitive, and any matches returned are strictly based on the specified characters of the pattern. " }, { "code": null, "e": 26050, "s": 25992, "text": "The file names returned are sorted in alphabetical order." }, { "code": null, "e": 26058, "s": 26050, "text": "Syntax:" }, { "code": null, "e": 26138, "s": 26058, "text": "list.files(path = “.”, pattern = NULL, full.names = FALSE, ignore.case = FALSE)" }, { "code": null, "e": 26152, "s": 26138, "text": "Parameters : " }, { "code": null, "e": 26235, "s": 26152, "text": "path – (Default : current working directory) A character vector of full path names" }, { "code": null, "e": 26293, "s": 26235, "text": "pattern – regular expression to match the file names with" }, { "code": null, "e": 26363, "s": 26293, "text": "full.names – If TRUE, returns the absolute path of the file locations" }, { "code": null, "e": 26444, "s": 26363, "text": "ignore.case – Indicator of whether to ignore the case while searching for files." }, { "code": null, "e": 26453, "s": 26444, "text": "Example:" }, { "code": null, "e": 26455, "s": 26453, "text": "R" }, { "code": "# list all the file names of the# specified patternfnames <- list.files(pattern = \"\\\\.pdf$\") print (\"Names of files\")print (fnames)", "e": 26588, "s": 26455, "text": null }, { "code": null, "e": 26595, "s": 26588, "text": "Output" }, { "code": null, "e": 26617, "s": 26595, "text": "[1] “Names of files” " }, { "code": null, "e": 26661, "s": 26617, "text": "[1] “cubegfg.pdf” “maytravelform.pdf”" }, { "code": null, "e": 26761, "s": 26661, "text": "The case of the file name can also be ignored by setting the attribute of ignore.case as the TRUE. " }, { "code": null, "e": 26770, "s": 26761, "text": "Example:" }, { "code": null, "e": 26772, "s": 26770, "text": "R" }, { "code": "# list all the file names of the # specified patternfnames <- list.files(pattern = \"\\\\.pdf$\", ignore.case = TRUE) print (\"Names of files\")print (fnames)", "e": 26947, "s": 26772, "text": null }, { "code": null, "e": 26954, "s": 26947, "text": "Output" }, { "code": null, "e": 26976, "s": 26954, "text": "[1] “Names of files” " }, { "code": null, "e": 27031, "s": 26976, "text": "[1] “cubegfg.pdf” “maytravelform.pdf” “pdf2.pDf”" }, { "code": null, "e": 27301, "s": 27031, "text": "The Sys.glob() method in R is used to extract the file names with the matched pattern. This method is used to expand wild cards, termed as “globbing” in file paths. The special character “*” is used to find matches for zero or more characters, in the retrieved string. " }, { "code": null, "e": 27309, "s": 27301, "text": "Syntax:" }, { "code": null, "e": 27329, "s": 27309, "text": "Sys.glob ( pattern)" }, { "code": null, "e": 27343, "s": 27329, "text": "Parameters : " }, { "code": null, "e": 27418, "s": 27343, "text": "pattern – character vector of patterns for relative or absolute file paths" }, { "code": null, "e": 27427, "s": 27418, "text": "Example:" }, { "code": null, "e": 27429, "s": 27427, "text": "R" }, { "code": "# list all the file names of # the specified patternfnames <- Sys.glob(\"*.png\") print (\"Names of files\")print (fnames)", "e": 27549, "s": 27429, "text": null }, { "code": null, "e": 27556, "s": 27549, "text": "Output" }, { "code": null, "e": 27578, "s": 27556, "text": "[1] “Names of files” " }, { "code": null, "e": 27666, "s": 27578, "text": "[1] “Screenshot 2021-06-03 at 4.35.54 PM.png” “cubegfg.png” " }, { "code": null, "e": 27681, "s": 27666, "text": "[3] “gfg.png” " }, { "code": null, "e": 27688, "s": 27681, "text": "Picked" }, { "code": null, "e": 27709, "s": 27688, "text": "R directory-programs" }, { "code": null, "e": 27720, "s": 27709, "text": "R Language" }, { "code": null, "e": 27818, "s": 27720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27827, "s": 27818, "text": "Comments" }, { "code": null, "e": 27840, "s": 27827, "text": "Old Comments" }, { "code": null, "e": 27892, "s": 27840, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27930, "s": 27892, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27965, "s": 27930, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28023, "s": 27965, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28047, "s": 28023, "text": "Data Visualization in R" }, { "code": null, "e": 28084, "s": 28047, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 28127, "s": 28084, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28177, "s": 28127, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28214, "s": 28177, "text": "How to import an Excel File into R ?" } ]
Reverse String in Python
Suppose we have an array of characters. We have to reverse the string without using any additional space. So if the string is like [‘H’, ‘E’, ‘L’, ‘L’, ‘O’], the output will be [‘O’, ‘L’, ‘L’, ‘E’, ‘H’] To solve this, we will follow these steps − Take two pointers to start = 0 and end = length of the string – 1 swap first and last characters increase start by 1 and decrease-end by 1 Let us see the following implementation to get a better understanding − Live Demo class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ start = 0 end = len(s)-1 while start<end: s[start],s[end] = s[end],s[start] start+=1 end-=1string_1 = ["H","E","L","L","O"] ob1 = Solution() ob1.reverseString(string_1) print(string_1) String = ["H","E","L","L","O"] ["O","L","L","E","H"]
[ { "code": null, "e": 1265, "s": 1062, "text": "Suppose we have an array of characters. We have to reverse the string without using any additional space. So if the string is like [‘H’, ‘E’, ‘L’, ‘L’, ‘O’], the output will be [‘O’, ‘L’, ‘L’, ‘E’, ‘H’]" }, { "code": null, "e": 1309, "s": 1265, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1375, "s": 1309, "text": "Take two pointers to start = 0 and end = length of the string – 1" }, { "code": null, "e": 1406, "s": 1375, "text": "swap first and last characters" }, { "code": null, "e": 1448, "s": 1406, "text": "increase start by 1 and decrease-end by 1" }, { "code": null, "e": 1520, "s": 1448, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1531, "s": 1520, "text": " Live Demo" }, { "code": null, "e": 1931, "s": 1531, "text": "class Solution(object):\n def reverseString(self, s):\n \"\"\"\n :type s: List[str]\n :rtype: None Do not return anything, modify s in-place instead.\n \"\"\"\n start = 0\n end = len(s)-1\n while start<end:\n s[start],s[end] = s[end],s[start]\n start+=1\n end-=1string_1 = [\"H\",\"E\",\"L\",\"L\",\"O\"]\nob1 = Solution()\nob1.reverseString(string_1)\nprint(string_1)" }, { "code": null, "e": 1963, "s": 1931, "text": "String = [\"H\",\"E\",\"L\",\"L\",\"O\"]\n" }, { "code": null, "e": 1985, "s": 1963, "text": "[\"O\",\"L\",\"L\",\"E\",\"H\"]" } ]
The Ultimate Beginner’s Guide To Implement A Neural Network From Scratch | by Ravsehaj Singh Puri | Towards Data Science
Neural networks have been with us for a long time but they have gathered importance in recent years due to advancement in computing machinery as well as growing needs of technology in various aspects of life. From the perspective of a beginner in machine learning, a neural network is considered as a black box which can ingest some data and spit out predictions or classification categories depending upon the problem at hand. The beauty of neural networks is that they are based on simple calculus and linear algebra or a combination of both. These work together to come up with close to accurate results when provided with high quantity and quality data. So, if you are motivated to learn the basics of how a neural network actually works, you have reached the right place. Follow me along this post and you’ll be able to build your own neural network from scratch. A neural network’s architecture is derived from the structure of a human brain while from a mathematical point of view, it can be understood as a function which maps a set of inputs to desired outputs. The main idea of this post is to understand this function in detail and implementing it in python. A neural network comprises of 7 Parts : Input Layer (X) : This layer contains the values corresponding to the features in our dataset.A set of weights and biases (W1,W2,..etc); (b1,b2,..etc) : These weights and biases are represented in the form matrices and they decide the importance of each feature/column in our dataset.Hidden Layer : This layer acts as a brain of the neural network and also as an interface between the input and the output layer. There can be one or more than one hidden layers in a neural network.Output Layer (ŷ) : The values transmitted from the input layer will reach this layer via the hidden layer(s).A set of activation functions (A) : This is the component which adds a non-linearity flavour to an otherwise linear model. These functions are applied to the output of each layer except the input layer and activate/transform them.The Loss function (L) : This function calculates the measure as to how well our guess/prediction is, and it is used while back propagating through the network.Optimiser : This optimiser is a function that updates the model parameters according to gradients which are calculated during back propagation (You’ll learn shortly). Input Layer (X) : This layer contains the values corresponding to the features in our dataset. A set of weights and biases (W1,W2,..etc); (b1,b2,..etc) : These weights and biases are represented in the form matrices and they decide the importance of each feature/column in our dataset. Hidden Layer : This layer acts as a brain of the neural network and also as an interface between the input and the output layer. There can be one or more than one hidden layers in a neural network. Output Layer (ŷ) : The values transmitted from the input layer will reach this layer via the hidden layer(s). A set of activation functions (A) : This is the component which adds a non-linearity flavour to an otherwise linear model. These functions are applied to the output of each layer except the input layer and activate/transform them. The Loss function (L) : This function calculates the measure as to how well our guess/prediction is, and it is used while back propagating through the network. Optimiser : This optimiser is a function that updates the model parameters according to gradients which are calculated during back propagation (You’ll learn shortly). Neural networks learn/train from the training data and then their performance is tested using test data. There are 2 parts of the training process: Feed forwardBack-propagation Feed forward Back-propagation Feed forward is basically traversing the neural network from input layer to the output layer by predicting a value. On the other hand, back-propagation makes the network actually learn by computing gradients and pushing them back through the network and finally updating the model parameters. Let us first see how these 2 processes work on paper and then we will convert our equations into code. Let us first design our neural network architecture. The architecture which we will be using for this post is shown below: As far as our architecture is concerned, we just need 2 equations to carry out the feed forward process and for future purposes, you may remember: number of layers of the neural network = number of hidden layers + 1(output layer) number of weight matrices = number of layers We will be using ReLu and Sigmoid activation functions in this post but other activation functions can alse be applied. Here, X, W1, b1, W2 and b2 are matrices and matrix level computations are done in both the equations above. For better understanding, we can have a look at these matrices representing X, W1, b1, W2 and b2. In this post, we are ignoring the bias terms b1 and b2 but they can be dealt with in a similar manner. Let us define a few values first : n1= number of neurons in the input layer, n2= number of neurons in the hidden layer, n3= number of neurons in the output layer. Now, you might be thinking of how to decide the number of neurons for Input layer, hidden layer and output layer. Here is the answer. number of neurons in the input layer (n1)= number of features/columns in our dataset i.e. the number of independent variables. number of neurons in the hidden layer (n2) is flexible. number of neurons in the output layer (n3) = Dimensions of X: [m, n1] ; Dimensions of W1: [n1, n2] ; Dimensions of W2: [n2, n3] Back propagation is an essential part in training a neural network. It is a method of learning on the basis of gradients which are calculated using the most beautiful part of calculus i.e. the Chain Rule. This chain rule is repetitively applied to calculate gradients across the network. To make it more clear, a gradient is the derivative of loss function w.r.t. to a model parameter (weight or bias). As mentioned earlier, we won’t be using bias terms and will only consider weights as model parameters. So, we have 2 model parameters i.e. W1 and W2. The loss function which we will be using is MSE (Mean Square Error). Now let us see how back propagation actually works mathematically. where m= number of training examples/rows in the dataset y= ground truth/label in the dataset Let us calculate the gradient of loss w.r.t. W2 using chain rule : The derivation of ‘Sigmoid_derivative’ term is not in context of this post but it has been beautifully explained here. Therefore, our first gradient term simply turns out to be : Now, moving further, we calculate our second gradient term i.e. the derivative of loss w.r.t. W1 in a similar way : You can also refer to this post to know more about these activation functions and their derivatives. towardsdatascience.com So, now that we have calculated the gradients w.r.t. W1 and W2, it is time to perform the optimisation steps. We will be using Gradient Descent Optimizer which is also called Vanilla Gradient Descent to update W1 and W2. You might be knowing that gradient descent algorithm has a hyper-parameter named as learning rate, which has a great importance in the training process. Tuning of this hyper-parameter is very essential and is done by using validation testing which is not in scope of this post. Now that we have learnt the mathematical concepts behind a neural network, let us convert these concepts into code and train a neural network on a real-world machine learning problem. We will be using the famous IRIS dataset to train our network and then predict flower categories. You can download the dataset from here. import numpy as npimport pandas as pdfrom sklearn import preprocessingfrom sklearn.preprocessing import StandardScalerfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_split data=pd.read_csv('IRIS.csv')X=data.iloc[:,:-1].valuesY=data.iloc[:,-1].valuesStandardScaler=StandardScaler()X=StandardScaler.fit_transform(X)label_encoder=LabelEncoder()Y=label_encoder.fit_transform(Y)Y=Y.reshape(-1,1)enc=preprocessing.OneHotEncoder()enc.fit(Y)onehotlabels=enc.transform(Y).toarray()Y=onehotlabels After doing aforesaid basic pre-processing on the input data, we move on to create our neural network class which contains the feed forward and back-propagation functions. But first, let us split our data into train and test. X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0) I am also writing code to define functions which can calculate function values and function derivative values. I have written code for 3 activation functions and used only two (Relu and Sigmoid) out of them. However, you can try out various combinations of these activation functions and also incorporate other activation functions in your code. def ReLU(x): return (abs(x.astype(float))+x.astype(float))/2def ReLU_derivative(x): y=x np.piecewise(y,[ReLU(y)==0,ReLU(y)==y],[0,1]) return ydef tanh(x): return np.tanh(x.astype(float))def tanh_derivative(x): return 1-np.square(tanh(x))def sigmoid(x): return 1/(1+np.exp(-x.astype(float)))def sigmoid_derivative(x): return x*(1-x) Defining the neural network class : class Neural_Network: def __init__(self,x,y,h): self.input=x self.weights1=np.random.randn(self.input.shape[1],h) self.weights2=np.random.randn(h,3) self.y=y self.output=np.zeros(y.shape) The class ‘Neural_Network’ accepts 3 parameters: x, y and h which are corresponding to X_train, Y_train and number of neurons in the hidden layer. As mentioned earlier, number of neurons in the hidden layer is flexible and therefore we will pass its value along with X_train and Y_train while creating an instance of our class. ‘weights1’ and ‘weights2’ matrices are initialized from a random distribution and by passing the dimensions required for the respective weight matrices. As previously W1 and W2 matrices have been shown along with their dimensions, we pass these dimensions to this random function to generate our initial weights. def FeedForward(self): self.layer1=ReLU(np.dot(self.input,self.weights1)) self.output=sigmoid(np.dot(self.layer1,self.weights2)) Our first function in the class is ‘FeedForward’ which is the first step in the training process of a neural network. The code follows ‘Equation-1’ and ‘Equation-2’ described earlier. Next, we move on to the most essential part, the back-propagation. def BackPropogation(self): m=len(self.input) d_weights2=-(1/m)*np.dot(self.layer1.T,(self.y-self.output) *sigmoid_derivative(self.output))d_weights1=-(1/m)*np.dot(self.input.T,(np.dot((self.y- self.output)*sigmoid_derivative(self.output),self.weights2.T)* ReLU_derivative(self.layer1)))self.weights2=self.weights2 - lr*d_weights2 self.weights1=self.weights1 - lr*d_weights1 The back-propagation step calculates gradients w.r.t. the model parameters while traversing back in the network from output layer to the input layer. This is governed by ‘Equation-3’ and ‘Equation-4’ which we obtained using chain rule. You will observe that both the terms ‘d_weights2’ and ‘d_weights1’ consist of 2 types of operations i.e. dot product and normal multiplication. In NumPy, np.dot(X,Y) represents matrix multiplication between X and Y whereas np.multiply(X,Y) or simply X*Y represents element wise multiplication between X and Y. To get more insights on how this piece of code is working, I will give you a small task which i myself did when i first implemented this from scratch. If you look at the hidden layer, for each neuron (blue), there are 3 connections entering the neuron. Each such connection is emerging from a distinct neuron in the input layer. The basics of neural network suggest that there is a linear relation between the blue neuron of hidden layer and the set of neurons from which it is receiving information through the connections. This relation can be represented in the form of an equation. mentioned below : Now, extending this equation to each and every neuron(blue) of the hidden layer, we obtain 4 such equations as we have 4 neurons in the hidden layer. The work that has been done till now, only represents 1 training example/row. In order to send our training data all at once into the feed forward function, we will have to use matrices to perform this operation. But the task really is to verify with full confidence that solving(on paper) the above piece of code which includes dot products and element-wise multiplications matches these 4 linear equations we discussed. But this time we will be applying these equations on all the rows of our training data simultaneously. I hope you enjoyed getting your hands dirty in solving matrices and equations but trust me it is worth spending time on. Moving further, we define a function which will predict the output class at run time after our model is trained. def predict(self,X): self.layert_1=ReLU(np.dot(X,self.weights1)) return sigmoid(np.dot(self.layert_1,self.weights2)) This is the last function in the ‘Neural_Network’ class and the ‘predict’ function does nothing but normal feed forward using the final optimized weights. Now that we have defined our class, it is time to actually use it. #----Defining parameters and instantiating Neural_Network class----#epochs=10000 #Number of training iterationslr=0.5 # learning rate used in Gradient Descentn=len(X_test)m=len(X)nn1=Neural_Network(X_train,Y_train)#creating an object of Neural_Network class#----------------------Training Starts-----------------------------#for i in range(epochs): nn1.FeedForward() y_predict_train=enc.inverse_transform(nn1.output.round()) y_predict_test=enc.inverse_transform(nn1.predict(X_test).round()) y_train=enc.inverse_transform(Y_train) y_test=enc.inverse_transform(Y_test) train_accuracy=(m-np.count_nonzero(y_train-y_predict_train))/m test_accuracy=(n-np.count_nonzero(y_test-y_predict_test))/n nn1.BackPropogation() cost=(1/m)*np.sum(np.square(nn1.y-nn1.output)) print("Epoch {}/{} ==============================================================:- ".format(i+1,epochs))#----------------Displaying Final Metrics--------------------------#print("MSE_Cost: {} , Train_Accuracy: {} , Test_Accuracy: {} ".format(cost,train_accuracy,test_accuracy)) After training for 10000 epochs, the following is the result: Train accuracy : 0.97777 Test accuracy : 0.9 The results look amazing as compared to other machine learning models when applied to the same problem at hand. This network can be extended to a 3- layer network which will have 2 hidden layers using same concepts. You can also try different optimizers like AdaGrad, Adam etc. You can access my additional work on the ‘Adult Income Prediction’ dataset which uses a similar neural network in my GitHub repository, the link to which is provided below: github.com In this post, we started learning the basic architecture of a neural network and went further into the components of a neural network architecture. We also witnessed the mathematics behind the working of the same and got a detailed explanation of application of chain rule and basic calculus in developing equations for back-propagation which is a major part of the training process. Finally, we converted our mathematical concepts and equations into code and implemented a full fledged neural network on the IRIS dataset. Thanks a lot for reading through the article. I hope you understood each and every aspect of it. Feel free to ask any question in the responses section.
[ { "code": null, "e": 381, "s": 172, "text": "Neural networks have been with us for a long time but they have gathered importance in recent years due to advancement in computing machinery as well as growing needs of technology in various aspects of life." }, { "code": null, "e": 830, "s": 381, "text": "From the perspective of a beginner in machine learning, a neural network is considered as a black box which can ingest some data and spit out predictions or classification categories depending upon the problem at hand. The beauty of neural networks is that they are based on simple calculus and linear algebra or a combination of both. These work together to come up with close to accurate results when provided with high quantity and quality data." }, { "code": null, "e": 1041, "s": 830, "text": "So, if you are motivated to learn the basics of how a neural network actually works, you have reached the right place. Follow me along this post and you’ll be able to build your own neural network from scratch." }, { "code": null, "e": 1342, "s": 1041, "text": "A neural network’s architecture is derived from the structure of a human brain while from a mathematical point of view, it can be understood as a function which maps a set of inputs to desired outputs. The main idea of this post is to understand this function in detail and implementing it in python." }, { "code": null, "e": 1382, "s": 1342, "text": "A neural network comprises of 7 Parts :" }, { "code": null, "e": 2529, "s": 1382, "text": "Input Layer (X) : This layer contains the values corresponding to the features in our dataset.A set of weights and biases (W1,W2,..etc); (b1,b2,..etc) : These weights and biases are represented in the form matrices and they decide the importance of each feature/column in our dataset.Hidden Layer : This layer acts as a brain of the neural network and also as an interface between the input and the output layer. There can be one or more than one hidden layers in a neural network.Output Layer (ŷ) : The values transmitted from the input layer will reach this layer via the hidden layer(s).A set of activation functions (A) : This is the component which adds a non-linearity flavour to an otherwise linear model. These functions are applied to the output of each layer except the input layer and activate/transform them.The Loss function (L) : This function calculates the measure as to how well our guess/prediction is, and it is used while back propagating through the network.Optimiser : This optimiser is a function that updates the model parameters according to gradients which are calculated during back propagation (You’ll learn shortly)." }, { "code": null, "e": 2624, "s": 2529, "text": "Input Layer (X) : This layer contains the values corresponding to the features in our dataset." }, { "code": null, "e": 2815, "s": 2624, "text": "A set of weights and biases (W1,W2,..etc); (b1,b2,..etc) : These weights and biases are represented in the form matrices and they decide the importance of each feature/column in our dataset." }, { "code": null, "e": 3013, "s": 2815, "text": "Hidden Layer : This layer acts as a brain of the neural network and also as an interface between the input and the output layer. There can be one or more than one hidden layers in a neural network." }, { "code": null, "e": 3124, "s": 3013, "text": "Output Layer (ŷ) : The values transmitted from the input layer will reach this layer via the hidden layer(s)." }, { "code": null, "e": 3355, "s": 3124, "text": "A set of activation functions (A) : This is the component which adds a non-linearity flavour to an otherwise linear model. These functions are applied to the output of each layer except the input layer and activate/transform them." }, { "code": null, "e": 3515, "s": 3355, "text": "The Loss function (L) : This function calculates the measure as to how well our guess/prediction is, and it is used while back propagating through the network." }, { "code": null, "e": 3682, "s": 3515, "text": "Optimiser : This optimiser is a function that updates the model parameters according to gradients which are calculated during back propagation (You’ll learn shortly)." }, { "code": null, "e": 3830, "s": 3682, "text": "Neural networks learn/train from the training data and then their performance is tested using test data. There are 2 parts of the training process:" }, { "code": null, "e": 3859, "s": 3830, "text": "Feed forwardBack-propagation" }, { "code": null, "e": 3872, "s": 3859, "text": "Feed forward" }, { "code": null, "e": 3889, "s": 3872, "text": "Back-propagation" }, { "code": null, "e": 4285, "s": 3889, "text": "Feed forward is basically traversing the neural network from input layer to the output layer by predicting a value. On the other hand, back-propagation makes the network actually learn by computing gradients and pushing them back through the network and finally updating the model parameters. Let us first see how these 2 processes work on paper and then we will convert our equations into code." }, { "code": null, "e": 4408, "s": 4285, "text": "Let us first design our neural network architecture. The architecture which we will be using for this post is shown below:" }, { "code": null, "e": 4555, "s": 4408, "text": "As far as our architecture is concerned, we just need 2 equations to carry out the feed forward process and for future purposes, you may remember:" }, { "code": null, "e": 4638, "s": 4555, "text": "number of layers of the neural network = number of hidden layers + 1(output layer)" }, { "code": null, "e": 4683, "s": 4638, "text": "number of weight matrices = number of layers" }, { "code": null, "e": 4803, "s": 4683, "text": "We will be using ReLu and Sigmoid activation functions in this post but other activation functions can alse be applied." }, { "code": null, "e": 5112, "s": 4803, "text": "Here, X, W1, b1, W2 and b2 are matrices and matrix level computations are done in both the equations above. For better understanding, we can have a look at these matrices representing X, W1, b1, W2 and b2. In this post, we are ignoring the bias terms b1 and b2 but they can be dealt with in a similar manner." }, { "code": null, "e": 5147, "s": 5112, "text": "Let us define a few values first :" }, { "code": null, "e": 5275, "s": 5147, "text": "n1= number of neurons in the input layer, n2= number of neurons in the hidden layer, n3= number of neurons in the output layer." }, { "code": null, "e": 5409, "s": 5275, "text": "Now, you might be thinking of how to decide the number of neurons for Input layer, hidden layer and output layer. Here is the answer." }, { "code": null, "e": 5536, "s": 5409, "text": "number of neurons in the input layer (n1)= number of features/columns in our dataset i.e. the number of independent variables." }, { "code": null, "e": 5592, "s": 5536, "text": "number of neurons in the hidden layer (n2) is flexible." }, { "code": null, "e": 5637, "s": 5592, "text": "number of neurons in the output layer (n3) =" }, { "code": null, "e": 5693, "s": 5637, "text": "Dimensions of X: [m, n1] ; Dimensions of W1: [n1, n2] ;" }, { "code": null, "e": 5720, "s": 5693, "text": "Dimensions of W2: [n2, n3]" }, { "code": null, "e": 6123, "s": 5720, "text": "Back propagation is an essential part in training a neural network. It is a method of learning on the basis of gradients which are calculated using the most beautiful part of calculus i.e. the Chain Rule. This chain rule is repetitively applied to calculate gradients across the network. To make it more clear, a gradient is the derivative of loss function w.r.t. to a model parameter (weight or bias)." }, { "code": null, "e": 6409, "s": 6123, "text": "As mentioned earlier, we won’t be using bias terms and will only consider weights as model parameters. So, we have 2 model parameters i.e. W1 and W2. The loss function which we will be using is MSE (Mean Square Error). Now let us see how back propagation actually works mathematically." }, { "code": null, "e": 6466, "s": 6409, "text": "where m= number of training examples/rows in the dataset" }, { "code": null, "e": 6503, "s": 6466, "text": "y= ground truth/label in the dataset" }, { "code": null, "e": 6570, "s": 6503, "text": "Let us calculate the gradient of loss w.r.t. W2 using chain rule :" }, { "code": null, "e": 6689, "s": 6570, "text": "The derivation of ‘Sigmoid_derivative’ term is not in context of this post but it has been beautifully explained here." }, { "code": null, "e": 6749, "s": 6689, "text": "Therefore, our first gradient term simply turns out to be :" }, { "code": null, "e": 6865, "s": 6749, "text": "Now, moving further, we calculate our second gradient term i.e. the derivative of loss w.r.t. W1 in a similar way :" }, { "code": null, "e": 6966, "s": 6865, "text": "You can also refer to this post to know more about these activation functions and their derivatives." }, { "code": null, "e": 6989, "s": 6966, "text": "towardsdatascience.com" }, { "code": null, "e": 7488, "s": 6989, "text": "So, now that we have calculated the gradients w.r.t. W1 and W2, it is time to perform the optimisation steps. We will be using Gradient Descent Optimizer which is also called Vanilla Gradient Descent to update W1 and W2. You might be knowing that gradient descent algorithm has a hyper-parameter named as learning rate, which has a great importance in the training process. Tuning of this hyper-parameter is very essential and is done by using validation testing which is not in scope of this post." }, { "code": null, "e": 7810, "s": 7488, "text": "Now that we have learnt the mathematical concepts behind a neural network, let us convert these concepts into code and train a neural network on a real-world machine learning problem. We will be using the famous IRIS dataset to train our network and then predict flower categories. You can download the dataset from here." }, { "code": null, "e": 8027, "s": 7810, "text": "import numpy as npimport pandas as pdfrom sklearn import preprocessingfrom sklearn.preprocessing import StandardScalerfrom sklearn.preprocessing import LabelEncoderfrom sklearn.model_selection import train_test_split" }, { "code": null, "e": 8344, "s": 8027, "text": "data=pd.read_csv('IRIS.csv')X=data.iloc[:,:-1].valuesY=data.iloc[:,-1].valuesStandardScaler=StandardScaler()X=StandardScaler.fit_transform(X)label_encoder=LabelEncoder()Y=label_encoder.fit_transform(Y)Y=Y.reshape(-1,1)enc=preprocessing.OneHotEncoder()enc.fit(Y)onehotlabels=enc.transform(Y).toarray()Y=onehotlabels " }, { "code": null, "e": 8570, "s": 8344, "text": "After doing aforesaid basic pre-processing on the input data, we move on to create our neural network class which contains the feed forward and back-propagation functions. But first, let us split our data into train and test." }, { "code": null, "e": 8651, "s": 8570, "text": "X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=0)" }, { "code": null, "e": 8997, "s": 8651, "text": "I am also writing code to define functions which can calculate function values and function derivative values. I have written code for 3 activation functions and used only two (Relu and Sigmoid) out of them. However, you can try out various combinations of these activation functions and also incorporate other activation functions in your code." }, { "code": null, "e": 9345, "s": 8997, "text": "def ReLU(x): return (abs(x.astype(float))+x.astype(float))/2def ReLU_derivative(x): y=x np.piecewise(y,[ReLU(y)==0,ReLU(y)==y],[0,1]) return ydef tanh(x): return np.tanh(x.astype(float))def tanh_derivative(x): return 1-np.square(tanh(x))def sigmoid(x): return 1/(1+np.exp(-x.astype(float)))def sigmoid_derivative(x): return x*(1-x)" }, { "code": null, "e": 9381, "s": 9345, "text": "Defining the neural network class :" }, { "code": null, "e": 9596, "s": 9381, "text": "class Neural_Network: def __init__(self,x,y,h): self.input=x self.weights1=np.random.randn(self.input.shape[1],h) self.weights2=np.random.randn(h,3) self.y=y self.output=np.zeros(y.shape)" }, { "code": null, "e": 9924, "s": 9596, "text": "The class ‘Neural_Network’ accepts 3 parameters: x, y and h which are corresponding to X_train, Y_train and number of neurons in the hidden layer. As mentioned earlier, number of neurons in the hidden layer is flexible and therefore we will pass its value along with X_train and Y_train while creating an instance of our class." }, { "code": null, "e": 10237, "s": 9924, "text": "‘weights1’ and ‘weights2’ matrices are initialized from a random distribution and by passing the dimensions required for the respective weight matrices. As previously W1 and W2 matrices have been shown along with their dimensions, we pass these dimensions to this random function to generate our initial weights." }, { "code": null, "e": 10379, "s": 10237, "text": " def FeedForward(self): self.layer1=ReLU(np.dot(self.input,self.weights1)) self.output=sigmoid(np.dot(self.layer1,self.weights2))" }, { "code": null, "e": 10563, "s": 10379, "text": "Our first function in the class is ‘FeedForward’ which is the first step in the training process of a neural network. The code follows ‘Equation-1’ and ‘Equation-2’ described earlier." }, { "code": null, "e": 10630, "s": 10563, "text": "Next, we move on to the most essential part, the back-propagation." }, { "code": null, "e": 11031, "s": 10630, "text": "def BackPropogation(self): m=len(self.input) d_weights2=-(1/m)*np.dot(self.layer1.T,(self.y-self.output) *sigmoid_derivative(self.output))d_weights1=-(1/m)*np.dot(self.input.T,(np.dot((self.y- self.output)*sigmoid_derivative(self.output),self.weights2.T)* ReLU_derivative(self.layer1)))self.weights2=self.weights2 - lr*d_weights2 self.weights1=self.weights1 - lr*d_weights1" }, { "code": null, "e": 11728, "s": 11031, "text": "The back-propagation step calculates gradients w.r.t. the model parameters while traversing back in the network from output layer to the input layer. This is governed by ‘Equation-3’ and ‘Equation-4’ which we obtained using chain rule. You will observe that both the terms ‘d_weights2’ and ‘d_weights1’ consist of 2 types of operations i.e. dot product and normal multiplication. In NumPy, np.dot(X,Y) represents matrix multiplication between X and Y whereas np.multiply(X,Y) or simply X*Y represents element wise multiplication between X and Y. To get more insights on how this piece of code is working, I will give you a small task which i myself did when i first implemented this from scratch." }, { "code": null, "e": 12181, "s": 11728, "text": "If you look at the hidden layer, for each neuron (blue), there are 3 connections entering the neuron. Each such connection is emerging from a distinct neuron in the input layer. The basics of neural network suggest that there is a linear relation between the blue neuron of hidden layer and the set of neurons from which it is receiving information through the connections. This relation can be represented in the form of an equation. mentioned below :" }, { "code": null, "e": 12856, "s": 12181, "text": "Now, extending this equation to each and every neuron(blue) of the hidden layer, we obtain 4 such equations as we have 4 neurons in the hidden layer. The work that has been done till now, only represents 1 training example/row. In order to send our training data all at once into the feed forward function, we will have to use matrices to perform this operation. But the task really is to verify with full confidence that solving(on paper) the above piece of code which includes dot products and element-wise multiplications matches these 4 linear equations we discussed. But this time we will be applying these equations on all the rows of our training data simultaneously." }, { "code": null, "e": 12977, "s": 12856, "text": "I hope you enjoyed getting your hands dirty in solving matrices and equations but trust me it is worth spending time on." }, { "code": null, "e": 13090, "s": 12977, "text": "Moving further, we define a function which will predict the output class at run time after our model is trained." }, { "code": null, "e": 13211, "s": 13090, "text": "def predict(self,X): self.layert_1=ReLU(np.dot(X,self.weights1)) return sigmoid(np.dot(self.layert_1,self.weights2))" }, { "code": null, "e": 13366, "s": 13211, "text": "This is the last function in the ‘Neural_Network’ class and the ‘predict’ function does nothing but normal feed forward using the final optimized weights." }, { "code": null, "e": 13433, "s": 13366, "text": "Now that we have defined our class, it is time to actually use it." }, { "code": null, "e": 14492, "s": 13433, "text": "#----Defining parameters and instantiating Neural_Network class----#epochs=10000 #Number of training iterationslr=0.5 # learning rate used in Gradient Descentn=len(X_test)m=len(X)nn1=Neural_Network(X_train,Y_train)#creating an object of Neural_Network class#----------------------Training Starts-----------------------------#for i in range(epochs): nn1.FeedForward() y_predict_train=enc.inverse_transform(nn1.output.round()) y_predict_test=enc.inverse_transform(nn1.predict(X_test).round()) y_train=enc.inverse_transform(Y_train) y_test=enc.inverse_transform(Y_test) train_accuracy=(m-np.count_nonzero(y_train-y_predict_train))/m test_accuracy=(n-np.count_nonzero(y_test-y_predict_test))/n nn1.BackPropogation() cost=(1/m)*np.sum(np.square(nn1.y-nn1.output)) print(\"Epoch {}/{} ==============================================================:- \".format(i+1,epochs))#----------------Displaying Final Metrics--------------------------#print(\"MSE_Cost: {} , Train_Accuracy: {} , Test_Accuracy: {} \".format(cost,train_accuracy,test_accuracy))" }, { "code": null, "e": 14554, "s": 14492, "text": "After training for 10000 epochs, the following is the result:" }, { "code": null, "e": 14579, "s": 14554, "text": "Train accuracy : 0.97777" }, { "code": null, "e": 14599, "s": 14579, "text": "Test accuracy : 0.9" }, { "code": null, "e": 14877, "s": 14599, "text": "The results look amazing as compared to other machine learning models when applied to the same problem at hand. This network can be extended to a 3- layer network which will have 2 hidden layers using same concepts. You can also try different optimizers like AdaGrad, Adam etc." }, { "code": null, "e": 15050, "s": 14877, "text": "You can access my additional work on the ‘Adult Income Prediction’ dataset which uses a similar neural network in my GitHub repository, the link to which is provided below:" }, { "code": null, "e": 15061, "s": 15050, "text": "github.com" }, { "code": null, "e": 15584, "s": 15061, "text": "In this post, we started learning the basic architecture of a neural network and went further into the components of a neural network architecture. We also witnessed the mathematics behind the working of the same and got a detailed explanation of application of chain rule and basic calculus in developing equations for back-propagation which is a major part of the training process. Finally, we converted our mathematical concepts and equations into code and implemented a full fledged neural network on the IRIS dataset." } ]
How can we prevent the resizing of UI controls in JavaFX?
In JavaFX the javafx.scene.control package provides various classes for nodes specially designed for UI applications by instantiating these classes you can create UI elements such as button, Label, etc.. You can resize the created elements using the setPrefWidth() or, setPrefHeight() or, setprefSize() methods accordingly. To prevent the resize of the UI controls you need to set the minimum-maximum and preferred width/height to same value as − button.setMinWidth(80.0); button.setPrefWidth(80.0); button.setMaxWidth(80.0); The following JavaFX example contains two buttons and a slider. You can resize the button (Hello) by moving the slider. Once you click the PreventResizing button, then you cannot resize the “Hello” button further. import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.geometry.Insets; import javafx.geometry.Orientation; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class PreventingResize extends Application { public void start(Stage stage) { //Creating a button Button button = new Button("Hello"); //Creating a slider to resize the button Slider slider = new Slider(40, 200, 40); //Setting its orientation to Horizontal slider.setPrefHeight(180); slider.setOrientation(Orientation.VERTICAL); slider.setShowTickLabels(true); slider.setShowTickMarks(true); slider.setMajorTickUnit(40); slider.setBlockIncrement(20); slider.valueProperty().addListener(new ChangeListener<Number>() { public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){ button.setPrefSize((double)newValue, (double)newValue); } }); //Preventing the resize Button prevent = new Button("Prevent Resizing"); //Setting action to the button prevent.setOnAction(e -> { button.setMinWidth(45); button.setPrefWidth(45); button.setMaxWidth(45); button.setMinHeight(25); button.setMaxHeight(25); button.setPrefHeight(25); }); //Creating the pane BorderPane pane = new BorderPane(); pane.setCenter(button); pane.setRight(prevent); pane.setLeft(new VBox(new Label("Button Reize"), slider)); pane.setPadding(new Insets(10, 10, 10, 10)); //Preparing the scene Scene scene = new Scene(pane, 595, 250); stage.setTitle("Preventing Resize"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1266, "s": 1062, "text": "In JavaFX the javafx.scene.control package provides various classes for nodes specially designed for UI applications by instantiating these classes you can create UI elements such as button, Label, etc.." }, { "code": null, "e": 1386, "s": 1266, "text": "You can resize the created elements using the setPrefWidth() or, setPrefHeight() or, setprefSize() methods accordingly." }, { "code": null, "e": 1509, "s": 1386, "text": "To prevent the resize of the UI controls you need to set the minimum-maximum and preferred width/height to same value as −" }, { "code": null, "e": 1588, "s": 1509, "text": "button.setMinWidth(80.0);\nbutton.setPrefWidth(80.0);\nbutton.setMaxWidth(80.0);" }, { "code": null, "e": 1802, "s": 1588, "text": "The following JavaFX example contains two buttons and a slider. You can resize the button (Hello) by moving the slider. Once you click the PreventResizing button, then you cannot resize the “Hello” button further." }, { "code": null, "e": 3877, "s": 1802, "text": "import javafx.application.Application;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.geometry.Insets;\nimport javafx.geometry.Orientation;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Slider;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\npublic class PreventingResize extends Application {\n public void start(Stage stage) {\n //Creating a button\n Button button = new Button(\"Hello\");\n //Creating a slider to resize the button\n Slider slider = new Slider(40, 200, 40);\n //Setting its orientation to Horizontal\n slider.setPrefHeight(180);\n slider.setOrientation(Orientation.VERTICAL);\n slider.setShowTickLabels(true);\n slider.setShowTickMarks(true);\n slider.setMajorTickUnit(40);\n slider.setBlockIncrement(20);\n slider.valueProperty().addListener(new ChangeListener<Number>() {\n public void changed(ObservableValue <?extends Number>observable, Number oldValue, Number newValue){\n button.setPrefSize((double)newValue, (double)newValue);\n }\n });\n //Preventing the resize\n Button prevent = new Button(\"Prevent Resizing\");\n //Setting action to the button\n prevent.setOnAction(e -> {\n button.setMinWidth(45);\n button.setPrefWidth(45);\n button.setMaxWidth(45);\n button.setMinHeight(25);\n button.setMaxHeight(25);\n button.setPrefHeight(25);\n });\n //Creating the pane\n BorderPane pane = new BorderPane();\n pane.setCenter(button);\n pane.setRight(prevent);\n pane.setLeft(new VBox(new Label(\"Button Reize\"), slider));\n pane.setPadding(new Insets(10, 10, 10, 10));\n //Preparing the scene\n Scene scene = new Scene(pane, 595, 250);\n stage.setTitle(\"Preventing Resize\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
How to detect duplicate values in primitive Java array?
To detect the duplicate values in an array you need to compare each element of the array to all the remaining elements, in case of a match you got your duplicate element. One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison. import java.util.Arrays; import java.util.Scanner; public class DetectDuplcate { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created::"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i=0; i<size; i++) { myArray[i] = sc.nextInt(); } System.out.println("The array created is ::"+Arrays.toString(myArray)); System.out.println("indices of the duplicate elements :: "); for(int i=0; i<myArray.length; i++) { for (int j=i+1; j<myArray.length; j++) { if(myArray[i] == myArray[j]) { System.out.println(j); } } } } } Enter the size of the array that is to be created :: 6 Enter the elements of the array :: 87 52 87 63 41 63 The array created is :: [87, 52, 87, 63, 41, 63] indices of the duplicate elements :: 2 5 Solution 2: In addition to this we have a more reliable solution: The interface set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false: import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class DetectDuplcateUsingSet { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created::"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i=0; i<size; i++) { myArray[i] = sc.nextInt(); } System.out.println("The array created is ::"+Arrays.toString(myArray)); System.out.println("indices of duplicate elements in the array are elements::"); Set set = new HashSet(); for(int i=0; i<myArray.length; i++) { if(!set.add(myArray[i])) { System.out.println(i); } } } } Enter the size of the array that is to be created :: 5 Enter the elements of the array :: 78 56 23 78 45 The array created is :: [78, 56, 23, 78, 45] indices of duplicate elements in the array are elements:: 3
[ { "code": null, "e": 1233, "s": 1062, "text": "To detect the duplicate values in an array you need to compare each element of the array to all the remaining elements, in case of a match you got your duplicate element." }, { "code": null, "e": 1403, "s": 1233, "text": "One solution to do so you need to use two loops (nested) where the inner loop starts with i+1 (where i is the variable of outer loop) to avoid repetitions in comparison." }, { "code": null, "e": 2235, "s": 1403, "text": "import java.util.Arrays;\nimport java.util.Scanner;\n\npublic class DetectDuplcate {\n \n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created::\");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array ::\");\n \n for(int i=0; i<size; i++) {\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"The array created is ::\"+Arrays.toString(myArray));\n System.out.println(\"indices of the duplicate elements :: \");\n \n for(int i=0; i<myArray.length; i++) {\n for (int j=i+1; j<myArray.length; j++) {\n if(myArray[i] == myArray[j]) {\n System.out.println(j);\n }\n }\n }\n }\n}" }, { "code": null, "e": 2433, "s": 2235, "text": "Enter the size of the array that is to be created ::\n6\nEnter the elements of the array ::\n87\n52\n87\n63\n41\n63\nThe array created is :: [87, 52, 87, 63, 41, 63]\nindices of the duplicate elements ::\n2\n5" }, { "code": null, "e": 2499, "s": 2433, "text": "Solution 2: In addition to this we have a more reliable solution:" }, { "code": null, "e": 2701, "s": 2499, "text": "The interface set does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false:" }, { "code": null, "e": 3557, "s": 2701, "text": "import java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Scanner;\nimport java.util.Set;\n\npublic class DetectDuplcateUsingSet {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the size of the array that is to be created::\");\n int size = sc.nextInt();\n int[] myArray = new int[size];\n System.out.println(\"Enter the elements of the array ::\");\n\n for(int i=0; i<size; i++) {\n myArray[i] = sc.nextInt();\n }\n System.out.println(\"The array created is ::\"+Arrays.toString(myArray));\n System.out.println(\"indices of duplicate elements in the array are elements::\");\n Set set = new HashSet();\n \n for(int i=0; i<myArray.length; i++) {\n if(!set.add(myArray[i])) {\n System.out.println(i);\n }\n }\n }\n}" }, { "code": null, "e": 3767, "s": 3557, "text": "Enter the size of the array that is to be created ::\n5\nEnter the elements of the array ::\n78\n56\n23\n78\n45\nThe array created is :: [78, 56, 23, 78, 45]\nindices of duplicate elements in the array are elements::\n3" } ]
How to insert a pandas DataFrame to an existing PostgreSQL table? - GeeksforGeeks
22 Nov, 2021 In this article, we are going to see how to insert a pandas DataFrame to an existing PostgreSQL table. pandas: Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns. psycopg2: PostgreSQL is a powerful, open source object-relational database system. PostgreSQL runs on all major operating systems. PostgreSQL follows ACID property of DataBase system and has the support of triggers, updatable views and materialized views, foreign keys. sqlalchemy: SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL we start the code by importing packages and creating a connection string of the format: ‘postgres://user:password@host/database’ The create_engine() function takes the connection string as an argument and forms a connection to the PostgreSQL database, after connecting we create a dictionary, and further convert it into a dataframe using the method pandas.DataFrame() method. The to_sql() method is used to insert a pandas data frame into the Postgresql table. Finally, we execute commands using the execute() method to execute our SQL commands and fetchall() method to fetch the records. df.to_sql(‘data’, con=conn, if_exists=’replace’, index=False) arguments are: name of the table connection if_exists : if the table already exists the function we want to apply . ex: ‘append’ help us add data instead of replacing the data. index : True or False Example 1: Insert a pandas DataFrame to an existing PostgreSQL table using sqlalchemy. The create table command used to create a table in the PostgreSQL database in the following example is: create table data( Name varchar, Age bigint); Code: Python3 import psycopg2 import pandas as pd from sqlalchemy import create_engine conn_string = 'postgres://user:password@host/data1' db = create_engine(conn_string) conn = db.connect() # our dataframe data = {'Name': ['Tom', 'dick', 'harry'], 'Age': [22, 21, 24]} # Create DataFrame df = pd.DataFrame(data) df.to_sql('data', con=conn, if_exists='replace', index=False) conn = psycopg2.connect(conn_string ) conn.autocommit = True cursor = conn.cursor() sql1 = '''select * from data;''' cursor.execute(sql1) for i in cursor.fetchall(): print(i) # conn.commit() conn.close() Output: ('Tom', 22) ('dick', 21) ('harry', 24) Output in PostgreSQL: output table in PostgreSQL Example 2: Insert a pandas DataFrame to an existing PostgreSQL table without using sqlalchemy. As usual, we form a connection to PostgreSQL using the connect() command and execute the execute_values() method, where there’s the ‘insert’ SQL command is executed. a try-except clause is included to make sure the errors are caught if any. To view or download the CSV file used in the below program: click here. The create table command used to create a table in the PostgreSQL database in the following example is : create table fossil_fuels_c02(year int, country varchar,total int,solidfuel int, liquidfuel int,gasfuel int,cement int,gasflaring int,percapita int,bunkerfuels int); Code: Python3 import psycopg2 import numpy as np import psycopg2.extras as extras import pandas as pd def execute_values(conn, df, table): tuples = [tuple(x) for x in df.to_numpy()] cols = ','.join(list(df.columns)) # SQL query to execute query = "INSERT INTO %s(%s) VALUES %%s" % (table, cols) cursor = conn.cursor() try: extras.execute_values(cursor, query, tuples) conn.commit() except (Exception, psycopg2.DatabaseError) as error: print("Error: %s" % error) conn.rollback() cursor.close() return 1 print("the dataframe is inserted") cursor.close() conn = psycopg2.connect( database="ENVIRONMENT_DATABASE", user='postgres', password='pass', host='127.0.0.1', port='5432' ) df = pd.read_csv('fossilfuels.csv') execute_values(conn, df, 'fossil_fuels_c02') Output: the dataframe is inserted after inserting the dataFrame Picked Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23973, "s": 23942, "text": " \n22 Nov, 2021\n" }, { "code": null, "e": 24076, "s": 23973, "text": "In this article, we are going to see how to insert a pandas DataFrame to an existing PostgreSQL table." }, { "code": null, "e": 24421, "s": 24076, "text": "pandas: Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame consists of three principal components, the data, rows, and columns." }, { "code": null, "e": 24691, "s": 24421, "text": "psycopg2: PostgreSQL is a powerful, open source object-relational database system. PostgreSQL runs on all major operating systems. PostgreSQL follows ACID property of DataBase system and has the support of triggers, updatable views and materialized views, foreign keys." }, { "code": null, "e": 24841, "s": 24691, "text": "sqlalchemy: SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL" }, { "code": null, "e": 24929, "s": 24841, "text": "we start the code by importing packages and creating a connection string of the format:" }, { "code": null, "e": 24970, "s": 24929, "text": "‘postgres://user:password@host/database’" }, { "code": null, "e": 25218, "s": 24970, "text": "The create_engine() function takes the connection string as an argument and forms a connection to the PostgreSQL database, after connecting we create a dictionary, and further convert it into a dataframe using the method pandas.DataFrame() method." }, { "code": null, "e": 25432, "s": 25218, "text": "The to_sql() method is used to insert a pandas data frame into the Postgresql table. Finally, we execute commands using the execute() method to execute our SQL commands and fetchall() method to fetch the records." }, { "code": null, "e": 25494, "s": 25432, "text": "df.to_sql(‘data’, con=conn, if_exists=’replace’, index=False)" }, { "code": null, "e": 25509, "s": 25494, "text": "arguments are:" }, { "code": null, "e": 25527, "s": 25509, "text": "name of the table" }, { "code": null, "e": 25538, "s": 25527, "text": "connection" }, { "code": null, "e": 25671, "s": 25538, "text": "if_exists : if the table already exists the function we want to apply . ex: ‘append’ help us add data instead of replacing the data." }, { "code": null, "e": 25693, "s": 25671, "text": "index : True or False" }, { "code": null, "e": 25704, "s": 25693, "text": "Example 1:" }, { "code": null, "e": 25885, "s": 25704, "text": "Insert a pandas DataFrame to an existing PostgreSQL table using sqlalchemy. The create table command used to create a table in the PostgreSQL database in the following example is:" }, { "code": null, "e": 25931, "s": 25885, "text": "create table data( Name varchar, Age bigint);" }, { "code": null, "e": 25937, "s": 25931, "text": "Code:" }, { "code": null, "e": 25945, "s": 25937, "text": "Python3" }, { "code": "\n\n\n\n\n\n\nimport psycopg2 \nimport pandas as pd \nfrom sqlalchemy import create_engine \n \n \nconn_string = 'postgres://user:password@host/data1'\n \ndb = create_engine(conn_string) \nconn = db.connect() \n \n \n# our dataframe \ndata = {'Name': ['Tom', 'dick', 'harry'], \n 'Age': [22, 21, 24]} \n \n# Create DataFrame \ndf = pd.DataFrame(data) \ndf.to_sql('data', con=conn, if_exists='replace', \n index=False) \nconn = psycopg2.connect(conn_string \n ) \nconn.autocommit = True\ncursor = conn.cursor() \n \nsql1 = '''select * from data;'''\ncursor.execute(sql1) \nfor i in cursor.fetchall(): \n print(i) \n \n# conn.commit() \nconn.close() \n\n\n\n\n\n", "e": 26623, "s": 25955, "text": null }, { "code": null, "e": 26631, "s": 26623, "text": "Output:" }, { "code": null, "e": 26670, "s": 26631, "text": "('Tom', 22)\n('dick', 21)\n('harry', 24)" }, { "code": null, "e": 26692, "s": 26670, "text": "Output in PostgreSQL:" }, { "code": null, "e": 26719, "s": 26692, "text": "output table in PostgreSQL" }, { "code": null, "e": 26730, "s": 26719, "text": "Example 2:" }, { "code": null, "e": 27055, "s": 26730, "text": "Insert a pandas DataFrame to an existing PostgreSQL table without using sqlalchemy. As usual, we form a connection to PostgreSQL using the connect() command and execute the execute_values() method, where there’s the ‘insert’ SQL command is executed. a try-except clause is included to make sure the errors are caught if any." }, { "code": null, "e": 27128, "s": 27055, "text": "To view or download the CSV file used in the below program: click here. " }, { "code": null, "e": 27233, "s": 27128, "text": "The create table command used to create a table in the PostgreSQL database in the following example is :" }, { "code": null, "e": 27399, "s": 27233, "text": "create table fossil_fuels_c02(year int, country varchar,total int,solidfuel int, liquidfuel int,gasfuel int,cement int,gasflaring int,percapita int,bunkerfuels int);" }, { "code": null, "e": 27405, "s": 27399, "text": "Code:" }, { "code": null, "e": 27413, "s": 27405, "text": "Python3" }, { "code": "\n\n\n\n\n\n\nimport psycopg2 \nimport numpy as np \nimport psycopg2.extras as extras \nimport pandas as pd \n \n \ndef execute_values(conn, df, table): \n \n tuples = [tuple(x) for x in df.to_numpy()] \n \n cols = ','.join(list(df.columns)) \n # SQL query to execute \n query = \"INSERT INTO %s(%s) VALUES %%s\" % (table, cols) \n cursor = conn.cursor() \n try: \n extras.execute_values(cursor, query, tuples) \n conn.commit() \n except (Exception, psycopg2.DatabaseError) as error: \n print(\"Error: %s\" % error) \n conn.rollback() \n cursor.close() \n return 1\n print(\"the dataframe is inserted\") \n cursor.close() \n \n \nconn = psycopg2.connect( \n database=\"ENVIRONMENT_DATABASE\", user='postgres', password='pass', host='127.0.0.1', port='5432'\n) \n \ndf = pd.read_csv('fossilfuels.csv') \n \nexecute_values(conn, df, 'fossil_fuels_c02') \n\n\n\n\n\n", "e": 28314, "s": 27423, "text": null }, { "code": null, "e": 28322, "s": 28314, "text": "Output:" }, { "code": null, "e": 28348, "s": 28322, "text": "the dataframe is inserted" }, { "code": null, "e": 28378, "s": 28348, "text": "after inserting the dataFrame" }, { "code": null, "e": 28387, "s": 28378, "text": "\nPicked\n" }, { "code": null, "e": 28396, "s": 28387, "text": "\nPython\n" }, { "code": null, "e": 28601, "s": 28396, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 28622, "s": 28601, "text": "Python OOPs Concepts" }, { "code": null, "e": 28654, "s": 28622, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28677, "s": 28654, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 28699, "s": 28677, "text": "Defaultdict in Python" }, { "code": null, "e": 28726, "s": 28699, "text": "Python Classes and Objects" }, { "code": null, "e": 28742, "s": 28726, "text": "Deque in Python" }, { "code": null, "e": 28784, "s": 28742, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28840, "s": 28784, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28885, "s": 28840, "text": "Python - Ways to remove duplicates from list" } ]
MongoDB - Text Indexes - GeeksforGeeks
17 Feb, 2021 MongoDB is a document-based NoSQL database. As the data is stored in the format of the document, it can hold a huge amount of data and as it is a NoSQL database type, there is no strict necessity to have referential integrity relationships. So searching is an important criteria here and for that MongoDB provides Text indexes to support text search queries especially on string content. Text indexes should be either a string or an array of string elements. In MongoDB, we can create text indexes using db.collectionName.createIndex() method. So, to index a field that contains either string or an array of string elements, pass a document in the createIndex() method that contains the field and the string literal(i.e., “text”). Using this method you are allowed to index multiple fields for the text index. Also, a compound index can contain text index key in combination with ascending and descending index key. And if you want to drop a text index, just use the index name. Syntax: db.collectionName.createIndex( { field: “text” } ) Example: Database: ggf Collection: studentsposts Documents: Two documents Now, Let us create a text index on “title” field of “studentsposts” collection in order to search inside the collection. db.studentsposts.createIndex({title: "text"}) Now we will see how to search using Text Index: db.studentsposts.find({$text:{$search: "mongodb"}}).pretty() Output is self-explanatory above as we have created index on “title” field, and we have tried to search the text “mongodb”. It is present in both the documents in the “title” field. Hence, the result is 2 documents here. Sometimes there may be necessities to delete the text indexes too as it was created wrongly or need to be modified in a different manner or totally want to delete that. So, using db.collection.dropIndex() method we can delete text index. This method deletes the specified index from the given collection. Syntax: db.collection.dropIndex("TextIndex") Example: First, we find the index of the field. db.studentsposts.getIndexes() Now we drop the text index using dropIndex() method. db.studentsposts.dropIndex("title_text") For a text index, the weight of an indexed field is the significance of the field. In MongoDB, for each index field in the document, MongoDB sums the results by multiplying the number of matches by weight. Now using this sum, MongoDB calculates the score for the document. The default weight of the index field is 1 and you can adjust the weight of the index using createIndex() method. Example: db.studentsposts.createIndex({title:"text", tags:"text"}, {weights:{title:10, tags:5}, name:"TextIndex"}) Here, the weight of the title and tags field is 10 and 5. Using wildcard specifier($**) you are allowed to create multiple text indexes fields. Due to the wildcard text index MongoDB indexes each and every field that holds string data in all the documents present in the given collection. Wildcard text index is useful for unstructured data where we don’t know which field contains string data or for ad-hoc query. It allowed searching text on all the fields that contain string data. Wild text index can be part of the compound index. Example: db.studentsposts.createIndex( { "$**": "text" } ) Here, we create the text indexes using a wildcard specifier. Now, we will see all the indexes present in the studentsposts collection. At most one text index is allowed per collection With $text query expression, we cannot use hint() Together Text Index and Sort cannot give the required results. The sort operations cannot use the ordering in the text index. Compound Index cannot include multi-key or geospatial index fields. MongoDB Picked Technical Scripter 2020 MongoDB Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments MongoDB - Distinct() Method How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method MongoDB insertMany() Method - db.Collection.insertMany() MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Update() Method Create user and add role in MongoDB MongoDB - sort() Method
[ { "code": null, "e": 23879, "s": 23851, "text": "\n17 Feb, 2021" }, { "code": null, "e": 24338, "s": 23879, "text": "MongoDB is a document-based NoSQL database. As the data is stored in the format of the document, it can hold a huge amount of data and as it is a NoSQL database type, there is no strict necessity to have referential integrity relationships. So searching is an important criteria here and for that MongoDB provides Text indexes to support text search queries especially on string content. Text indexes should be either a string or an array of string elements." }, { "code": null, "e": 24858, "s": 24338, "text": "In MongoDB, we can create text indexes using db.collectionName.createIndex() method. So, to index a field that contains either string or an array of string elements, pass a document in the createIndex() method that contains the field and the string literal(i.e., “text”). Using this method you are allowed to index multiple fields for the text index. Also, a compound index can contain text index key in combination with ascending and descending index key. And if you want to drop a text index, just use the index name." }, { "code": null, "e": 24866, "s": 24858, "text": "Syntax:" }, { "code": null, "e": 24917, "s": 24866, "text": "db.collectionName.createIndex( { field: “text” } )" }, { "code": null, "e": 24926, "s": 24917, "text": "Example:" }, { "code": null, "e": 24940, "s": 24926, "text": "Database: ggf" }, { "code": null, "e": 24966, "s": 24940, "text": "Collection: studentsposts" }, { "code": null, "e": 24991, "s": 24966, "text": "Documents: Two documents" }, { "code": null, "e": 25112, "s": 24991, "text": "Now, Let us create a text index on “title” field of “studentsposts” collection in order to search inside the collection." }, { "code": null, "e": 25158, "s": 25112, "text": "db.studentsposts.createIndex({title: \"text\"})" }, { "code": null, "e": 25206, "s": 25158, "text": "Now we will see how to search using Text Index:" }, { "code": null, "e": 25267, "s": 25206, "text": "db.studentsposts.find({$text:{$search: \"mongodb\"}}).pretty()" }, { "code": null, "e": 25488, "s": 25267, "text": "Output is self-explanatory above as we have created index on “title” field, and we have tried to search the text “mongodb”. It is present in both the documents in the “title” field. Hence, the result is 2 documents here." }, { "code": null, "e": 25793, "s": 25488, "text": "Sometimes there may be necessities to delete the text indexes too as it was created wrongly or need to be modified in a different manner or totally want to delete that. So, using db.collection.dropIndex() method we can delete text index. This method deletes the specified index from the given collection." }, { "code": null, "e": 25801, "s": 25793, "text": "Syntax:" }, { "code": null, "e": 25838, "s": 25801, "text": "db.collection.dropIndex(\"TextIndex\")" }, { "code": null, "e": 25847, "s": 25838, "text": "Example:" }, { "code": null, "e": 25886, "s": 25847, "text": "First, we find the index of the field." }, { "code": null, "e": 25916, "s": 25886, "text": "db.studentsposts.getIndexes()" }, { "code": null, "e": 25969, "s": 25916, "text": "Now we drop the text index using dropIndex() method." }, { "code": null, "e": 26010, "s": 25969, "text": "db.studentsposts.dropIndex(\"title_text\")" }, { "code": null, "e": 26397, "s": 26010, "text": "For a text index, the weight of an indexed field is the significance of the field. In MongoDB, for each index field in the document, MongoDB sums the results by multiplying the number of matches by weight. Now using this sum, MongoDB calculates the score for the document. The default weight of the index field is 1 and you can adjust the weight of the index using createIndex() method." }, { "code": null, "e": 26406, "s": 26397, "text": "Example:" }, { "code": null, "e": 26573, "s": 26406, "text": "db.studentsposts.createIndex({title:\"text\", tags:\"text\"}, \n {weights:{title:10, tags:5}, \n name:\"TextIndex\"})" }, { "code": null, "e": 26631, "s": 26573, "text": "Here, the weight of the title and tags field is 10 and 5." }, { "code": null, "e": 27109, "s": 26631, "text": "Using wildcard specifier($**) you are allowed to create multiple text indexes fields. Due to the wildcard text index MongoDB indexes each and every field that holds string data in all the documents present in the given collection. Wildcard text index is useful for unstructured data where we don’t know which field contains string data or for ad-hoc query. It allowed searching text on all the fields that contain string data. Wild text index can be part of the compound index." }, { "code": null, "e": 27118, "s": 27109, "text": "Example:" }, { "code": null, "e": 27168, "s": 27118, "text": "db.studentsposts.createIndex( { \"$**\": \"text\" } )" }, { "code": null, "e": 27229, "s": 27168, "text": "Here, we create the text indexes using a wildcard specifier." }, { "code": null, "e": 27303, "s": 27229, "text": "Now, we will see all the indexes present in the studentsposts collection." }, { "code": null, "e": 27352, "s": 27303, "text": "At most one text index is allowed per collection" }, { "code": null, "e": 27402, "s": 27352, "text": "With $text query expression, we cannot use hint()" }, { "code": null, "e": 27528, "s": 27402, "text": "Together Text Index and Sort cannot give the required results. The sort operations cannot use the ordering in the text index." }, { "code": null, "e": 27596, "s": 27528, "text": "Compound Index cannot include multi-key or geospatial index fields." }, { "code": null, "e": 27604, "s": 27596, "text": "MongoDB" }, { "code": null, "e": 27611, "s": 27604, "text": "Picked" }, { "code": null, "e": 27635, "s": 27611, "text": "Technical Scripter 2020" }, { "code": null, "e": 27643, "s": 27635, "text": "MongoDB" }, { "code": null, "e": 27662, "s": 27643, "text": "Technical Scripter" }, { "code": null, "e": 27760, "s": 27662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27769, "s": 27760, "text": "Comments" }, { "code": null, "e": 27782, "s": 27769, "text": "Old Comments" }, { "code": null, "e": 27810, "s": 27782, "text": "MongoDB - Distinct() Method" }, { "code": null, "e": 27848, "s": 27810, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 27873, "s": 27848, "text": "MongoDB - limit() Method" }, { "code": null, "e": 27900, "s": 27873, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 27957, "s": 27900, "text": "MongoDB insertMany() Method - db.Collection.insertMany()" }, { "code": null, "e": 28012, "s": 27957, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 28038, "s": 28012, "text": "MongoDB - Update() Method" }, { "code": null, "e": 28074, "s": 28038, "text": "Create user and add role in MongoDB" } ]
From Scikit-learn to TensorFlow : Part 1 | by Karthik M Swamy | Towards Data Science
Over the past year and a half, TensorFlow has grown at a tremendous pace, both in terms of adoption rate and in compute speed. TensorFlow has established itself as the most sought after library for machine learning (ML) algorithm development. However, it seems to have also established itself as a library requiring definitions for sessions and graphs that are rather tedious and time consuming. Although it does a great job at efficiently computing gradients to train CNNs, RNNs and LSTMs, that’s not all. In this series of posts, I want to discuss how TensorFlow can be used as a general purpose ML library. More specifically, we will discuss how it is similar to scikit-learn, another ML library immensely popular among data scientists and developers alike. While scikit-learn has highly-optimised algorithms in its armoury, it lacks the ability to scale-up when faced with a large number of data points. However, TensorFlow provides quite a number of advantages over scikit-learn: High performance ML modules Customisability Scaling-up to cater to large data points Ability to utilise GPUs and train across geographically distributed GPU devices Device agnostic compute Leverage Google Cloud to make inferences on a trained ML model Highly flexible Apache 2.0 license while scikit-learn is on BSD license, (although both are commercially usable, Apache 2.0 is less prone to patent litigations) Understand functionalities that are similar between scikit-learn and TensorFlow which will allow scikit-learn users to seamlessly use TensorFlow. Develop a program to classify flower varieties from the Iris flowers dataset using scikit-learn and TensorFlow to understand the effort required to build such a system. Showcase how easy TensorFlow could be for prototyping new ideas. One of the reason for scikit-learn’s popularity is owing to its simple classifier.fit() / classifier.predict() methods that remain the same for any classifier that is used. This simple user experience has allowed developers to concentrate on the algorithm and its parameters rather than worry about the APIs that need to be called to accomplish the task at hand. On the other hand, we have High-level API in TensorFlow that was inspired by scikit-learn. These functions in TensorFlow work very similar to scikit-learn, with similar fit and predict methods along with other functionalities that allow further fine-tuning. Before we delve into developing our classification framework using TensorFlow’s High-level API calls, let’s discuss TensorFlow’s low-level computation framework. TensorFlow uses computation graphs to perform all its computations. Computations are represented as an instance of the tf.Graph object where the data is represented as tf.Tensor object and operations on such tensor objects using the tf.Operation object. The graph is then executed in a session using the tf.Session object. As it is evident, creating a classification framework using TensorFlow’s low-level API would require an effort to test out a simple ML prototype. This is one of the reasons why we discuss TensorFlow’s high-level API to compare with scikit-learn’s API. We will discuss about the low-level APIs and its usage in later posts. We build a classifier using scikit-learn’s SVM module and TensorFlow’s High-Level API to classify flowers based on features of the flower. In this case, the dataset provides 4 different features such as sepal width, sepal length, petal width and petal length to classify the flower into one of the three flower species (Iris setosa, Iris versicolor, and Iris virginica.) The code for this project is available on my GitHub page. If we look at the notebook on the GitHub link above, we can see that the data load and split functionalities are shared by both the frameworks. We define an SVM classifier in scikit-learn as follows: # ------------------------------------------# Scikit Learn Implementation# ------------------------------------------# Use support vector classificationclassifier_sk = svm.SVC()# Use the train data to train this classifierclassifier_sk.fit(x_train, y_train)# Use the trained model to predict on the test datapredictions = classifier_sk.predict(x_test)score = metrics.accuracy_score(y_test, predictions) In the code snippet above, we simply define a support vector classifier svm.SVC(), the object of which is used for training and prediction. Training is achieved using the fit() while prediction is achieved using the predict() method call. We finally calculate the accuracy value in the final line of this four line code snippet. On the other hand, in TensorFlow we can use a deep neural network (DNN) classifier for the same task. We use the DNNClassifier available under TensorFlow’s contrib module as follows: # ------------------------------------------# TensorFlow Implementation# ------------------------------------------# Extract the features from the training datafeats = tf.contrib.learn.infer_real_valued_columns_from_input(x_train)# Building a 3-layer DNN with 50 units each.classifier_tf = tf.contrib.learn.DNNClassifier(feature_columns=feats, hidden_units=[50, 50, 50], n_classes=3)# Use the train data to train this classifierclassifier_tf.fit(x_train, y_train, steps=5000)# Use the trained model to predict on the test datapredictions = list(classifier_tf.predict(x_test, as_iterable=True))score = metrics.accuracy_score(y_test, predictions) In the code snippet above, we can see how we can build a DNN for the almost the same number of lines (except for the additional line for converting the input data into features.) This additional line accomplishes the task of converting the input data into dense, fixed-length float values. While the task of moving from one framework to another is often daunting and at times frustrating, TensorFlow seems to have a bridge that allows developers to transition smoothly move in from a different framework. The contrib.learn module provides such a bridge that allows a familiar path from scikit-learn or Keras, into TensorFlow. TensorFlow is also accommodating enough to include readers that are highly optimised for production quality usage while at the same time supports most file formats that the ML community uses. This allows for developers to avoid depending on other frameworks such as Pandas (which does the heavy-lifting of reading files but still requires manually feeding the data into the ML framework.) TensorFlow readers were also shown to be high performance at the TensorFlow Dev Summit held earlier this year. In this post, we began our exploration into developing a classifier using scikit-learn and TensorFlow for accomplishing a simple task. We discussed how the High-Level TensorFlow API is similar to scikit-learn’s API. You can access the code discussed in this blog at my GitHub page. In the next post, I’m planning to introduce some more scikit modules and its TensorFlow counterparts. Do you have anything specific in mind? Tweet to me @krtk or connect with me on LinkedIn.
[ { "code": null, "e": 298, "s": 171, "text": "Over the past year and a half, TensorFlow has grown at a tremendous pace, both in terms of adoption rate and in compute speed." }, { "code": null, "e": 678, "s": 298, "text": "TensorFlow has established itself as the most sought after library for machine learning (ML) algorithm development. However, it seems to have also established itself as a library requiring definitions for sessions and graphs that are rather tedious and time consuming. Although it does a great job at efficiently computing gradients to train CNNs, RNNs and LSTMs, that’s not all." }, { "code": null, "e": 932, "s": 678, "text": "In this series of posts, I want to discuss how TensorFlow can be used as a general purpose ML library. More specifically, we will discuss how it is similar to scikit-learn, another ML library immensely popular among data scientists and developers alike." }, { "code": null, "e": 1156, "s": 932, "text": "While scikit-learn has highly-optimised algorithms in its armoury, it lacks the ability to scale-up when faced with a large number of data points. However, TensorFlow provides quite a number of advantages over scikit-learn:" }, { "code": null, "e": 1184, "s": 1156, "text": "High performance ML modules" }, { "code": null, "e": 1200, "s": 1184, "text": "Customisability" }, { "code": null, "e": 1241, "s": 1200, "text": "Scaling-up to cater to large data points" }, { "code": null, "e": 1321, "s": 1241, "text": "Ability to utilise GPUs and train across geographically distributed GPU devices" }, { "code": null, "e": 1345, "s": 1321, "text": "Device agnostic compute" }, { "code": null, "e": 1408, "s": 1345, "text": "Leverage Google Cloud to make inferences on a trained ML model" }, { "code": null, "e": 1569, "s": 1408, "text": "Highly flexible Apache 2.0 license while scikit-learn is on BSD license, (although both are commercially usable, Apache 2.0 is less prone to patent litigations)" }, { "code": null, "e": 1715, "s": 1569, "text": "Understand functionalities that are similar between scikit-learn and TensorFlow which will allow scikit-learn users to seamlessly use TensorFlow." }, { "code": null, "e": 1884, "s": 1715, "text": "Develop a program to classify flower varieties from the Iris flowers dataset using scikit-learn and TensorFlow to understand the effort required to build such a system." }, { "code": null, "e": 1949, "s": 1884, "text": "Showcase how easy TensorFlow could be for prototyping new ideas." }, { "code": null, "e": 2020, "s": 1949, "text": "One of the reason for scikit-learn’s popularity is owing to its simple" }, { "code": null, "e": 2061, "s": 2020, "text": "classifier.fit() / classifier.predict() " }, { "code": null, "e": 2313, "s": 2061, "text": "methods that remain the same for any classifier that is used. This simple user experience has allowed developers to concentrate on the algorithm and its parameters rather than worry about the APIs that need to be called to accomplish the task at hand." }, { "code": null, "e": 2571, "s": 2313, "text": "On the other hand, we have High-level API in TensorFlow that was inspired by scikit-learn. These functions in TensorFlow work very similar to scikit-learn, with similar fit and predict methods along with other functionalities that allow further fine-tuning." }, { "code": null, "e": 3379, "s": 2571, "text": "Before we delve into developing our classification framework using TensorFlow’s High-level API calls, let’s discuss TensorFlow’s low-level computation framework. TensorFlow uses computation graphs to perform all its computations. Computations are represented as an instance of the tf.Graph object where the data is represented as tf.Tensor object and operations on such tensor objects using the tf.Operation object. The graph is then executed in a session using the tf.Session object. As it is evident, creating a classification framework using TensorFlow’s low-level API would require an effort to test out a simple ML prototype. This is one of the reasons why we discuss TensorFlow’s high-level API to compare with scikit-learn’s API. We will discuss about the low-level APIs and its usage in later posts." }, { "code": null, "e": 3750, "s": 3379, "text": "We build a classifier using scikit-learn’s SVM module and TensorFlow’s High-Level API to classify flowers based on features of the flower. In this case, the dataset provides 4 different features such as sepal width, sepal length, petal width and petal length to classify the flower into one of the three flower species (Iris setosa, Iris versicolor, and Iris virginica.)" }, { "code": null, "e": 3808, "s": 3750, "text": "The code for this project is available on my GitHub page." }, { "code": null, "e": 4008, "s": 3808, "text": "If we look at the notebook on the GitHub link above, we can see that the data load and split functionalities are shared by both the frameworks. We define an SVM classifier in scikit-learn as follows:" }, { "code": null, "e": 4411, "s": 4008, "text": "# ------------------------------------------# Scikit Learn Implementation# ------------------------------------------# Use support vector classificationclassifier_sk = svm.SVC()# Use the train data to train this classifierclassifier_sk.fit(x_train, y_train)# Use the trained model to predict on the test datapredictions = classifier_sk.predict(x_test)score = metrics.accuracy_score(y_test, predictions)" }, { "code": null, "e": 4740, "s": 4411, "text": "In the code snippet above, we simply define a support vector classifier svm.SVC(), the object of which is used for training and prediction. Training is achieved using the fit() while prediction is achieved using the predict() method call. We finally calculate the accuracy value in the final line of this four line code snippet." }, { "code": null, "e": 4923, "s": 4740, "text": "On the other hand, in TensorFlow we can use a deep neural network (DNN) classifier for the same task. We use the DNNClassifier available under TensorFlow’s contrib module as follows:" }, { "code": null, "e": 5662, "s": 4923, "text": "# ------------------------------------------# TensorFlow Implementation# ------------------------------------------# Extract the features from the training datafeats = tf.contrib.learn.infer_real_valued_columns_from_input(x_train)# Building a 3-layer DNN with 50 units each.classifier_tf = tf.contrib.learn.DNNClassifier(feature_columns=feats, hidden_units=[50, 50, 50], n_classes=3)# Use the train data to train this classifierclassifier_tf.fit(x_train, y_train, steps=5000)# Use the trained model to predict on the test datapredictions = list(classifier_tf.predict(x_test, as_iterable=True))score = metrics.accuracy_score(y_test, predictions)" }, { "code": null, "e": 5952, "s": 5662, "text": "In the code snippet above, we can see how we can build a DNN for the almost the same number of lines (except for the additional line for converting the input data into features.) This additional line accomplishes the task of converting the input data into dense, fixed-length float values." }, { "code": null, "e": 6288, "s": 5952, "text": "While the task of moving from one framework to another is often daunting and at times frustrating, TensorFlow seems to have a bridge that allows developers to transition smoothly move in from a different framework. The contrib.learn module provides such a bridge that allows a familiar path from scikit-learn or Keras, into TensorFlow." }, { "code": null, "e": 6788, "s": 6288, "text": "TensorFlow is also accommodating enough to include readers that are highly optimised for production quality usage while at the same time supports most file formats that the ML community uses. This allows for developers to avoid depending on other frameworks such as Pandas (which does the heavy-lifting of reading files but still requires manually feeding the data into the ML framework.) TensorFlow readers were also shown to be high performance at the TensorFlow Dev Summit held earlier this year." }, { "code": null, "e": 7070, "s": 6788, "text": "In this post, we began our exploration into developing a classifier using scikit-learn and TensorFlow for accomplishing a simple task. We discussed how the High-Level TensorFlow API is similar to scikit-learn’s API. You can access the code discussed in this blog at my GitHub page." } ]
Circular (polar) histogram in Python
To plot circular (polar) histogram in Python, we can take the following steps− Create data points for theta, radii and width using numpy. Add a subplot to the current figure, where projection='polar' and nrows=1, ncols=1 and index=1. . Make a bar plot using bar() method, with theta, radii and width data points Iterate radii and bars after zipping them together and set the face color of the bar and the alpha value. Lesser the alpha value, greater the transparency. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True N = 20 theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) ax = plt.subplot(111, projection='polar') bars = ax.bar(theta, radii, width=width, bottom=0.0) for r, bar in zip(radii, bars): bar.set_facecolor(plt.cm.rainbow(r / 10.0)) bar.set_alpha(0.5) plt.show()
[ { "code": null, "e": 1141, "s": 1062, "text": "To plot circular (polar) histogram in Python, we can take the following steps−" }, { "code": null, "e": 1200, "s": 1141, "text": "Create data points for theta, radii and width using numpy." }, { "code": null, "e": 1296, "s": 1200, "text": "Add a subplot to the current figure, where projection='polar' and nrows=1, ncols=1 and\nindex=1." }, { "code": null, "e": 1374, "s": 1296, "text": ". Make a bar plot using bar() method, with theta, radii and width data points" }, { "code": null, "e": 1530, "s": 1374, "text": "Iterate radii and bars after zipping them together and set the face color of the bar and the alpha\nvalue. Lesser the alpha value, greater the transparency." }, { "code": null, "e": 1572, "s": 1530, "text": "To display the figure, use show() method." }, { "code": null, "e": 2042, "s": 1572, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nN = 20\ntheta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)\nradii = 10 * np.random.rand(N)\nwidth = np.pi / 4 * np.random.rand(N)\nax = plt.subplot(111, projection='polar')\nbars = ax.bar(theta, radii, width=width, bottom=0.0)\nfor r, bar in zip(radii, bars):\nbar.set_facecolor(plt.cm.rainbow(r / 10.0))\nbar.set_alpha(0.5)\nplt.show()" } ]
Demonstrate constructors in a Multilevel Hierarchy in Java
Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A. A program that demonstrates constructors in a Multilevel Hierarchy in Java is given as follows: Live Demo class A { A() { System.out.println("This is constructor of class A"); } } class B extends A { B() { System.out.println("This is constructor of class B"); } } class C extends B { C() { System.out.println("This is constructor of class C"); } } public class Demo { public static void main(String args[]) { C obj = new C(); } } This is constructor of class A This is constructor of class B This is constructor of class C Now let us understand the above program. The class A contains the constructor A(). The class B uses the extends keyword to inherit class A. It also contains the constructor B(). The class C uses the extends keyword to inherit class B. It contains the constructor C(). A code snippet which demonstrates this is as follows: class A { A() { System.out.println("This is constructor of class A"); } } class B extends A { B() { System.out.println("This is constructor of class B"); } } class C extends B { C() { System.out.println("This is constructor of class C"); } } In the main() method in class Demo, an object obj of class C is created. A code snippet which demonstrates this is as follows: public class Demo { public static void main(String args[]) { C obj = new C(); } }
[ { "code": null, "e": 1233, "s": 1062, "text": "Multilevel inheritance is when a class inherits a class which inherits another class. An example of this is class C inherits class B and class B in turn inherits class A." }, { "code": null, "e": 1329, "s": 1233, "text": "A program that demonstrates constructors in a Multilevel Hierarchy in Java is given as follows:" }, { "code": null, "e": 1340, "s": 1329, "text": " Live Demo" }, { "code": null, "e": 1712, "s": 1340, "text": "class A {\n A() {\n System.out.println(\"This is constructor of class A\");\n }\n}\nclass B extends A {\n B() {\n System.out.println(\"This is constructor of class B\");\n }\n}\nclass C extends B {\n C() {\n System.out.println(\"This is constructor of class C\");\n }\n}\npublic class Demo {\n public static void main(String args[]) {\n C obj = new C();\n }\n}" }, { "code": null, "e": 1805, "s": 1712, "text": "This is constructor of class A\nThis is constructor of class B\nThis is constructor of class C" }, { "code": null, "e": 1846, "s": 1805, "text": "Now let us understand the above program." }, { "code": null, "e": 2127, "s": 1846, "text": "The class A contains the constructor A(). The class B uses the extends keyword to inherit class A. It also contains the constructor B(). The class C uses the extends keyword to inherit class B. It contains the constructor C(). A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2405, "s": 2127, "text": "class A {\n A() {\n System.out.println(\"This is constructor of class A\");\n }\n}\nclass B extends A {\n B() {\n System.out.println(\"This is constructor of class B\");\n }\n}\nclass C extends B {\n C() {\n System.out.println(\"This is constructor of class C\");\n }\n}" }, { "code": null, "e": 2532, "s": 2405, "text": "In the main() method in class Demo, an object obj of class C is created. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2626, "s": 2532, "text": "public class Demo {\n public static void main(String args[]) {\n C obj = new C();\n }\n}" } ]
Demystifying Support Vector Machines | by Dhairya Kumar | Towards Data Science
This is my second article of the Demystifying series. You can check out the first article here — towardsdatascience.com In this article, I will focus on Support Vector Machines or SVM. It is one of the most popular machine learning algorithms and it enjoyed its Numero Uno status for almost a decade (the early 1990s to 2000s). However, it is still a very basic and important algorithm which you should definitely have in your arsenal. So let’s start with SVM. The topics that I will cover in this article are as follows SVM Introduction Geometric Intuition Why we use +1 and -1 for support vector planes Loss Function Dual form of SVM Kernel and its types nu-SVM Support Vector Machine (SVM) is a machine learning algorithm that can be used for both classification and regression problems. However, it is mostly used in classification problems. In this algorithm, we plot each data item as a point in n-dimensional space (where n is the number of features you have). Then, we perform classification by finding the hyperplane that best differentiates the two classes. If you have a n-dimensional space, then the dimension of the hyperplane will be n-1. Ex — If you have a 2d space then it will be a line, If you have a 3d space then it will be a plane and so on. The main idea behind SVM is to find a plane that best separates the positive and negative points and the distance between the positive plane and the negative plane is maximum. The rationale behind choosing the decision boundaries with larger margins is that it reduces the generalisation error and the decision boundaries with smaller margins usually lead to overfitting. Another important thing that you may have noted from the above image is that support vectors are basically the points that lie on the positive and negative hyperplane. Now let’s take a closer look at how do we actually maximise the margin. Let’s consider the following equations — These are just the equations of the positive and negative hyperplanes. I have only added ‘b’ to this equation which is the y-intercept. If you are wondering why have I taken the values of positive and negative hyperplanes as +1 and -1 respectively then just hold that thought for a while as I will explain in detail the reason for doing so, later in the article. After subtracting equations (1) and (2) , we get — We can normalise this equation by the length of the vector w, which is defined as follows So our final equation is — The left side of this equation is basically the distance between positive and negative hyperplane, which is actually the margin that we want to maximize. So our optimisation function in case of SVM is — argmax( 2 / ||W||) for all isuch that Yi(W^T * Xi+b) >= 1 Here Yi(W^T * Xi+b) >= 1 implies that the points are perfectly linearly separable. So all the positive points lie on the positive side of the plane and all the negative points lie on the negative side Now the problem with this approach is that you will almost never find a dataset in real life which is perfectly linearly separable. The approach that we followed is called the Hard-Margin SVM and it is rarely used in real life. So in order to use the SVM in real-world applications, a modified version was created, called the Soft- Margin SVM. Let’s first look at the equation for Soft Margin SVM If you are not able to comprehend this equation, don’t worry about it too much , I will explain each and every term. One thing that might look familiar to you is the term ||W||/2 . Earlier we were looking to maximize the term 2/||W|| but now since we inverted it, therefore we have changed argmax to argmin. You might have already guessed that ‘n’ denotes the number of data points. So the 2 newly added terms in this equation are — C = It is a hyperparameterζ (Zeta) = It denotes the distance of misclassified points In order to better understand the term zeta, let’s look at the following example. Here, ★ represents positive points and ⬤ represents negative points. As I said in the case of Hard-margin SVM, it is very rare that we find a dataset which is perfectly linearly separable and here we have a point x1 which is a positive point but it does not lie in the positive plane. So in this particular case the distance between the point x1 and the plane Π is 0.5 (towards the negative plane). For point x1 - Y(W^T * X + b) = -0.5Since class label(Y) is +1 and the distance is -0.5, since it is towards the negative plane We can re-write the above equation as follows — Y(W^T * X + b) = 1 - 1.5 So in general form we can write it as Y(W^T * X + b) = 1 - ζ So basically what ζ represent is the distance of the misclassified point from its actual plane.You can observe that the distance of x1 from positive plane Π + is 1.5 and that is exactly the value of ζ in this case. As I mentioned above C is a hyperparameter and it can be tuned effectively to avoid overfitting and underfitting. As C increases the tendency of the model to overfit increasesAs C decreases the tendency of the model to underfit increases It is not necessary that we always choose +1 and -1. So let’s choose any arbitrary value of k here. The only restriction is that it should be greater than 0. We can’t choose distinct values for our planes i.e we can’t take +k1 and -k2 as we want our positive and negative planes to be equally distant from our plane Π Now our updated margin is - 2*k / ||W||for k = 5 we get10/||W|| So now we will use 10/||W|| instead of 2/||W|| that is the only difference and since k is a constant here therefore it doesn’t really matter what value we are choosing, as it will not affect our optimisation problem. So we use +1 and -1 for simplifying the mathematical calculations. The loss function used in SVM is hinge loss. In simple terms, we can understand hinge loss as a function whose value is non-zero till a certain point let’s say ‘z’ and after that point ‘z’ it is equal to zero. We looked at the equation for Soft-Margin SVM. Here the second term which contains ζ and C is the loss term. Now we will look at how we got this term. Let Y(W^T * X + b) = Z -- (i)// Here we are just substituting the value of Y(W^T * X + b) so that it is more readableSo from (i) we can say that If Z > = 1 then the point is correctly classified andIf Z < 1 then the point is misclassified If you didn’t understand the above substitution, then let me clarify it further. Suppose you have 2 points x1 and x2 where x1 is positive and x2 is negative. Now for a point x2 which lies in the negative plane the value for (W^T * X + b) will be negative and its Y value will be -1. So, Y*(W^T * X + b) = -1 * (-ve value) = +ve value Similarly for a positive point x1, (W^T * X + b) will be positive and its Y value will also be positive. So, Y*(W^T * X + b) = +1 * (+ve value) = +ve value. Now if you have another point x3 which is positive but lies in the negative plane then (W^T * X + b) will be negative but class label Y is still positive. So, Y*(W^T * X + b) = +1 * (-ve value) = -ve value So the crux here is that Y*(W^T * X + b) will only be positive if the point is correctly classified and we have just substituted Y*(W^T * X + b) as Z. Now that you are comfortable with the concept of Z (hopefully), let’s look at our loss function. So our loss function is fairly simple and if you are not able to understand how it works then I will break it down for you. As explained earlier - If Z >= 1 then the point is correctly classified andIf Z < 1 then the point is misclassified So we will consider 2 cases here. Case 1 — ( Z ≥1) If Z ≥1 then 1-Z will be less than 0 so Max(0, 1-Z ) = 0 It makes sense intuitively as if Z≥1 then it mean we have correctly classified the point and therefore our loss is 0. Case 2— ( Z < 1) If Z <1 then 1-Z will be greater than 0 so Max(0, 1-Z ) = 1-Z Final Step As we already know that - Y(W^T * X + b) = 1 — ζ (Refer to Understanding Zeta sub-section) So we can rewrite it as -1 - Y(W^T * X + b) = ζAnd Y(W^T * X + b) = ZSo 1-Z = ζ And from the above cases we can see that the term that we want to minimise is 1-Z. This is exactly what we have written here. We just substituted 1-Z with ζ The above Equation 1 that we derived is the primal form of SVM.However in order to leverage the power of kernels we use the dual form of SVMs.So let’s look at the dual form of SVM. The reason for using the dual form of SVM is that it allows us to leverage the power of kernels which is a key feature of SVM and if you are not familiar with kernels then don’t worry about it too much, I will explain kernels in the next section. But for now just understand that we use the dual form of SVM in order to leverage the power of kernels. It is proven mathematically that Equation 2 is equivalent to Equation 1. The mathematical proof of how we actually got to this dual form is beyond the scope of this article as it is a bit mathematically intense. If you want to understand the maths behind it then you can checkout the following video — In this video Prof. Patrick Henry Winston provided a brilliant mathematical explanation and I would highly suggest that you checkout this video to better understand the concept of SVMs. The most important thing to note here is that the value of αi will be non-zero only for support vectors. So we basically only care about the support vectors. We can update our Equation 2 as follows — Earlier we were using Xi^T . Xj i.e. we were taking the dot product of Xi and Xj which is equivalent to Cosine similarity function. So we can just replace this cosine similarity function with any other function of Xi and Xj.This is called the kernel trick. Now let’s understand what the hell is a kernel. In the above Equation 3, we can replace K with any kernel function. Now you must be wondering how does that change anything. Why does it even matter which function we use? So let’s try to answer those questions. Suppose you have a dataset that is not linearly separable. Now how would you use SVM to separate this data? There is no way that we can fit a plane that can separate these 2 classes. Enter Kernels.... The main use of a kernel function is that it allows us to project our dataset onto higher dimension where we can fit a plane to separate our dataset. So we can project our above dataset onto a higher dimension and then we can find a plane that can separate the 2 classes.This is exactly the reason why SVM was super popular in the early 90s. The 2 most popular types of kernels are — Polynomial KernelRadial Basis Function (RBF) Kernel Polynomial Kernel Radial Basis Function (RBF) Kernel Polynomial Kernel — So for a quadratic kernel we will have something like this — RBF Kernel — Here d is the distance between x1 and x2 i.e. d = ||x1-x2|| and σ is a hyperparameter. nu is a hyperparameter that we can use for defining the percentage of error that is acceptable. 0 <= nu <= 1 // The value of nu is between 0 and 1Let's understand it with an example.Suppose nu = 0.01 and N (Number of data points)= 100,000* Percentage of errors <= 1%* Number of Support Vectors >= 1% of N i.e. 1000 So with the help of nu hyperparameter we can do 2 things — We can control the error percentage for our model. We can’t control but we can determine the number of support vectors. And with that we have come to the end of this article. Thanks a ton for reading it. You can clap if you want . IT’S FREE. My LinkedIn, Twitter and GithubYou can check out my website to know more about me and my work.
[ { "code": null, "e": 269, "s": 172, "text": "This is my second article of the Demystifying series. You can check out the first article here —" }, { "code": null, "e": 292, "s": 269, "text": "towardsdatascience.com" }, { "code": null, "e": 633, "s": 292, "text": "In this article, I will focus on Support Vector Machines or SVM. It is one of the most popular machine learning algorithms and it enjoyed its Numero Uno status for almost a decade (the early 1990s to 2000s). However, it is still a very basic and important algorithm which you should definitely have in your arsenal. So let’s start with SVM." }, { "code": null, "e": 693, "s": 633, "text": "The topics that I will cover in this article are as follows" }, { "code": null, "e": 710, "s": 693, "text": "SVM Introduction" }, { "code": null, "e": 730, "s": 710, "text": "Geometric Intuition" }, { "code": null, "e": 777, "s": 730, "text": "Why we use +1 and -1 for support vector planes" }, { "code": null, "e": 791, "s": 777, "text": "Loss Function" }, { "code": null, "e": 808, "s": 791, "text": "Dual form of SVM" }, { "code": null, "e": 829, "s": 808, "text": "Kernel and its types" }, { "code": null, "e": 836, "s": 829, "text": "nu-SVM" }, { "code": null, "e": 1240, "s": 836, "text": "Support Vector Machine (SVM) is a machine learning algorithm that can be used for both classification and regression problems. However, it is mostly used in classification problems. In this algorithm, we plot each data item as a point in n-dimensional space (where n is the number of features you have). Then, we perform classification by finding the hyperplane that best differentiates the two classes." }, { "code": null, "e": 1325, "s": 1240, "text": "If you have a n-dimensional space, then the dimension of the hyperplane will be n-1." }, { "code": null, "e": 1435, "s": 1325, "text": "Ex — If you have a 2d space then it will be a line, If you have a 3d space then it will be a plane and so on." }, { "code": null, "e": 1611, "s": 1435, "text": "The main idea behind SVM is to find a plane that best separates the positive and negative points and the distance between the positive plane and the negative plane is maximum." }, { "code": null, "e": 1807, "s": 1611, "text": "The rationale behind choosing the decision boundaries with larger margins is that it reduces the generalisation error and the decision boundaries with smaller margins usually lead to overfitting." }, { "code": null, "e": 1975, "s": 1807, "text": "Another important thing that you may have noted from the above image is that support vectors are basically the points that lie on the positive and negative hyperplane." }, { "code": null, "e": 2047, "s": 1975, "text": "Now let’s take a closer look at how do we actually maximise the margin." }, { "code": null, "e": 2088, "s": 2047, "text": "Let’s consider the following equations —" }, { "code": null, "e": 2451, "s": 2088, "text": "These are just the equations of the positive and negative hyperplanes. I have only added ‘b’ to this equation which is the y-intercept. If you are wondering why have I taken the values of positive and negative hyperplanes as +1 and -1 respectively then just hold that thought for a while as I will explain in detail the reason for doing so, later in the article." }, { "code": null, "e": 2502, "s": 2451, "text": "After subtracting equations (1) and (2) , we get —" }, { "code": null, "e": 2592, "s": 2502, "text": "We can normalise this equation by the length of the vector w, which is defined as follows" }, { "code": null, "e": 2619, "s": 2592, "text": "So our final equation is —" }, { "code": null, "e": 2773, "s": 2619, "text": "The left side of this equation is basically the distance between positive and negative hyperplane, which is actually the margin that we want to maximize." }, { "code": null, "e": 2822, "s": 2773, "text": "So our optimisation function in case of SVM is —" }, { "code": null, "e": 2880, "s": 2822, "text": "argmax( 2 / ||W||) for all isuch that Yi(W^T * Xi+b) >= 1" }, { "code": null, "e": 3081, "s": 2880, "text": "Here Yi(W^T * Xi+b) >= 1 implies that the points are perfectly linearly separable. So all the positive points lie on the positive side of the plane and all the negative points lie on the negative side" }, { "code": null, "e": 3425, "s": 3081, "text": "Now the problem with this approach is that you will almost never find a dataset in real life which is perfectly linearly separable. The approach that we followed is called the Hard-Margin SVM and it is rarely used in real life. So in order to use the SVM in real-world applications, a modified version was created, called the Soft- Margin SVM." }, { "code": null, "e": 3478, "s": 3425, "text": "Let’s first look at the equation for Soft Margin SVM" }, { "code": null, "e": 3786, "s": 3478, "text": "If you are not able to comprehend this equation, don’t worry about it too much , I will explain each and every term. One thing that might look familiar to you is the term ||W||/2 . Earlier we were looking to maximize the term 2/||W|| but now since we inverted it, therefore we have changed argmax to argmin." }, { "code": null, "e": 3911, "s": 3786, "text": "You might have already guessed that ‘n’ denotes the number of data points. So the 2 newly added terms in this equation are —" }, { "code": null, "e": 4006, "s": 3911, "text": "C = It is a hyperparameterζ (Zeta) = It denotes the distance of misclassified points " }, { "code": null, "e": 4088, "s": 4006, "text": "In order to better understand the term zeta, let’s look at the following example." }, { "code": null, "e": 4157, "s": 4088, "text": "Here, ★ represents positive points and ⬤ represents negative points." }, { "code": null, "e": 4373, "s": 4157, "text": "As I said in the case of Hard-margin SVM, it is very rare that we find a dataset which is perfectly linearly separable and here we have a point x1 which is a positive point but it does not lie in the positive plane." }, { "code": null, "e": 4487, "s": 4373, "text": "So in this particular case the distance between the point x1 and the plane Π is 0.5 (towards the negative plane)." }, { "code": null, "e": 4616, "s": 4487, "text": "For point x1 - Y(W^T * X + b) = -0.5Since class label(Y) is +1 and the distance is -0.5, since it is towards the negative plane" }, { "code": null, "e": 4664, "s": 4616, "text": "We can re-write the above equation as follows —" }, { "code": null, "e": 4753, "s": 4664, "text": "Y(W^T * X + b) = 1 - 1.5 So in general form we can write it as Y(W^T * X + b) = 1 - ζ" }, { "code": null, "e": 4968, "s": 4753, "text": "So basically what ζ represent is the distance of the misclassified point from its actual plane.You can observe that the distance of x1 from positive plane Π + is 1.5 and that is exactly the value of ζ in this case." }, { "code": null, "e": 5082, "s": 4968, "text": "As I mentioned above C is a hyperparameter and it can be tuned effectively to avoid overfitting and underfitting." }, { "code": null, "e": 5206, "s": 5082, "text": "As C increases the tendency of the model to overfit increasesAs C decreases the tendency of the model to underfit increases" }, { "code": null, "e": 5364, "s": 5206, "text": "It is not necessary that we always choose +1 and -1. So let’s choose any arbitrary value of k here. The only restriction is that it should be greater than 0." }, { "code": null, "e": 5524, "s": 5364, "text": "We can’t choose distinct values for our planes i.e we can’t take +k1 and -k2 as we want our positive and negative planes to be equally distant from our plane Π" }, { "code": null, "e": 5552, "s": 5524, "text": "Now our updated margin is -" }, { "code": null, "e": 5588, "s": 5552, "text": "2*k / ||W||for k = 5 we get10/||W||" }, { "code": null, "e": 5805, "s": 5588, "text": "So now we will use 10/||W|| instead of 2/||W|| that is the only difference and since k is a constant here therefore it doesn’t really matter what value we are choosing, as it will not affect our optimisation problem." }, { "code": null, "e": 5872, "s": 5805, "text": "So we use +1 and -1 for simplifying the mathematical calculations." }, { "code": null, "e": 6082, "s": 5872, "text": "The loss function used in SVM is hinge loss. In simple terms, we can understand hinge loss as a function whose value is non-zero till a certain point let’s say ‘z’ and after that point ‘z’ it is equal to zero." }, { "code": null, "e": 6129, "s": 6082, "text": "We looked at the equation for Soft-Margin SVM." }, { "code": null, "e": 6233, "s": 6129, "text": "Here the second term which contains ζ and C is the loss term. Now we will look at how we got this term." }, { "code": null, "e": 6479, "s": 6233, "text": "Let Y(W^T * X + b) = Z -- (i)// Here we are just substituting the value of Y(W^T * X + b) so that it is more readableSo from (i) we can say that If Z > = 1 then the point is correctly classified andIf Z < 1 then the point is misclassified " }, { "code": null, "e": 6560, "s": 6479, "text": "If you didn’t understand the above substitution, then let me clarify it further." }, { "code": null, "e": 6762, "s": 6560, "text": "Suppose you have 2 points x1 and x2 where x1 is positive and x2 is negative. Now for a point x2 which lies in the negative plane the value for (W^T * X + b) will be negative and its Y value will be -1." }, { "code": null, "e": 6813, "s": 6762, "text": "So, Y*(W^T * X + b) = -1 * (-ve value) = +ve value" }, { "code": null, "e": 6970, "s": 6813, "text": "Similarly for a positive point x1, (W^T * X + b) will be positive and its Y value will also be positive. So, Y*(W^T * X + b) = +1 * (+ve value) = +ve value." }, { "code": null, "e": 7125, "s": 6970, "text": "Now if you have another point x3 which is positive but lies in the negative plane then (W^T * X + b) will be negative but class label Y is still positive." }, { "code": null, "e": 7176, "s": 7125, "text": "So, Y*(W^T * X + b) = +1 * (-ve value) = -ve value" }, { "code": null, "e": 7327, "s": 7176, "text": "So the crux here is that Y*(W^T * X + b) will only be positive if the point is correctly classified and we have just substituted Y*(W^T * X + b) as Z." }, { "code": null, "e": 7424, "s": 7327, "text": "Now that you are comfortable with the concept of Z (hopefully), let’s look at our loss function." }, { "code": null, "e": 7548, "s": 7424, "text": "So our loss function is fairly simple and if you are not able to understand how it works then I will break it down for you." }, { "code": null, "e": 7571, "s": 7548, "text": "As explained earlier -" }, { "code": null, "e": 7669, "s": 7571, "text": "If Z >= 1 then the point is correctly classified andIf Z < 1 then the point is misclassified" }, { "code": null, "e": 7703, "s": 7669, "text": "So we will consider 2 cases here." }, { "code": null, "e": 7720, "s": 7703, "text": "Case 1 — ( Z ≥1)" }, { "code": null, "e": 7777, "s": 7720, "text": "If Z ≥1 then 1-Z will be less than 0 so Max(0, 1-Z ) = 0" }, { "code": null, "e": 7895, "s": 7777, "text": "It makes sense intuitively as if Z≥1 then it mean we have correctly classified the point and therefore our loss is 0." }, { "code": null, "e": 7912, "s": 7895, "text": "Case 2— ( Z < 1)" }, { "code": null, "e": 7974, "s": 7912, "text": "If Z <1 then 1-Z will be greater than 0 so Max(0, 1-Z ) = 1-Z" }, { "code": null, "e": 7985, "s": 7974, "text": "Final Step" }, { "code": null, "e": 8011, "s": 7985, "text": "As we already know that -" }, { "code": null, "e": 8076, "s": 8011, "text": "Y(W^T * X + b) = 1 — ζ (Refer to Understanding Zeta sub-section)" }, { "code": null, "e": 8156, "s": 8076, "text": "So we can rewrite it as -1 - Y(W^T * X + b) = ζAnd Y(W^T * X + b) = ZSo 1-Z = ζ" }, { "code": null, "e": 8239, "s": 8156, "text": "And from the above cases we can see that the term that we want to minimise is 1-Z." }, { "code": null, "e": 8313, "s": 8239, "text": "This is exactly what we have written here. We just substituted 1-Z with ζ" }, { "code": null, "e": 8494, "s": 8313, "text": "The above Equation 1 that we derived is the primal form of SVM.However in order to leverage the power of kernels we use the dual form of SVMs.So let’s look at the dual form of SVM." }, { "code": null, "e": 8845, "s": 8494, "text": "The reason for using the dual form of SVM is that it allows us to leverage the power of kernels which is a key feature of SVM and if you are not familiar with kernels then don’t worry about it too much, I will explain kernels in the next section. But for now just understand that we use the dual form of SVM in order to leverage the power of kernels." }, { "code": null, "e": 8918, "s": 8845, "text": "It is proven mathematically that Equation 2 is equivalent to Equation 1." }, { "code": null, "e": 9147, "s": 8918, "text": "The mathematical proof of how we actually got to this dual form is beyond the scope of this article as it is a bit mathematically intense. If you want to understand the maths behind it then you can checkout the following video —" }, { "code": null, "e": 9333, "s": 9147, "text": "In this video Prof. Patrick Henry Winston provided a brilliant mathematical explanation and I would highly suggest that you checkout this video to better understand the concept of SVMs." }, { "code": null, "e": 9491, "s": 9333, "text": "The most important thing to note here is that the value of αi will be non-zero only for support vectors. So we basically only care about the support vectors." }, { "code": null, "e": 9533, "s": 9491, "text": "We can update our Equation 2 as follows —" }, { "code": null, "e": 9838, "s": 9533, "text": "Earlier we were using Xi^T . Xj i.e. we were taking the dot product of Xi and Xj which is equivalent to Cosine similarity function. So we can just replace this cosine similarity function with any other function of Xi and Xj.This is called the kernel trick. Now let’s understand what the hell is a kernel." }, { "code": null, "e": 10050, "s": 9838, "text": "In the above Equation 3, we can replace K with any kernel function. Now you must be wondering how does that change anything. Why does it even matter which function we use? So let’s try to answer those questions." }, { "code": null, "e": 10109, "s": 10050, "text": "Suppose you have a dataset that is not linearly separable." }, { "code": null, "e": 10233, "s": 10109, "text": "Now how would you use SVM to separate this data? There is no way that we can fit a plane that can separate these 2 classes." }, { "code": null, "e": 10251, "s": 10233, "text": "Enter Kernels...." }, { "code": null, "e": 10401, "s": 10251, "text": "The main use of a kernel function is that it allows us to project our dataset onto higher dimension where we can fit a plane to separate our dataset." }, { "code": null, "e": 10593, "s": 10401, "text": "So we can project our above dataset onto a higher dimension and then we can find a plane that can separate the 2 classes.This is exactly the reason why SVM was super popular in the early 90s." }, { "code": null, "e": 10635, "s": 10593, "text": "The 2 most popular types of kernels are —" }, { "code": null, "e": 10687, "s": 10635, "text": "Polynomial KernelRadial Basis Function (RBF) Kernel" }, { "code": null, "e": 10705, "s": 10687, "text": "Polynomial Kernel" }, { "code": null, "e": 10740, "s": 10705, "text": "Radial Basis Function (RBF) Kernel" }, { "code": null, "e": 10760, "s": 10740, "text": "Polynomial Kernel —" }, { "code": null, "e": 10821, "s": 10760, "text": "So for a quadratic kernel we will have something like this —" }, { "code": null, "e": 10834, "s": 10821, "text": "RBF Kernel —" }, { "code": null, "e": 10921, "s": 10834, "text": "Here d is the distance between x1 and x2 i.e. d = ||x1-x2|| and σ is a hyperparameter." }, { "code": null, "e": 11017, "s": 10921, "text": "nu is a hyperparameter that we can use for defining the percentage of error that is acceptable." }, { "code": null, "e": 11237, "s": 11017, "text": "0 <= nu <= 1 // The value of nu is between 0 and 1Let's understand it with an example.Suppose nu = 0.01 and N (Number of data points)= 100,000* Percentage of errors <= 1%* Number of Support Vectors >= 1% of N i.e. 1000" }, { "code": null, "e": 11296, "s": 11237, "text": "So with the help of nu hyperparameter we can do 2 things —" }, { "code": null, "e": 11347, "s": 11296, "text": "We can control the error percentage for our model." }, { "code": null, "e": 11416, "s": 11347, "text": "We can’t control but we can determine the number of support vectors." }, { "code": null, "e": 11500, "s": 11416, "text": "And with that we have come to the end of this article. Thanks a ton for reading it." }, { "code": null, "e": 11538, "s": 11500, "text": "You can clap if you want . IT’S FREE." } ]
Another Twitter sentiment analysis with Python-Part 2 | by Ricky Kim | Towards Data Science
This blog post is the second part of the Twitter sentiment analysis project I am currently doing for my capstone project in General Assembly London. You can find the first part here. Before I move on to EDA, and data visualisation, I have made some changes to the data cleaning part, due to the faults of the data cleaning function I defined in the previous post. The first issue I realised is that, during the cleaning process, negation words are split into two parts, and the ‘t’ after the apostrophe vanishes when I filter tokens with length more than one syllable. This makes words like “can’t” end up as same as “can”. This seems like not a trivial matter for sentiment analysis purpose. The second issue I realised is that, some of the url link doesn’t start with “http”, sometimes people paste link in “www.websitename.com" form. This wasn’t properly handled when I defined the url address regex pattern as ‘https?://[A-Za-z0–9./]+’. And another problem of this regex pattern is that it only detects alphabet, number, period, slash. This means it will fail to catch the part of the url, if it contains any other special character such as “=”, “_”, “~”, etc. The third issue is with the regex pattern for twitter ID. In the previous cleaning function I defined it as ‘@[A-Za-z0–9]+’, but with a little googling, I found out that twitter ID also allows underscore symbol as a character can be used with ID. Except for underscore symbol, only characters allowed are alphabets and numbers. Below is the updated datacleaning function. The order of the cleaning is SoupingBOM removingurl address(‘http:’pattern), twitter ID removingurl address(‘www.'pattern) removinglower-casenegation handlingremoving numbers and special characterstokenizing and joining Souping BOM removing url address(‘http:’pattern), twitter ID removing url address(‘www.'pattern) removing lower-case negation handling removing numbers and special characters tokenizing and joining import pandas as pd import numpy as npimport matplotlib.pyplot as pltplt.style.use('fivethirtyeight')%matplotlib inline%config InlineBackend.figure_format = 'retina'import refrom bs4 import BeautifulSoupfrom nltk.tokenize import WordPunctTokenizertok = WordPunctTokenizer()pat1 = r'@[A-Za-z0-9_]+'pat2 = r'https?://[^ ]+'combined_pat = r'|'.join((pat1, pat2))www_pat = r'www.[^ ]+'negations_dic = {"isn't":"is not", "aren't":"are not", "wasn't":"was not", "weren't":"were not", "haven't":"have not","hasn't":"has not","hadn't":"had not","won't":"will not", "wouldn't":"would not", "don't":"do not", "doesn't":"does not","didn't":"did not", "can't":"can not","couldn't":"could not","shouldn't":"should not","mightn't":"might not", "mustn't":"must not"}neg_pattern = re.compile(r'\b(' + '|'.join(negations_dic.keys()) + r')\b')def tweet_cleaner_updated(text): soup = BeautifulSoup(text, 'lxml') souped = soup.get_text() try: bom_removed = souped.decode("utf-8-sig").replace(u"\ufffd", "?") except: bom_removed = souped stripped = re.sub(combined_pat, '', bom_removed) stripped = re.sub(www_pat, '', stripped) lower_case = stripped.lower() neg_handled = neg_pattern.sub(lambda x: negations_dic[x.group()], lower_case) letters_only = re.sub("[^a-zA-Z]", " ", neg_handled) # During the letters_only process two lines above, it has created unnecessay white spaces, # I will tokenize and join together to remove unneccessary white spaces words = [x for x in tok.tokenize(letters_only) if len(x) > 1] return (" ".join(words)).strip() After I updated the cleaning function, I re-cleaned the whole 1.6 million entries in the dataset. You can find the detail of the cleaning process from my previous post. After the cleaning, I exported the cleaned data as csv, then load it as data frame, and it looks as below. csv = 'clean_tweet.csv'my_df = pd.read_csv(csv,index_col=0)my_df.head() my_df.info() It looks like there are some null entries in the data, let’s investigate further. my_df[my_df.isnull().any(axis=1)].head() np.sum(my_df.isnull().any(axis=1)) my_df.isnull().any(axis=0) It seems like 3,981 entries have null entries for text column. This is strange, because the original dataset had no null entries, thus if there are any null entries in the cleaned dataset, it must have happened during the cleaning process. df = pd.read_csv("./trainingandtestdata/training.1600000.processed.noemoticon.csv",header=None)df.iloc[my_df[my_df.isnull().any(axis=1)].index,:].head() By looking these entries in the original data, it seems like only text information they had was either twitter ID or url address. Anyway, these are the info I decided to discard for the sentiment analysis, so I will drop these null rows, and update the data frame. my_df.dropna(inplace=True)my_df.reset_index(drop=True,inplace=True)my_df.info() The first text visualisation I chose is the controversial word cloud. A word cloud represents word usage in a document by resizing individual words proportionally to its frequency, and then presenting them in random arrangement. There were a lot of debates around word cloud, and I somewhat agree to the points of people who are against using word cloud as data analysis. Some of the concerns over word cloud is that, it supports only the crudest sorts of textual analysis, and it is often applied to situations where textual analysis is not appropriate, and it leaves viewers to figure out the context of the data by themselves without providing the narrative. But in the case of tweets, textual analysis is the most important analysis, and it provides a general idea of what kind of words are frequent in the corpus, in a sort of quick and dirty way. So, I will give it a go, and figure out what other methods can be used for text visualisation. For the word cloud, I used the python library wordcloud. neg_tweets = my_df[my_df.target == 0]neg_string = []for t in neg_tweets.text: neg_string.append(t)neg_string = pd.Series(neg_string).str.cat(sep=' ')from wordcloud import WordCloudwordcloud = WordCloud(width=1600, height=800,max_font_size=200).generate(neg_string)plt.figure(figsize=(12,10))plt.imshow(wordcloud, interpolation="bilinear")plt.axis("off")plt.show() Some of big words can be interpreted quite neutral, such as “today”,”now”,etc. I can see some of the words in smaller size make sense to be in negative tweets, such as “damn”,”ugh”,”miss”,”bad”, etc. But there is “love” in rather big size, so I wanted to see what is happening. for t in neg_tweets.text[:200]: if 'love' in t: print t OK, even though the tweets contain the word “love”, in these cases it is negative sentiment, because the tweet has mixed emotions like “love” but “miss”. Or sometimes used in a sarcastic way. pos_tweets = my_df[my_df.target == 1]pos_string = []for t in pos_tweets.text: pos_string.append(t)pos_string = pd.Series(pos_string).str.cat(sep=' ')wordcloud = WordCloud(width=1600, height=800,max_font_size=200,colormap='magma').generate(pos_string) plt.figure(figsize=(12,10)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") plt.show() Again I see some netural words in big size, “today”,”now”, but words like “haha”, “love”, “awesome” also stand out. Interestingly, the word “work” was quite big in negative word cloud, but also quite big in positive word cloud. It might implies that many people express negative sentiment towards work, but also many people are positive about works. In order for me to implement a couple of data visualisation in the next step, I need term frequency data. What kind of words are used in the tweets, and how many times it is used in entire corpus. I used count vectorizer to calculate the term frequencies, even though the count vectorizer is also for fit, train and predict, but at this stage, I will just be extracting the term frequencies for the visualisation. There are parameter options available for count vectorizer, such as removing stop words, limiting the maximum number of terms. However, in order to get a full picture of the dataset first, I implemented with stop words included, and not limiting the maximum number of terms. from sklearn.feature_extraction.text import CountVectorizercvec = CountVectorizer()cvec.fit(my_df.text) len(cvec.get_feature_names()) OK, it looks like the count vectorizer has extracted 264,936 words out of the corpus. !Important update (10/01/2018): I just realised that I didn’t have to go through all the batching I did below. Yes! All the batching and computation I did below can be done in much less lines of code (not exactly one line though). Once you transform the data with the fitted count vectorizer, you can directly get the term frequency from the sparse matrix. And all this can be done in less than a second! If you read below, you can see I spent almost 40mins to get the term frequency table. I guess I learned this lesson the hardest way possible. The code for getting the term frequency directly from sparse matrix is as below. neg_doc_matrix = cvec.transform(my_df[my_df.target == 0].text)pos_doc_matrix = cvec.transform(my_df[my_df.target == 1].text)neg_tf = np.sum(neg_doc_matrix,axis=0)pos_tf = np.sum(pos_doc_matrix,axis=0)neg = np.squeeze(np.asarray(neg_tf))pos = np.squeeze(np.asarray(pos_tf))term_freq_df = pd.DataFrame([neg,pos],columns=cvec.get_feature_names()).transpose() I will leave below as I have originally written, as a reminder of my own stupidity for myself. The moral of the story is, if you can work directly with sparse matrix, you should definitely do it without transforming into dense matrix! For below part, I had to go through many trial and errors, because of the memory usage overload. If the code takes time to implement, but still running, it is OK, but it was not the matter of how long it takes the block to run, my mac book pro just simply gave up and either killed the kernel or froze. After numerous attempts, I have finally succeded in processing the data in batches. The mistake I kept making was, when I slice the document matrix, I tried to slice it in ‘document_matrix.toarray()[start_index,end_index]’, and I finally realised because I was trying to first convert whole documnet_matrix to array, and then slice from there, no matter how I change the batch size, my poor macbook pro couldn’t handle the request. After I change my slicing to ‘document_matrix[start_index,end_index].toarray()’, my mac book pro did a wonderful job for me. Also your mac book can be an excellent lap warmer for cold winter days during the processing of the below task. In Asia, we call this “two birds with one stone”. You’re welcome. document_matrix = cvec.transform(my_df.text)my_df[my_df.target == 0].tail() %%timeneg_batches = np.linspace(0,798179,100).astype(int)i=0neg_tf = []while i < len(neg_batches)-1: batch_result = np.sum(document_matrix[neg_batches[i]:neg_batches[i+1]].toarray(),axis=0) neg_tf.append(batch_result) if (i % 10 == 0) | (i == len(neg_batches)-2): print neg_batches[i+1],"entries' term freuquency calculated" i += 1 my_df.tail() %%timepos_batches = np.linspace(798179,1596019,100).astype(int)i=0pos_tf = []while i < len(pos_batches)-1: batch_result = np.sum(document_matrix[pos_batches[i]:pos_batches[i+1]].toarray(),axis=0) pos_tf.append(batch_result) if (i % 10 == 0) | (i == len(pos_batches)-2): print pos_batches[i+1],"entries' term freuquency calculated" i += 1 neg = np.sum(neg_tf,axis=0)pos = np.sum(pos_tf,axis=0)term_freq_df = pd.DataFrame([neg,pos],columns=cvec.get_feature_names()).transpose()term_freq_df.head() term_freq_df.columns = ['negative', 'positive']term_freq_df['total'] = term_freq_df['negative'] + term_freq_df['positive']term_freq_df.sort_values(by='total', ascending=False).iloc[:10] OK, the term frequency data frame has been created! And as you can see the most frequent words are all stop words like “to”, “the”, etc. You might wonder why go through all the heavy processing without removing the stop words and not limiting the maximum terms, to get term frequency dominated by stop words? It is because I really want to test Zipf’s law with the result I got from the above. I need the stop words! You will see what I mean. I will tell you more about Zipf’s law in the next post, and I promise there will be more visualisation. You will see that above term frequency calculation wasn’t for nothing. As always, you can find the Jupyter notebook from below link.
[ { "code": null, "e": 355, "s": 172, "text": "This blog post is the second part of the Twitter sentiment analysis project I am currently doing for my capstone project in General Assembly London. You can find the first part here." }, { "code": null, "e": 536, "s": 355, "text": "Before I move on to EDA, and data visualisation, I have made some changes to the data cleaning part, due to the faults of the data cleaning function I defined in the previous post." }, { "code": null, "e": 865, "s": 536, "text": "The first issue I realised is that, during the cleaning process, negation words are split into two parts, and the ‘t’ after the apostrophe vanishes when I filter tokens with length more than one syllable. This makes words like “can’t” end up as same as “can”. This seems like not a trivial matter for sentiment analysis purpose." }, { "code": null, "e": 1337, "s": 865, "text": "The second issue I realised is that, some of the url link doesn’t start with “http”, sometimes people paste link in “www.websitename.com\" form. This wasn’t properly handled when I defined the url address regex pattern as ‘https?://[A-Za-z0–9./]+’. And another problem of this regex pattern is that it only detects alphabet, number, period, slash. This means it will fail to catch the part of the url, if it contains any other special character such as “=”, “_”, “~”, etc." }, { "code": null, "e": 1665, "s": 1337, "text": "The third issue is with the regex pattern for twitter ID. In the previous cleaning function I defined it as ‘@[A-Za-z0–9]+’, but with a little googling, I found out that twitter ID also allows underscore symbol as a character can be used with ID. Except for underscore symbol, only characters allowed are alphabets and numbers." }, { "code": null, "e": 1738, "s": 1665, "text": "Below is the updated datacleaning function. The order of the cleaning is" }, { "code": null, "e": 1929, "s": 1738, "text": "SoupingBOM removingurl address(‘http:’pattern), twitter ID removingurl address(‘www.'pattern) removinglower-casenegation handlingremoving numbers and special characterstokenizing and joining" }, { "code": null, "e": 1937, "s": 1929, "text": "Souping" }, { "code": null, "e": 1950, "s": 1937, "text": "BOM removing" }, { "code": null, "e": 1999, "s": 1950, "text": "url address(‘http:’pattern), twitter ID removing" }, { "code": null, "e": 2035, "s": 1999, "text": "url address(‘www.'pattern) removing" }, { "code": null, "e": 2046, "s": 2035, "text": "lower-case" }, { "code": null, "e": 2064, "s": 2046, "text": "negation handling" }, { "code": null, "e": 2104, "s": 2064, "text": "removing numbers and special characters" }, { "code": null, "e": 2127, "s": 2104, "text": "tokenizing and joining" }, { "code": null, "e": 3768, "s": 2127, "text": "import pandas as pd import numpy as npimport matplotlib.pyplot as pltplt.style.use('fivethirtyeight')%matplotlib inline%config InlineBackend.figure_format = 'retina'import refrom bs4 import BeautifulSoupfrom nltk.tokenize import WordPunctTokenizertok = WordPunctTokenizer()pat1 = r'@[A-Za-z0-9_]+'pat2 = r'https?://[^ ]+'combined_pat = r'|'.join((pat1, pat2))www_pat = r'www.[^ ]+'negations_dic = {\"isn't\":\"is not\", \"aren't\":\"are not\", \"wasn't\":\"was not\", \"weren't\":\"were not\", \"haven't\":\"have not\",\"hasn't\":\"has not\",\"hadn't\":\"had not\",\"won't\":\"will not\", \"wouldn't\":\"would not\", \"don't\":\"do not\", \"doesn't\":\"does not\",\"didn't\":\"did not\", \"can't\":\"can not\",\"couldn't\":\"could not\",\"shouldn't\":\"should not\",\"mightn't\":\"might not\", \"mustn't\":\"must not\"}neg_pattern = re.compile(r'\\b(' + '|'.join(negations_dic.keys()) + r')\\b')def tweet_cleaner_updated(text): soup = BeautifulSoup(text, 'lxml') souped = soup.get_text() try: bom_removed = souped.decode(\"utf-8-sig\").replace(u\"\\ufffd\", \"?\") except: bom_removed = souped stripped = re.sub(combined_pat, '', bom_removed) stripped = re.sub(www_pat, '', stripped) lower_case = stripped.lower() neg_handled = neg_pattern.sub(lambda x: negations_dic[x.group()], lower_case) letters_only = re.sub(\"[^a-zA-Z]\", \" \", neg_handled) # During the letters_only process two lines above, it has created unnecessay white spaces, # I will tokenize and join together to remove unneccessary white spaces words = [x for x in tok.tokenize(letters_only) if len(x) > 1] return (\" \".join(words)).strip()" }, { "code": null, "e": 3937, "s": 3768, "text": "After I updated the cleaning function, I re-cleaned the whole 1.6 million entries in the dataset. You can find the detail of the cleaning process from my previous post." }, { "code": null, "e": 4044, "s": 3937, "text": "After the cleaning, I exported the cleaned data as csv, then load it as data frame, and it looks as below." }, { "code": null, "e": 4116, "s": 4044, "text": "csv = 'clean_tweet.csv'my_df = pd.read_csv(csv,index_col=0)my_df.head()" }, { "code": null, "e": 4129, "s": 4116, "text": "my_df.info()" }, { "code": null, "e": 4211, "s": 4129, "text": "It looks like there are some null entries in the data, let’s investigate further." }, { "code": null, "e": 4252, "s": 4211, "text": "my_df[my_df.isnull().any(axis=1)].head()" }, { "code": null, "e": 4287, "s": 4252, "text": "np.sum(my_df.isnull().any(axis=1))" }, { "code": null, "e": 4314, "s": 4287, "text": "my_df.isnull().any(axis=0)" }, { "code": null, "e": 4554, "s": 4314, "text": "It seems like 3,981 entries have null entries for text column. This is strange, because the original dataset had no null entries, thus if there are any null entries in the cleaned dataset, it must have happened during the cleaning process." }, { "code": null, "e": 4707, "s": 4554, "text": "df = pd.read_csv(\"./trainingandtestdata/training.1600000.processed.noemoticon.csv\",header=None)df.iloc[my_df[my_df.isnull().any(axis=1)].index,:].head()" }, { "code": null, "e": 4972, "s": 4707, "text": "By looking these entries in the original data, it seems like only text information they had was either twitter ID or url address. Anyway, these are the info I decided to discard for the sentiment analysis, so I will drop these null rows, and update the data frame." }, { "code": null, "e": 5052, "s": 4972, "text": "my_df.dropna(inplace=True)my_df.reset_index(drop=True,inplace=True)my_df.info()" }, { "code": null, "e": 5714, "s": 5052, "text": "The first text visualisation I chose is the controversial word cloud. A word cloud represents word usage in a document by resizing individual words proportionally to its frequency, and then presenting them in random arrangement. There were a lot of debates around word cloud, and I somewhat agree to the points of people who are against using word cloud as data analysis. Some of the concerns over word cloud is that, it supports only the crudest sorts of textual analysis, and it is often applied to situations where textual analysis is not appropriate, and it leaves viewers to figure out the context of the data by themselves without providing the narrative." }, { "code": null, "e": 6000, "s": 5714, "text": "But in the case of tweets, textual analysis is the most important analysis, and it provides a general idea of what kind of words are frequent in the corpus, in a sort of quick and dirty way. So, I will give it a go, and figure out what other methods can be used for text visualisation." }, { "code": null, "e": 6057, "s": 6000, "text": "For the word cloud, I used the python library wordcloud." }, { "code": null, "e": 6424, "s": 6057, "text": "neg_tweets = my_df[my_df.target == 0]neg_string = []for t in neg_tweets.text: neg_string.append(t)neg_string = pd.Series(neg_string).str.cat(sep=' ')from wordcloud import WordCloudwordcloud = WordCloud(width=1600, height=800,max_font_size=200).generate(neg_string)plt.figure(figsize=(12,10))plt.imshow(wordcloud, interpolation=\"bilinear\")plt.axis(\"off\")plt.show()" }, { "code": null, "e": 6702, "s": 6424, "text": "Some of big words can be interpreted quite neutral, such as “today”,”now”,etc. I can see some of the words in smaller size make sense to be in negative tweets, such as “damn”,”ugh”,”miss”,”bad”, etc. But there is “love” in rather big size, so I wanted to see what is happening." }, { "code": null, "e": 6768, "s": 6702, "text": "for t in neg_tweets.text[:200]: if 'love' in t: print t" }, { "code": null, "e": 6960, "s": 6768, "text": "OK, even though the tweets contain the word “love”, in these cases it is negative sentiment, because the tweet has mixed emotions like “love” but “miss”. Or sometimes used in a sarcastic way." }, { "code": null, "e": 7317, "s": 6960, "text": "pos_tweets = my_df[my_df.target == 1]pos_string = []for t in pos_tweets.text: pos_string.append(t)pos_string = pd.Series(pos_string).str.cat(sep=' ')wordcloud = WordCloud(width=1600, height=800,max_font_size=200,colormap='magma').generate(pos_string) plt.figure(figsize=(12,10)) plt.imshow(wordcloud, interpolation=\"bilinear\") plt.axis(\"off\") plt.show()" }, { "code": null, "e": 7433, "s": 7317, "text": "Again I see some netural words in big size, “today”,”now”, but words like “haha”, “love”, “awesome” also stand out." }, { "code": null, "e": 7667, "s": 7433, "text": "Interestingly, the word “work” was quite big in negative word cloud, but also quite big in positive word cloud. It might implies that many people express negative sentiment towards work, but also many people are positive about works." }, { "code": null, "e": 8081, "s": 7667, "text": "In order for me to implement a couple of data visualisation in the next step, I need term frequency data. What kind of words are used in the tweets, and how many times it is used in entire corpus. I used count vectorizer to calculate the term frequencies, even though the count vectorizer is also for fit, train and predict, but at this stage, I will just be extracting the term frequencies for the visualisation." }, { "code": null, "e": 8356, "s": 8081, "text": "There are parameter options available for count vectorizer, such as removing stop words, limiting the maximum number of terms. However, in order to get a full picture of the dataset first, I implemented with stop words included, and not limiting the maximum number of terms." }, { "code": null, "e": 8460, "s": 8356, "text": "from sklearn.feature_extraction.text import CountVectorizercvec = CountVectorizer()cvec.fit(my_df.text)" }, { "code": null, "e": 8490, "s": 8460, "text": "len(cvec.get_feature_names())" }, { "code": null, "e": 8576, "s": 8490, "text": "OK, it looks like the count vectorizer has extracted 264,936 words out of the corpus." }, { "code": null, "e": 8687, "s": 8576, "text": "!Important update (10/01/2018): I just realised that I didn’t have to go through all the batching I did below." }, { "code": null, "e": 9204, "s": 8687, "text": "Yes! All the batching and computation I did below can be done in much less lines of code (not exactly one line though). Once you transform the data with the fitted count vectorizer, you can directly get the term frequency from the sparse matrix. And all this can be done in less than a second! If you read below, you can see I spent almost 40mins to get the term frequency table. I guess I learned this lesson the hardest way possible. The code for getting the term frequency directly from sparse matrix is as below." }, { "code": null, "e": 9560, "s": 9204, "text": "neg_doc_matrix = cvec.transform(my_df[my_df.target == 0].text)pos_doc_matrix = cvec.transform(my_df[my_df.target == 1].text)neg_tf = np.sum(neg_doc_matrix,axis=0)pos_tf = np.sum(pos_doc_matrix,axis=0)neg = np.squeeze(np.asarray(neg_tf))pos = np.squeeze(np.asarray(pos_tf))term_freq_df = pd.DataFrame([neg,pos],columns=cvec.get_feature_names()).transpose()" }, { "code": null, "e": 9795, "s": 9560, "text": "I will leave below as I have originally written, as a reminder of my own stupidity for myself. The moral of the story is, if you can work directly with sparse matrix, you should definitely do it without transforming into dense matrix!" }, { "code": null, "e": 10182, "s": 9795, "text": "For below part, I had to go through many trial and errors, because of the memory usage overload. If the code takes time to implement, but still running, it is OK, but it was not the matter of how long it takes the block to run, my mac book pro just simply gave up and either killed the kernel or froze. After numerous attempts, I have finally succeded in processing the data in batches." }, { "code": null, "e": 10655, "s": 10182, "text": "The mistake I kept making was, when I slice the document matrix, I tried to slice it in ‘document_matrix.toarray()[start_index,end_index]’, and I finally realised because I was trying to first convert whole documnet_matrix to array, and then slice from there, no matter how I change the batch size, my poor macbook pro couldn’t handle the request. After I change my slicing to ‘document_matrix[start_index,end_index].toarray()’, my mac book pro did a wonderful job for me." }, { "code": null, "e": 10833, "s": 10655, "text": "Also your mac book can be an excellent lap warmer for cold winter days during the processing of the below task. In Asia, we call this “two birds with one stone”. You’re welcome." }, { "code": null, "e": 10909, "s": 10833, "text": "document_matrix = cvec.transform(my_df.text)my_df[my_df.target == 0].tail()" }, { "code": null, "e": 11260, "s": 10909, "text": "%%timeneg_batches = np.linspace(0,798179,100).astype(int)i=0neg_tf = []while i < len(neg_batches)-1: batch_result = np.sum(document_matrix[neg_batches[i]:neg_batches[i+1]].toarray(),axis=0) neg_tf.append(batch_result) if (i % 10 == 0) | (i == len(neg_batches)-2): print neg_batches[i+1],\"entries' term freuquency calculated\" i += 1" }, { "code": null, "e": 11273, "s": 11260, "text": "my_df.tail()" }, { "code": null, "e": 11630, "s": 11273, "text": "%%timepos_batches = np.linspace(798179,1596019,100).astype(int)i=0pos_tf = []while i < len(pos_batches)-1: batch_result = np.sum(document_matrix[pos_batches[i]:pos_batches[i+1]].toarray(),axis=0) pos_tf.append(batch_result) if (i % 10 == 0) | (i == len(pos_batches)-2): print pos_batches[i+1],\"entries' term freuquency calculated\" i += 1" }, { "code": null, "e": 11787, "s": 11630, "text": "neg = np.sum(neg_tf,axis=0)pos = np.sum(pos_tf,axis=0)term_freq_df = pd.DataFrame([neg,pos],columns=cvec.get_feature_names()).transpose()term_freq_df.head()" }, { "code": null, "e": 11973, "s": 11787, "text": "term_freq_df.columns = ['negative', 'positive']term_freq_df['total'] = term_freq_df['negative'] + term_freq_df['positive']term_freq_df.sort_values(by='total', ascending=False).iloc[:10]" }, { "code": null, "e": 12416, "s": 11973, "text": "OK, the term frequency data frame has been created! And as you can see the most frequent words are all stop words like “to”, “the”, etc. You might wonder why go through all the heavy processing without removing the stop words and not limiting the maximum terms, to get term frequency dominated by stop words? It is because I really want to test Zipf’s law with the result I got from the above. I need the stop words! You will see what I mean." }, { "code": null, "e": 12591, "s": 12416, "text": "I will tell you more about Zipf’s law in the next post, and I promise there will be more visualisation. You will see that above term frequency calculation wasn’t for nothing." } ]
How to create a table from view in MySQL?
To create a table from the view below is the syntax − create table yourTableName select *from yourViewName; Let us first create a table − mysql> create table DemoTable830(Name varchar(100)); Query OK, 0 rows affected (0.91 sec) Insert some records in the table using insert command − mysql> insert into DemoTable830 values('Chris'); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable830 values('Robert'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable830 values('David'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable830 values('Mike'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select *from DemoTable830; This will produce the following output − +--------+ | Name | +--------+ | Chris | | Robert | | David | | Mike | +--------+ 4 rows in set (0.00 sec) Following is the query to create a view − mysql> create view table_view AS select *from DemoTable830; Query OK, 0 rows affected (0.39 sec) Now, we will create a table from view. Following is the query − mysql> create table DemoTable831 select *from table_view; Query OK, 4 rows affected (1.64 sec) Records: 4 Duplicates: 0 Warnings: 0 Let us check the records of the table which has been created from the view − mysql> select *from DemoTable831; This will produce the following output − +--------+ | Name | +--------+ | Chris | | Robert | | David | | Mike | +--------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1116, "s": 1062, "text": "To create a table from the view below is the syntax −" }, { "code": null, "e": 1170, "s": 1116, "text": "create table yourTableName select *from yourViewName;" }, { "code": null, "e": 1200, "s": 1170, "text": "Let us first create a table −" }, { "code": null, "e": 1290, "s": 1200, "text": "mysql> create table DemoTable830(Name varchar(100));\nQuery OK, 0 rows affected (0.91 sec)" }, { "code": null, "e": 1346, "s": 1290, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1686, "s": 1346, "text": "mysql> insert into DemoTable830 values('Chris');\nQuery OK, 1 row affected (0.41 sec)\nmysql> insert into DemoTable830 values('Robert');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable830 values('David');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable830 values('Mike');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 1746, "s": 1686, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1780, "s": 1746, "text": "mysql> select *from DemoTable830;" }, { "code": null, "e": 1821, "s": 1780, "text": "This will produce the following output −" }, { "code": null, "e": 1934, "s": 1821, "text": "+--------+\n| Name |\n+--------+\n| Chris |\n| Robert |\n| David |\n| Mike |\n+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1976, "s": 1934, "text": "Following is the query to create a view −" }, { "code": null, "e": 2073, "s": 1976, "text": "mysql> create view table_view AS select *from DemoTable830;\nQuery OK, 0 rows affected (0.39 sec)" }, { "code": null, "e": 2137, "s": 2073, "text": "Now, we will create a table from view. Following is the query −" }, { "code": null, "e": 2269, "s": 2137, "text": "mysql> create table DemoTable831 select *from table_view;\nQuery OK, 4 rows affected (1.64 sec)\nRecords: 4 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2346, "s": 2269, "text": "Let us check the records of the table which has been created from the view −" }, { "code": null, "e": 2380, "s": 2346, "text": "mysql> select *from DemoTable831;" }, { "code": null, "e": 2421, "s": 2380, "text": "This will produce the following output −" }, { "code": null, "e": 2534, "s": 2421, "text": "+--------+\n| Name |\n+--------+\n| Chris |\n| Robert |\n| David |\n| Mike |\n+--------+\n4 rows in set (0.00 sec)" } ]
How to measure the goodness of a regression model | by Gianluca Malato | Towards Data Science
Regression models are very useful and widely used in machine learning. However, they might show some problems when comes to measure the goodness of a trained model. While classification models have some standard tools that can be used to assess their performance (i.e. area under the ROC curve, confusion matrix, F-1 score etc.), regression models’ performance can be measured in many different ways. In this article, I’ll show you some techniques I’ve used in my experience as a Data Scientist. In this example, I’ll show you how to measure the goodness of a trained model using the famous iris dataset. I’ll use a linear regression model to predict the value of the Sepal Length as a function of the other variables. First, we’ll load the iris dataset and split it in training and holdout. data(iris)set.seed(1)training_idx = sample(1:nrow(iris),nrow(iris)*0.8,replace=FALSE)holdout_idx = setdiff(1:nrow(iris),training_idx)training = iris[training_idx,]holdout = iris[holdout_idx,] Then we can perform a simple linear regression in order to describe the variable Sepal.Length as a linear function of the others. This is the model we want to check the goodness of. m = lm(Sepal.Length ~ .,training) All we need to do now is compare the residuals in the training set with the residuals in the holdout. Remember that the residuals are the differences between the real value and the predicted value. training_res = training$Sepal.Length - predict(m,training)holdout_res = holdout$Sepal.Length - predict(m,holdout) If our training procedure has produced overfitting, the residuals in the training set will be very small compared with the residuals in the holdout. That’s a negative signal that should invite us to simplify the model or remove some variables. Let’s now perform some statistical checks. The first thing we have to check is whether the residuals are biased or not. We know from elementary statistics that the mean value of the residuals is zero, so we can start checking with a Student’s t-test if it’s true or not for our holdout sample. t.test(holdout_res,mu=0) As we can see, the p-value is greater than 5%, so we cannot reject the null hypothesis and can say that the mean value of the holdout residuals is statistically similar to 0. Then, we can test if the holdout residuals have the same average as the training ones. This is called Welch’s t-test. t.test(training_res,holdout_res) Again, a p-value higher than 5% can make us tell that there aren’t enough reasons to assume that the mean values are different. After we have checked the mean value, there comes the variance. We obviously want that the holdout residuals show a behavior not so much different from the training residuals, so we can compare the variances of the two sets and check whether the holdout variance is higher than the training variance. A good test to check if a variance is greater than another one is the F-test, but it only works with normally distributed residuals. If the distribution is not normal, the test might give wrong results. So, if we really want to use this test, we must check the normality of the residuals using (for example) a Shapiro-Wilk test. Both p-values are higher than 5%, so we can say that both sets show normally distributed residuals. We can safely go on performing the F-test. var.test(training_res,holdout_res) The p-value is 72%, which is greater than 5% and allows us to say that the two sets have the same variance. KS test is very general and useful for many situations. Generally speaking, we expect that, if our model works well, the probability distribution of the holdout residuals is similar to the probability distribution of the training residuals. The KS test has been created to compare probability distributions, so it can be used for this purpose. However, it carries some approximations that can be dangerous to our analysis. Significative differences between probability distributions can be hidden in the general considerations made by the test. Last, KS distribution is known only with some kind of approximation and, consequently, the p-value; so I suggest to use this test with care. ks.test(training_res,holdout_res) Again, the large p-value can make us tell that the two distributions are the same. A Professor of mine at the University usually said: “you have to look at data by your eyes”. In machine learning, it’s definitely true. The best way to take a look at a regression data is by plotting the predicted values against the real values in the holdout set. In a perfect condition, we expect that the points lie on the 45 degrees line passing through the origin (y = x is the equation). The nearer the points to this line, the better the regression. If our data make a shapeless blob in the Cartesian plane, there is definitely something wrong. plot(holdout$Sepal.Length,predict(m,holdout))abline(0,1) Well, it could have been better, but it’s not completely wrong. Points lie approximatively on the straight line. Finally, we can calculate a linear regression line from the previous plot and check if its intercept is statistically different from zero and its slope is statistically different from 1. To perform these checks, we can use a simple linear model and the statistical theory behind the Student’s t-test. Remember the definition of the t variable with n-1 degrees of freedom: When we use the summarize function of R on a linear model, it gives us the estimates of the parameters and their standard errors (i.e. the complete denominator of the t definition). For the intercept, we have mu = 0, while the slope has mu = 1. test_model = lm(real ~ predicted, data.frame(real=holdout$Sepal.Length,predicted=predict(m,holdout)))s = summary(test_model)intercept = s$coefficients["(Intercept)","Estimate"]intercept_error = s$coefficients["(Intercept)","Std. Error"]slope = s$coefficients["predicted","Estimate"]slope_error = s$coefficients["predicted","Std. Error"]t_intercept = intercept/intercept_errort_slope = (slope-1)/slope_error Now we have the t values, so we can perform a two-sided t-test in order to calculate the p-values. They are greater than 5% but not too high in absolute value. As usual, it depends on the problem. If the residuals are normally distributed, t-test and F-test are enough. If they are not, maybe a first plot can help us discover a macroscopic bias before using a Kolmogorov-Smirnov test. However, non-normally distributed residuals should always raise an alarm in our head and make us search for some hidden phenomenon we haven’t considered yet. In this short article, I’ve shown you some methods to calculate the goodness of a regression model. Though there are many possible ways to measure it, these simple techniques can be very useful in many situations and easily explainable to a non-technical audience.
[ { "code": null, "e": 668, "s": 172, "text": "Regression models are very useful and widely used in machine learning. However, they might show some problems when comes to measure the goodness of a trained model. While classification models have some standard tools that can be used to assess their performance (i.e. area under the ROC curve, confusion matrix, F-1 score etc.), regression models’ performance can be measured in many different ways. In this article, I’ll show you some techniques I’ve used in my experience as a Data Scientist." }, { "code": null, "e": 891, "s": 668, "text": "In this example, I’ll show you how to measure the goodness of a trained model using the famous iris dataset. I’ll use a linear regression model to predict the value of the Sepal Length as a function of the other variables." }, { "code": null, "e": 964, "s": 891, "text": "First, we’ll load the iris dataset and split it in training and holdout." }, { "code": null, "e": 1156, "s": 964, "text": "data(iris)set.seed(1)training_idx = sample(1:nrow(iris),nrow(iris)*0.8,replace=FALSE)holdout_idx = setdiff(1:nrow(iris),training_idx)training = iris[training_idx,]holdout = iris[holdout_idx,]" }, { "code": null, "e": 1338, "s": 1156, "text": "Then we can perform a simple linear regression in order to describe the variable Sepal.Length as a linear function of the others. This is the model we want to check the goodness of." }, { "code": null, "e": 1372, "s": 1338, "text": "m = lm(Sepal.Length ~ .,training)" }, { "code": null, "e": 1570, "s": 1372, "text": "All we need to do now is compare the residuals in the training set with the residuals in the holdout. Remember that the residuals are the differences between the real value and the predicted value." }, { "code": null, "e": 1684, "s": 1570, "text": "training_res = training$Sepal.Length - predict(m,training)holdout_res = holdout$Sepal.Length - predict(m,holdout)" }, { "code": null, "e": 1928, "s": 1684, "text": "If our training procedure has produced overfitting, the residuals in the training set will be very small compared with the residuals in the holdout. That’s a negative signal that should invite us to simplify the model or remove some variables." }, { "code": null, "e": 1971, "s": 1928, "text": "Let’s now perform some statistical checks." }, { "code": null, "e": 2222, "s": 1971, "text": "The first thing we have to check is whether the residuals are biased or not. We know from elementary statistics that the mean value of the residuals is zero, so we can start checking with a Student’s t-test if it’s true or not for our holdout sample." }, { "code": null, "e": 2247, "s": 2222, "text": "t.test(holdout_res,mu=0)" }, { "code": null, "e": 2422, "s": 2247, "text": "As we can see, the p-value is greater than 5%, so we cannot reject the null hypothesis and can say that the mean value of the holdout residuals is statistically similar to 0." }, { "code": null, "e": 2540, "s": 2422, "text": "Then, we can test if the holdout residuals have the same average as the training ones. This is called Welch’s t-test." }, { "code": null, "e": 2573, "s": 2540, "text": "t.test(training_res,holdout_res)" }, { "code": null, "e": 2701, "s": 2573, "text": "Again, a p-value higher than 5% can make us tell that there aren’t enough reasons to assume that the mean values are different." }, { "code": null, "e": 3002, "s": 2701, "text": "After we have checked the mean value, there comes the variance. We obviously want that the holdout residuals show a behavior not so much different from the training residuals, so we can compare the variances of the two sets and check whether the holdout variance is higher than the training variance." }, { "code": null, "e": 3205, "s": 3002, "text": "A good test to check if a variance is greater than another one is the F-test, but it only works with normally distributed residuals. If the distribution is not normal, the test might give wrong results." }, { "code": null, "e": 3331, "s": 3205, "text": "So, if we really want to use this test, we must check the normality of the residuals using (for example) a Shapiro-Wilk test." }, { "code": null, "e": 3474, "s": 3331, "text": "Both p-values are higher than 5%, so we can say that both sets show normally distributed residuals. We can safely go on performing the F-test." }, { "code": null, "e": 3509, "s": 3474, "text": "var.test(training_res,holdout_res)" }, { "code": null, "e": 3617, "s": 3509, "text": "The p-value is 72%, which is greater than 5% and allows us to say that the two sets have the same variance." }, { "code": null, "e": 4303, "s": 3617, "text": "KS test is very general and useful for many situations. Generally speaking, we expect that, if our model works well, the probability distribution of the holdout residuals is similar to the probability distribution of the training residuals. The KS test has been created to compare probability distributions, so it can be used for this purpose. However, it carries some approximations that can be dangerous to our analysis. Significative differences between probability distributions can be hidden in the general considerations made by the test. Last, KS distribution is known only with some kind of approximation and, consequently, the p-value; so I suggest to use this test with care." }, { "code": null, "e": 4337, "s": 4303, "text": "ks.test(training_res,holdout_res)" }, { "code": null, "e": 4420, "s": 4337, "text": "Again, the large p-value can make us tell that the two distributions are the same." }, { "code": null, "e": 4556, "s": 4420, "text": "A Professor of mine at the University usually said: “you have to look at data by your eyes”. In machine learning, it’s definitely true." }, { "code": null, "e": 4972, "s": 4556, "text": "The best way to take a look at a regression data is by plotting the predicted values against the real values in the holdout set. In a perfect condition, we expect that the points lie on the 45 degrees line passing through the origin (y = x is the equation). The nearer the points to this line, the better the regression. If our data make a shapeless blob in the Cartesian plane, there is definitely something wrong." }, { "code": null, "e": 5029, "s": 4972, "text": "plot(holdout$Sepal.Length,predict(m,holdout))abline(0,1)" }, { "code": null, "e": 5142, "s": 5029, "text": "Well, it could have been better, but it’s not completely wrong. Points lie approximatively on the straight line." }, { "code": null, "e": 5443, "s": 5142, "text": "Finally, we can calculate a linear regression line from the previous plot and check if its intercept is statistically different from zero and its slope is statistically different from 1. To perform these checks, we can use a simple linear model and the statistical theory behind the Student’s t-test." }, { "code": null, "e": 5514, "s": 5443, "text": "Remember the definition of the t variable with n-1 degrees of freedom:" }, { "code": null, "e": 5696, "s": 5514, "text": "When we use the summarize function of R on a linear model, it gives us the estimates of the parameters and their standard errors (i.e. the complete denominator of the t definition)." }, { "code": null, "e": 5759, "s": 5696, "text": "For the intercept, we have mu = 0, while the slope has mu = 1." }, { "code": null, "e": 6167, "s": 5759, "text": "test_model = lm(real ~ predicted, data.frame(real=holdout$Sepal.Length,predicted=predict(m,holdout)))s = summary(test_model)intercept = s$coefficients[\"(Intercept)\",\"Estimate\"]intercept_error = s$coefficients[\"(Intercept)\",\"Std. Error\"]slope = s$coefficients[\"predicted\",\"Estimate\"]slope_error = s$coefficients[\"predicted\",\"Std. Error\"]t_intercept = intercept/intercept_errort_slope = (slope-1)/slope_error" }, { "code": null, "e": 6266, "s": 6167, "text": "Now we have the t values, so we can perform a two-sided t-test in order to calculate the p-values." }, { "code": null, "e": 6327, "s": 6266, "text": "They are greater than 5% but not too high in absolute value." }, { "code": null, "e": 6553, "s": 6327, "text": "As usual, it depends on the problem. If the residuals are normally distributed, t-test and F-test are enough. If they are not, maybe a first plot can help us discover a macroscopic bias before using a Kolmogorov-Smirnov test." }, { "code": null, "e": 6711, "s": 6553, "text": "However, non-normally distributed residuals should always raise an alarm in our head and make us search for some hidden phenomenon we haven’t considered yet." } ]
What is the difference between a Java method and a native method?
A native method is the one whose method implementation is done in other languages like c++ and Java. These programs are linked to Java using JNI or JNA interfaces. The difference between normal method and native method is That the native method declaration contains native keyword and, the implementation of the method will be other programming language. public class Tester { public native int getValue(int i); public static void main(String[] args) { System.loadLibrary("Tester"); System.out.println(new Tester().getValue(2)); } } #include <jni.h> #include "Tester.h" JNIEXPORT jint JNICALL Java_Tester_getValue( JNIEnv *env, jobject obj, jint i) { return i * i; } javac Tester.java javah -jni Tester gcc -shared -fpic -o libTester.so -I${JAVA_HOME}/include \ -I${JAVA_HOME}/include/linux Tester.c java -Djava.library.path=. Tester 4
[ { "code": null, "e": 1226, "s": 1062, "text": "A native method is the one whose method implementation is done in other languages like c++ and Java. These programs are linked to Java using JNI or JNA interfaces." }, { "code": null, "e": 1417, "s": 1226, "text": "The difference between normal method and native method is That the native method declaration contains native keyword and, the implementation of the method will be other programming language." }, { "code": null, "e": 1620, "s": 1417, "text": "public class Tester {\n public native int getValue(int i);\n \n public static void main(String[] args) {\n System.loadLibrary(\"Tester\");\n System.out.println(new Tester().getValue(2));\n }\n}" }, { "code": null, "e": 1758, "s": 1620, "text": "#include <jni.h>\n#include \"Tester.h\"\n\nJNIEXPORT jint JNICALL Java_Tester_getValue(\nJNIEnv *env, jobject obj, jint i) {\n return i * i;\n}" }, { "code": null, "e": 1925, "s": 1758, "text": "javac Tester.java\njavah -jni Tester\ngcc -shared -fpic -o libTester.so -I${JAVA_HOME}/include \\\n-I${JAVA_HOME}/include/linux Tester.c\njava -Djava.library.path=. Tester" }, { "code": null, "e": 1928, "s": 1925, "text": "4\n" } ]
Styling First-Letters with CSS ::first-letter
CSS can help us style the first letter of an element using the ::first-letter pseudo-element. Note that punctuation marks, digraphs and content property can change the first-letter. The following examples illustrate CSS ::first-letter pseudo-element. Live Demo <!DOCTYPE html> <html> <head> <style> body { text-align: center; } ::first-letter { font-size: 3em; color: sienna; box-shadow: -10px 0 10px green; background-color: gainsboro; } </style> </head> <body> <h2>Proin ut diam eros</h2> <p>Donec rutrum a erat vitae interdum. </p> <p>Integer eleifend lectus sit amet purus semper, ut pharetra metus gravida.</p> </body> </html> This will produce the following result − Live Demo <!DOCTYPE html> <html> <head> <style> body { text-align: center; } body > * { background-color: slategrey; } ::first-letter { font-size: 1.6em; color: darkviolet; background-color: silver; text-shadow: -15px 8px palevioletred; } </style> </head> <body> <h2>Proin ut diam eros <p>Donec rutrum a erat vitae interdum. </p> <p>Integer eleifend lectus sit amet purus semper, ut pharetra metus gravida.</p> </body> </html> This will produce the following result −
[ { "code": null, "e": 1244, "s": 1062, "text": "CSS can help us style the first letter of an element using the ::first-letter pseudo-element. Note that punctuation marks, digraphs and content property can change the first-letter." }, { "code": null, "e": 1313, "s": 1244, "text": "The following examples illustrate CSS ::first-letter pseudo-element." }, { "code": null, "e": 1324, "s": 1313, "text": " Live Demo" }, { "code": null, "e": 1710, "s": 1324, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n text-align: center;\n}\n::first-letter {\n font-size: 3em;\n color: sienna;\n box-shadow: -10px 0 10px green;\n background-color: gainsboro;\n}\n</style>\n</head>\n<body>\n<h2>Proin ut diam eros</h2>\n<p>Donec rutrum a erat vitae interdum. </p>\n<p>Integer eleifend lectus sit amet purus semper, ut pharetra metus gravida.</p>\n</body>\n</html>" }, { "code": null, "e": 1751, "s": 1710, "text": "This will produce the following result −" }, { "code": null, "e": 1762, "s": 1751, "text": " Live Demo" }, { "code": null, "e": 2197, "s": 1762, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n text-align: center;\n}\nbody > * {\n background-color: slategrey;\n}\n::first-letter {\n font-size: 1.6em;\n color: darkviolet;\n background-color: silver;\n text-shadow: -15px 8px palevioletred;\n}\n</style>\n</head>\n<body>\n<h2>Proin ut diam eros\n<p>Donec rutrum a erat vitae interdum. </p>\n<p>Integer eleifend lectus sit amet purus semper, ut pharetra metus gravida.</p>\n</body>\n</html>" }, { "code": null, "e": 2238, "s": 2197, "text": "This will produce the following result −" } ]
ABC Analysis with K-Means Clustering | by Andrew Udell | Towards Data Science
ABC analysis assumes that revenue-generating items in an inventory follow a Pareto distribution, where a very small percent of items generate the most amount of revenue. Using the following conventions, an item in inventory is assigned a letter based on importance: A items are 20% of items, but contribute 70% of revenue B items are 30% of items, but contribute 25% of revenue C items are 50% of items, but contribute 5% of revenue Keep in mind these numbers are rough and will vary significantly based on the actual distribution of sales. The key takeaway is that A items are a small percent of inventory, but contribute the most to revenue, C items are a large percent of inventory, but contribute the least to revenue, and B items fall somewhere in the middle. Both inventory planning and warehousing strategies rely on ABC analysis to make key logistic decisions. For example, a warehouse manager usually wants A items closest to the shipping docks to reduce the time required to pick them. This boosts productivity and reduces labor costs. Broadly speaking, K-means clustering is an unsupervised machine learning technique which attempts to group together similar observations. It does so by calculating a mean, or centroid, of each random group, or cluster, and places observations into the cluster with the nearest mean. Once observations are added to the clusters, the centroids are calculated again and points are accordingly removed or added to the clusters. This process repeats until the clusters are stable (ie, observations are no longer added or removed from the clusters). This simple machine learning algorithm may be used for ABC analysis. The largest disadvantage of K-means clustering is that it requires the number of clusters need to be known in advance. While difficult to estimate in many situations, we know we want to divide the inventory in three clusters for ABC analysis: A, B, and C. Additionally, by the nature of using distance from the mean, K-means clustering makes the assumption that the clusters are circular in shape. Under this assumption, more nuanced classification problems would fail to classify properly, but ABC analysis is simple enough that it may adequately be represented. On a similar note, using distance as a metric often distorts high-dimensional data. Luckily, ABC analysis only examines two parameters: the revenue an item generates and how that revenue is distributed. All these factors makes K-means clustering an optimal solution to determine the A, B, and C items. The data used in this project are from popular online retailer, Wish. The data set includes only the online sale of clothing throughout the summer. Most importantly, it features the number of units sold and the price sold, which will yield the revenue per item. The full data set may be found on Kaggle. The goal is to sort all the items in the data set into an ABC categorization based on importance. When viewing the results, there should be relatively few A items that drive the majority of the revenue and a large number of C items that don’t provide much revenue. The distribution of these should be that A items sell the most, C items sell the least, and B items fall in the middle of the two. If items are randomly distributed through the data (ie, the first highest selling item is an A and the second is a C), there’s a problem that needs addressing. All data formatting and analysis will be done in python. # Import librariesimport pandas as pdimport numpy as np# read the data to a dataframedf = pd.read_csv("Summer_Sales_08.2020.csv") Before crunching any numbers, the Pandas and NumPy libraries are imported to help manage the data. Next, the data, previously saved as a CSV file, is read into a dataframe. # Add a column for revenuesdf["revenue"] = df["units_sold"] * df["price"] A new column is added to the dataframe for revenue by simply multiplying the number units sold by the price. It’s possible the price varied over time, especially as flash sales occurred, but without further data to analyze, the assumption is made that all items sold at a one, stable price. import seaborn as snssns.distplot(df["revenue"]) The figure above demonstrates the Pareto distribution found in the data. The vast majority of the items generate less than €200,000 in revenue (Although it’s not explicit in the graph, further analysis found about two-thirds of the items generate less than €20,000). At the same time, a handful of items sell between €400,000 and €800,000, which drive a majority of the revenue. # Create bins functiondef bins(x): for bar in range(20000, 820000, 20000): if x <= bar: return bar# Create new column to apply the bin functiondf["rev_dist"] = df["revenue"].apply(lambda x: bins(x)) A function is written to classify the amount of revenue an item generates into bins and then applied to the dataframe. If an item generates €20,000 or less, it gets classified as €20,000. It an items makes between €20,000 and €40,000, it gets classified as €40,000 and so on for each increment of €20,000. Choosing a bin size is crucial to making a good estimate. The bins shouldn’t be either too large or too small or else the final ABC classification will be skewed. In this case, the bin size was chosen so that each bin had fewer items in them than the preceding bin. An initial estimate may have to made and tweaked to get the desired effect. # Create a support column of 1’s to facilitate the pivot tabledf["count"] = 1# Create a pivot table of the revenue distributionspivot_table = pd.pivot_table(df, index = ["rev_dist"], values = ["count"], aggfunc = np.sum) A pivot table is created to enumerate the number of items that fall in each categories. For example, 1,072 items generate €20,000 or less. 120 items make between €20,000 and €40,000 and so on. To properly train the model, it’s not sufficient to simply look at how much revenue each item generates. It also needs to know how the revenue is distributed. This pivot table provides a very manageable data set for the model to train on. # import model from SKLearnfrom sklearn.cluster import KMeans# K -clusters is equal to 3 because things will be sorted into A, B, and Ckmeans = KMeans(n_clusters=3)kmeans.fit(pivot_table) The K-means model from scikit-learn is imported and initialized. As mentioned before, the parameter n_clusters is set to three, because we want to divide the data into three clusters. The model is then fit onto the pivot table. pivot_table["category"] = kmeans.labels_ A new column is placed on the pivot table giving the classification from the model. It’s worth noting that that by default the K-means model from scikit-learn will classify items on a numerical scale instead of the alphabetical scale used in ABC analysis. Consequently, each row will be labeled as either zero, one, or two. Luckily, while the labels differ, the actual underlying pattern remains the same. As a result, the numerical labels will correlate to an alphabetical label, but will require review to determine. In this case, zero is A, one is C and two is B. # Create a dictionary to give alphabetical labelsABC_dict = { 0: "A", 1: "C", 2: "B"}pivot_table["ABC"] = pivot_table["category"].apply(lambda x: ABC_dict[x]) A quick dictionary was written and applied to the pivot table to give each row its ABC classification. # Merge the dataframes so that there's a new column to identify ABCdf = pd.merge(df, pivot_table, on = "rev_dist", how ="left") Recall that the the model was trained on a pivot table. The ABC classification hasn’t been assigned to the items, yet. Instead, it’s been assigned to a revenue classification. This means that while we don’t immediately know which items are in the A category, we know that certain revenue classifications (ie, €780,000 to €800,000) are rated as A items. As a result, we can simply merge the main dataframe and the pivot table to give each item its ABC classification. When analyzing the final distribution of items, it was found that: A items represent 11.4% of items, but 61.7% of revenue B items represent 20.5% of items, but 30.7% of revenue C items represent 68.1% of items, but 7.6% of revenue While these numbers don’t perfectly match a Pareto distribution, it’s very likely that the data itself varies from those idealized numbers. Instead, it’s more important that the clusters very clearly convey that a small portion of the inventory generates the majority of the revenue. Likewise all the A items were top selling items while all the C items were bottom selling items and B items fell perfectly in the middle. The model was a success! While K-means clustering probably isn’t the most efficient way to perform ABC analysis, it demonstrates the model’s ability to find the same underlying pattern. With this success, it opens the door to using more unsupervised learning techniques to uncover sales and logistics insights. Clustering in particular provides an intuitive way to segment product along patterns which may or may not be obvious to human eyes and may provide the cutting edge for those who use it.
[ { "code": null, "e": 437, "s": 171, "text": "ABC analysis assumes that revenue-generating items in an inventory follow a Pareto distribution, where a very small percent of items generate the most amount of revenue. Using the following conventions, an item in inventory is assigned a letter based on importance:" }, { "code": null, "e": 493, "s": 437, "text": "A items are 20% of items, but contribute 70% of revenue" }, { "code": null, "e": 549, "s": 493, "text": "B items are 30% of items, but contribute 25% of revenue" }, { "code": null, "e": 604, "s": 549, "text": "C items are 50% of items, but contribute 5% of revenue" }, { "code": null, "e": 936, "s": 604, "text": "Keep in mind these numbers are rough and will vary significantly based on the actual distribution of sales. The key takeaway is that A items are a small percent of inventory, but contribute the most to revenue, C items are a large percent of inventory, but contribute the least to revenue, and B items fall somewhere in the middle." }, { "code": null, "e": 1217, "s": 936, "text": "Both inventory planning and warehousing strategies rely on ABC analysis to make key logistic decisions. For example, a warehouse manager usually wants A items closest to the shipping docks to reduce the time required to pick them. This boosts productivity and reduces labor costs." }, { "code": null, "e": 1500, "s": 1217, "text": "Broadly speaking, K-means clustering is an unsupervised machine learning technique which attempts to group together similar observations. It does so by calculating a mean, or centroid, of each random group, or cluster, and places observations into the cluster with the nearest mean." }, { "code": null, "e": 1761, "s": 1500, "text": "Once observations are added to the clusters, the centroids are calculated again and points are accordingly removed or added to the clusters. This process repeats until the clusters are stable (ie, observations are no longer added or removed from the clusters)." }, { "code": null, "e": 1830, "s": 1761, "text": "This simple machine learning algorithm may be used for ABC analysis." }, { "code": null, "e": 2086, "s": 1830, "text": "The largest disadvantage of K-means clustering is that it requires the number of clusters need to be known in advance. While difficult to estimate in many situations, we know we want to divide the inventory in three clusters for ABC analysis: A, B, and C." }, { "code": null, "e": 2394, "s": 2086, "text": "Additionally, by the nature of using distance from the mean, K-means clustering makes the assumption that the clusters are circular in shape. Under this assumption, more nuanced classification problems would fail to classify properly, but ABC analysis is simple enough that it may adequately be represented." }, { "code": null, "e": 2597, "s": 2394, "text": "On a similar note, using distance as a metric often distorts high-dimensional data. Luckily, ABC analysis only examines two parameters: the revenue an item generates and how that revenue is distributed." }, { "code": null, "e": 2696, "s": 2597, "text": "All these factors makes K-means clustering an optimal solution to determine the A, B, and C items." }, { "code": null, "e": 3000, "s": 2696, "text": "The data used in this project are from popular online retailer, Wish. The data set includes only the online sale of clothing throughout the summer. Most importantly, it features the number of units sold and the price sold, which will yield the revenue per item. The full data set may be found on Kaggle." }, { "code": null, "e": 3265, "s": 3000, "text": "The goal is to sort all the items in the data set into an ABC categorization based on importance. When viewing the results, there should be relatively few A items that drive the majority of the revenue and a large number of C items that don’t provide much revenue." }, { "code": null, "e": 3556, "s": 3265, "text": "The distribution of these should be that A items sell the most, C items sell the least, and B items fall in the middle of the two. If items are randomly distributed through the data (ie, the first highest selling item is an A and the second is a C), there’s a problem that needs addressing." }, { "code": null, "e": 3613, "s": 3556, "text": "All data formatting and analysis will be done in python." }, { "code": null, "e": 3743, "s": 3613, "text": "# Import librariesimport pandas as pdimport numpy as np# read the data to a dataframedf = pd.read_csv(\"Summer_Sales_08.2020.csv\")" }, { "code": null, "e": 3842, "s": 3743, "text": "Before crunching any numbers, the Pandas and NumPy libraries are imported to help manage the data." }, { "code": null, "e": 3916, "s": 3842, "text": "Next, the data, previously saved as a CSV file, is read into a dataframe." }, { "code": null, "e": 3990, "s": 3916, "text": "# Add a column for revenuesdf[\"revenue\"] = df[\"units_sold\"] * df[\"price\"]" }, { "code": null, "e": 4281, "s": 3990, "text": "A new column is added to the dataframe for revenue by simply multiplying the number units sold by the price. It’s possible the price varied over time, especially as flash sales occurred, but without further data to analyze, the assumption is made that all items sold at a one, stable price." }, { "code": null, "e": 4330, "s": 4281, "text": "import seaborn as snssns.distplot(df[\"revenue\"])" }, { "code": null, "e": 4709, "s": 4330, "text": "The figure above demonstrates the Pareto distribution found in the data. The vast majority of the items generate less than €200,000 in revenue (Although it’s not explicit in the graph, further analysis found about two-thirds of the items generate less than €20,000). At the same time, a handful of items sell between €400,000 and €800,000, which drive a majority of the revenue." }, { "code": null, "e": 4929, "s": 4709, "text": "# Create bins functiondef bins(x): for bar in range(20000, 820000, 20000): if x <= bar: return bar# Create new column to apply the bin functiondf[\"rev_dist\"] = df[\"revenue\"].apply(lambda x: bins(x))" }, { "code": null, "e": 5235, "s": 4929, "text": "A function is written to classify the amount of revenue an item generates into bins and then applied to the dataframe. If an item generates €20,000 or less, it gets classified as €20,000. It an items makes between €20,000 and €40,000, it gets classified as €40,000 and so on for each increment of €20,000." }, { "code": null, "e": 5577, "s": 5235, "text": "Choosing a bin size is crucial to making a good estimate. The bins shouldn’t be either too large or too small or else the final ABC classification will be skewed. In this case, the bin size was chosen so that each bin had fewer items in them than the preceding bin. An initial estimate may have to made and tweaked to get the desired effect." }, { "code": null, "e": 5798, "s": 5577, "text": "# Create a support column of 1’s to facilitate the pivot tabledf[\"count\"] = 1# Create a pivot table of the revenue distributionspivot_table = pd.pivot_table(df, index = [\"rev_dist\"], values = [\"count\"], aggfunc = np.sum)" }, { "code": null, "e": 5991, "s": 5798, "text": "A pivot table is created to enumerate the number of items that fall in each categories. For example, 1,072 items generate €20,000 or less. 120 items make between €20,000 and €40,000 and so on." }, { "code": null, "e": 6230, "s": 5991, "text": "To properly train the model, it’s not sufficient to simply look at how much revenue each item generates. It also needs to know how the revenue is distributed. This pivot table provides a very manageable data set for the model to train on." }, { "code": null, "e": 6418, "s": 6230, "text": "# import model from SKLearnfrom sklearn.cluster import KMeans# K -clusters is equal to 3 because things will be sorted into A, B, and Ckmeans = KMeans(n_clusters=3)kmeans.fit(pivot_table)" }, { "code": null, "e": 6646, "s": 6418, "text": "The K-means model from scikit-learn is imported and initialized. As mentioned before, the parameter n_clusters is set to three, because we want to divide the data into three clusters. The model is then fit onto the pivot table." }, { "code": null, "e": 6687, "s": 6646, "text": "pivot_table[\"category\"] = kmeans.labels_" }, { "code": null, "e": 7011, "s": 6687, "text": "A new column is placed on the pivot table giving the classification from the model. It’s worth noting that that by default the K-means model from scikit-learn will classify items on a numerical scale instead of the alphabetical scale used in ABC analysis. Consequently, each row will be labeled as either zero, one, or two." }, { "code": null, "e": 7254, "s": 7011, "text": "Luckily, while the labels differ, the actual underlying pattern remains the same. As a result, the numerical labels will correlate to an alphabetical label, but will require review to determine. In this case, zero is A, one is C and two is B." }, { "code": null, "e": 7426, "s": 7254, "text": "# Create a dictionary to give alphabetical labelsABC_dict = { 0: \"A\", 1: \"C\", 2: \"B\"}pivot_table[\"ABC\"] = pivot_table[\"category\"].apply(lambda x: ABC_dict[x])" }, { "code": null, "e": 7529, "s": 7426, "text": "A quick dictionary was written and applied to the pivot table to give each row its ABC classification." }, { "code": null, "e": 7657, "s": 7529, "text": "# Merge the dataframes so that there's a new column to identify ABCdf = pd.merge(df, pivot_table, on = \"rev_dist\", how =\"left\")" }, { "code": null, "e": 7833, "s": 7657, "text": "Recall that the the model was trained on a pivot table. The ABC classification hasn’t been assigned to the items, yet. Instead, it’s been assigned to a revenue classification." }, { "code": null, "e": 8010, "s": 7833, "text": "This means that while we don’t immediately know which items are in the A category, we know that certain revenue classifications (ie, €780,000 to €800,000) are rated as A items." }, { "code": null, "e": 8124, "s": 8010, "text": "As a result, we can simply merge the main dataframe and the pivot table to give each item its ABC classification." }, { "code": null, "e": 8191, "s": 8124, "text": "When analyzing the final distribution of items, it was found that:" }, { "code": null, "e": 8246, "s": 8191, "text": "A items represent 11.4% of items, but 61.7% of revenue" }, { "code": null, "e": 8301, "s": 8246, "text": "B items represent 20.5% of items, but 30.7% of revenue" }, { "code": null, "e": 8355, "s": 8301, "text": "C items represent 68.1% of items, but 7.6% of revenue" }, { "code": null, "e": 8639, "s": 8355, "text": "While these numbers don’t perfectly match a Pareto distribution, it’s very likely that the data itself varies from those idealized numbers. Instead, it’s more important that the clusters very clearly convey that a small portion of the inventory generates the majority of the revenue." }, { "code": null, "e": 8802, "s": 8639, "text": "Likewise all the A items were top selling items while all the C items were bottom selling items and B items fell perfectly in the middle. The model was a success!" }, { "code": null, "e": 8963, "s": 8802, "text": "While K-means clustering probably isn’t the most efficient way to perform ABC analysis, it demonstrates the model’s ability to find the same underlying pattern." } ]
How to get the datatype of MySQL table columns?
You can get the MySQL table columns data type with the help of “information_schema.columns”. The syntax is as follows − SELECT DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where table_schema = ’yourDatabaseName’ and table_name = ’yourTableName’. To understand the above syntax, let us first create a table − mysql> create table DataTypeDemo −> ( −> Id int, −> Address varchar(200), −> Money decimal(10,4) −> ); Query OK, 0 rows affected (0.60 sec) Apply the above syntax to get the MySQL columns data type. The query is as follows − mysql> select data_type from information_schema.columns where table_schema = 'business' and able_name = 'DataTypeDemo'; The following is the output − +-----------+ | DATA_TYPE | +-----------+ | int | | varchar | | decimal | +-----------+ 3 rows in set (0.00 sec) If you want, include the column name as well in the output before the datatype. The query is as follows − mysql> select column_name,data_type from information_schema.columns where table_schema = 'business' and table_name = 'DataTypeDemo'; The following output displays the column name corresponding to the data type − +-------------+-----------+ | COLUMN_NAME | DATA_TYPE | +-------------+-----------+ | Id | int | | Address | varchar | | Money | decimal | +-------------+-----------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1155, "s": 1062, "text": "You can get the MySQL table columns data type with the help of “information_schema.columns”." }, { "code": null, "e": 1182, "s": 1155, "text": "The syntax is as follows −" }, { "code": null, "e": 1305, "s": 1182, "text": "SELECT DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where\ntable_schema = ’yourDatabaseName’ and table_name = ’yourTableName’." }, { "code": null, "e": 1367, "s": 1305, "text": "To understand the above syntax, let us first create a table −" }, { "code": null, "e": 1516, "s": 1367, "text": "mysql> create table DataTypeDemo\n−> (\n −> Id int,\n −> Address varchar(200),\n −> Money decimal(10,4)\n−> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1601, "s": 1516, "text": "Apply the above syntax to get the MySQL columns data type. The query is as follows −" }, { "code": null, "e": 1721, "s": 1601, "text": "mysql> select data_type from information_schema.columns where table_schema = 'business' and able_name = 'DataTypeDemo';" }, { "code": null, "e": 1751, "s": 1721, "text": "The following is the output −" }, { "code": null, "e": 1874, "s": 1751, "text": "+-----------+\n| DATA_TYPE |\n+-----------+\n| int |\n| varchar |\n| decimal |\n+-----------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1980, "s": 1874, "text": "If you want, include the column name as well in the output before the datatype. The query is as follows −" }, { "code": null, "e": 2113, "s": 1980, "text": "mysql> select column_name,data_type from information_schema.columns where table_schema = 'business' and table_name = 'DataTypeDemo';" }, { "code": null, "e": 2192, "s": 2113, "text": "The following output displays the column name corresponding to the data type −" }, { "code": null, "e": 2413, "s": 2192, "text": "+-------------+-----------+\n| COLUMN_NAME | DATA_TYPE |\n+-------------+-----------+\n| Id | int |\n| Address | varchar |\n| Money | decimal |\n+-------------+-----------+\n3 rows in set (0.00 sec)" } ]
How to change text font in HTML?
To change the text font in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-family, font-size, font-style, etc. HTML5 do not support the <font> tag, so the CSS style is used to change font. The <font> tag deprecated in HTML5. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to change the font in HTML Live Demo <!DOCTYPE html> <html> <head> <title>HTML Font</title> </head> <body> <h1>Our Products</h1> <p style = "font-family:georgia,garamond,serif;font-size:16px;font-style:italic;"> This is demo text </p> </body> </html>
[ { "code": null, "e": 1290, "s": 1062, "text": "To change the text font in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property font-family, font-size, font-style, etc." }, { "code": null, "e": 1404, "s": 1290, "text": "HTML5 do not support the <font> tag, so the CSS style is used to change font. The <font> tag deprecated in HTML5." }, { "code": null, "e": 1566, "s": 1404, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1631, "s": 1566, "text": "You can try to run the following code to change the font in HTML" }, { "code": null, "e": 1641, "s": 1631, "text": "Live Demo" }, { "code": null, "e": 1902, "s": 1641, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Font</title>\n </head>\n\n <body>\n <h1>Our Products</h1>\n <p style = \"font-family:georgia,garamond,serif;font-size:16px;font-style:italic;\">\n This is demo text\n </p>\n </body>\n\n</html>" } ]
multimap value_comp() function in C++ STL - GeeksforGeeks
22 Oct, 2018 The multimap::value_comp() method returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. Here the 1st object compares the object of type std::multimap::type. The arguments taken by this function object are of member type type. It is defined in multimap as an alias of pair. Syntax: multimap::compared_value value_comp() const; Here compared_value is a nested class type Parameters: It does not accepts any parameter. Return Value: This method returns the comparison object which is an object of the member type multimap::compared_value, which is a nested class that uses the internal comparison object to generate the appropriate comparison functional class. Below program illustrate the multimap value_comp() function: // C++ program to show// the use of multimap::value_comp #include <iostream>#include <map>using namespace std; int main(){ multimap<char, int> m; // making of pair m.insert(make_pair('a', 10)); m.insert(make_pair('b', 20)); m.insert(make_pair('c', 30)); m.insert(make_pair('d', 40)); pair<char, int> p = *m.rbegin(); // last element multimap<char, int>::iterator i = m.begin(); do { cout << (*i).first << " = " << (*i).second << '\n'; } while (m.value_comp()(*i++, p)); return 0;} a = 10 b = 20 c = 30 d = 40 CPP-Functions cpp-multimap cpp-multimap-functions Picked C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ Inline Functions in C++ List in C++ Standard Template Library (STL) std::string class in C++ new and delete operators in C++ for dynamic memory
[ { "code": null, "e": 24018, "s": 23990, "text": "\n22 Oct, 2018" }, { "code": null, "e": 24370, "s": 24018, "text": "The multimap::value_comp() method returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. Here the 1st object compares the object of type std::multimap::type. The arguments taken by this function object are of member type type. It is defined in multimap as an alias of pair." }, { "code": null, "e": 24378, "s": 24370, "text": "Syntax:" }, { "code": null, "e": 24423, "s": 24378, "text": "multimap::compared_value value_comp() const;" }, { "code": null, "e": 24466, "s": 24423, "text": "Here compared_value is a nested class type" }, { "code": null, "e": 24513, "s": 24466, "text": "Parameters: It does not accepts any parameter." }, { "code": null, "e": 24755, "s": 24513, "text": "Return Value: This method returns the comparison object which is an object of the member type multimap::compared_value, which is a nested class that uses the internal comparison object to generate the appropriate comparison functional class." }, { "code": null, "e": 24816, "s": 24755, "text": "Below program illustrate the multimap value_comp() function:" }, { "code": "// C++ program to show// the use of multimap::value_comp #include <iostream>#include <map>using namespace std; int main(){ multimap<char, int> m; // making of pair m.insert(make_pair('a', 10)); m.insert(make_pair('b', 20)); m.insert(make_pair('c', 30)); m.insert(make_pair('d', 40)); pair<char, int> p = *m.rbegin(); // last element multimap<char, int>::iterator i = m.begin(); do { cout << (*i).first << \" = \" << (*i).second << '\\n'; } while (m.value_comp()(*i++, p)); return 0;}", "e": 25380, "s": 24816, "text": null }, { "code": null, "e": 25409, "s": 25380, "text": "a = 10\nb = 20\nc = 30\nd = 40\n" }, { "code": null, "e": 25423, "s": 25409, "text": "CPP-Functions" }, { "code": null, "e": 25436, "s": 25423, "text": "cpp-multimap" }, { "code": null, "e": 25459, "s": 25436, "text": "cpp-multimap-functions" }, { "code": null, "e": 25466, "s": 25459, "text": "Picked" }, { "code": null, "e": 25470, "s": 25466, "text": "C++" }, { "code": null, "e": 25474, "s": 25470, "text": "CPP" }, { "code": null, "e": 25572, "s": 25474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25581, "s": 25572, "text": "Comments" }, { "code": null, "e": 25594, "s": 25581, "text": "Old Comments" }, { "code": null, "e": 25615, "s": 25594, "text": "Iterators in C++ STL" }, { "code": null, "e": 25643, "s": 25615, "text": "Operator Overloading in C++" }, { "code": null, "e": 25676, "s": 25643, "text": "Friend class and function in C++" }, { "code": null, "e": 25696, "s": 25676, "text": "Polymorphism in C++" }, { "code": null, "e": 25720, "s": 25696, "text": "Sorting a vector in C++" }, { "code": null, "e": 25756, "s": 25720, "text": "Convert string to char array in C++" }, { "code": null, "e": 25780, "s": 25756, "text": "Inline Functions in C++" }, { "code": null, "e": 25824, "s": 25780, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 25849, "s": 25824, "text": "std::string class in C++" } ]
Python Modules for Web Scraping
In this chapter, let us learn various Python modules that we can use for web scraping. Virtualenv is a tool to create isolated Python environments. With the help of virtualenv, we can create a folder that contains all necessary executables to use the packages that our Python project requires. It also allows us to add and modify Python modules without access to the global installation. You can use the following command to install virtualenv − (base) D:\ProgramData>pip install virtualenv Collecting virtualenv Downloading https://files.pythonhosted.org/packages/b6/30/96a02b2287098b23b875bc8c2f58071c3 5d2efe84f747b64d523721dc2b5/virtualenv-16.0.0-py2.py3-none-any.whl (1.9MB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.9MB 86kB/s Installing collected packages: virtualenv Successfully installed virtualenv-16.0.0 Now, we need to create a directory which will represent the project with the help of following command − (base) D:\ProgramData>mkdir webscrap Now, enter into that directory with the help of this following command − (base) D:\ProgramData>cd webscrap Now, we need to initialize virtual environment folder of our choice as follows − (base) D:\ProgramData\webscrap>virtualenv websc Using base prefix 'd:\\programdata' New python executable in D:\ProgramData\webscrap\websc\Scripts\python.exe Installing setuptools, pip, wheel...done. Now, activate the virtual environment with the command given below. Once successfully activated, you will see the name of it on the left hand side in brackets. (base) D:\ProgramData\webscrap>websc\scripts\activate We can install any module in this environment as follows − (websc) (base) D:\ProgramData\webscrap>pip install requests Collecting requests Downloading https://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69 c4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl (9 1kB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 92kB 148kB/s Collecting chardet<3.1.0,>=3.0.2 (from requests) Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca 55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133 kB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 143kB 369kB/s Collecting certifi>=2017.4.17 (from requests) Downloading https://files.pythonhosted.org/packages/df/f7/04fee6ac349e915b82171f8e23cee6364 4d83663b34c539f7a09aed18f9e/certifi-2018.8.24-py2.py3-none-any.whl (147kB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 153kB 527kB/s Collecting urllib3<1.24,>=1.21.1 (from requests) Downloading https://files.pythonhosted.org/packages/bd/c9/6fdd990019071a4a32a5e7cb78a1d92c5 3851ef4f56f62a3486e6a7d8ffb/urllib3-1.23-py2.py3-none-any.whl (133k B) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 143kB 517kB/s Collecting idna<2.8,>=2.5 (from requests) Downloading https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746 a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl (58kB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 61kB 339kB/s Installing collected packages: chardet, certifi, urllib3, idna, requests Successfully installed certifi-2018.8.24 chardet-3.0.4 idna-2.7 requests-2.19.1 urllib3-1.23 For deactivating the virtual environment, we can use the following command − (websc) (base) D:\ProgramData\webscrap>deactivate (base) D:\ProgramData\webscrap> You can see that (websc) has been deactivated. Web scraping is the process of constructing an agent which can extract, parse, download and organize useful information from the web automatically. In other words, instead of manually saving the data from websites, the web scraping software will automatically load and extract data from multiple websites as per our requirement. In this section, we are going to discuss about useful Python libraries for web scraping. It is a simple python web scraping library. It is an efficient HTTP library used for accessing web pages. With the help of Requests, we can get the raw HTML of web pages which can then be parsed for retrieving the data. Before using requests, let us understand its installation. We can install it in either on our virtual environment or on the global installation. With the help of pip command, we can easily install it as follows − (base) D:\ProgramData> pip install requests Collecting requests Using cached https://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69 c4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl Requirement already satisfied: idna<2.8,>=2.5 in d:\programdata\lib\sitepackages (from requests) (2.6) Requirement already satisfied: urllib3<1.24,>=1.21.1 in d:\programdata\lib\site-packages (from requests) (1.22) Requirement already satisfied: certifi>=2017.4.17 in d:\programdata\lib\sitepackages (from requests) (2018.1.18) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in d:\programdata\lib\site-packages (from requests) (3.0.4) Installing collected packages: requests Successfully installed requests-2.19.1 In this example, we are making a GET HTTP request for a web page. For this we need to first import requests library as follows − In [1]: import requests In this following line of code, we use requests to make a GET HTTP requests for the url: https://authoraditiagarwal.com/ by making a GET request. In [2]: r = requests.get('https://authoraditiagarwal.com/') Now we can retrieve the content by using .text property as follows − In [5]: r.text[:200] Observe that in the following output, we got the first 200 characters. Out[5]: '<!DOCTYPE html>\n<html lang="en-US"\n\titemscope \n\titemtype="http://schema.org/WebSite" \n\tprefix="og: http://ogp.me/ns#" >\n<head>\n\t<meta charset ="UTF-8" />\n\t<meta http-equiv="X-UA-Compatible" content="IE' It is another Python library that can be used for retrieving data from URLs similar to the requests library. You can read more on this at its technical documentation at https://urllib3.readthedocs.io/en/latest/. Using the pip command, we can install urllib3 either in our virtual environment or in global installation. (base) D:\ProgramData>pip install urllib3 Collecting urllib3 Using cached https://files.pythonhosted.org/packages/bd/c9/6fdd990019071a4a32a5e7cb78a1d92c5 3851ef4f56f62a3486e6a7d8ffb/urllib3-1.23-py2.py3-none-any.whl Installing collected packages: urllib3 Successfully installed urllib3-1.23 In the following example, we are scraping the web page by using Urllib3 and BeautifulSoup. We are using Urllib3 at the place of requests library for getting the raw data (HTML) from web page. Then we are using BeautifulSoup for parsing that HTML data. import urllib3 from bs4 import BeautifulSoup http = urllib3.PoolManager() r = http.request('GET', 'https://authoraditiagarwal.com') soup = BeautifulSoup(r.data, 'lxml') print (soup.title) print (soup.title.text) This is the output you will observe when you run this code − <title>Learn and Grow with Aditi Agarwal</title> Learn and Grow with Aditi Agarwal It is an open source automated testing suite for web applications across different browsers and platforms. It is not a single tool but a suite of software. We have selenium bindings for Python, Java, C#, Ruby and JavaScript. Here we are going to perform web scraping by using selenium and its Python bindings. You can learn more about Selenium with Java on the link Selenium. Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, IE, Chrome, Remote etc. The current supported Python versions are 2.7, 3.5 and above. Using the pip command, we can install urllib3 either in our virtual environment or in global installation. pip install selenium As selenium requires a driver to interface with the chosen browser, we need to download it. The following table shows different browsers and their links for downloading the same. Chrome https://sites.google.com/a/chromium.org/ Edge https://developer.microsoft.com/ Firefox https://github.com/ Safari https://webkit.org/ This example shows web scraping using selenium. It can also be used for testing which is called selenium testing. After downloading the particular driver for the specified version of browser, we need to do programming in Python. First, need to import webdriver from selenium as follows − from selenium import webdriver Now, provide the path of web driver which we have downloaded as per our requirement − path = r'C:\\Users\\gaurav\\Desktop\\Chromedriver' browser = webdriver.Chrome(executable_path = path) Now, provide the url which we want to open in that web browser now controlled by our Python script. browser.get('https://authoraditiagarwal.com/leadershipmanagement') We can also scrape a particular element by providing the xpath as provided in lxml. browser.find_element_by_xpath('/html/body').click() You can check the browser, controlled by Python script, for output. Scrapy is a fast, open-source web crawling framework written in Python, used to extract the data from the web page with the help of selectors based on XPath. Scrapy was first released on June 26, 2008 licensed under BSD, with a milestone 1.0 releasing in June 2015. It provides us all the tools we need to extract, process and structure the data from websites. Using the pip command, we can install urllib3 either in our virtual environment or in global installation. pip install scrapy For more detail study of Scrapy you can go to the link Scrapy 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": 1999, "s": 1912, "text": "In this chapter, let us learn various Python modules that we can use for web scraping." }, { "code": null, "e": 2300, "s": 1999, "text": "Virtualenv is a tool to create isolated Python environments. With the help of virtualenv, we can create a folder that contains all necessary executables to use the packages that our Python project requires. It also allows us to add and modify Python modules without access to the global installation." }, { "code": null, "e": 2358, "s": 2300, "text": "You can use the following command to install virtualenv −" }, { "code": null, "e": 2735, "s": 2358, "text": "(base) D:\\ProgramData>pip install virtualenv\nCollecting virtualenv\n Downloading\nhttps://files.pythonhosted.org/packages/b6/30/96a02b2287098b23b875bc8c2f58071c3\n5d2efe84f747b64d523721dc2b5/virtualenv-16.0.0-py2.py3-none-any.whl\n(1.9MB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.9MB 86kB/s\nInstalling collected packages: virtualenv\nSuccessfully installed virtualenv-16.0.0\n" }, { "code": null, "e": 2840, "s": 2735, "text": "Now, we need to create a directory which will represent the project with the help of following command −" }, { "code": null, "e": 2878, "s": 2840, "text": "(base) D:\\ProgramData>mkdir webscrap\n" }, { "code": null, "e": 2951, "s": 2878, "text": "Now, enter into that directory with the help of this following command −" }, { "code": null, "e": 2986, "s": 2951, "text": "(base) D:\\ProgramData>cd webscrap\n" }, { "code": null, "e": 3067, "s": 2986, "text": "Now, we need to initialize virtual environment folder of our choice as follows −" }, { "code": null, "e": 3268, "s": 3067, "text": "(base) D:\\ProgramData\\webscrap>virtualenv websc\nUsing base prefix 'd:\\\\programdata'\nNew python executable in D:\\ProgramData\\webscrap\\websc\\Scripts\\python.exe\nInstalling setuptools, pip, wheel...done.\n" }, { "code": null, "e": 3428, "s": 3268, "text": "Now, activate the virtual environment with the command given below. Once successfully activated, you will see the name of it on the left hand side in brackets." }, { "code": null, "e": 3483, "s": 3428, "text": "(base) D:\\ProgramData\\webscrap>websc\\scripts\\activate\n" }, { "code": null, "e": 3542, "s": 3483, "text": "We can install any module in this environment as follows −" }, { "code": null, "e": 5089, "s": 3542, "text": "(websc) (base) D:\\ProgramData\\webscrap>pip install requests\nCollecting requests\n Downloading\nhttps://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69\nc4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl (9\n1kB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 92kB 148kB/s\nCollecting chardet<3.1.0,>=3.0.2 (from requests)\n Downloading\nhttps://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca\n55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133\nkB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 143kB 369kB/s\nCollecting certifi>=2017.4.17 (from requests)\n Downloading\nhttps://files.pythonhosted.org/packages/df/f7/04fee6ac349e915b82171f8e23cee6364\n4d83663b34c539f7a09aed18f9e/certifi-2018.8.24-py2.py3-none-any.whl\n(147kB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 153kB 527kB/s\nCollecting urllib3<1.24,>=1.21.1 (from requests)\n Downloading\nhttps://files.pythonhosted.org/packages/bd/c9/6fdd990019071a4a32a5e7cb78a1d92c5\n3851ef4f56f62a3486e6a7d8ffb/urllib3-1.23-py2.py3-none-any.whl (133k\nB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 143kB 517kB/s\nCollecting idna<2.8,>=2.5 (from requests)\n Downloading\nhttps://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746\na97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl (58kB)\n 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 61kB 339kB/s\nInstalling collected packages: chardet, certifi, urllib3, idna, requests\nSuccessfully installed certifi-2018.8.24 chardet-3.0.4 idna-2.7 requests-2.19.1\nurllib3-1.23\n" }, { "code": null, "e": 5166, "s": 5089, "text": "For deactivating the virtual environment, we can use the following command −" }, { "code": null, "e": 5249, "s": 5166, "text": "(websc) (base) D:\\ProgramData\\webscrap>deactivate\n(base) D:\\ProgramData\\webscrap>\n" }, { "code": null, "e": 5296, "s": 5249, "text": "You can see that (websc) has been deactivated." }, { "code": null, "e": 5625, "s": 5296, "text": "Web scraping is the process of constructing an agent which can extract, parse, download and organize useful information from the web automatically. In other words, instead of manually saving the data from websites, the web scraping software will automatically load and extract data from multiple websites as per our requirement." }, { "code": null, "e": 5714, "s": 5625, "text": "In this section, we are going to discuss about useful Python libraries for web scraping." }, { "code": null, "e": 5993, "s": 5714, "text": "It is a simple python web scraping library. It is an efficient HTTP library used for accessing web pages. With the help of Requests, we can get the raw HTML of web pages which can then be parsed for retrieving the data. Before using requests, let us understand its installation." }, { "code": null, "e": 6147, "s": 5993, "text": "We can install it in either on our virtual environment or on the global installation. With the help of pip command, we can easily install it as follows −" }, { "code": null, "e": 6890, "s": 6147, "text": "(base) D:\\ProgramData> pip install requests\nCollecting requests\nUsing cached\nhttps://files.pythonhosted.org/packages/65/47/7e02164a2a3db50ed6d8a6ab1d6d60b69\nc4c3fdf57a284257925dfc12bda/requests-2.19.1-py2.py3-none-any.whl\nRequirement already satisfied: idna<2.8,>=2.5 in d:\\programdata\\lib\\sitepackages\n(from requests) (2.6)\nRequirement already satisfied: urllib3<1.24,>=1.21.1 in\nd:\\programdata\\lib\\site-packages (from requests) (1.22)\nRequirement already satisfied: certifi>=2017.4.17 in d:\\programdata\\lib\\sitepackages\n(from requests) (2018.1.18)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in\nd:\\programdata\\lib\\site-packages (from requests) (3.0.4)\nInstalling collected packages: requests\nSuccessfully installed requests-2.19.1\n" }, { "code": null, "e": 7019, "s": 6890, "text": "In this example, we are making a GET HTTP request for a web page. For this we need to first import requests library as follows −" }, { "code": null, "e": 7044, "s": 7019, "text": "In [1]: import requests\n" }, { "code": null, "e": 7190, "s": 7044, "text": "In this following line of code, we use requests to make a GET HTTP requests for the url: https://authoraditiagarwal.com/ by making a GET request." }, { "code": null, "e": 7251, "s": 7190, "text": "In [2]: r = requests.get('https://authoraditiagarwal.com/')\n" }, { "code": null, "e": 7320, "s": 7251, "text": "Now we can retrieve the content by using .text property as follows −" }, { "code": null, "e": 7342, "s": 7320, "text": "In [5]: r.text[:200]\n" }, { "code": null, "e": 7413, "s": 7342, "text": "Observe that in the following output, we got the first 200 characters." }, { "code": null, "e": 7638, "s": 7413, "text": "Out[5]: '<!DOCTYPE html>\\n<html lang=\"en-US\"\\n\\titemscope\n\\n\\titemtype=\"http://schema.org/WebSite\" \\n\\tprefix=\"og: http://ogp.me/ns#\"\n>\\n<head>\\n\\t<meta charset\n=\"UTF-8\" />\\n\\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE'\n" }, { "code": null, "e": 7850, "s": 7638, "text": "It is another Python library that can be used for retrieving data from URLs similar to the requests library. You can read more on this at its technical documentation at\nhttps://urllib3.readthedocs.io/en/latest/." }, { "code": null, "e": 7957, "s": 7850, "text": "Using the pip command, we can install urllib3 either in our virtual environment or in global installation." }, { "code": null, "e": 8249, "s": 7957, "text": "(base) D:\\ProgramData>pip install urllib3\nCollecting urllib3\nUsing cached\nhttps://files.pythonhosted.org/packages/bd/c9/6fdd990019071a4a32a5e7cb78a1d92c5\n3851ef4f56f62a3486e6a7d8ffb/urllib3-1.23-py2.py3-none-any.whl\nInstalling collected packages: urllib3\nSuccessfully installed urllib3-1.23\n" }, { "code": null, "e": 8501, "s": 8249, "text": "In the following example, we are scraping the web page by using Urllib3 and BeautifulSoup. We are using Urllib3 at the place of requests library for getting the raw data (HTML) from web page. Then we are using BeautifulSoup for parsing that HTML data." }, { "code": null, "e": 8713, "s": 8501, "text": "import urllib3\nfrom bs4 import BeautifulSoup\nhttp = urllib3.PoolManager()\nr = http.request('GET', 'https://authoraditiagarwal.com')\nsoup = BeautifulSoup(r.data, 'lxml')\nprint (soup.title)\nprint (soup.title.text)" }, { "code": null, "e": 8774, "s": 8713, "text": "This is the output you will observe when you run this code −" }, { "code": null, "e": 8858, "s": 8774, "text": "<title>Learn and Grow with Aditi Agarwal</title>\nLearn and Grow with Aditi Agarwal\n" }, { "code": null, "e": 9235, "s": 8858, "text": "It is an open source automated testing suite for web applications across different browsers and platforms. It is not a single tool but a suite of software. We have selenium bindings for Python, Java, C#, Ruby and JavaScript. Here we are going to perform web scraping by using selenium and its Python bindings. You can learn more about Selenium with Java on the link Selenium. " }, { "code": null, "e": 9415, "s": 9235, "text": "Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, IE, Chrome, Remote etc. The current supported Python versions are 2.7, 3.5 and above." }, { "code": null, "e": 9522, "s": 9415, "text": "Using the pip command, we can install urllib3 either in our virtual environment or in global installation." }, { "code": null, "e": 9544, "s": 9522, "text": "pip install selenium\n" }, { "code": null, "e": 9723, "s": 9544, "text": "As selenium requires a driver to interface with the chosen browser, we need to download it. The following table shows different browsers and their links for downloading the same." }, { "code": null, "e": 9730, "s": 9723, "text": "Chrome" }, { "code": null, "e": 9771, "s": 9730, "text": "https://sites.google.com/a/chromium.org/" }, { "code": null, "e": 9776, "s": 9771, "text": "Edge" }, { "code": null, "e": 9809, "s": 9776, "text": "https://developer.microsoft.com/" }, { "code": null, "e": 9817, "s": 9809, "text": "Firefox" }, { "code": null, "e": 9837, "s": 9817, "text": "https://github.com/" }, { "code": null, "e": 9844, "s": 9837, "text": "Safari" }, { "code": null, "e": 9864, "s": 9844, "text": "https://webkit.org/" }, { "code": null, "e": 9978, "s": 9864, "text": "This example shows web scraping using selenium. It can also be used for testing which is called selenium testing." }, { "code": null, "e": 10093, "s": 9978, "text": "After downloading the particular driver for the specified version of browser, we need to do programming in Python." }, { "code": null, "e": 10152, "s": 10093, "text": "First, need to import webdriver from selenium as follows −" }, { "code": null, "e": 10184, "s": 10152, "text": "from selenium import webdriver\n" }, { "code": null, "e": 10270, "s": 10184, "text": "Now, provide the path of web driver which we have downloaded as per our requirement −" }, { "code": null, "e": 10373, "s": 10270, "text": "path = r'C:\\\\Users\\\\gaurav\\\\Desktop\\\\Chromedriver'\nbrowser = webdriver.Chrome(executable_path = path)\n" }, { "code": null, "e": 10473, "s": 10373, "text": "Now, provide the url which we want to open in that web browser now controlled by our Python script." }, { "code": null, "e": 10541, "s": 10473, "text": "browser.get('https://authoraditiagarwal.com/leadershipmanagement')\n" }, { "code": null, "e": 10625, "s": 10541, "text": "We can also scrape a particular element by providing the xpath as provided in lxml." }, { "code": null, "e": 10678, "s": 10625, "text": "browser.find_element_by_xpath('/html/body').click()\n" }, { "code": null, "e": 10746, "s": 10678, "text": "You can check the browser, controlled by Python script, for output." }, { "code": null, "e": 11107, "s": 10746, "text": "Scrapy is a fast, open-source web crawling framework written in Python, used to extract the data from the web page with the help of selectors based on XPath. Scrapy was first released on June 26, 2008 licensed under BSD, with a milestone 1.0 releasing in June 2015. It provides us all the tools we need to extract, process and structure the data from websites." }, { "code": null, "e": 11214, "s": 11107, "text": "Using the pip command, we can install urllib3 either in our virtual environment or in global installation." }, { "code": null, "e": 11234, "s": 11214, "text": "pip install scrapy\n" }, { "code": null, "e": 11296, "s": 11234, "text": "For more detail study of Scrapy you can go to the link\nScrapy" }, { "code": null, "e": 11333, "s": 11296, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 11349, "s": 11333, "text": " Malhar Lathkar" }, { "code": null, "e": 11382, "s": 11349, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 11401, "s": 11382, "text": " Arnab Chakraborty" }, { "code": null, "e": 11436, "s": 11401, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 11458, "s": 11436, "text": " In28Minutes Official" }, { "code": null, "e": 11492, "s": 11458, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 11520, "s": 11492, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11555, "s": 11520, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 11569, "s": 11555, "text": " Lets Kode It" }, { "code": null, "e": 11602, "s": 11569, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 11619, "s": 11602, "text": " Abhilash Nelson" }, { "code": null, "e": 11626, "s": 11619, "text": " Print" }, { "code": null, "e": 11637, "s": 11626, "text": " Add Notes" } ]
Drowsiness Detection with Machine Learning | by Grant Zhong | Towards Data Science
Team Members: Grant Zhong, Rui Ying, He Wang, Aurangzaib Siddiqui, Gaurav Choudhary “1 in 25 adult drivers report that they have fallen asleep at the wheel in the past 30 days” If you have driven before, you’ve been drowsy at the wheel at some point. It’s not something we like to admit but it’s an important problem with serious consequences that needs to be addressed. 1 in 4 vehicle accidents are caused by drowsy driving and 1 in 25 adult drivers report that they have fallen asleep at the wheel in the past 30 days. The scariest part is that drowsy driving isn’t just falling asleep while driving. Drowsy driving can be as small as a brief state of unconsciousness when the driver is not paying full attention to the road. Drowsy driving results in over 71,000 injuries, 1,500 deaths, and $12.5 billion in monetary losses per year. Due to the relevance of this problem, we believe it is important to develop a solution for drowsiness detection, especially in the early stages to prevent accidents. Additionally, we believe that drowsiness can negatively impact people in working and classroom environments as well. Although sleep deprivation and college go hand in hand, drowsiness in the workplace especially while working with heavy machinery may result in serious injuries similar to those that occur while driving drowsily. Our solution to this problem is to build a detection system that identifies key attributes of drowsiness and triggers an alert when someone is drowsy before it is too late. For our training and test data, we used the Real-Life Drowsiness Dataset created by a research team from the University of Texas at Arlington specifically for detecting multi-stage drowsiness. The end goal is to detect not only extreme and visible cases of drowsiness but allow our system to detect softer signals of drowsiness as well. The dataset consists of around 30 hours of videos of 60 unique participants. From the dataset, we were able to extract facial landmarks from 44 videos of 22 participants. This allowed us to obtain a sufficient amount of data for both the alert and drowsy state. For each video, we used OpenCV to extract 1 frame per second starting at the 3-minute mark until the end of the video. import cv2data = []labels = []for j in [60]: for i in [10]: vidcap = cv2.VideoCapture(‘drive/My Drive/Fold5_part2/’ + str(j) +’/’ + str(i) + ‘.mp4’) sec = 0 frameRate = 1 success, image = getFrame(sec) count = 0 while success and count < 240: landmarks = extract_face_landmarks(image) if sum(sum(landmarks)) != 0: count += 1 data.append(landmarks) labels.append([i]) sec = sec + frameRate sec = round(sec, 2) success, image = getFrame(sec) print(count) else: sec = sec + frameRate sec = round(sec, 2) success, image = getFrame(sec) print(“not detected”) Each video was approximately 10 minutes long, so we extracted around 240 frames per video, resulting in 10560 frames for the entire dataset. There were 68 total landmarks per frame but we decided to keep the landmarks for the eyes and mouth only (Points 37–68). These were the important data points we used to extract the features for our model. As briefly alluded to earlier, based on the facial landmarks that we extracted from the frames of the videos, we ventured into developing suitable features for our classification model. While we hypothesized and tested several features, the four core features that we concluded on for our final models were eye aspect ratio, mouth aspect ratio, pupil circularity, and finally, mouth aspect ratio over eye aspect ratio. Eye Aspect Ratio (EAR) EAR, as the name suggests, is the ratio of the length of the eyes to the width of the eyes. The length of the eyes is calculated by averaging over two distinct vertical lines across the eyes as illustrated in the figure below. Our hypothesis was that when an individual is drowsy, their eyes are likely to get smaller and they are likely to blink more. Based on this hypothesis, we expected our model to predict the class as drowsy if the eye aspect ratio for an individual over successive frames started to decline i.e. their eyes started to be more closed or they were blinking faster. Mouth Aspect Ratio (MAR) Computationally similar to the EAR, the MAR, as you would expect, measures the ratio of the length of the mouth to the width of the mouth. Our hypothesis was that as an individual becomes drowsy, they are likely to yawn and lose control over their mouth, making their MAR to be higher than usual in this state. Pupil Circularity (PUC) PUC is a measure complementary to EAR, but it places a greater emphasis on the pupil instead of the entire eye. For example, someone who has their eyes half-open or almost closed will have a much lower pupil circularity value versus someone who has their eyes fully open due to the squared term in the denominator. Similar to the EAR, the expectation was that when an individual is drowsy, their pupil circularity is likely to decline. Mouth aspect ratio over Eye aspect ratio (MOE) Finally, we decided to add MOE as another feature. MOE is simply the ratio of the MAR to the EAR. The benefit of using this feature is that EAR and MAR are expected to move in opposite directions if the state of the individual changes. As opposed to both EAR and MAR, MOE as a measure will be more responsive to these changes as it will capture the subtle changes in both EAR and MAR and will exaggerate the changes as the denominator and numerator move in opposite directions. Because the MOE takes MAR as the numerator and EAR as the denominator, our theory was that as the individual gets drowsy, the MOE will increase. While all these features made intuitive sense, when tested with our classification models, they yielded poor results in the range of 55% to 60% accuracy which is only a minor improvement over the baseline accuracy of 50% for a binary balanced classification problem. Nonetheless, this disappointment led us to our most important discovery: the features weren’t wrong, we just weren’t looking at them correctly. When we were testing our models with the four core features discussed above, we witnessed an alarming pattern. Whenever we randomly split the frames in our training and test, our model would yield results with accuracy as high 70%, however, whenever we split the frames by individuals (i.e. an individual that is in the test set will not be in the training set), our model performance would be poor as alluded to earlier. This led us to the realization that our model was struggling with new faces and the primary reason for this struggle was the fact that each individual has different core features in their default alert state. That is, person A may naturally have much smaller eyes than person B. If a model is trained on person B, the model, when tested on person A, will always predict the state as drowsy because it will detect a fall in EAR and PUC and a rise in MOE even though person A was alert. Based on this discovery, we hypothesized that normalizing the features for each individual is likely to yield better results and as it turned out, we were correct. To normalize the features of each individual, we took the first three frames for each individual’s alert video and used them as the baseline for normalization. The mean and standard deviation of each feature for these three frames were calculated and used to normalize each feature individually for each participant. Mathematically, this is what the normalization equation looked like: Now that we had normalized each of the four core features, our feature set had eight features, each core feature complemented by its normalized version. We tested all eight features in our models and our results improved significantly. After we extracted and normalized our features, we wanted to try a series of modeling techniques, starting with the most basic classification models like logistic regression and Naive Bayes, moving on to more complex models containing neural networks and other deep learning approaches. It’s important to note the performance-interpretability tradeoff here. Although we prioritize top-performing models, interpretability is also important to us if we were to commercialize this solution and present its business implications to stakeholders who are not familiar with the machine learning lingo. In order to train and test our models, we split our dataset into data from 17 videos and data from 5 videos respectively. As a result, our training dataset contains 8160 rows and our test dataset contains 2400 rows. How do we introduce sequence to basic classification methods? One challenge we faced during this project was that we were trying to predict the label for each frame in the sequence. While complex models like LSTM and RNN can account for sequential data, basic classification models cannot. The way we dealt with this problem was to average the original prediction results with the prediction results from the previous two frames. Since our dataset was divided into training and test based on the individual participants and the data points are all in the order of time sequence, averaging makes sense in this case and allowed us to deliver more accurate predictions. From the different classification methods we tried, K-Nearest Neighbor (kNN, k = 25) had the highest out-of-sample accuracy of 77.21%. Naive Bayes performed the worst at 57.75% and we concluded that this was because the model has a harder time dealing with numerical data. Although kNN yielded the highest accuracy, the false-negative rate was quite high at 0.42 which means that there is a 42% probability that someone who is actually drowsy would be detected as alert by our system. In order to decrease the false-negative rate, we lowered the threshold from 0.5 to 0.4 which allowed our model to predict more cases drowsy than alert. Although the accuracies for some of the other models increased, kNN still reported the highest accuracy at 76.63% (k = 18) despite a decline in its own accuracy. We wanted to get a sense of feature importance so we visualized the results from our Random Forest model. Mouth Aspect Ratio after normalization turned out to be the most important feature out of our 8 features. This makes sense because when we are drowsy, we tend to yawn more frequently. Normalizing our features exaggerated this effect and made it a better indicator of drowsiness in different participants. Convolutional Neural Networks (CNN) are typically used to analyze image data and map images to output variables. However, we decided to build a 1-D CNN and send in numerical features as sequential input data to try and understand the spatial relationship between each feature for the two states. Our CNN model has 5 layers including 1 convolutional layer, 1 flatten later, 2 fully connected dense layers, and 1 dropout layer before the output layer. The flatten layer flattens the output from the convolutional layer and makes it linear before passing it into the first dense layer. The dropout layer randomly drops 20% of the output nodes from the second dense layer in order to prevent our model from overfitting to the training data. The final dense layer has a single output node that outputs 0 for alert and 1 for drowsy. Another method to deal with sequential data is using an LSTM model. LSTM networks are a special kind of Recurrent Neural Networks (RNN), capable of learning long-term dependencies in the data. Recurrent Neural Networks are feedback neural networks that have internal memory that allows information to persist. How can RNNs have an internal memory space while processing new data ? The answer is that when making a decision, RNNs consider not only the current input but also the output that it has learned from the previous inputs. This is also the main difference between RNNs and other neural networks. In other neural networks, the inputs are independent of each other. In RNNs, the inputs are related to each other. The formula is as below: We chose to use an LSTM network because it allows us to study long sequences without having to worry about the gradient vanishing problems faced by traditional RNNs. Within the LSTM network, there are three gates for each time step: Forget Gate, Input gate, and Output Gate. Forget Gate: as its name suggests, the gate tries to “forget” part of the memory from the previous output. Input Gate: the gate decides what should be kept from the input in order to modify the memory. Output Gate: the gate decides what the output is by combining the input and memory. First, we converted our videos into batches of data. Then, each batch was sent through a fully connected layer with 1024 hidden units using the sigmoid activation function. The next layer is our LSTM layer with 512 hidden units followed by 3 more FC layers until the final output layer as displayed below. After hyperparameter tuning, our optimized LSTM model achieved an overall accuracy of 77.08% with a much lower false-negative rate of 0.3 compared to the false-negative rate of our kNN model (0.42). Transfer learning focuses on using the knowledge gained while solving one problem and applying it to solve a different but related problem. It is a useful set of techniques especially for cases when we have limited time to train the model or limited data to fully train a neural network. Since the data we were working with had very few unique samples, we believed this problem would be a good candidate for using transfer learning. The model we decided to use is VGG16 with the Imagenet dataset. VGG16 is a convolutional neural network model which was proposed by K. Simonyan and A. Zisserman from the University of Oxford in their paper “Very Deep Convolutional Networks for Large-Scale Image Recognition”. The model managed to achieve 92.7% top-5 test accuracy in ImageNet, which is a dataset of over 14 million images belonging to 1000 classes. ImageNet is a dataset with over 15 million labeled high-resolution images belonging to about 22,000 different categories. The images were collected from the internet and labeled by human labelers using Amazon’s crowd-sourcing tool, Mechanical Turk. Since 2010, as part of the Pascal Visual Object Challenge, a competition called the ImageNet Large-Scale Visual Recognition Challenge (ILSVRC) is held annually. ILSVRC uses a smaller set of ImageNet with roughly 1000 images in each of 1000 categories. There are approximately 1.2 million training images, 50,000 validation images, and 150,000 testing images. ImageNet consists of images with different resolutions. Therefore, the resolution of images needs to be changed to a fixed value of 256×256. The image is rescaled and cropped out and the central 256×256 patch forms the resulting image. The input to cov1 layer is a 224 x 224 RGB image. The image is passed through a stack of convolutional layers, where the filters are used with a very small receptive field: 3×3. In one of the configurations, the model also utilizes 1×1 convolution filters, which can be seen as a linear transformation of the input channels followed by non-linear transformations. The convolution stride is fixed to 1 pixel; the spatial padding of convolutional layer input is such that the spatial resolution is preserved after convolution, i.e. the padding is 1-pixel for 3×3 convolutional layers. Spatial pooling is carried out by five max-pooling layers, which follow some of the convolutional layers. Not all the conv. layers are followed by max-pooling. Max-pooling is performed over a 2×2 pixel window, with a stride of 2. Three Fully-Connected (FC) layers follow a stack of convolutional layers: the first two have 4096 channels each, the third performs 1000-way ILSVRC classification and therefore contains 1000 channels. The final layer is a soft-max layer. The configuration of the fully connected layers is the same in all networks. All hidden layers are equipped with the rectification (ReLU) non-linearity. It is also noted that barring one none of the networks contain Local Response Normalisation (LRN), because such normalization does not improve the performance of the model, but leads to increased computation time. We split the training videos into 34,000 images which were screenshots taken every 10 frames. We fed these images to the VGG16 model. We believed that the number of images was sufficient to train the pre-trained model. We got the following accuracy scores after training the model for 50 epochs. Our results are shown below. It was clear that the model was overfitting. A possible explanation for this is that images that we passed through the model were of 22 respondents sitting virtually motionless in front of a camera with undisturbed backgrounds. So despite taking a large number of frames (34,000) into our model, the model was essentially trying to learn from 22 sets of virtually identical images. Hence the model didn’t really have enough training data in a true sense. We learned quite a few things throughout this project. First, simpler models can be just as efficient at completing tasks as more complex models. In our case, the K-Nearest Neighbor model gave an accuracy similar to the LSTM model. However, because we do not want to misclassify people who are drowsy as alert, ultimately it is better to use the more complex model with a lower false-negative rate than a simpler model that may be cheaper to deploy. Second, normalization was crucial to our performance. We recognized that everybody has a different baseline for eye and mouth aspect ratios and normalizing for each participant was necessary. Outside of runtime for our models, data pre-processing and feature extraction/normalization took up a bulk of our time. It will be interesting to update our project and look into how we can decrease the false-negative rate for kNN and other simpler models. Moving forward, there are a few things we can do to further improve our results and fine-tune the models. First, we need to incorporate distance between the facial landmarks to account for any movement by the subject in the video. Realistically the participants will not be static on the screen and we believe sudden movements by the participant may signal drowsiness or waking up from micro-sleep. Second, we want to update parameters with our more complex models (NNs, ensembles, etc.) in order to achieve better results. Third and finally, we would like to collect our own training data from a larger sample of participants (more data!!!) while including new distinct signals of drowsiness like sudden head movement, hand movement, or even tracking eye movements. We wanted to include a few screenshots of our system in action! First, we need to calibrate the system to the participant as shown below. Now, the system should automatically detect whether the participant is drowsy or alert. Examples are shown below. Thank you so much for reading through our entire blog! Feel free to reach out to any of us on LinkedIn with any questions or suggestions on how we can improve our system. Full project and code can be viewed on GitHub! We would like to give a special “Thank You” to Dr. Joydeep Ghosh who was able to provide incredibly valuable guidance throughout this project.
[ { "code": null, "e": 256, "s": 172, "text": "Team Members: Grant Zhong, Rui Ying, He Wang, Aurangzaib Siddiqui, Gaurav Choudhary" }, { "code": null, "e": 349, "s": 256, "text": "“1 in 25 adult drivers report that they have fallen asleep at the wheel in the past 30 days”" }, { "code": null, "e": 1175, "s": 349, "text": "If you have driven before, you’ve been drowsy at the wheel at some point. It’s not something we like to admit but it’s an important problem with serious consequences that needs to be addressed. 1 in 4 vehicle accidents are caused by drowsy driving and 1 in 25 adult drivers report that they have fallen asleep at the wheel in the past 30 days. The scariest part is that drowsy driving isn’t just falling asleep while driving. Drowsy driving can be as small as a brief state of unconsciousness when the driver is not paying full attention to the road. Drowsy driving results in over 71,000 injuries, 1,500 deaths, and $12.5 billion in monetary losses per year. Due to the relevance of this problem, we believe it is important to develop a solution for drowsiness detection, especially in the early stages to prevent accidents." }, { "code": null, "e": 1505, "s": 1175, "text": "Additionally, we believe that drowsiness can negatively impact people in working and classroom environments as well. Although sleep deprivation and college go hand in hand, drowsiness in the workplace especially while working with heavy machinery may result in serious injuries similar to those that occur while driving drowsily." }, { "code": null, "e": 1678, "s": 1505, "text": "Our solution to this problem is to build a detection system that identifies key attributes of drowsiness and triggers an alert when someone is drowsy before it is too late." }, { "code": null, "e": 2277, "s": 1678, "text": "For our training and test data, we used the Real-Life Drowsiness Dataset created by a research team from the University of Texas at Arlington specifically for detecting multi-stage drowsiness. The end goal is to detect not only extreme and visible cases of drowsiness but allow our system to detect softer signals of drowsiness as well. The dataset consists of around 30 hours of videos of 60 unique participants. From the dataset, we were able to extract facial landmarks from 44 videos of 22 participants. This allowed us to obtain a sufficient amount of data for both the alert and drowsy state." }, { "code": null, "e": 2396, "s": 2277, "text": "For each video, we used OpenCV to extract 1 frame per second starting at the 3-minute mark until the end of the video." }, { "code": null, "e": 3131, "s": 2396, "text": "import cv2data = []labels = []for j in [60]: for i in [10]: vidcap = cv2.VideoCapture(‘drive/My Drive/Fold5_part2/’ + str(j) +’/’ + str(i) + ‘.mp4’) sec = 0 frameRate = 1 success, image = getFrame(sec) count = 0 while success and count < 240: landmarks = extract_face_landmarks(image) if sum(sum(landmarks)) != 0: count += 1 data.append(landmarks) labels.append([i]) sec = sec + frameRate sec = round(sec, 2) success, image = getFrame(sec) print(count) else: sec = sec + frameRate sec = round(sec, 2) success, image = getFrame(sec) print(“not detected”)" }, { "code": null, "e": 3272, "s": 3131, "text": "Each video was approximately 10 minutes long, so we extracted around 240 frames per video, resulting in 10560 frames for the entire dataset." }, { "code": null, "e": 3477, "s": 3272, "text": "There were 68 total landmarks per frame but we decided to keep the landmarks for the eyes and mouth only (Points 37–68). These were the important data points we used to extract the features for our model." }, { "code": null, "e": 3896, "s": 3477, "text": "As briefly alluded to earlier, based on the facial landmarks that we extracted from the frames of the videos, we ventured into developing suitable features for our classification model. While we hypothesized and tested several features, the four core features that we concluded on for our final models were eye aspect ratio, mouth aspect ratio, pupil circularity, and finally, mouth aspect ratio over eye aspect ratio." }, { "code": null, "e": 3919, "s": 3896, "text": "Eye Aspect Ratio (EAR)" }, { "code": null, "e": 4146, "s": 3919, "text": "EAR, as the name suggests, is the ratio of the length of the eyes to the width of the eyes. The length of the eyes is calculated by averaging over two distinct vertical lines across the eyes as illustrated in the figure below." }, { "code": null, "e": 4507, "s": 4146, "text": "Our hypothesis was that when an individual is drowsy, their eyes are likely to get smaller and they are likely to blink more. Based on this hypothesis, we expected our model to predict the class as drowsy if the eye aspect ratio for an individual over successive frames started to decline i.e. their eyes started to be more closed or they were blinking faster." }, { "code": null, "e": 4532, "s": 4507, "text": "Mouth Aspect Ratio (MAR)" }, { "code": null, "e": 4843, "s": 4532, "text": "Computationally similar to the EAR, the MAR, as you would expect, measures the ratio of the length of the mouth to the width of the mouth. Our hypothesis was that as an individual becomes drowsy, they are likely to yawn and lose control over their mouth, making their MAR to be higher than usual in this state." }, { "code": null, "e": 4867, "s": 4843, "text": "Pupil Circularity (PUC)" }, { "code": null, "e": 4979, "s": 4867, "text": "PUC is a measure complementary to EAR, but it places a greater emphasis on the pupil instead of the entire eye." }, { "code": null, "e": 5303, "s": 4979, "text": "For example, someone who has their eyes half-open or almost closed will have a much lower pupil circularity value versus someone who has their eyes fully open due to the squared term in the denominator. Similar to the EAR, the expectation was that when an individual is drowsy, their pupil circularity is likely to decline." }, { "code": null, "e": 5350, "s": 5303, "text": "Mouth aspect ratio over Eye aspect ratio (MOE)" }, { "code": null, "e": 5448, "s": 5350, "text": "Finally, we decided to add MOE as another feature. MOE is simply the ratio of the MAR to the EAR." }, { "code": null, "e": 5973, "s": 5448, "text": "The benefit of using this feature is that EAR and MAR are expected to move in opposite directions if the state of the individual changes. As opposed to both EAR and MAR, MOE as a measure will be more responsive to these changes as it will capture the subtle changes in both EAR and MAR and will exaggerate the changes as the denominator and numerator move in opposite directions. Because the MOE takes MAR as the numerator and EAR as the denominator, our theory was that as the individual gets drowsy, the MOE will increase." }, { "code": null, "e": 6384, "s": 5973, "text": "While all these features made intuitive sense, when tested with our classification models, they yielded poor results in the range of 55% to 60% accuracy which is only a minor improvement over the baseline accuracy of 50% for a binary balanced classification problem. Nonetheless, this disappointment led us to our most important discovery: the features weren’t wrong, we just weren’t looking at them correctly." }, { "code": null, "e": 6806, "s": 6384, "text": "When we were testing our models with the four core features discussed above, we witnessed an alarming pattern. Whenever we randomly split the frames in our training and test, our model would yield results with accuracy as high 70%, however, whenever we split the frames by individuals (i.e. an individual that is in the test set will not be in the training set), our model performance would be poor as alluded to earlier." }, { "code": null, "e": 7455, "s": 6806, "text": "This led us to the realization that our model was struggling with new faces and the primary reason for this struggle was the fact that each individual has different core features in their default alert state. That is, person A may naturally have much smaller eyes than person B. If a model is trained on person B, the model, when tested on person A, will always predict the state as drowsy because it will detect a fall in EAR and PUC and a rise in MOE even though person A was alert. Based on this discovery, we hypothesized that normalizing the features for each individual is likely to yield better results and as it turned out, we were correct." }, { "code": null, "e": 7841, "s": 7455, "text": "To normalize the features of each individual, we took the first three frames for each individual’s alert video and used them as the baseline for normalization. The mean and standard deviation of each feature for these three frames were calculated and used to normalize each feature individually for each participant. Mathematically, this is what the normalization equation looked like:" }, { "code": null, "e": 8077, "s": 7841, "text": "Now that we had normalized each of the four core features, our feature set had eight features, each core feature complemented by its normalized version. We tested all eight features in our models and our results improved significantly." }, { "code": null, "e": 8888, "s": 8077, "text": "After we extracted and normalized our features, we wanted to try a series of modeling techniques, starting with the most basic classification models like logistic regression and Naive Bayes, moving on to more complex models containing neural networks and other deep learning approaches. It’s important to note the performance-interpretability tradeoff here. Although we prioritize top-performing models, interpretability is also important to us if we were to commercialize this solution and present its business implications to stakeholders who are not familiar with the machine learning lingo. In order to train and test our models, we split our dataset into data from 17 videos and data from 5 videos respectively. As a result, our training dataset contains 8160 rows and our test dataset contains 2400 rows." }, { "code": null, "e": 8950, "s": 8888, "text": "How do we introduce sequence to basic classification methods?" }, { "code": null, "e": 9178, "s": 8950, "text": "One challenge we faced during this project was that we were trying to predict the label for each frame in the sequence. While complex models like LSTM and RNN can account for sequential data, basic classification models cannot." }, { "code": null, "e": 9555, "s": 9178, "text": "The way we dealt with this problem was to average the original prediction results with the prediction results from the previous two frames. Since our dataset was divided into training and test based on the individual participants and the data points are all in the order of time sequence, averaging makes sense in this case and allowed us to deliver more accurate predictions." }, { "code": null, "e": 10354, "s": 9555, "text": "From the different classification methods we tried, K-Nearest Neighbor (kNN, k = 25) had the highest out-of-sample accuracy of 77.21%. Naive Bayes performed the worst at 57.75% and we concluded that this was because the model has a harder time dealing with numerical data. Although kNN yielded the highest accuracy, the false-negative rate was quite high at 0.42 which means that there is a 42% probability that someone who is actually drowsy would be detected as alert by our system. In order to decrease the false-negative rate, we lowered the threshold from 0.5 to 0.4 which allowed our model to predict more cases drowsy than alert. Although the accuracies for some of the other models increased, kNN still reported the highest accuracy at 76.63% (k = 18) despite a decline in its own accuracy." }, { "code": null, "e": 10460, "s": 10354, "text": "We wanted to get a sense of feature importance so we visualized the results from our Random Forest model." }, { "code": null, "e": 10765, "s": 10460, "text": "Mouth Aspect Ratio after normalization turned out to be the most important feature out of our 8 features. This makes sense because when we are drowsy, we tend to yawn more frequently. Normalizing our features exaggerated this effect and made it a better indicator of drowsiness in different participants." }, { "code": null, "e": 11592, "s": 10765, "text": "Convolutional Neural Networks (CNN) are typically used to analyze image data and map images to output variables. However, we decided to build a 1-D CNN and send in numerical features as sequential input data to try and understand the spatial relationship between each feature for the two states. Our CNN model has 5 layers including 1 convolutional layer, 1 flatten later, 2 fully connected dense layers, and 1 dropout layer before the output layer. The flatten layer flattens the output from the convolutional layer and makes it linear before passing it into the first dense layer. The dropout layer randomly drops 20% of the output nodes from the second dense layer in order to prevent our model from overfitting to the training data. The final dense layer has a single output node that outputs 0 for alert and 1 for drowsy." }, { "code": null, "e": 11902, "s": 11592, "text": "Another method to deal with sequential data is using an LSTM model. LSTM networks are a special kind of Recurrent Neural Networks (RNN), capable of learning long-term dependencies in the data. Recurrent Neural Networks are feedback neural networks that have internal memory that allows information to persist." }, { "code": null, "e": 11973, "s": 11902, "text": "How can RNNs have an internal memory space while processing new data ?" }, { "code": null, "e": 12336, "s": 11973, "text": "The answer is that when making a decision, RNNs consider not only the current input but also the output that it has learned from the previous inputs. This is also the main difference between RNNs and other neural networks. In other neural networks, the inputs are independent of each other. In RNNs, the inputs are related to each other. The formula is as below:" }, { "code": null, "e": 12611, "s": 12336, "text": "We chose to use an LSTM network because it allows us to study long sequences without having to worry about the gradient vanishing problems faced by traditional RNNs. Within the LSTM network, there are three gates for each time step: Forget Gate, Input gate, and Output Gate." }, { "code": null, "e": 12718, "s": 12611, "text": "Forget Gate: as its name suggests, the gate tries to “forget” part of the memory from the previous output." }, { "code": null, "e": 12813, "s": 12718, "text": "Input Gate: the gate decides what should be kept from the input in order to modify the memory." }, { "code": null, "e": 12897, "s": 12813, "text": "Output Gate: the gate decides what the output is by combining the input and memory." }, { "code": null, "e": 13203, "s": 12897, "text": "First, we converted our videos into batches of data. Then, each batch was sent through a fully connected layer with 1024 hidden units using the sigmoid activation function. The next layer is our LSTM layer with 512 hidden units followed by 3 more FC layers until the final output layer as displayed below." }, { "code": null, "e": 13402, "s": 13203, "text": "After hyperparameter tuning, our optimized LSTM model achieved an overall accuracy of 77.08% with a much lower false-negative rate of 0.3 compared to the false-negative rate of our kNN model (0.42)." }, { "code": null, "e": 13899, "s": 13402, "text": "Transfer learning focuses on using the knowledge gained while solving one problem and applying it to solve a different but related problem. It is a useful set of techniques especially for cases when we have limited time to train the model or limited data to fully train a neural network. Since the data we were working with had very few unique samples, we believed this problem would be a good candidate for using transfer learning. The model we decided to use is VGG16 with the Imagenet dataset." }, { "code": null, "e": 14251, "s": 13899, "text": "VGG16 is a convolutional neural network model which was proposed by K. Simonyan and A. Zisserman from the University of Oxford in their paper “Very Deep Convolutional Networks for Large-Scale Image Recognition”. The model managed to achieve 92.7% top-5 test accuracy in ImageNet, which is a dataset of over 14 million images belonging to 1000 classes." }, { "code": null, "e": 15095, "s": 14251, "text": "ImageNet is a dataset with over 15 million labeled high-resolution images belonging to about 22,000 different categories. The images were collected from the internet and labeled by human labelers using Amazon’s crowd-sourcing tool, Mechanical Turk. Since 2010, as part of the Pascal Visual Object Challenge, a competition called the ImageNet Large-Scale Visual Recognition Challenge (ILSVRC) is held annually. ILSVRC uses a smaller set of ImageNet with roughly 1000 images in each of 1000 categories. There are approximately 1.2 million training images, 50,000 validation images, and 150,000 testing images. ImageNet consists of images with different resolutions. Therefore, the resolution of images needs to be changed to a fixed value of 256×256. The image is rescaled and cropped out and the central 256×256 patch forms the resulting image." }, { "code": null, "e": 15908, "s": 15095, "text": "The input to cov1 layer is a 224 x 224 RGB image. The image is passed through a stack of convolutional layers, where the filters are used with a very small receptive field: 3×3. In one of the configurations, the model also utilizes 1×1 convolution filters, which can be seen as a linear transformation of the input channels followed by non-linear transformations. The convolution stride is fixed to 1 pixel; the spatial padding of convolutional layer input is such that the spatial resolution is preserved after convolution, i.e. the padding is 1-pixel for 3×3 convolutional layers. Spatial pooling is carried out by five max-pooling layers, which follow some of the convolutional layers. Not all the conv. layers are followed by max-pooling. Max-pooling is performed over a 2×2 pixel window, with a stride of 2." }, { "code": null, "e": 16223, "s": 15908, "text": "Three Fully-Connected (FC) layers follow a stack of convolutional layers: the first two have 4096 channels each, the third performs 1000-way ILSVRC classification and therefore contains 1000 channels. The final layer is a soft-max layer. The configuration of the fully connected layers is the same in all networks." }, { "code": null, "e": 16513, "s": 16223, "text": "All hidden layers are equipped with the rectification (ReLU) non-linearity. It is also noted that barring one none of the networks contain Local Response Normalisation (LRN), because such normalization does not improve the performance of the model, but leads to increased computation time." }, { "code": null, "e": 16838, "s": 16513, "text": "We split the training videos into 34,000 images which were screenshots taken every 10 frames. We fed these images to the VGG16 model. We believed that the number of images was sufficient to train the pre-trained model. We got the following accuracy scores after training the model for 50 epochs. Our results are shown below." }, { "code": null, "e": 17293, "s": 16838, "text": "It was clear that the model was overfitting. A possible explanation for this is that images that we passed through the model were of 22 respondents sitting virtually motionless in front of a camera with undisturbed backgrounds. So despite taking a large number of frames (34,000) into our model, the model was essentially trying to learn from 22 sets of virtually identical images. Hence the model didn’t really have enough training data in a true sense." }, { "code": null, "e": 18192, "s": 17293, "text": "We learned quite a few things throughout this project. First, simpler models can be just as efficient at completing tasks as more complex models. In our case, the K-Nearest Neighbor model gave an accuracy similar to the LSTM model. However, because we do not want to misclassify people who are drowsy as alert, ultimately it is better to use the more complex model with a lower false-negative rate than a simpler model that may be cheaper to deploy. Second, normalization was crucial to our performance. We recognized that everybody has a different baseline for eye and mouth aspect ratios and normalizing for each participant was necessary. Outside of runtime for our models, data pre-processing and feature extraction/normalization took up a bulk of our time. It will be interesting to update our project and look into how we can decrease the false-negative rate for kNN and other simpler models." }, { "code": null, "e": 18959, "s": 18192, "text": "Moving forward, there are a few things we can do to further improve our results and fine-tune the models. First, we need to incorporate distance between the facial landmarks to account for any movement by the subject in the video. Realistically the participants will not be static on the screen and we believe sudden movements by the participant may signal drowsiness or waking up from micro-sleep. Second, we want to update parameters with our more complex models (NNs, ensembles, etc.) in order to achieve better results. Third and finally, we would like to collect our own training data from a larger sample of participants (more data!!!) while including new distinct signals of drowsiness like sudden head movement, hand movement, or even tracking eye movements." }, { "code": null, "e": 19023, "s": 18959, "text": "We wanted to include a few screenshots of our system in action!" }, { "code": null, "e": 19097, "s": 19023, "text": "First, we need to calibrate the system to the participant as shown below." }, { "code": null, "e": 19211, "s": 19097, "text": "Now, the system should automatically detect whether the participant is drowsy or alert. Examples are shown below." }, { "code": null, "e": 19382, "s": 19211, "text": "Thank you so much for reading through our entire blog! Feel free to reach out to any of us on LinkedIn with any questions or suggestions on how we can improve our system." }, { "code": null, "e": 19429, "s": 19382, "text": "Full project and code can be viewed on GitHub!" } ]
Thread Pools in C#
Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused. Let us see how to create a thread pool. Firstly, use the following namespace − using System.Threading; Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem − ThreadPool.QueueUserWorkItem(new WaitCallback(Run)); Iterate this in a loop and compare it with a normal Thread object.
[ { "code": null, "e": 1295, "s": 1062, "text": "Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused." }, { "code": null, "e": 1335, "s": 1295, "text": "Let us see how to create a thread pool." }, { "code": null, "e": 1374, "s": 1335, "text": "Firstly, use the following namespace −" }, { "code": null, "e": 1398, "s": 1374, "text": "using System.Threading;" }, { "code": null, "e": 1495, "s": 1398, "text": "Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem −" }, { "code": null, "e": 1549, "s": 1495, "text": "ThreadPool.QueueUserWorkItem(new WaitCallback(Run));\n" }, { "code": null, "e": 1616, "s": 1549, "text": "Iterate this in a loop and compare it with a normal Thread object." } ]
Batch Script - Echo Command - GeeksforGeeks
05 Nov, 2021 In most of the modern and traditional operating systems, there are one or more user interfaces (e.g. Command Line Interface(CLI), Graphical User Interface(GUI), Touch Screen Interface, etc.) provided by the shell to interact with the kernel. Command Prompt, PowerShell in Windows, Terminal in Linux, Terminology in Bodhi Linux, and various types of Terminal Emulators [also called Pseudo Terminals] (e.g. Cmder, XTerm, Termux, Cool Retro Term, Tilix, PuTTY, etc.) are the examples of CLI applications. They act as interpreters for the various types of commands we write. We can perform most of the required operations (e.g. I/O, file management, network management, etc.) by executing proper commands in the command line. If we want to execute a series of commands/instructions we can do that by writing those commands line by line in a text file and giving it a special extension (e.g. .bat or .cmd for Windows/DOS and .sh for Linux) and then executing this file in the CLI application. Now all the commands will be executed (interpreted) serially in a sequence (one by one) by the shell just like any interpreted programming language. This type of scripting is called Batch Scripting (in Windows) and Bash Scripting (in Linux). Step 1: Open your preferred directory using the file explorer and click on View. Then go to the Show/hide section and make sure that the “File name extensions” are ticked. Step 2: Now create a text file and give it a name (e.g. 123.bat) and edit it with notepad and write the following commands and save it. echo on echo "Great day ahead" ver Step 3: Now save the file and execute this in the CLI app (basically in CMD). The output will be like the following. It was a very basic example of batch scripting. Hereby using echo on we ensure that command echoing is on i.e. all the commands will be displayed including this command itself. The next command prints a string “Great day ahead” on the screen and the ver command displays the version of the currently running OS. Note that the commands are not case sensitive (e.g. echo and ECHO will give the same output). Now I will discuss everything about the ECHO command. The ECHO command is used to print some text (string) on the screen or to turn the on/off command echoing on the screen. echo [<any text message to print on the screen>] or echo [<on> | <off>] When echo is used without any parameter it will show the current command echoing setting (on/off). echo Example: We can print any text message on the screen using echo. The message is not needed to be enclosed within single quotes or double quotes ( ‘ or “), moreover any type of quote will also be printed on the screen. echo <any text message to print on the screen> Example: By using echo on we can turn on command echoing i.e. all the commands in a batch file will also be printed on the screen as well as their outputs. By using echo off we can turn off command echoing i.e. no commands in the batch file will be printed on the screen but only their outputs, but the command echo off itself will be printed. echo [<on> | <off>] Example: This is an example where the command echoing is turned on. Let’s see the output. Example: This is an example where the command echoing is turned off. Let’s see the output. We have seen that when we use echo off it will turn off command echoing but it will print the command echo off itself. To handle this situation we can use @echo off as it will turn off command echoing and also will not print this command itself. @echo off Example: Let’s see the output. We can declare a variable and set its value using the following syntax. set variable_name=value We can print the value of a variable using the following syntax. echo %variable_name% Note that we can put the %variable_name% anywhere between any text to be printed. Example: We can concatenate two string variables and print the new string using echo. Example: Batch-script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n05 Nov, 2021" }, { "code": null, "e": 24737, "s": 24015, "text": "In most of the modern and traditional operating systems, there are one or more user interfaces (e.g. Command Line Interface(CLI), Graphical User Interface(GUI), Touch Screen Interface, etc.) provided by the shell to interact with the kernel. Command Prompt, PowerShell in Windows, Terminal in Linux, Terminology in Bodhi Linux, and various types of Terminal Emulators [also called Pseudo Terminals] (e.g. Cmder, XTerm, Termux, Cool Retro Term, Tilix, PuTTY, etc.) are the examples of CLI applications. They act as interpreters for the various types of commands we write. We can perform most of the required operations (e.g. I/O, file management, network management, etc.) by executing proper commands in the command line." }, { "code": null, "e": 25246, "s": 24737, "text": "If we want to execute a series of commands/instructions we can do that by writing those commands line by line in a text file and giving it a special extension (e.g. .bat or .cmd for Windows/DOS and .sh for Linux) and then executing this file in the CLI application. Now all the commands will be executed (interpreted) serially in a sequence (one by one) by the shell just like any interpreted programming language. This type of scripting is called Batch Scripting (in Windows) and Bash Scripting (in Linux). " }, { "code": null, "e": 25418, "s": 25246, "text": "Step 1: Open your preferred directory using the file explorer and click on View. Then go to the Show/hide section and make sure that the “File name extensions” are ticked." }, { "code": null, "e": 25554, "s": 25418, "text": "Step 2: Now create a text file and give it a name (e.g. 123.bat) and edit it with notepad and write the following commands and save it." }, { "code": null, "e": 25589, "s": 25554, "text": "echo on\necho \"Great day ahead\"\nver" }, { "code": null, "e": 25706, "s": 25589, "text": "Step 3: Now save the file and execute this in the CLI app (basically in CMD). The output will be like the following." }, { "code": null, "e": 26166, "s": 25706, "text": "It was a very basic example of batch scripting. Hereby using echo on we ensure that command echoing is on i.e. all the commands will be displayed including this command itself. The next command prints a string “Great day ahead” on the screen and the ver command displays the version of the currently running OS. Note that the commands are not case sensitive (e.g. echo and ECHO will give the same output). Now I will discuss everything about the ECHO command." }, { "code": null, "e": 26286, "s": 26166, "text": "The ECHO command is used to print some text (string) on the screen or to turn the on/off command echoing on the screen." }, { "code": null, "e": 26335, "s": 26286, "text": "echo [<any text message to print on the screen>]" }, { "code": null, "e": 26338, "s": 26335, "text": "or" }, { "code": null, "e": 26358, "s": 26338, "text": "echo [<on> | <off>]" }, { "code": null, "e": 26457, "s": 26358, "text": "When echo is used without any parameter it will show the current command echoing setting (on/off)." }, { "code": null, "e": 26462, "s": 26457, "text": "echo" }, { "code": null, "e": 26471, "s": 26462, "text": "Example:" }, { "code": null, "e": 26682, "s": 26471, "text": "We can print any text message on the screen using echo. The message is not needed to be enclosed within single quotes or double quotes ( ‘ or “), moreover any type of quote will also be printed on the screen." }, { "code": null, "e": 26729, "s": 26682, "text": "echo <any text message to print on the screen>" }, { "code": null, "e": 26740, "s": 26729, "text": " Example:" }, { "code": null, "e": 26887, "s": 26740, "text": "By using echo on we can turn on command echoing i.e. all the commands in a batch file will also be printed on the screen as well as their outputs." }, { "code": null, "e": 27075, "s": 26887, "text": "By using echo off we can turn off command echoing i.e. no commands in the batch file will be printed on the screen but only their outputs, but the command echo off itself will be printed." }, { "code": null, "e": 27095, "s": 27075, "text": "echo [<on> | <off>]" }, { "code": null, "e": 27104, "s": 27095, "text": "Example:" }, { "code": null, "e": 27163, "s": 27104, "text": "This is an example where the command echoing is turned on." }, { "code": null, "e": 27185, "s": 27163, "text": "Let’s see the output." }, { "code": null, "e": 27194, "s": 27185, "text": "Example:" }, { "code": null, "e": 27254, "s": 27194, "text": "This is an example where the command echoing is turned off." }, { "code": null, "e": 27276, "s": 27254, "text": "Let’s see the output." }, { "code": null, "e": 27522, "s": 27276, "text": "We have seen that when we use echo off it will turn off command echoing but it will print the command echo off itself. To handle this situation we can use @echo off as it will turn off command echoing and also will not print this command itself." }, { "code": null, "e": 27532, "s": 27522, "text": "@echo off" }, { "code": null, "e": 27541, "s": 27532, "text": "Example:" }, { "code": null, "e": 27563, "s": 27541, "text": "Let’s see the output." }, { "code": null, "e": 27635, "s": 27563, "text": "We can declare a variable and set its value using the following syntax." }, { "code": null, "e": 27659, "s": 27635, "text": "set variable_name=value" }, { "code": null, "e": 27724, "s": 27659, "text": "We can print the value of a variable using the following syntax." }, { "code": null, "e": 27745, "s": 27724, "text": "echo %variable_name%" }, { "code": null, "e": 27827, "s": 27745, "text": "Note that we can put the %variable_name% anywhere between any text to be printed." }, { "code": null, "e": 27836, "s": 27827, "text": "Example:" }, { "code": null, "e": 27913, "s": 27836, "text": "We can concatenate two string variables and print the new string using echo." }, { "code": null, "e": 27922, "s": 27913, "text": "Example:" }, { "code": null, "e": 27935, "s": 27922, "text": "Batch-script" }, { "code": null, "e": 27942, "s": 27935, "text": "Picked" }, { "code": null, "e": 27953, "s": 27942, "text": "Linux-Unix" }, { "code": null, "e": 28051, "s": 27953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28060, "s": 28051, "text": "Comments" }, { "code": null, "e": 28073, "s": 28060, "text": "Old Comments" }, { "code": null, "e": 28108, "s": 28073, "text": "scp command in Linux with Examples" }, { "code": null, "e": 28145, "s": 28108, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 28179, "s": 28145, "text": "mv command in Linux with examples" }, { "code": null, "e": 28205, "s": 28179, "text": "Thread functions in C/C++" }, { "code": null, "e": 28231, "s": 28205, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28268, "s": 28231, "text": "chown command in Linux with Examples" }, { "code": null, "e": 28308, "s": 28268, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 28337, "s": 28308, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 28379, "s": 28337, "text": "Named Pipe or FIFO with example C program" } ]
ArrayList of ArrayList in Java - GeeksforGeeks
11 Dec, 2018 We have discussed that an array of ArrayList is not possible without warning. A better idea is to use ArrayList of ArrayList. // Java code to demonstrate the concept of// array of ArrayList import java.util.*;public class Arraylist { public static void main(String[] args) { int n = 3; // Here aList is an ArrayList of ArrayLists ArrayList<ArrayList<Integer> > aList = new ArrayList<ArrayList<Integer> >(n); // Create n lists one by one and append to the // master list (ArrayList of ArrayList) ArrayList<Integer> a1 = new ArrayList<Integer>(); a1.add(1); a1.add(2); aList.add(a1); ArrayList<Integer> a2 = new ArrayList<Integer>(); a2.add(5); aList.add(a2); ArrayList<Integer> a3 = new ArrayList<Integer>(); a3.add(10); a3.add(20); a3.add(30); aList.add(a3); for (int i = 0; i < aList.size(); i++) { for (int j = 0; j < aList.get(i).size(); j++) { System.out.print(aList.get(i).get(j) + " "); } System.out.println(); } }} 1 2 5 10 20 30 Java - util package Java-ArrayList Java-Arrays Java-Collections Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Multithreading in Java Set in Java
[ { "code": null, "e": 24412, "s": 24384, "text": "\n11 Dec, 2018" }, { "code": null, "e": 24538, "s": 24412, "text": "We have discussed that an array of ArrayList is not possible without warning. A better idea is to use ArrayList of ArrayList." }, { "code": "// Java code to demonstrate the concept of// array of ArrayList import java.util.*;public class Arraylist { public static void main(String[] args) { int n = 3; // Here aList is an ArrayList of ArrayLists ArrayList<ArrayList<Integer> > aList = new ArrayList<ArrayList<Integer> >(n); // Create n lists one by one and append to the // master list (ArrayList of ArrayList) ArrayList<Integer> a1 = new ArrayList<Integer>(); a1.add(1); a1.add(2); aList.add(a1); ArrayList<Integer> a2 = new ArrayList<Integer>(); a2.add(5); aList.add(a2); ArrayList<Integer> a3 = new ArrayList<Integer>(); a3.add(10); a3.add(20); a3.add(30); aList.add(a3); for (int i = 0; i < aList.size(); i++) { for (int j = 0; j < aList.get(i).size(); j++) { System.out.print(aList.get(i).get(j) + \" \"); } System.out.println(); } }}", "e": 25554, "s": 24538, "text": null }, { "code": null, "e": 25572, "s": 25554, "text": "1 2 \n5 \n10 20 30\n" }, { "code": null, "e": 25592, "s": 25572, "text": "Java - util package" }, { "code": null, "e": 25607, "s": 25592, "text": "Java-ArrayList" }, { "code": null, "e": 25619, "s": 25607, "text": "Java-Arrays" }, { "code": null, "e": 25636, "s": 25619, "text": "Java-Collections" }, { "code": null, "e": 25655, "s": 25636, "text": "Java-List-Programs" }, { "code": null, "e": 25660, "s": 25655, "text": "Java" }, { "code": null, "e": 25665, "s": 25660, "text": "Java" }, { "code": null, "e": 25682, "s": 25665, "text": "Java-Collections" }, { "code": null, "e": 25780, "s": 25682, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25789, "s": 25780, "text": "Comments" }, { "code": null, "e": 25802, "s": 25789, "text": "Old Comments" }, { "code": null, "e": 25832, "s": 25802, "text": "HashMap in Java with Examples" }, { "code": null, "e": 25851, "s": 25832, "text": "Interfaces in Java" }, { "code": null, "e": 25902, "s": 25851, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 25933, "s": 25902, "text": "How to iterate any Map in Java" }, { "code": null, "e": 25965, "s": 25933, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 25989, "s": 25965, "text": "Singleton Class in Java" }, { "code": null, "e": 26008, "s": 25989, "text": "Overriding in Java" }, { "code": null, "e": 26028, "s": 26008, "text": "Collections in Java" }, { "code": null, "e": 26051, "s": 26028, "text": "Multithreading in Java" } ]
Tryit Editor v3.7
HTML Input types Tryit: input number with restrictions
[ { "code": null, "e": 27, "s": 10, "text": "HTML Input types" } ]
Externalizable Interface in Java
Externalization is used whenever we need to customize serialization mechanism. If a class implements an Externalizable interface then, object serialization will be done using writeExternal() method. Whereas at receiver's end when an Externalizable object is a reconstructed instance will be created using no argument constructor and then the readExternal() method is called. If a class implements only Serializable interface object serialization will be done using ObjectoutputStream. At the receiver's end, the serializable object is reconstructed using ObjectInputStream. Below example showcases usage of Externalizable interface. import java.io.Externalizable; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; public class Tester { public static void main(String[] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.age = 30; try ( FileOutputStream fileOut = new FileOutputStream("test.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); ) { out.writeObject(e); }catch (IOException i) { System.out.println(i.getMessage()); } try ( FileInputStream fileIn = new FileInputStream("test.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); ) { e = (Employee)in.readObject(); System.out.println(e.name); System.out.println(e.age); } catch (IOException i) { System.out.println(i.getMessage()); } catch (ClassNotFoundException e1) { System.out.println(e1.getMessage()); } } } class Employee implements Externalizable { public Employee(){} String name; int age; public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeInt(age); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = (String)in.readObject(); age = in.readInt(); } } This will produce the following result − Reyan Ali 30
[ { "code": null, "e": 1437, "s": 1062, "text": "Externalization is used whenever we need to customize serialization mechanism. If a class implements an Externalizable interface then, object serialization will be done using writeExternal() method. Whereas at receiver's end when an Externalizable object is a reconstructed instance will be created using no argument constructor and then the readExternal() method is called." }, { "code": null, "e": 1636, "s": 1437, "text": "If a class implements only Serializable interface object serialization will be done using ObjectoutputStream. At the receiver's end, the serializable object is reconstructed using ObjectInputStream." }, { "code": null, "e": 1695, "s": 1636, "text": "Below example showcases usage of Externalizable interface." }, { "code": null, "e": 3198, "s": 1695, "text": "import java.io.Externalizable;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInput;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutput;\nimport java.io.ObjectOutputStream;\n\npublic class Tester {\n public static void main(String[] args) {\n\n Employee e = new Employee();\n e.name = \"Reyan Ali\";\n e.age = 30;\n try (\n FileOutputStream fileOut = new FileOutputStream(\"test.txt\");\n ObjectOutputStream out = new ObjectOutputStream(fileOut);\n ) {\n out.writeObject(e);\n }catch (IOException i) {\n System.out.println(i.getMessage());\n }\n try (\n FileInputStream fileIn = new FileInputStream(\"test.txt\");\n ObjectInputStream in = new ObjectInputStream(fileIn);\n ) {\n e = (Employee)in.readObject();\n System.out.println(e.name);\n System.out.println(e.age);\n } catch (IOException i) {\n System.out.println(i.getMessage());\n } catch (ClassNotFoundException e1) {\n System.out.println(e1.getMessage());\n }\n }\n}\n\nclass Employee implements Externalizable {\n public Employee(){}\n String name;\n int age;\n public void writeExternal(ObjectOutput out) throws IOException {\n out.writeObject(name);\n out.writeInt(age);\n }\n public void readExternal(ObjectInput in) throws IOException,\n ClassNotFoundException {\n name = (String)in.readObject();\n age = in.readInt();\n }\n}" }, { "code": null, "e": 3239, "s": 3198, "text": "This will produce the following result −" }, { "code": null, "e": 3252, "s": 3239, "text": "Reyan Ali\n30" } ]